aoptx86.pas 638 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945
  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. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  103. class function IsBTXAcceptable(p : tai) : boolean; static;
  104. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  105. conversion was successful }
  106. function ConvertLEA(const p : taicpu): Boolean;
  107. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  108. function FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  109. procedure DebugMsg(const s : string; p : tai);inline;
  110. class function IsExitCode(p : tai) : boolean; static;
  111. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  112. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  113. procedure RemoveLastDeallocForFuncRes(p : tai);
  114. function DoArithCombineOpt(var p : tai) : Boolean;
  115. function DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  116. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  117. function PrePeepholeOptSxx(var p : tai) : boolean;
  118. function PrePeepholeOptIMUL(var p : tai) : boolean;
  119. function PrePeepholeOptAND(var p : tai) : boolean;
  120. function OptPass1Test(var p: tai): boolean;
  121. function OptPass1Add(var p: tai): boolean;
  122. function OptPass1AND(var p : tai) : boolean;
  123. function OptPass1_V_MOVAP(var p : tai) : boolean;
  124. function OptPass1VOP(var p : tai) : boolean;
  125. function OptPass1MOV(var p : tai) : boolean;
  126. function OptPass1Movx(var p : tai) : boolean;
  127. function OptPass1MOVXX(var p : tai) : boolean;
  128. function OptPass1OP(var p : tai) : boolean;
  129. function OptPass1LEA(var p : tai) : boolean;
  130. function OptPass1Sub(var p : tai) : boolean;
  131. function OptPass1SHLSAL(var p : tai) : boolean;
  132. function OptPass1SHR(var p : tai) : boolean;
  133. function OptPass1FSTP(var p : tai) : boolean;
  134. function OptPass1FLD(var p : tai) : boolean;
  135. function OptPass1Cmp(var p : tai) : boolean;
  136. function OptPass1PXor(var p : tai) : boolean;
  137. function OptPass1VPXor(var p: tai): boolean;
  138. function OptPass1Imul(var p : tai) : boolean;
  139. function OptPass1Jcc(var p : tai) : boolean;
  140. function OptPass1SHXX(var p: tai): boolean;
  141. function OptPass1VMOVDQ(var p: tai): Boolean;
  142. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  143. function OptPass2Movx(var p : tai): Boolean;
  144. function OptPass2MOV(var p : tai) : boolean;
  145. function OptPass2Imul(var p : tai) : boolean;
  146. function OptPass2Jmp(var p : tai) : boolean;
  147. function OptPass2Jcc(var p : tai) : boolean;
  148. function OptPass2Lea(var p: tai): Boolean;
  149. function OptPass2SUB(var p: tai): Boolean;
  150. function OptPass2ADD(var p : tai): Boolean;
  151. function OptPass2SETcc(var p : tai) : boolean;
  152. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  153. function PostPeepholeOptMov(var p : tai) : Boolean;
  154. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  155. function PostPeepholeOptXor(var p : tai) : Boolean;
  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 TrySwapMovOp(var p, hp1: tai): Boolean;
  169. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  170. { Processor-dependent reference optimisation }
  171. class procedure OptimizeRefs(var p: taicpu); static;
  172. end;
  173. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  174. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  175. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  176. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  177. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  178. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  179. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  180. {$if max_operands>2}
  181. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  182. {$endif max_operands>2}
  183. function RefsEqual(const r1, r2: treference): boolean;
  184. { Note that Result is set to True if the references COULD overlap but the
  185. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  186. might still overlap because %reg2 could be equal to %reg1-4 }
  187. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  188. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  189. { returns true, if ref is a reference using only the registers passed as base and index
  190. and having an offset }
  191. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  192. implementation
  193. uses
  194. cutils,verbose,
  195. systems,
  196. globals,
  197. cpuinfo,
  198. procinfo,
  199. paramgr,
  200. aasmbase,
  201. aoptbase,aoptutils,
  202. symconst,symsym,
  203. cgx86,
  204. itcpugas;
  205. {$ifdef DEBUG_AOPTCPU}
  206. const
  207. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  208. {$else DEBUG_AOPTCPU}
  209. { Empty strings help the optimizer to remove string concatenations that won't
  210. ever appear to the user on release builds. [Kit] }
  211. const
  212. SPeepholeOptimization = '';
  213. {$endif DEBUG_AOPTCPU}
  214. LIST_STEP_SIZE = 4;
  215. type
  216. TJumpTrackingItem = class(TLinkedListItem)
  217. private
  218. FSymbol: TAsmSymbol;
  219. FRefs: LongInt;
  220. public
  221. constructor Create(ASymbol: TAsmSymbol);
  222. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  223. property Symbol: TAsmSymbol read FSymbol;
  224. property Refs: LongInt read FRefs;
  225. end;
  226. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  227. begin
  228. inherited Create;
  229. FSymbol := ASymbol;
  230. FRefs := 0;
  231. end;
  232. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  233. begin
  234. Inc(FRefs);
  235. end;
  236. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  237. begin
  238. result :=
  239. (instr.typ = ait_instruction) and
  240. (taicpu(instr).opcode = op) and
  241. ((opsize = []) or (taicpu(instr).opsize in opsize));
  242. end;
  243. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  244. begin
  245. result :=
  246. (instr.typ = ait_instruction) and
  247. ((taicpu(instr).opcode = op1) or
  248. (taicpu(instr).opcode = op2)
  249. ) and
  250. ((opsize = []) or (taicpu(instr).opsize in opsize));
  251. end;
  252. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  253. begin
  254. result :=
  255. (instr.typ = ait_instruction) and
  256. ((taicpu(instr).opcode = op1) or
  257. (taicpu(instr).opcode = op2) or
  258. (taicpu(instr).opcode = op3)
  259. ) and
  260. ((opsize = []) or (taicpu(instr).opsize in opsize));
  261. end;
  262. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  263. const opsize : topsizes) : boolean;
  264. var
  265. op : TAsmOp;
  266. begin
  267. result:=false;
  268. if (instr.typ <> ait_instruction) or
  269. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  270. exit;
  271. for op in ops do
  272. begin
  273. if taicpu(instr).opcode = op then
  274. begin
  275. result:=true;
  276. exit;
  277. end;
  278. end;
  279. end;
  280. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  281. begin
  282. result := (oper.typ = top_reg) and (oper.reg = reg);
  283. end;
  284. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  285. begin
  286. result := (oper.typ = top_const) and (oper.val = a);
  287. end;
  288. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  289. begin
  290. result := oper1.typ = oper2.typ;
  291. if result then
  292. case oper1.typ of
  293. top_const:
  294. Result:=oper1.val = oper2.val;
  295. top_reg:
  296. Result:=oper1.reg = oper2.reg;
  297. top_ref:
  298. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  299. else
  300. internalerror(2013102801);
  301. end
  302. end;
  303. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  304. begin
  305. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  306. if result then
  307. case oper1.typ of
  308. top_const:
  309. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  310. top_reg:
  311. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  312. top_ref:
  313. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  314. else
  315. internalerror(2020052401);
  316. end
  317. end;
  318. function RefsEqual(const r1, r2: treference): boolean;
  319. begin
  320. RefsEqual :=
  321. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  322. (r1.relsymbol = r2.relsymbol) and
  323. (r1.segment = r2.segment) and (r1.base = r2.base) and
  324. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  325. (r1.offset = r2.offset) and
  326. (r1.volatility + r2.volatility = []);
  327. end;
  328. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  329. begin
  330. if (r1.symbol<>r2.symbol) then
  331. { If the index registers are different, there's a chance one could
  332. be set so it equals the other symbol }
  333. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  334. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  335. (r1.relsymbol = r2.relsymbol) and
  336. (r1.segment = r2.segment) and (r1.base = r2.base) and
  337. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  338. (r1.volatility + r2.volatility = []) then
  339. { In this case, it all depends on the offsets }
  340. Exit(abs(r1.offset - r2.offset) < Range);
  341. { There's a chance things MIGHT overlap, so take no chances }
  342. Result := True;
  343. end;
  344. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  345. begin
  346. Result:=(ref.offset=0) and
  347. (ref.scalefactor in [0,1]) and
  348. (ref.segment=NR_NO) and
  349. (ref.symbol=nil) and
  350. (ref.relsymbol=nil) and
  351. ((base=NR_INVALID) or
  352. (ref.base=base)) and
  353. ((index=NR_INVALID) or
  354. (ref.index=index)) and
  355. (ref.volatility=[]);
  356. end;
  357. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  358. begin
  359. Result:=(ref.scalefactor in [0,1]) and
  360. (ref.segment=NR_NO) and
  361. (ref.symbol=nil) and
  362. (ref.relsymbol=nil) and
  363. ((base=NR_INVALID) or
  364. (ref.base=base)) and
  365. ((index=NR_INVALID) or
  366. (ref.index=index)) and
  367. (ref.volatility=[]);
  368. end;
  369. function InstrReadsFlags(p: tai): boolean;
  370. begin
  371. InstrReadsFlags := true;
  372. case p.typ of
  373. ait_instruction:
  374. if InsProp[taicpu(p).opcode].Ch*
  375. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  376. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  377. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  378. exit;
  379. ait_label:
  380. exit;
  381. else
  382. ;
  383. end;
  384. InstrReadsFlags := false;
  385. end;
  386. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  387. begin
  388. Next:=Current;
  389. repeat
  390. Result:=GetNextInstruction(Next,Next);
  391. until not (Result) or
  392. not(cs_opt_level3 in current_settings.optimizerswitches) or
  393. (Next.typ<>ait_instruction) or
  394. RegInInstruction(reg,Next) or
  395. is_calljmp(taicpu(Next).opcode);
  396. end;
  397. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  398. var
  399. GetNextResult: Boolean;
  400. begin
  401. Result:=0;
  402. Next:=Current;
  403. repeat
  404. GetNextResult := GetNextInstruction(Next,Next);
  405. if GetNextResult then
  406. Inc(Result)
  407. else
  408. { Must return zero upon hitting the end of the linked list without a match }
  409. Result := 0;
  410. until not (GetNextResult) or
  411. not(cs_opt_level3 in current_settings.optimizerswitches) or
  412. (Next.typ<>ait_instruction) or
  413. RegInInstruction(reg,Next) or
  414. is_calljmp(taicpu(Next).opcode);
  415. end;
  416. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  417. procedure TrackJump(Symbol: TAsmSymbol);
  418. var
  419. Search: TJumpTrackingItem;
  420. begin
  421. { See if an entry already exists in our jump tracking list
  422. (faster to search backwards due to the higher chance of
  423. matching destinations) }
  424. Search := TJumpTrackingItem(JumpTracking.Last);
  425. while Assigned(Search) do
  426. begin
  427. if Search.Symbol = Symbol then
  428. begin
  429. { Found it - remove it so it can be pushed to the front }
  430. JumpTracking.Remove(Search);
  431. Break;
  432. end;
  433. Search := TJumpTrackingItem(Search.Previous);
  434. end;
  435. if not Assigned(Search) then
  436. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  437. JumpTracking.Concat(Search);
  438. Search.IncRefs;
  439. end;
  440. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  441. var
  442. Search: TJumpTrackingItem;
  443. begin
  444. Result := False;
  445. { See if this label appears in the tracking list }
  446. Search := TJumpTrackingItem(JumpTracking.Last);
  447. while Assigned(Search) do
  448. begin
  449. if Search.Symbol = Symbol then
  450. begin
  451. { Found it - let's see what we can discover }
  452. if Search.Symbol.getrefs = Search.Refs then
  453. begin
  454. { Success - all the references are accounted for }
  455. JumpTracking.Remove(Search);
  456. Search.Free;
  457. { It is logically impossible for CrossJump to be false here
  458. because we must have run into a conditional jump for
  459. this label at some point }
  460. if not CrossJump then
  461. InternalError(2022041710);
  462. if JumpTracking.First = nil then
  463. { Tracking list is now empty - no more cross jumps }
  464. CrossJump := False;
  465. Result := True;
  466. Exit;
  467. end;
  468. { If the references don't match, it's possible to enter
  469. this label through other means, so drop out }
  470. Exit;
  471. end;
  472. Search := TJumpTrackingItem(Search.Previous);
  473. end;
  474. end;
  475. var
  476. Next_Label: tai;
  477. begin
  478. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  479. Next := Current;
  480. repeat
  481. Result := GetNextInstruction(Next,Next);
  482. if not Result then
  483. Break;
  484. if Next.typ = ait_align then
  485. Result := SkipAligns(Next, Next);
  486. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  487. if is_calljmpuncondret(taicpu(Next).opcode) then
  488. begin
  489. if (taicpu(Next).opcode = A_JMP) and
  490. { Remove dead code now to save time }
  491. RemoveDeadCodeAfterJump(taicpu(Next)) then
  492. { A jump was removed, but not the current instruction, and
  493. Result doesn't necessarily translate into an optimisation
  494. routine's Result, so use the "Force New Iteration" flag so
  495. mark a new pass }
  496. Include(OptsToCheck, aoc_ForceNewIteration);
  497. if not Assigned(JumpTracking) then
  498. begin
  499. { Cross-label optimisations often causes other optimisations
  500. to perform worse because they're not given the chance to
  501. optimise locally. In this case, don't do the cross-label
  502. optimisations yet, but flag them as a potential possibility
  503. for the next iteration of Pass 1 }
  504. if not NotFirstIteration then
  505. Include(OptsToCheck, aoc_ForceNewIteration);
  506. end
  507. else if IsJumpToLabel(taicpu(Next)) and
  508. GetNextInstruction(Next, Next_Label) and
  509. SkipAligns(Next_Label, Next_Label) then
  510. begin
  511. { If we have JMP .lbl, and the label after it has all of its
  512. references tracked, then this is probably an if-else style of
  513. block and we can keep tracking. If the label for this jump
  514. then appears later and is fully tracked, then it's the end
  515. of the if-else blocks and the code paths converge (thus
  516. marking the end of the cross-jump) }
  517. if (Next_Label.typ = ait_label) then
  518. begin
  519. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  520. begin
  521. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  522. Next := Next_Label;
  523. { CrossJump gets set to false by LabelAccountedFor if the
  524. list is completely emptied (as it indicates that all
  525. code paths have converged). We could avoid this nuance
  526. by moving the TrackJump call to before the
  527. LabelAccountedFor call, but this is slower in situations
  528. where LabelAccountedFor would return False due to the
  529. creation of a new object that is not used and destroyed
  530. soon after. }
  531. CrossJump := True;
  532. Continue;
  533. end;
  534. end
  535. else if (Next_Label.typ <> ait_marker) then
  536. { We just did a RemoveDeadCodeAfterJump, so either we find
  537. a label, the end of the procedure or some kind of marker}
  538. InternalError(2022041720);
  539. end;
  540. Result := False;
  541. Exit;
  542. end
  543. else
  544. begin
  545. if not Assigned(JumpTracking) then
  546. begin
  547. { Cross-label optimisations often causes other optimisations
  548. to perform worse because they're not given the chance to
  549. optimise locally. In this case, don't do the cross-label
  550. optimisations yet, but flag them as a potential possibility
  551. for the next iteration of Pass 1 }
  552. if not NotFirstIteration then
  553. Include(OptsToCheck, aoc_ForceNewIteration);
  554. end
  555. else if IsJumpToLabel(taicpu(Next)) then
  556. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  557. else
  558. { Conditional jumps should always be a jump to label }
  559. InternalError(2022041701);
  560. CrossJump := True;
  561. Continue;
  562. end;
  563. if Next.typ = ait_label then
  564. begin
  565. if not Assigned(JumpTracking) then
  566. begin
  567. { Cross-label optimisations often causes other optimisations
  568. to perform worse because they're not given the chance to
  569. optimise locally. In this case, don't do the cross-label
  570. optimisations yet, but flag them as a potential possibility
  571. for the next iteration of Pass 1 }
  572. if not NotFirstIteration then
  573. Include(OptsToCheck, aoc_ForceNewIteration);
  574. end
  575. else if LabelAccountedFor(tai_label(Next).labsym) then
  576. Continue;
  577. { If we reach here, we're at a label that hasn't been seen before
  578. (or JumpTracking was nil) }
  579. Break;
  580. end;
  581. until not Result or
  582. not (cs_opt_level3 in current_settings.optimizerswitches) or
  583. not (Next.typ in [ait_label, ait_instruction]) or
  584. RegInInstruction(reg,Next);
  585. end;
  586. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  587. begin
  588. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  589. begin
  590. Result:=GetNextInstruction(Current,Next);
  591. exit;
  592. end;
  593. Next:=tai(Current.Next);
  594. Result:=false;
  595. while assigned(Next) do
  596. begin
  597. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  598. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  599. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  600. exit
  601. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  602. begin
  603. Result:=true;
  604. exit;
  605. end;
  606. Next:=tai(Next.Next);
  607. end;
  608. end;
  609. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  610. begin
  611. Result:=RegReadByInstruction(reg,hp);
  612. end;
  613. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  614. var
  615. p: taicpu;
  616. opcount: longint;
  617. begin
  618. RegReadByInstruction := false;
  619. if hp.typ <> ait_instruction then
  620. exit;
  621. p := taicpu(hp);
  622. case p.opcode of
  623. A_CALL:
  624. regreadbyinstruction := true;
  625. A_IMUL:
  626. case p.ops of
  627. 1:
  628. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  629. (
  630. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  631. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  632. );
  633. 2,3:
  634. regReadByInstruction :=
  635. reginop(reg,p.oper[0]^) or
  636. reginop(reg,p.oper[1]^);
  637. else
  638. InternalError(2019112801);
  639. end;
  640. A_MUL:
  641. begin
  642. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  643. (
  644. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  645. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  646. );
  647. end;
  648. A_IDIV,A_DIV:
  649. begin
  650. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  651. (
  652. (getregtype(reg)=R_INTREGISTER) and
  653. (
  654. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  655. )
  656. );
  657. end;
  658. else
  659. begin
  660. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  661. begin
  662. RegReadByInstruction := false;
  663. exit;
  664. end;
  665. for opcount := 0 to p.ops-1 do
  666. if (p.oper[opCount]^.typ = top_ref) and
  667. RegInRef(reg,p.oper[opcount]^.ref^) then
  668. begin
  669. RegReadByInstruction := true;
  670. exit
  671. end;
  672. { special handling for SSE MOVSD }
  673. if (p.opcode=A_MOVSD) and (p.ops>0) then
  674. begin
  675. if p.ops<>2 then
  676. internalerror(2017042702);
  677. regReadByInstruction := reginop(reg,p.oper[0]^) or
  678. (
  679. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  680. );
  681. exit;
  682. end;
  683. with insprop[p.opcode] do
  684. begin
  685. case getregtype(reg) of
  686. R_INTREGISTER:
  687. begin
  688. case getsupreg(reg) of
  689. RS_EAX:
  690. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  691. begin
  692. RegReadByInstruction := true;
  693. exit
  694. end;
  695. RS_ECX:
  696. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  697. begin
  698. RegReadByInstruction := true;
  699. exit
  700. end;
  701. RS_EDX:
  702. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  703. begin
  704. RegReadByInstruction := true;
  705. exit
  706. end;
  707. RS_EBX:
  708. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  709. begin
  710. RegReadByInstruction := true;
  711. exit
  712. end;
  713. RS_ESP:
  714. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  715. begin
  716. RegReadByInstruction := true;
  717. exit
  718. end;
  719. RS_EBP:
  720. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  721. begin
  722. RegReadByInstruction := true;
  723. exit
  724. end;
  725. RS_ESI:
  726. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  727. begin
  728. RegReadByInstruction := true;
  729. exit
  730. end;
  731. RS_EDI:
  732. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  733. begin
  734. RegReadByInstruction := true;
  735. exit
  736. end;
  737. end;
  738. end;
  739. R_MMREGISTER:
  740. begin
  741. case getsupreg(reg) of
  742. RS_XMM0:
  743. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  744. begin
  745. RegReadByInstruction := true;
  746. exit
  747. end;
  748. end;
  749. end;
  750. else
  751. ;
  752. end;
  753. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  754. begin
  755. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  756. begin
  757. case p.condition of
  758. C_A,C_NBE, { CF=0 and ZF=0 }
  759. C_BE,C_NA: { CF=1 or ZF=1 }
  760. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  761. C_AE,C_NB,C_NC, { CF=0 }
  762. C_B,C_NAE,C_C: { CF=1 }
  763. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  764. C_NE,C_NZ, { ZF=0 }
  765. C_E,C_Z: { ZF=1 }
  766. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  767. C_G,C_NLE, { ZF=0 and SF=OF }
  768. C_LE,C_NG: { ZF=1 or SF<>OF }
  769. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  770. C_GE,C_NL, { SF=OF }
  771. C_L,C_NGE: { SF<>OF }
  772. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  773. C_NO, { OF=0 }
  774. C_O: { OF=1 }
  775. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  776. C_NP,C_PO, { PF=0 }
  777. C_P,C_PE: { PF=1 }
  778. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  779. C_NS, { SF=0 }
  780. C_S: { SF=1 }
  781. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  782. else
  783. internalerror(2017042701);
  784. end;
  785. if RegReadByInstruction then
  786. exit;
  787. end;
  788. case getsubreg(reg) of
  789. R_SUBW,R_SUBD,R_SUBQ:
  790. RegReadByInstruction :=
  791. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  792. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  793. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  794. R_SUBFLAGCARRY:
  795. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  796. R_SUBFLAGPARITY:
  797. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  798. R_SUBFLAGAUXILIARY:
  799. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  800. R_SUBFLAGZERO:
  801. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  802. R_SUBFLAGSIGN:
  803. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  804. R_SUBFLAGOVERFLOW:
  805. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  806. R_SUBFLAGINTERRUPT:
  807. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  808. R_SUBFLAGDIRECTION:
  809. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  810. else
  811. internalerror(2017042601);
  812. end;
  813. exit;
  814. end;
  815. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  816. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  817. (p.oper[0]^.reg=p.oper[1]^.reg) then
  818. exit;
  819. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  820. begin
  821. RegReadByInstruction := true;
  822. exit
  823. end;
  824. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  825. begin
  826. RegReadByInstruction := true;
  827. exit
  828. end;
  829. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  830. begin
  831. RegReadByInstruction := true;
  832. exit
  833. end;
  834. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  835. begin
  836. RegReadByInstruction := true;
  837. exit
  838. end;
  839. end;
  840. end;
  841. end;
  842. end;
  843. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  844. begin
  845. result:=false;
  846. if p1.typ<>ait_instruction then
  847. exit;
  848. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  849. exit(true);
  850. if (getregtype(reg)=R_INTREGISTER) and
  851. { change information for xmm movsd are not correct }
  852. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  853. begin
  854. case getsupreg(reg) of
  855. { RS_EAX = RS_RAX on x86-64 }
  856. RS_EAX:
  857. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  858. RS_ECX:
  859. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  860. RS_EDX:
  861. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  862. RS_EBX:
  863. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  864. RS_ESP:
  865. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  866. RS_EBP:
  867. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  868. RS_ESI:
  869. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  870. RS_EDI:
  871. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  872. else
  873. ;
  874. end;
  875. if result then
  876. exit;
  877. end
  878. else if getregtype(reg)=R_MMREGISTER then
  879. begin
  880. case getsupreg(reg) of
  881. RS_XMM0:
  882. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  883. else
  884. ;
  885. end;
  886. if result then
  887. exit;
  888. end
  889. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  890. begin
  891. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  892. exit(true);
  893. case getsubreg(reg) of
  894. R_SUBFLAGCARRY:
  895. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  896. R_SUBFLAGPARITY:
  897. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  898. R_SUBFLAGAUXILIARY:
  899. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  900. R_SUBFLAGZERO:
  901. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  902. R_SUBFLAGSIGN:
  903. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  904. R_SUBFLAGOVERFLOW:
  905. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  906. R_SUBFLAGINTERRUPT:
  907. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  908. R_SUBFLAGDIRECTION:
  909. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  910. R_SUBW,R_SUBD,R_SUBQ:
  911. { Everything except the direction bits }
  912. Result:=
  913. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  914. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  915. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  916. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  917. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  918. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  919. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  920. else
  921. ;
  922. end;
  923. if result then
  924. exit;
  925. end
  926. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  927. exit(true);
  928. Result:=inherited RegInInstruction(Reg, p1);
  929. end;
  930. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  931. const
  932. WriteOps: array[0..3] of set of TInsChange =
  933. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  934. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  935. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  936. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  937. var
  938. OperIdx: Integer;
  939. begin
  940. Result := False;
  941. if p1.typ <> ait_instruction then
  942. exit;
  943. with insprop[taicpu(p1).opcode] do
  944. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  945. begin
  946. case getsubreg(reg) of
  947. R_SUBW,R_SUBD,R_SUBQ:
  948. Result :=
  949. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  950. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  951. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  952. R_SUBFLAGCARRY:
  953. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  954. R_SUBFLAGPARITY:
  955. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  956. R_SUBFLAGAUXILIARY:
  957. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  958. R_SUBFLAGZERO:
  959. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  960. R_SUBFLAGSIGN:
  961. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  962. R_SUBFLAGOVERFLOW:
  963. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  964. R_SUBFLAGINTERRUPT:
  965. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  966. R_SUBFLAGDIRECTION:
  967. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  968. else
  969. internalerror(2017042602);
  970. end;
  971. exit;
  972. end;
  973. case taicpu(p1).opcode of
  974. A_CALL:
  975. { We could potentially set Result to False if the register in
  976. question is non-volatile for the subroutine's calling convention,
  977. but this would require detecting the calling convention in use and
  978. also assuming that the routine doesn't contain malformed assembly
  979. language, for example... so it could only be done under -O4 as it
  980. would be considered a side-effect. [Kit] }
  981. Result := True;
  982. A_MOVSD:
  983. { special handling for SSE MOVSD }
  984. if (taicpu(p1).ops>0) then
  985. begin
  986. if taicpu(p1).ops<>2 then
  987. internalerror(2017042703);
  988. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  989. end;
  990. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  991. so fix it here (FK)
  992. }
  993. A_VMOVSS,
  994. A_VMOVSD:
  995. begin
  996. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  997. exit;
  998. end;
  999. A_IMUL:
  1000. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1001. else
  1002. ;
  1003. end;
  1004. if Result then
  1005. exit;
  1006. with insprop[taicpu(p1).opcode] do
  1007. begin
  1008. if getregtype(reg)=R_INTREGISTER then
  1009. begin
  1010. case getsupreg(reg) of
  1011. RS_EAX:
  1012. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1013. begin
  1014. Result := True;
  1015. exit
  1016. end;
  1017. RS_ECX:
  1018. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1019. begin
  1020. Result := True;
  1021. exit
  1022. end;
  1023. RS_EDX:
  1024. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1025. begin
  1026. Result := True;
  1027. exit
  1028. end;
  1029. RS_EBX:
  1030. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1031. begin
  1032. Result := True;
  1033. exit
  1034. end;
  1035. RS_ESP:
  1036. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1037. begin
  1038. Result := True;
  1039. exit
  1040. end;
  1041. RS_EBP:
  1042. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1043. begin
  1044. Result := True;
  1045. exit
  1046. end;
  1047. RS_ESI:
  1048. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1049. begin
  1050. Result := True;
  1051. exit
  1052. end;
  1053. RS_EDI:
  1054. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1055. begin
  1056. Result := True;
  1057. exit
  1058. end;
  1059. end;
  1060. end;
  1061. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1062. if (WriteOps[OperIdx]*Ch<>[]) and
  1063. { The register doesn't get modified inside a reference }
  1064. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1065. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1066. begin
  1067. Result := true;
  1068. exit
  1069. end;
  1070. end;
  1071. end;
  1072. {$ifdef DEBUG_AOPTCPU}
  1073. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1074. begin
  1075. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1076. end;
  1077. function debug_tostr(i: tcgint): string; inline;
  1078. begin
  1079. Result := tostr(i);
  1080. end;
  1081. function debug_regname(r: TRegister): string; inline;
  1082. begin
  1083. Result := '%' + std_regname(r);
  1084. end;
  1085. { Debug output function - creates a string representation of an operator }
  1086. function debug_operstr(oper: TOper): string;
  1087. begin
  1088. case oper.typ of
  1089. top_const:
  1090. Result := '$' + debug_tostr(oper.val);
  1091. top_reg:
  1092. Result := debug_regname(oper.reg);
  1093. top_ref:
  1094. begin
  1095. if oper.ref^.offset <> 0 then
  1096. Result := debug_tostr(oper.ref^.offset) + '('
  1097. else
  1098. Result := '(';
  1099. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1100. begin
  1101. Result := Result + debug_regname(oper.ref^.base);
  1102. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1103. Result := Result + ',' + debug_regname(oper.ref^.index);
  1104. end
  1105. else
  1106. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1107. Result := Result + debug_regname(oper.ref^.index);
  1108. if (oper.ref^.scalefactor > 1) then
  1109. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1110. else
  1111. Result := Result + ')';
  1112. end;
  1113. else
  1114. Result := '[UNKNOWN]';
  1115. end;
  1116. end;
  1117. function debug_op2str(opcode: tasmop): string; inline;
  1118. begin
  1119. Result := std_op2str[opcode];
  1120. end;
  1121. function debug_opsize2str(opsize: topsize): string; inline;
  1122. begin
  1123. Result := gas_opsize2str[opsize];
  1124. end;
  1125. {$else DEBUG_AOPTCPU}
  1126. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1127. begin
  1128. end;
  1129. function debug_tostr(i: tcgint): string; inline;
  1130. begin
  1131. Result := '';
  1132. end;
  1133. function debug_regname(r: TRegister): string; inline;
  1134. begin
  1135. Result := '';
  1136. end;
  1137. function debug_operstr(oper: TOper): string; inline;
  1138. begin
  1139. Result := '';
  1140. end;
  1141. function debug_op2str(opcode: tasmop): string; inline;
  1142. begin
  1143. Result := '';
  1144. end;
  1145. function debug_opsize2str(opsize: topsize): string; inline;
  1146. begin
  1147. Result := '';
  1148. end;
  1149. {$endif DEBUG_AOPTCPU}
  1150. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1151. begin
  1152. {$ifdef x86_64}
  1153. { Always fine on x86-64 }
  1154. Result := True;
  1155. {$else x86_64}
  1156. Result :=
  1157. {$ifdef i8086}
  1158. (current_settings.cputype >= cpu_386) and
  1159. {$endif i8086}
  1160. (
  1161. { Always accept if optimising for size }
  1162. (cs_opt_size in current_settings.optimizerswitches) or
  1163. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1164. (current_settings.optimizecputype >= cpu_Pentium2)
  1165. );
  1166. {$endif x86_64}
  1167. end;
  1168. { Attempts to allocate a volatile integer register for use between p and hp,
  1169. using AUsedRegs for the current register usage information. Returns NR_NO
  1170. if no free register could be found }
  1171. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1172. var
  1173. RegSet: TCPURegisterSet;
  1174. CurrentSuperReg: Integer;
  1175. CurrentReg: TRegister;
  1176. Currentp: tai;
  1177. Breakout: Boolean;
  1178. begin
  1179. Result := NR_NO;
  1180. RegSet :=
  1181. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1182. current_procinfo.saved_regs_int;
  1183. for CurrentSuperReg in RegSet do
  1184. begin
  1185. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1186. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1187. {$if defined(i386) or defined(i8086)}
  1188. { If the target size is 8-bit, make sure we can actually encode it }
  1189. and (
  1190. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1191. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1192. )
  1193. {$endif i386 or i8086}
  1194. then
  1195. begin
  1196. Currentp := p;
  1197. Breakout := False;
  1198. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1199. begin
  1200. case Currentp.typ of
  1201. ait_instruction:
  1202. begin
  1203. if RegInInstruction(CurrentReg, Currentp) then
  1204. begin
  1205. Breakout := True;
  1206. Break;
  1207. end;
  1208. { Cannot allocate across an unconditional jump }
  1209. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1210. Exit;
  1211. end;
  1212. ait_marker:
  1213. { Don't try anything more if a marker is hit }
  1214. Exit;
  1215. ait_regalloc:
  1216. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1217. begin
  1218. Breakout := True;
  1219. Break;
  1220. end;
  1221. else
  1222. ;
  1223. end;
  1224. end;
  1225. if Breakout then
  1226. { Try the next register }
  1227. Continue;
  1228. { We have a free register available }
  1229. Result := CurrentReg;
  1230. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1231. Exit;
  1232. end;
  1233. end;
  1234. end;
  1235. { Attempts to allocate a volatile MM register for use between p and hp,
  1236. using AUsedRegs for the current register usage information. Returns NR_NO
  1237. if no free register could be found }
  1238. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1239. var
  1240. RegSet: TCPURegisterSet;
  1241. CurrentSuperReg: Integer;
  1242. CurrentReg: TRegister;
  1243. Currentp: tai;
  1244. Breakout: Boolean;
  1245. begin
  1246. Result := NR_NO;
  1247. RegSet :=
  1248. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1249. current_procinfo.saved_regs_mm;
  1250. for CurrentSuperReg in RegSet do
  1251. begin
  1252. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1253. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1254. begin
  1255. Currentp := p;
  1256. Breakout := False;
  1257. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1258. begin
  1259. case Currentp.typ of
  1260. ait_instruction:
  1261. begin
  1262. if RegInInstruction(CurrentReg, Currentp) then
  1263. begin
  1264. Breakout := True;
  1265. Break;
  1266. end;
  1267. { Cannot allocate across an unconditional jump }
  1268. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1269. Exit;
  1270. end;
  1271. ait_marker:
  1272. { Don't try anything more if a marker is hit }
  1273. Exit;
  1274. ait_regalloc:
  1275. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1276. begin
  1277. Breakout := True;
  1278. Break;
  1279. end;
  1280. else
  1281. ;
  1282. end;
  1283. end;
  1284. if Breakout then
  1285. { Try the next register }
  1286. Continue;
  1287. { We have a free register available }
  1288. Result := CurrentReg;
  1289. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1290. Exit;
  1291. end;
  1292. end;
  1293. end;
  1294. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1295. begin
  1296. if not SuperRegistersEqual(reg1,reg2) then
  1297. exit(false);
  1298. if getregtype(reg1)<>R_INTREGISTER then
  1299. exit(true); {because SuperRegisterEqual is true}
  1300. case getsubreg(reg1) of
  1301. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1302. higher, it preserves the high bits, so the new value depends on
  1303. reg2's previous value. In other words, it is equivalent to doing:
  1304. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1305. R_SUBL:
  1306. exit(getsubreg(reg2)=R_SUBL);
  1307. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1308. higher, it actually does a:
  1309. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1310. R_SUBH:
  1311. exit(getsubreg(reg2)=R_SUBH);
  1312. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1313. bits of reg2:
  1314. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1315. R_SUBW:
  1316. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1317. { a write to R_SUBD always overwrites every other subregister,
  1318. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1319. R_SUBD,
  1320. R_SUBQ:
  1321. exit(true);
  1322. else
  1323. internalerror(2017042801);
  1324. end;
  1325. end;
  1326. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1327. begin
  1328. if not SuperRegistersEqual(reg1,reg2) then
  1329. exit(false);
  1330. if getregtype(reg1)<>R_INTREGISTER then
  1331. exit(true); {because SuperRegisterEqual is true}
  1332. case getsubreg(reg1) of
  1333. R_SUBL:
  1334. exit(getsubreg(reg2)<>R_SUBH);
  1335. R_SUBH:
  1336. exit(getsubreg(reg2)<>R_SUBL);
  1337. R_SUBW,
  1338. R_SUBD,
  1339. R_SUBQ:
  1340. exit(true);
  1341. else
  1342. internalerror(2017042802);
  1343. end;
  1344. end;
  1345. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1346. var
  1347. hp1 : tai;
  1348. l : TCGInt;
  1349. begin
  1350. result:=false;
  1351. { changes the code sequence
  1352. shr/sar const1, x
  1353. shl const2, x
  1354. to
  1355. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1356. if GetNextInstruction(p, hp1) and
  1357. MatchInstruction(hp1,A_SHL,[]) and
  1358. (taicpu(p).oper[0]^.typ = top_const) and
  1359. (taicpu(hp1).oper[0]^.typ = top_const) and
  1360. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1361. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1362. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1363. begin
  1364. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1365. not(cs_opt_size in current_settings.optimizerswitches) then
  1366. begin
  1367. { shr/sar const1, %reg
  1368. shl const2, %reg
  1369. with const1 > const2 }
  1370. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1371. taicpu(hp1).opcode := A_AND;
  1372. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1373. case taicpu(p).opsize Of
  1374. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1375. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1376. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1377. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1378. else
  1379. Internalerror(2017050703)
  1380. end;
  1381. end
  1382. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1383. not(cs_opt_size in current_settings.optimizerswitches) then
  1384. begin
  1385. { shr/sar const1, %reg
  1386. shl const2, %reg
  1387. with const1 < const2 }
  1388. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1389. taicpu(p).opcode := A_AND;
  1390. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1391. case taicpu(p).opsize Of
  1392. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1393. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1394. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1395. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1396. else
  1397. Internalerror(2017050702)
  1398. end;
  1399. end
  1400. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1401. begin
  1402. { shr/sar const1, %reg
  1403. shl const2, %reg
  1404. with const1 = const2 }
  1405. taicpu(p).opcode := A_AND;
  1406. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1407. case taicpu(p).opsize Of
  1408. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1409. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1410. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1411. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1412. else
  1413. Internalerror(2017050701)
  1414. end;
  1415. RemoveInstruction(hp1);
  1416. end;
  1417. end;
  1418. end;
  1419. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1420. var
  1421. opsize : topsize;
  1422. hp1, hp2 : tai;
  1423. tmpref : treference;
  1424. ShiftValue : Cardinal;
  1425. BaseValue : TCGInt;
  1426. begin
  1427. result:=false;
  1428. opsize:=taicpu(p).opsize;
  1429. { changes certain "imul const, %reg"'s to lea sequences }
  1430. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1431. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1432. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1433. if (taicpu(p).oper[0]^.val = 1) then
  1434. if (taicpu(p).ops = 2) then
  1435. { remove "imul $1, reg" }
  1436. begin
  1437. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1438. Result := RemoveCurrentP(p);
  1439. end
  1440. else
  1441. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1442. begin
  1443. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1444. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1445. asml.InsertAfter(hp1, p);
  1446. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1447. RemoveCurrentP(p, hp1);
  1448. Result := True;
  1449. end
  1450. else if ((taicpu(p).ops <= 2) or
  1451. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1452. not(cs_opt_size in current_settings.optimizerswitches) and
  1453. (not(GetNextInstruction(p, hp1)) or
  1454. not((tai(hp1).typ = ait_instruction) and
  1455. ((taicpu(hp1).opcode=A_Jcc) and
  1456. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1457. begin
  1458. {
  1459. imul X, reg1, reg2 to
  1460. lea (reg1,reg1,Y), reg2
  1461. shl ZZ,reg2
  1462. imul XX, reg1 to
  1463. lea (reg1,reg1,YY), reg1
  1464. shl ZZ,reg2
  1465. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1466. it does not exist as a separate optimization target in FPC though.
  1467. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1468. at most two zeros
  1469. }
  1470. reference_reset(tmpref,1,[]);
  1471. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1472. begin
  1473. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1474. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1475. TmpRef.base := taicpu(p).oper[1]^.reg;
  1476. TmpRef.index := taicpu(p).oper[1]^.reg;
  1477. if not(BaseValue in [3,5,9]) then
  1478. Internalerror(2018110101);
  1479. TmpRef.ScaleFactor := BaseValue-1;
  1480. if (taicpu(p).ops = 2) then
  1481. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1482. else
  1483. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1484. AsmL.InsertAfter(hp1,p);
  1485. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1486. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1487. RemoveCurrentP(p, hp1);
  1488. if ShiftValue>0 then
  1489. begin
  1490. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1491. AsmL.InsertAfter(hp2,hp1);
  1492. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1493. end;
  1494. Result := True;
  1495. end;
  1496. end;
  1497. end;
  1498. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1499. begin
  1500. Result := False;
  1501. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1502. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1503. begin
  1504. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1505. taicpu(p).opcode := A_MOV;
  1506. Result := True;
  1507. end;
  1508. end;
  1509. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1510. var
  1511. p: taicpu absolute hp; { Implicit typecast }
  1512. i: Integer;
  1513. begin
  1514. Result := False;
  1515. if not assigned(hp) or
  1516. (hp.typ <> ait_instruction) then
  1517. Exit;
  1518. Prefetch(insprop[p.opcode]);
  1519. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1520. with insprop[p.opcode] do
  1521. begin
  1522. case getsubreg(reg) of
  1523. R_SUBW,R_SUBD,R_SUBQ:
  1524. Result:=
  1525. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1526. uncommon flags are checked first }
  1527. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1528. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1529. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1530. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1531. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1532. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1533. R_SUBFLAGCARRY:
  1534. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1535. R_SUBFLAGPARITY:
  1536. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1537. R_SUBFLAGAUXILIARY:
  1538. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1539. R_SUBFLAGZERO:
  1540. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1541. R_SUBFLAGSIGN:
  1542. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1543. R_SUBFLAGOVERFLOW:
  1544. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1545. R_SUBFLAGINTERRUPT:
  1546. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1547. R_SUBFLAGDIRECTION:
  1548. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1549. else
  1550. internalerror(2017050501);
  1551. end;
  1552. exit;
  1553. end;
  1554. { Handle special cases first }
  1555. case p.opcode of
  1556. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1557. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1558. begin
  1559. Result :=
  1560. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1561. (p.oper[1]^.typ = top_reg) and
  1562. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1563. (
  1564. (p.oper[0]^.typ = top_const) or
  1565. (
  1566. (p.oper[0]^.typ = top_reg) and
  1567. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1568. ) or (
  1569. (p.oper[0]^.typ = top_ref) and
  1570. not RegInRef(reg,p.oper[0]^.ref^)
  1571. )
  1572. );
  1573. end;
  1574. A_MUL, A_IMUL:
  1575. Result :=
  1576. (
  1577. (p.ops=3) and { IMUL only }
  1578. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1579. (
  1580. (
  1581. (p.oper[1]^.typ=top_reg) and
  1582. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1583. ) or (
  1584. (p.oper[1]^.typ=top_ref) and
  1585. not RegInRef(reg,p.oper[1]^.ref^)
  1586. )
  1587. )
  1588. ) or (
  1589. (
  1590. (p.ops=1) and
  1591. (
  1592. (
  1593. (
  1594. (p.oper[0]^.typ=top_reg) and
  1595. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1596. )
  1597. ) or (
  1598. (p.oper[0]^.typ=top_ref) and
  1599. not RegInRef(reg,p.oper[0]^.ref^)
  1600. )
  1601. ) and (
  1602. (
  1603. (p.opsize=S_B) and
  1604. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1605. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1606. ) or (
  1607. (p.opsize=S_W) and
  1608. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1609. ) or (
  1610. (p.opsize=S_L) and
  1611. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1612. {$ifdef x86_64}
  1613. ) or (
  1614. (p.opsize=S_Q) and
  1615. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1616. {$endif x86_64}
  1617. )
  1618. )
  1619. )
  1620. );
  1621. A_CBW:
  1622. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1623. {$ifndef x86_64}
  1624. A_LDS:
  1625. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1626. A_LES:
  1627. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1628. {$endif not x86_64}
  1629. A_LFS:
  1630. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1631. A_LGS:
  1632. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1633. A_LSS:
  1634. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1635. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1636. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1637. A_LODSB:
  1638. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1639. A_LODSW:
  1640. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1641. {$ifdef x86_64}
  1642. A_LODSQ:
  1643. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1644. {$endif x86_64}
  1645. A_LODSD:
  1646. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1647. A_FSTSW, A_FNSTSW:
  1648. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1649. else
  1650. begin
  1651. with insprop[p.opcode] do
  1652. begin
  1653. if (
  1654. { xor %reg,%reg etc. is classed as a new value }
  1655. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1656. MatchOpType(p, top_reg, top_reg) and
  1657. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1658. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1659. ) then
  1660. begin
  1661. Result := True;
  1662. Exit;
  1663. end;
  1664. { Make sure the entire register is overwritten }
  1665. if (getregtype(reg) = R_INTREGISTER) then
  1666. begin
  1667. if (p.ops > 0) then
  1668. begin
  1669. if RegInOp(reg, p.oper[0]^) then
  1670. begin
  1671. if (p.oper[0]^.typ = top_ref) then
  1672. begin
  1673. if RegInRef(reg, p.oper[0]^.ref^) then
  1674. begin
  1675. Result := False;
  1676. Exit;
  1677. end;
  1678. end
  1679. else if (p.oper[0]^.typ = top_reg) then
  1680. begin
  1681. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1682. begin
  1683. Result := False;
  1684. Exit;
  1685. end
  1686. else if ([Ch_WOp1]*Ch<>[]) then
  1687. begin
  1688. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1689. Result := True
  1690. else
  1691. begin
  1692. Result := False;
  1693. Exit;
  1694. end;
  1695. end;
  1696. end;
  1697. end;
  1698. if (p.ops > 1) then
  1699. begin
  1700. if RegInOp(reg, p.oper[1]^) then
  1701. begin
  1702. if (p.oper[1]^.typ = top_ref) then
  1703. begin
  1704. if RegInRef(reg, p.oper[1]^.ref^) then
  1705. begin
  1706. Result := False;
  1707. Exit;
  1708. end;
  1709. end
  1710. else if (p.oper[1]^.typ = top_reg) then
  1711. begin
  1712. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1713. begin
  1714. Result := False;
  1715. Exit;
  1716. end
  1717. else if ([Ch_WOp2]*Ch<>[]) then
  1718. begin
  1719. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1720. Result := True
  1721. else
  1722. begin
  1723. Result := False;
  1724. Exit;
  1725. end;
  1726. end;
  1727. end;
  1728. end;
  1729. if (p.ops > 2) then
  1730. begin
  1731. if RegInOp(reg, p.oper[2]^) then
  1732. begin
  1733. if (p.oper[2]^.typ = top_ref) then
  1734. begin
  1735. if RegInRef(reg, p.oper[2]^.ref^) then
  1736. begin
  1737. Result := False;
  1738. Exit;
  1739. end;
  1740. end
  1741. else if (p.oper[2]^.typ = top_reg) then
  1742. begin
  1743. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1744. begin
  1745. Result := False;
  1746. Exit;
  1747. end
  1748. else if ([Ch_WOp3]*Ch<>[]) then
  1749. begin
  1750. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1751. Result := True
  1752. else
  1753. begin
  1754. Result := False;
  1755. Exit;
  1756. end;
  1757. end;
  1758. end;
  1759. end;
  1760. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1761. begin
  1762. if (p.oper[3]^.typ = top_ref) then
  1763. begin
  1764. if RegInRef(reg, p.oper[3]^.ref^) then
  1765. begin
  1766. Result := False;
  1767. Exit;
  1768. end;
  1769. end
  1770. else if (p.oper[3]^.typ = top_reg) then
  1771. begin
  1772. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1773. begin
  1774. Result := False;
  1775. Exit;
  1776. end
  1777. else if ([Ch_WOp4]*Ch<>[]) then
  1778. begin
  1779. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1780. Result := True
  1781. else
  1782. begin
  1783. Result := False;
  1784. Exit;
  1785. end;
  1786. end;
  1787. end;
  1788. end;
  1789. end;
  1790. end;
  1791. end;
  1792. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1793. case getsupreg(reg) of
  1794. RS_EAX:
  1795. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1796. begin
  1797. Result := True;
  1798. Exit;
  1799. end;
  1800. RS_ECX:
  1801. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1802. begin
  1803. Result := True;
  1804. Exit;
  1805. end;
  1806. RS_EDX:
  1807. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1808. begin
  1809. Result := True;
  1810. Exit;
  1811. end;
  1812. RS_EBX:
  1813. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1814. begin
  1815. Result := True;
  1816. Exit;
  1817. end;
  1818. RS_ESP:
  1819. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1820. begin
  1821. Result := True;
  1822. Exit;
  1823. end;
  1824. RS_EBP:
  1825. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1826. begin
  1827. Result := True;
  1828. Exit;
  1829. end;
  1830. RS_ESI:
  1831. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1832. begin
  1833. Result := True;
  1834. Exit;
  1835. end;
  1836. RS_EDI:
  1837. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1838. begin
  1839. Result := True;
  1840. Exit;
  1841. end;
  1842. else
  1843. ;
  1844. end;
  1845. end;
  1846. end;
  1847. end;
  1848. end;
  1849. end;
  1850. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1851. var
  1852. hp2,hp3 : tai;
  1853. begin
  1854. { some x86-64 issue a NOP before the real exit code }
  1855. if MatchInstruction(p,A_NOP,[]) then
  1856. GetNextInstruction(p,p);
  1857. result:=assigned(p) and (p.typ=ait_instruction) and
  1858. ((taicpu(p).opcode = A_RET) or
  1859. ((taicpu(p).opcode=A_LEAVE) and
  1860. GetNextInstruction(p,hp2) and
  1861. MatchInstruction(hp2,A_RET,[S_NO])
  1862. ) or
  1863. (((taicpu(p).opcode=A_LEA) and
  1864. MatchOpType(taicpu(p),top_ref,top_reg) and
  1865. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1866. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1867. ) and
  1868. GetNextInstruction(p,hp2) and
  1869. MatchInstruction(hp2,A_RET,[S_NO])
  1870. ) or
  1871. ((((taicpu(p).opcode=A_MOV) and
  1872. MatchOpType(taicpu(p),top_reg,top_reg) and
  1873. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1874. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1875. ((taicpu(p).opcode=A_LEA) and
  1876. MatchOpType(taicpu(p),top_ref,top_reg) and
  1877. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1878. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1879. )
  1880. ) and
  1881. GetNextInstruction(p,hp2) and
  1882. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1883. MatchOpType(taicpu(hp2),top_reg) and
  1884. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1885. GetNextInstruction(hp2,hp3) and
  1886. MatchInstruction(hp3,A_RET,[S_NO])
  1887. )
  1888. );
  1889. end;
  1890. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1891. begin
  1892. isFoldableArithOp := False;
  1893. case hp1.opcode of
  1894. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1895. isFoldableArithOp :=
  1896. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1897. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1898. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1899. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1900. (taicpu(hp1).oper[1]^.reg = reg);
  1901. A_INC,A_DEC,A_NEG,A_NOT:
  1902. isFoldableArithOp :=
  1903. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1904. (taicpu(hp1).oper[0]^.reg = reg);
  1905. else
  1906. ;
  1907. end;
  1908. end;
  1909. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1910. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1911. var
  1912. hp2: tai;
  1913. begin
  1914. hp2 := p;
  1915. repeat
  1916. hp2 := tai(hp2.previous);
  1917. if assigned(hp2) and
  1918. (hp2.typ = ait_regalloc) and
  1919. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1920. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1921. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1922. begin
  1923. RemoveInstruction(hp2);
  1924. break;
  1925. end;
  1926. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1927. end;
  1928. begin
  1929. case current_procinfo.procdef.returndef.typ of
  1930. arraydef,recorddef,pointerdef,
  1931. stringdef,enumdef,procdef,objectdef,errordef,
  1932. filedef,setdef,procvardef,
  1933. classrefdef,forwarddef:
  1934. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1935. orddef:
  1936. if current_procinfo.procdef.returndef.size <> 0 then
  1937. begin
  1938. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1939. { for int64/qword }
  1940. if current_procinfo.procdef.returndef.size = 8 then
  1941. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1942. end;
  1943. else
  1944. ;
  1945. end;
  1946. end;
  1947. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1948. var
  1949. hp1,hp2 : tai;
  1950. begin
  1951. result:=false;
  1952. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1953. begin
  1954. { vmova* reg1,reg1
  1955. =>
  1956. <nop> }
  1957. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1958. begin
  1959. RemoveCurrentP(p);
  1960. result:=true;
  1961. exit;
  1962. end
  1963. else if GetNextInstruction(p,hp1) then
  1964. begin
  1965. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1966. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1967. begin
  1968. { vmova* reg1,reg2
  1969. vmova* reg2,reg3
  1970. dealloc reg2
  1971. =>
  1972. vmova* reg1,reg3 }
  1973. TransferUsedRegs(TmpUsedRegs);
  1974. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1975. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1976. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1977. begin
  1978. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1979. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1980. RemoveInstruction(hp1);
  1981. result:=true;
  1982. exit;
  1983. end
  1984. { special case:
  1985. vmova* reg1,<op>
  1986. vmova* <op>,reg1
  1987. =>
  1988. vmova* reg1,<op> }
  1989. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1990. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1991. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1992. ) then
  1993. begin
  1994. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1995. RemoveInstruction(hp1);
  1996. result:=true;
  1997. exit;
  1998. end
  1999. end
  2000. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2001. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2002. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2003. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2004. ) and
  2005. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2006. begin
  2007. { vmova* reg1,reg2
  2008. vmovs* reg2,<op>
  2009. dealloc reg2
  2010. =>
  2011. vmovs* reg1,reg3 }
  2012. TransferUsedRegs(TmpUsedRegs);
  2013. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2014. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2015. begin
  2016. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2017. taicpu(p).opcode:=taicpu(hp1).opcode;
  2018. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2019. RemoveInstruction(hp1);
  2020. result:=true;
  2021. exit;
  2022. end
  2023. end;
  2024. end;
  2025. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  2026. begin
  2027. if MatchInstruction(hp1,[A_VFMADDPD,
  2028. A_VFMADD132PD,
  2029. A_VFMADD132PS,
  2030. A_VFMADD132SD,
  2031. A_VFMADD132SS,
  2032. A_VFMADD213PD,
  2033. A_VFMADD213PS,
  2034. A_VFMADD213SD,
  2035. A_VFMADD213SS,
  2036. A_VFMADD231PD,
  2037. A_VFMADD231PS,
  2038. A_VFMADD231SD,
  2039. A_VFMADD231SS,
  2040. A_VFMADDSUB132PD,
  2041. A_VFMADDSUB132PS,
  2042. A_VFMADDSUB213PD,
  2043. A_VFMADDSUB213PS,
  2044. A_VFMADDSUB231PD,
  2045. A_VFMADDSUB231PS,
  2046. A_VFMSUB132PD,
  2047. A_VFMSUB132PS,
  2048. A_VFMSUB132SD,
  2049. A_VFMSUB132SS,
  2050. A_VFMSUB213PD,
  2051. A_VFMSUB213PS,
  2052. A_VFMSUB213SD,
  2053. A_VFMSUB213SS,
  2054. A_VFMSUB231PD,
  2055. A_VFMSUB231PS,
  2056. A_VFMSUB231SD,
  2057. A_VFMSUB231SS,
  2058. A_VFMSUBADD132PD,
  2059. A_VFMSUBADD132PS,
  2060. A_VFMSUBADD213PD,
  2061. A_VFMSUBADD213PS,
  2062. A_VFMSUBADD231PD,
  2063. A_VFMSUBADD231PS,
  2064. A_VFNMADD132PD,
  2065. A_VFNMADD132PS,
  2066. A_VFNMADD132SD,
  2067. A_VFNMADD132SS,
  2068. A_VFNMADD213PD,
  2069. A_VFNMADD213PS,
  2070. A_VFNMADD213SD,
  2071. A_VFNMADD213SS,
  2072. A_VFNMADD231PD,
  2073. A_VFNMADD231PS,
  2074. A_VFNMADD231SD,
  2075. A_VFNMADD231SS,
  2076. A_VFNMSUB132PD,
  2077. A_VFNMSUB132PS,
  2078. A_VFNMSUB132SD,
  2079. A_VFNMSUB132SS,
  2080. A_VFNMSUB213PD,
  2081. A_VFNMSUB213PS,
  2082. A_VFNMSUB213SD,
  2083. A_VFNMSUB213SS,
  2084. A_VFNMSUB231PD,
  2085. A_VFNMSUB231PS,
  2086. A_VFNMSUB231SD,
  2087. A_VFNMSUB231SS],[S_NO]) and
  2088. { we mix single and double opperations here because we assume that the compiler
  2089. generates vmovapd only after double operations and vmovaps only after single operations }
  2090. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  2091. GetNextInstruction(hp1,hp2) and
  2092. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2093. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2094. begin
  2095. TransferUsedRegs(TmpUsedRegs);
  2096. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2097. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2098. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2099. begin
  2100. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2101. RemoveCurrentP(p);
  2102. RemoveInstruction(hp2);
  2103. end;
  2104. end
  2105. else if (hp1.typ = ait_instruction) and
  2106. GetNextInstruction(hp1, hp2) and
  2107. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2108. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2109. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2110. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  2111. (((taicpu(p).opcode=A_MOVAPS) and
  2112. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2113. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2114. ((taicpu(p).opcode=A_MOVAPD) and
  2115. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2116. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2117. ) then
  2118. { change
  2119. movapX reg,reg2
  2120. addsX/subsX/... reg3, reg2
  2121. movapX reg2,reg
  2122. to
  2123. addsX/subsX/... reg3,reg
  2124. }
  2125. begin
  2126. TransferUsedRegs(TmpUsedRegs);
  2127. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2128. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2129. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2130. begin
  2131. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2132. debug_op2str(taicpu(p).opcode)+' '+
  2133. debug_op2str(taicpu(hp1).opcode)+' '+
  2134. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2135. { we cannot eliminate the first move if
  2136. the operations uses the same register for source and dest }
  2137. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2138. { Remember that hp1 is not necessarily the immediate
  2139. next instruction }
  2140. RemoveCurrentP(p);
  2141. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2142. RemoveInstruction(hp2);
  2143. result:=true;
  2144. end;
  2145. end
  2146. else if (hp1.typ = ait_instruction) and
  2147. (((taicpu(p).opcode=A_VMOVAPD) and
  2148. (taicpu(hp1).opcode=A_VCOMISD)) or
  2149. ((taicpu(p).opcode=A_VMOVAPS) and
  2150. ((taicpu(hp1).opcode=A_VCOMISS))
  2151. )
  2152. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2153. { change
  2154. movapX reg,reg1
  2155. vcomisX reg1,reg1
  2156. to
  2157. vcomisX reg,reg
  2158. }
  2159. begin
  2160. TransferUsedRegs(TmpUsedRegs);
  2161. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2162. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2163. begin
  2164. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2165. debug_op2str(taicpu(p).opcode)+' '+
  2166. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2167. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2168. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2169. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2170. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2171. RemoveCurrentP(p);
  2172. result:=true;
  2173. exit;
  2174. end;
  2175. end
  2176. end;
  2177. end;
  2178. end;
  2179. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2180. var
  2181. hp1 : tai;
  2182. begin
  2183. result:=false;
  2184. { replace
  2185. V<Op>X %mreg1,%mreg2,%mreg3
  2186. VMovX %mreg3,%mreg4
  2187. dealloc %mreg3
  2188. by
  2189. V<Op>X %mreg1,%mreg2,%mreg4
  2190. ?
  2191. }
  2192. if GetNextInstruction(p,hp1) and
  2193. { we mix single and double operations here because we assume that the compiler
  2194. generates vmovapd only after double operations and vmovaps only after single operations }
  2195. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2196. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2197. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2198. begin
  2199. TransferUsedRegs(TmpUsedRegs);
  2200. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2201. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2202. begin
  2203. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2204. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2205. RemoveInstruction(hp1);
  2206. result:=true;
  2207. end;
  2208. end;
  2209. end;
  2210. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2211. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2212. begin
  2213. Result := False;
  2214. { For safety reasons, only check for exact register matches }
  2215. { Check base register }
  2216. if (ref.base = AOldReg) then
  2217. begin
  2218. ref.base := ANewReg;
  2219. Result := True;
  2220. end;
  2221. { Check index register }
  2222. if (ref.index = AOldReg) then
  2223. begin
  2224. ref.index := ANewReg;
  2225. Result := True;
  2226. end;
  2227. end;
  2228. { Replaces all references to AOldReg in an operand to ANewReg }
  2229. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2230. var
  2231. OldSupReg, NewSupReg: TSuperRegister;
  2232. OldSubReg, NewSubReg: TSubRegister;
  2233. OldRegType: TRegisterType;
  2234. ThisOper: POper;
  2235. begin
  2236. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2237. Result := False;
  2238. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2239. InternalError(2020011801);
  2240. OldSupReg := getsupreg(AOldReg);
  2241. OldSubReg := getsubreg(AOldReg);
  2242. OldRegType := getregtype(AOldReg);
  2243. NewSupReg := getsupreg(ANewReg);
  2244. NewSubReg := getsubreg(ANewReg);
  2245. if OldRegType <> getregtype(ANewReg) then
  2246. InternalError(2020011802);
  2247. if OldSubReg <> NewSubReg then
  2248. InternalError(2020011803);
  2249. case ThisOper^.typ of
  2250. top_reg:
  2251. if (
  2252. (ThisOper^.reg = AOldReg) or
  2253. (
  2254. (OldRegType = R_INTREGISTER) and
  2255. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2256. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2257. (
  2258. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2259. {$ifndef x86_64}
  2260. and (
  2261. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2262. don't have an 8-bit representation }
  2263. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2264. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2265. )
  2266. {$endif x86_64}
  2267. )
  2268. )
  2269. ) then
  2270. begin
  2271. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2272. Result := True;
  2273. end;
  2274. top_ref:
  2275. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2276. Result := True;
  2277. else
  2278. ;
  2279. end;
  2280. end;
  2281. { Replaces all references to AOldReg in an instruction to ANewReg }
  2282. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2283. const
  2284. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2285. var
  2286. OperIdx: Integer;
  2287. begin
  2288. Result := False;
  2289. for OperIdx := 0 to p.ops - 1 do
  2290. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2291. begin
  2292. { The shift and rotate instructions can only use CL }
  2293. if not (
  2294. (OperIdx = 0) and
  2295. { This second condition just helps to avoid unnecessarily
  2296. calling MatchInstruction for 10 different opcodes }
  2297. (p.oper[0]^.reg = NR_CL) and
  2298. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2299. ) then
  2300. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2301. end
  2302. else if p.oper[OperIdx]^.typ = top_ref then
  2303. { It's okay to replace registers in references that get written to }
  2304. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2305. end;
  2306. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2307. begin
  2308. with ref^ do
  2309. Result :=
  2310. (index = NR_NO) and
  2311. (
  2312. {$ifdef x86_64}
  2313. (
  2314. (base = NR_RIP) and
  2315. (refaddr in [addr_pic, addr_pic_no_got])
  2316. ) or
  2317. {$endif x86_64}
  2318. (base = NR_STACK_POINTER_REG) or
  2319. (base = current_procinfo.framepointer)
  2320. );
  2321. end;
  2322. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2323. var
  2324. l: asizeint;
  2325. begin
  2326. Result := False;
  2327. { Should have been checked previously }
  2328. if p.opcode <> A_LEA then
  2329. InternalError(2020072501);
  2330. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2331. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2332. not(cs_opt_size in current_settings.optimizerswitches) then
  2333. exit;
  2334. with p.oper[0]^.ref^ do
  2335. begin
  2336. if (base <> p.oper[1]^.reg) or
  2337. (index <> NR_NO) or
  2338. assigned(symbol) then
  2339. exit;
  2340. l:=offset;
  2341. if (l=1) and UseIncDec then
  2342. begin
  2343. p.opcode:=A_INC;
  2344. p.loadreg(0,p.oper[1]^.reg);
  2345. p.ops:=1;
  2346. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2347. end
  2348. else if (l=-1) and UseIncDec then
  2349. begin
  2350. p.opcode:=A_DEC;
  2351. p.loadreg(0,p.oper[1]^.reg);
  2352. p.ops:=1;
  2353. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2354. end
  2355. else
  2356. begin
  2357. if (l<0) and (l<>-2147483648) then
  2358. begin
  2359. p.opcode:=A_SUB;
  2360. p.loadConst(0,-l);
  2361. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2362. end
  2363. else
  2364. begin
  2365. p.opcode:=A_ADD;
  2366. p.loadConst(0,l);
  2367. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2368. end;
  2369. end;
  2370. end;
  2371. Result := True;
  2372. end;
  2373. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2374. var
  2375. CurrentReg, ReplaceReg: TRegister;
  2376. begin
  2377. Result := False;
  2378. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2379. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2380. case hp.opcode of
  2381. A_FSTSW, A_FNSTSW,
  2382. A_IN, A_INS, A_OUT, A_OUTS,
  2383. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2384. { These routines have explicit operands, but they are restricted in
  2385. what they can be (e.g. IN and OUT can only read from AL, AX or
  2386. EAX. }
  2387. Exit;
  2388. A_IMUL:
  2389. begin
  2390. { The 1-operand version writes to implicit registers
  2391. The 2-operand version reads from the first operator, and reads
  2392. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2393. the 3-operand version reads from a register that it doesn't write to
  2394. }
  2395. case hp.ops of
  2396. 1:
  2397. if (
  2398. (
  2399. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2400. ) or
  2401. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2402. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2403. begin
  2404. Result := True;
  2405. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2406. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2407. end;
  2408. 2:
  2409. { Only modify the first parameter }
  2410. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2411. begin
  2412. Result := True;
  2413. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2414. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2415. end;
  2416. 3:
  2417. { Only modify the second parameter }
  2418. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2419. begin
  2420. Result := True;
  2421. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2422. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2423. end;
  2424. else
  2425. InternalError(2020012901);
  2426. end;
  2427. end;
  2428. else
  2429. if (hp.ops > 0) and
  2430. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2431. begin
  2432. Result := True;
  2433. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2434. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2435. end;
  2436. end;
  2437. end;
  2438. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2439. var
  2440. hp2: tai;
  2441. p_SourceReg, p_TargetReg: TRegister;
  2442. begin
  2443. Result := False;
  2444. { Backward optimisation. If we have:
  2445. func. %reg1,%reg2
  2446. mov %reg2,%reg3
  2447. (dealloc %reg2)
  2448. Change to:
  2449. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2450. Perform similar optimisations with 1, 3 and 4-operand instructions
  2451. that only have one output.
  2452. }
  2453. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2454. begin
  2455. p_SourceReg := taicpu(p).oper[0]^.reg;
  2456. p_TargetReg := taicpu(p).oper[1]^.reg;
  2457. TransferUsedRegs(TmpUsedRegs);
  2458. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2459. GetLastInstruction(p, hp2) and
  2460. (hp2.typ = ait_instruction) and
  2461. { Have to make sure it's an instruction that only reads from
  2462. the first operands and only writes (not reads or modifies) to
  2463. the last one; in essence, a pure function such as BSR, POPCNT
  2464. or ANDN }
  2465. (
  2466. (
  2467. (taicpu(hp2).ops = 1) and
  2468. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2469. ) or
  2470. (
  2471. (taicpu(hp2).ops = 2) and
  2472. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2473. ) or
  2474. (
  2475. (taicpu(hp2).ops = 3) and
  2476. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2477. ) or
  2478. (
  2479. (taicpu(hp2).ops = 4) and
  2480. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2481. )
  2482. ) and
  2483. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2484. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2485. begin
  2486. case taicpu(hp2).opcode of
  2487. A_FSTSW, A_FNSTSW,
  2488. A_IN, A_INS, A_OUT, A_OUTS,
  2489. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2490. { These routines have explicit operands, but they are restricted in
  2491. what they can be (e.g. IN and OUT can only read from AL, AX or
  2492. EAX. }
  2493. ;
  2494. else
  2495. begin
  2496. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2497. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2498. if not RegInInstruction(p_TargetReg, hp2) then
  2499. begin
  2500. { Since we're allocating from an earlier point, we
  2501. need to remove the register from the tracking }
  2502. ExcludeRegFromUsedRegs(p_TargetReg, TmpUsedRegs);
  2503. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2504. end;
  2505. RemoveCurrentp(p, hp1);
  2506. { If the Func was another MOV instruction, we might get
  2507. "mov %reg,%reg" that doesn't get removed in Pass 2
  2508. otherwise, so deal with it here (also do something
  2509. similar with lea (%reg),%reg}
  2510. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2511. begin
  2512. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2513. if p = hp2 then
  2514. RemoveCurrentp(p)
  2515. else
  2516. RemoveInstruction(hp2);
  2517. end;
  2518. Result := True;
  2519. Exit;
  2520. end;
  2521. end;
  2522. end;
  2523. end;
  2524. end;
  2525. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2526. var
  2527. hp1, hp2, hp3: tai;
  2528. DoOptimisation, TempBool: Boolean;
  2529. {$ifdef x86_64}
  2530. NewConst: TCGInt;
  2531. {$endif x86_64}
  2532. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2533. begin
  2534. if taicpu(hp1).opcode = signed_movop then
  2535. begin
  2536. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2537. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2538. end
  2539. else
  2540. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2541. end;
  2542. function TryConstMerge(var p1, p2: tai): Boolean;
  2543. var
  2544. ThisRef: TReference;
  2545. begin
  2546. Result := False;
  2547. ThisRef := taicpu(p2).oper[1]^.ref^;
  2548. { Only permit writes to the stack, since we can guarantee alignment with that }
  2549. if (ThisRef.index = NR_NO) and
  2550. (
  2551. (ThisRef.base = NR_STACK_POINTER_REG) or
  2552. (ThisRef.base = current_procinfo.framepointer)
  2553. ) then
  2554. begin
  2555. case taicpu(p).opsize of
  2556. S_B:
  2557. begin
  2558. { Word writes must be on a 2-byte boundary }
  2559. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2560. begin
  2561. { Reduce offset of second reference to see if it is sequential with the first }
  2562. Dec(ThisRef.offset, 1);
  2563. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2564. begin
  2565. { Make sure the constants aren't represented as a
  2566. negative number, as these won't merge properly }
  2567. taicpu(p1).opsize := S_W;
  2568. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2569. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2570. RemoveInstruction(p2);
  2571. Result := True;
  2572. end;
  2573. end;
  2574. end;
  2575. S_W:
  2576. begin
  2577. { Longword writes must be on a 4-byte boundary }
  2578. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2579. begin
  2580. { Reduce offset of second reference to see if it is sequential with the first }
  2581. Dec(ThisRef.offset, 2);
  2582. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2583. begin
  2584. { Make sure the constants aren't represented as a
  2585. negative number, as these won't merge properly }
  2586. taicpu(p1).opsize := S_L;
  2587. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2588. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2589. RemoveInstruction(p2);
  2590. Result := True;
  2591. end;
  2592. end;
  2593. end;
  2594. {$ifdef x86_64}
  2595. S_L:
  2596. begin
  2597. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2598. see if the constants can be encoded this way. }
  2599. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2600. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2601. { Quadword writes must be on an 8-byte boundary }
  2602. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2603. begin
  2604. { Reduce offset of second reference to see if it is sequential with the first }
  2605. Dec(ThisRef.offset, 4);
  2606. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2607. begin
  2608. { Make sure the constants aren't represented as a
  2609. negative number, as these won't merge properly }
  2610. taicpu(p1).opsize := S_Q;
  2611. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2612. taicpu(p1).oper[0]^.val := NewConst;
  2613. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2614. RemoveInstruction(p2);
  2615. Result := True;
  2616. end;
  2617. end;
  2618. end;
  2619. {$endif x86_64}
  2620. else
  2621. ;
  2622. end;
  2623. end;
  2624. end;
  2625. var
  2626. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2627. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2628. NewSize: topsize; NewOffset: asizeint;
  2629. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2630. SourceRef, TargetRef: TReference;
  2631. MovAligned, MovUnaligned: TAsmOp;
  2632. ThisRef: TReference;
  2633. JumpTracking: TLinkedList;
  2634. begin
  2635. Result:=false;
  2636. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2637. { remove mov reg1,reg1? }
  2638. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2639. then
  2640. begin
  2641. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2642. { take care of the register (de)allocs following p }
  2643. RemoveCurrentP(p, hp1);
  2644. Result:=true;
  2645. exit;
  2646. end;
  2647. { All the next optimisations require a next instruction }
  2648. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2649. Exit;
  2650. { Prevent compiler warnings }
  2651. p_TargetReg := NR_NO;
  2652. if taicpu(p).oper[1]^.typ = top_reg then
  2653. begin
  2654. { Saves on a large number of dereferences }
  2655. p_TargetReg := taicpu(p).oper[1]^.reg;
  2656. { Look for:
  2657. mov %reg1,%reg2
  2658. ??? %reg2,r/m
  2659. Change to:
  2660. mov %reg1,%reg2
  2661. ??? %reg1,r/m
  2662. }
  2663. if taicpu(p).oper[0]^.typ = top_reg then
  2664. begin
  2665. if RegReadByInstruction(p_TargetReg, hp1) and
  2666. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2667. begin
  2668. { A change has occurred, just not in p }
  2669. Result := True;
  2670. TransferUsedRegs(TmpUsedRegs);
  2671. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2672. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2673. { Just in case something didn't get modified (e.g. an
  2674. implicit register) }
  2675. not RegReadByInstruction(p_TargetReg, hp1) then
  2676. begin
  2677. { We can remove the original MOV }
  2678. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2679. RemoveCurrentp(p, hp1);
  2680. { UsedRegs got updated by RemoveCurrentp }
  2681. Result := True;
  2682. Exit;
  2683. end;
  2684. { If we know a MOV instruction has become a null operation, we might as well
  2685. get rid of it now to save time. }
  2686. if (taicpu(hp1).opcode = A_MOV) and
  2687. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2688. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2689. { Just being a register is enough to confirm it's a null operation }
  2690. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2691. begin
  2692. Result := True;
  2693. { Speed-up to reduce a pipeline stall... if we had something like...
  2694. movl %eax,%edx
  2695. movw %dx,%ax
  2696. ... the second instruction would change to movw %ax,%ax, but
  2697. given that it is now %ax that's active rather than %eax,
  2698. penalties might occur due to a partial register write, so instead,
  2699. change it to a MOVZX instruction when optimising for speed.
  2700. }
  2701. if not (cs_opt_size in current_settings.optimizerswitches) and
  2702. IsMOVZXAcceptable and
  2703. (taicpu(hp1).opsize < taicpu(p).opsize)
  2704. {$ifdef x86_64}
  2705. { operations already implicitly set the upper 64 bits to zero }
  2706. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2707. {$endif x86_64}
  2708. then
  2709. begin
  2710. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2711. case taicpu(p).opsize of
  2712. S_W:
  2713. if taicpu(hp1).opsize = S_B then
  2714. taicpu(hp1).opsize := S_BL
  2715. else
  2716. InternalError(2020012911);
  2717. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2718. case taicpu(hp1).opsize of
  2719. S_B:
  2720. taicpu(hp1).opsize := S_BL;
  2721. S_W:
  2722. taicpu(hp1).opsize := S_WL;
  2723. else
  2724. InternalError(2020012912);
  2725. end;
  2726. else
  2727. InternalError(2020012910);
  2728. end;
  2729. taicpu(hp1).opcode := A_MOVZX;
  2730. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2731. end
  2732. else
  2733. begin
  2734. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2735. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2736. RemoveInstruction(hp1);
  2737. { The instruction after what was hp1 is now the immediate next instruction,
  2738. so we can continue to make optimisations if it's present }
  2739. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2740. Exit;
  2741. hp1 := hp2;
  2742. end;
  2743. end;
  2744. end;
  2745. end;
  2746. end;
  2747. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2748. overwrites the original destination register. e.g.
  2749. movl ###,%reg2d
  2750. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2751. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2752. }
  2753. if (taicpu(p).oper[1]^.typ = top_reg) and
  2754. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2755. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2756. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2757. begin
  2758. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2759. begin
  2760. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2761. case taicpu(p).oper[0]^.typ of
  2762. top_const:
  2763. { We have something like:
  2764. movb $x, %regb
  2765. movzbl %regb,%regd
  2766. Change to:
  2767. movl $x, %regd
  2768. }
  2769. begin
  2770. case taicpu(hp1).opsize of
  2771. S_BW:
  2772. begin
  2773. convert_mov_value(A_MOVSX, $FF);
  2774. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2775. taicpu(p).opsize := S_W;
  2776. end;
  2777. S_BL:
  2778. begin
  2779. convert_mov_value(A_MOVSX, $FF);
  2780. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2781. taicpu(p).opsize := S_L;
  2782. end;
  2783. S_WL:
  2784. begin
  2785. convert_mov_value(A_MOVSX, $FFFF);
  2786. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2787. taicpu(p).opsize := S_L;
  2788. end;
  2789. {$ifdef x86_64}
  2790. S_BQ:
  2791. begin
  2792. convert_mov_value(A_MOVSX, $FF);
  2793. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2794. taicpu(p).opsize := S_Q;
  2795. end;
  2796. S_WQ:
  2797. begin
  2798. convert_mov_value(A_MOVSX, $FFFF);
  2799. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2800. taicpu(p).opsize := S_Q;
  2801. end;
  2802. S_LQ:
  2803. begin
  2804. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2805. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2806. taicpu(p).opsize := S_Q;
  2807. end;
  2808. {$endif x86_64}
  2809. else
  2810. { If hp1 was a MOV instruction, it should have been
  2811. optimised already }
  2812. InternalError(2020021001);
  2813. end;
  2814. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2815. RemoveInstruction(hp1);
  2816. Result := True;
  2817. Exit;
  2818. end;
  2819. top_ref:
  2820. begin
  2821. { We have something like:
  2822. movb mem, %regb
  2823. movzbl %regb,%regd
  2824. Change to:
  2825. movzbl mem, %regd
  2826. }
  2827. ThisRef := taicpu(p).oper[0]^.ref^;
  2828. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2829. begin
  2830. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2831. taicpu(hp1).loadref(0, ThisRef);
  2832. { Make sure any registers in the references are properly tracked }
  2833. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2834. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2835. if (ThisRef.index <> NR_NO) then
  2836. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2837. RemoveCurrentP(p, hp1);
  2838. Result := True;
  2839. Exit;
  2840. end;
  2841. end;
  2842. else
  2843. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2844. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2845. Exit;
  2846. end;
  2847. end
  2848. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2849. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2850. optimised }
  2851. else
  2852. begin
  2853. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2854. RemoveCurrentP(p, hp1);
  2855. Result := True;
  2856. Exit;
  2857. end;
  2858. end;
  2859. if (taicpu(hp1).opcode = A_AND) and
  2860. (taicpu(p).oper[1]^.typ = top_reg) and
  2861. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2862. begin
  2863. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2864. begin
  2865. case taicpu(p).opsize of
  2866. S_L:
  2867. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2868. begin
  2869. { Optimize out:
  2870. mov x, %reg
  2871. and ffffffffh, %reg
  2872. }
  2873. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2874. RemoveInstruction(hp1);
  2875. Result:=true;
  2876. exit;
  2877. end;
  2878. S_Q: { TODO: Confirm if this is even possible }
  2879. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2880. begin
  2881. { Optimize out:
  2882. mov x, %reg
  2883. and ffffffffffffffffh, %reg
  2884. }
  2885. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2886. RemoveInstruction(hp1);
  2887. Result:=true;
  2888. exit;
  2889. end;
  2890. else
  2891. ;
  2892. end;
  2893. if (
  2894. (taicpu(p).oper[0]^.typ=top_reg) or
  2895. (
  2896. (taicpu(p).oper[0]^.typ=top_ref) and
  2897. (taicpu(p).oper[0]^.ref^.refaddr<>addr_full)
  2898. )
  2899. ) and
  2900. GetNextInstruction(hp1,hp2) and
  2901. MatchInstruction(hp2,A_TEST,[]) and
  2902. (
  2903. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  2904. (
  2905. { If the register being tested is smaller than the one
  2906. that received a bitwise AND, permit it if the constant
  2907. fits into the smaller size }
  2908. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  2909. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  2910. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  2911. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  2912. (
  2913. (
  2914. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  2915. (taicpu(hp1).oper[0]^.val <= $FF)
  2916. ) or
  2917. (
  2918. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  2919. (taicpu(hp1).oper[0]^.val <= $FFFF)
  2920. {$ifdef x86_64}
  2921. ) or
  2922. (
  2923. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  2924. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  2925. {$endif x86_64}
  2926. )
  2927. )
  2928. )
  2929. ) and
  2930. (
  2931. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2932. MatchOperand(taicpu(hp2).oper[0]^,-1)
  2933. ) and
  2934. GetNextInstruction(hp2,hp3) and
  2935. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2936. (taicpu(hp3).condition in [C_E,C_NE]) then
  2937. begin
  2938. TransferUsedRegs(TmpUsedRegs);
  2939. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2940. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2941. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2942. begin
  2943. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2944. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2945. taicpu(hp1).opcode:=A_TEST;
  2946. { Shrink the TEST instruction down to the smallest possible size }
  2947. case taicpu(hp1).oper[0]^.val of
  2948. 0..255:
  2949. if (taicpu(hp1).opsize <> S_B)
  2950. {$ifndef x86_64}
  2951. and (
  2952. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  2953. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  2954. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  2955. )
  2956. {$endif x86_64}
  2957. then
  2958. begin
  2959. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  2960. { Only print debug message if the TEST instruction
  2961. is a different size before and after }
  2962. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  2963. taicpu(hp1).opsize := S_B;
  2964. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  2965. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  2966. end;
  2967. 256..65535:
  2968. if (taicpu(hp1).opsize <> S_W) then
  2969. begin
  2970. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  2971. { Only print debug message if the TEST instruction
  2972. is a different size before and after }
  2973. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  2974. taicpu(hp1).opsize := S_W;
  2975. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  2976. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  2977. end;
  2978. {$ifdef x86_64}
  2979. 65536..$7FFFFFFF:
  2980. if (taicpu(hp1).opsize <> S_L) then
  2981. begin
  2982. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  2983. { Only print debug message if the TEST instruction
  2984. is a different size before and after }
  2985. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  2986. taicpu(hp1).opsize := S_L;
  2987. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  2988. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2989. end;
  2990. {$endif x86_64}
  2991. else
  2992. ;
  2993. end;
  2994. RemoveInstruction(hp2);
  2995. RemoveCurrentP(p, hp1);
  2996. Result:=true;
  2997. exit;
  2998. end;
  2999. end;
  3000. end
  3001. else if IsMOVZXAcceptable and
  3002. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  3003. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3004. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3005. then
  3006. begin
  3007. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3008. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3009. case taicpu(p).opsize of
  3010. S_B:
  3011. if (taicpu(hp1).oper[0]^.val = $ff) then
  3012. begin
  3013. { Convert:
  3014. movb x, %regl movb x, %regl
  3015. andw ffh, %regw andl ffh, %regd
  3016. To:
  3017. movzbw x, %regd movzbl x, %regd
  3018. (Identical registers, just different sizes)
  3019. }
  3020. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3021. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3022. case taicpu(hp1).opsize of
  3023. S_W: NewSize := S_BW;
  3024. S_L: NewSize := S_BL;
  3025. {$ifdef x86_64}
  3026. S_Q: NewSize := S_BQ;
  3027. {$endif x86_64}
  3028. else
  3029. InternalError(2018011510);
  3030. end;
  3031. end
  3032. else
  3033. NewSize := S_NO;
  3034. S_W:
  3035. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3036. begin
  3037. { Convert:
  3038. movw x, %regw
  3039. andl ffffh, %regd
  3040. To:
  3041. movzwl x, %regd
  3042. (Identical registers, just different sizes)
  3043. }
  3044. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3045. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3046. case taicpu(hp1).opsize of
  3047. S_L: NewSize := S_WL;
  3048. {$ifdef x86_64}
  3049. S_Q: NewSize := S_WQ;
  3050. {$endif x86_64}
  3051. else
  3052. InternalError(2018011511);
  3053. end;
  3054. end
  3055. else
  3056. NewSize := S_NO;
  3057. else
  3058. NewSize := S_NO;
  3059. end;
  3060. if NewSize <> S_NO then
  3061. begin
  3062. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3063. { The actual optimization }
  3064. taicpu(p).opcode := A_MOVZX;
  3065. taicpu(p).changeopsize(NewSize);
  3066. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  3067. { Safeguard if "and" is followed by a conditional command }
  3068. TransferUsedRegs(TmpUsedRegs);
  3069. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  3070. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3071. begin
  3072. { At this point, the "and" command is effectively equivalent to
  3073. "test %reg,%reg". This will be handled separately by the
  3074. Peephole Optimizer. [Kit] }
  3075. DebugMsg(SPeepholeOptimization + PreMessage +
  3076. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3077. end
  3078. else
  3079. begin
  3080. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3081. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3082. RemoveInstruction(hp1);
  3083. end;
  3084. Result := True;
  3085. Exit;
  3086. end;
  3087. end;
  3088. end;
  3089. if (taicpu(hp1).opcode = A_OR) and
  3090. (taicpu(p).oper[1]^.typ = top_reg) and
  3091. MatchOperand(taicpu(p).oper[0]^, 0) and
  3092. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3093. begin
  3094. { mov 0, %reg
  3095. or ###,%reg
  3096. Change to (only if the flags are not used):
  3097. mov ###,%reg
  3098. }
  3099. TransferUsedRegs(TmpUsedRegs);
  3100. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3101. DoOptimisation := True;
  3102. { Even if the flags are used, we might be able to do the optimisation
  3103. if the conditions are predictable }
  3104. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3105. begin
  3106. { Only perform if ### = %reg (the same register) or equal to 0,
  3107. so %reg is guaranteed to still have a value of zero }
  3108. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3109. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3110. begin
  3111. hp2 := hp1;
  3112. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3113. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3114. GetNextInstruction(hp2, hp3) do
  3115. begin
  3116. { Don't continue modifying if the flags state is getting changed }
  3117. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3118. Break;
  3119. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  3120. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3121. begin
  3122. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3123. begin
  3124. { Condition is always true }
  3125. case taicpu(hp3).opcode of
  3126. A_Jcc:
  3127. begin
  3128. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3129. { Check for jump shortcuts before we destroy the condition }
  3130. DoJumpOptimizations(hp3, TempBool);
  3131. MakeUnconditional(taicpu(hp3));
  3132. Result := True;
  3133. end;
  3134. A_CMOVcc:
  3135. begin
  3136. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3137. taicpu(hp3).opcode := A_MOV;
  3138. taicpu(hp3).condition := C_None;
  3139. Result := True;
  3140. end;
  3141. A_SETcc:
  3142. begin
  3143. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3144. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3145. taicpu(hp3).opcode := A_MOV;
  3146. taicpu(hp3).ops := 2;
  3147. taicpu(hp3).condition := C_None;
  3148. taicpu(hp3).opsize := S_B;
  3149. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3150. taicpu(hp3).loadconst(0, 1);
  3151. Result := True;
  3152. end;
  3153. else
  3154. InternalError(2021090701);
  3155. end;
  3156. end
  3157. 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
  3158. begin
  3159. { Condition is always false }
  3160. case taicpu(hp3).opcode of
  3161. A_Jcc:
  3162. begin
  3163. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3164. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3165. RemoveInstruction(hp3);
  3166. Result := True;
  3167. { Since hp3 was deleted, hp2 must not be updated }
  3168. Continue;
  3169. end;
  3170. A_CMOVcc:
  3171. begin
  3172. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3173. RemoveInstruction(hp3);
  3174. Result := True;
  3175. { Since hp3 was deleted, hp2 must not be updated }
  3176. Continue;
  3177. end;
  3178. A_SETcc:
  3179. begin
  3180. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3181. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3182. taicpu(hp3).opcode := A_MOV;
  3183. taicpu(hp3).ops := 2;
  3184. taicpu(hp3).condition := C_None;
  3185. taicpu(hp3).opsize := S_B;
  3186. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3187. taicpu(hp3).loadconst(0, 0);
  3188. Result := True;
  3189. end;
  3190. else
  3191. InternalError(2021090702);
  3192. end;
  3193. end
  3194. else
  3195. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3196. DoOptimisation := False;
  3197. end;
  3198. hp2 := hp3;
  3199. end;
  3200. { Flags are still in use - don't optimise }
  3201. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3202. DoOptimisation := False;
  3203. end
  3204. else
  3205. DoOptimisation := False;
  3206. end;
  3207. if DoOptimisation then
  3208. begin
  3209. {$ifdef x86_64}
  3210. { OR only supports 32-bit sign-extended constants for 64-bit
  3211. instructions, so compensate for this if the constant is
  3212. encoded as a value greater than or equal to 2^31 }
  3213. if (taicpu(hp1).opsize = S_Q) and
  3214. (taicpu(hp1).oper[0]^.typ = top_const) and
  3215. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3216. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3217. {$endif x86_64}
  3218. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3219. taicpu(hp1).opcode := A_MOV;
  3220. RemoveCurrentP(p, hp1);
  3221. Result := True;
  3222. Exit;
  3223. end;
  3224. end;
  3225. { Next instruction is also a MOV ? }
  3226. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3227. begin
  3228. if MatchOpType(taicpu(p), top_const, top_ref) and
  3229. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3230. TryConstMerge(p, hp1) then
  3231. begin
  3232. Result := True;
  3233. { In case we have four byte writes in a row, check for 2 more
  3234. right now so we don't have to wait for another iteration of
  3235. pass 1
  3236. }
  3237. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3238. case taicpu(p).opsize of
  3239. S_W:
  3240. begin
  3241. if GetNextInstruction(p, hp1) and
  3242. MatchInstruction(hp1, A_MOV, [S_B]) and
  3243. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3244. GetNextInstruction(hp1, hp2) and
  3245. MatchInstruction(hp2, A_MOV, [S_B]) and
  3246. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3247. { Try to merge the two bytes }
  3248. TryConstMerge(hp1, hp2) then
  3249. { Now try to merge the two words (hp2 will get deleted) }
  3250. TryConstMerge(p, hp1);
  3251. end;
  3252. S_L:
  3253. begin
  3254. { Though this only really benefits x86_64 and not i386, it
  3255. gets a potential optimisation done faster and hence
  3256. reduces the number of times OptPass1MOV is entered }
  3257. if GetNextInstruction(p, hp1) and
  3258. MatchInstruction(hp1, A_MOV, [S_W]) and
  3259. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3260. GetNextInstruction(hp1, hp2) and
  3261. MatchInstruction(hp2, A_MOV, [S_W]) and
  3262. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3263. { Try to merge the two words }
  3264. TryConstMerge(hp1, hp2) then
  3265. { This will always fail on i386, so don't bother
  3266. calling it unless we're doing x86_64 }
  3267. {$ifdef x86_64}
  3268. { Now try to merge the two longwords (hp2 will get deleted) }
  3269. TryConstMerge(p, hp1)
  3270. {$endif x86_64}
  3271. ;
  3272. end;
  3273. else
  3274. ;
  3275. end;
  3276. Exit;
  3277. end;
  3278. if (taicpu(p).oper[1]^.typ = top_reg) and
  3279. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3280. begin
  3281. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3282. TransferUsedRegs(TmpUsedRegs);
  3283. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3284. { we have
  3285. mov x, %treg
  3286. mov %treg, y
  3287. }
  3288. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3289. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3290. { we've got
  3291. mov x, %treg
  3292. mov %treg, y
  3293. with %treg is not used after }
  3294. case taicpu(p).oper[0]^.typ Of
  3295. { top_reg is covered by DeepMOVOpt }
  3296. top_const:
  3297. begin
  3298. { change
  3299. mov const, %treg
  3300. mov %treg, y
  3301. to
  3302. mov const, y
  3303. }
  3304. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3305. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3306. begin
  3307. if taicpu(hp1).oper[1]^.typ=top_reg then
  3308. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3309. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3310. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3311. RemoveInstruction(hp1);
  3312. Result:=true;
  3313. Exit;
  3314. end;
  3315. end;
  3316. top_ref:
  3317. case taicpu(hp1).oper[1]^.typ of
  3318. top_reg:
  3319. begin
  3320. { change
  3321. mov mem, %treg
  3322. mov %treg, %reg
  3323. to
  3324. mov mem, %reg"
  3325. }
  3326. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3327. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3328. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3329. RemoveInstruction(hp1);
  3330. Result:=true;
  3331. Exit;
  3332. end;
  3333. top_ref:
  3334. begin
  3335. {$ifdef x86_64}
  3336. { Look for the following to simplify:
  3337. mov x(mem1), %reg
  3338. mov %reg, y(mem2)
  3339. mov x+8(mem1), %reg
  3340. mov %reg, y+8(mem2)
  3341. Change to:
  3342. movdqu x(mem1), %xmmreg
  3343. movdqu %xmmreg, y(mem2)
  3344. ...but only as long as the memory blocks don't overlap
  3345. }
  3346. SourceRef := taicpu(p).oper[0]^.ref^;
  3347. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3348. if (taicpu(p).opsize = S_Q) and
  3349. GetNextInstruction(hp1, hp2) and
  3350. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3351. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3352. begin
  3353. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3354. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3355. Inc(SourceRef.offset, 8);
  3356. if UseAVX then
  3357. begin
  3358. MovAligned := A_VMOVDQA;
  3359. MovUnaligned := A_VMOVDQU;
  3360. end
  3361. else
  3362. begin
  3363. MovAligned := A_MOVDQA;
  3364. MovUnaligned := A_MOVDQU;
  3365. end;
  3366. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3367. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3368. begin
  3369. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3370. Inc(TargetRef.offset, 8);
  3371. if GetNextInstruction(hp2, hp3) and
  3372. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3373. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3374. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3375. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3376. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3377. begin
  3378. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3379. if NewMMReg <> NR_NO then
  3380. begin
  3381. { Remember that the offsets are 8 ahead }
  3382. if ((SourceRef.offset mod 16) = 8) and
  3383. (
  3384. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3385. (SourceRef.base = current_procinfo.framepointer) or
  3386. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3387. ) then
  3388. taicpu(p).opcode := MovAligned
  3389. else
  3390. taicpu(p).opcode := MovUnaligned;
  3391. taicpu(p).opsize := S_XMM;
  3392. taicpu(p).oper[1]^.reg := NewMMReg;
  3393. if ((TargetRef.offset mod 16) = 8) and
  3394. (
  3395. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3396. (TargetRef.base = current_procinfo.framepointer) or
  3397. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3398. ) then
  3399. taicpu(hp1).opcode := MovAligned
  3400. else
  3401. taicpu(hp1).opcode := MovUnaligned;
  3402. taicpu(hp1).opsize := S_XMM;
  3403. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3404. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3405. RemoveInstruction(hp2);
  3406. RemoveInstruction(hp3);
  3407. Result := True;
  3408. Exit;
  3409. end;
  3410. end;
  3411. end
  3412. else
  3413. begin
  3414. { See if the next references are 8 less rather than 8 greater }
  3415. Dec(SourceRef.offset, 16); { -8 the other way }
  3416. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3417. begin
  3418. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3419. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3420. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3421. GetNextInstruction(hp2, hp3) and
  3422. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3423. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3424. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3425. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3426. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3427. begin
  3428. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3429. if NewMMReg <> NR_NO then
  3430. begin
  3431. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3432. if ((SourceRef.offset mod 16) = 0) and
  3433. (
  3434. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3435. (SourceRef.base = current_procinfo.framepointer) or
  3436. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3437. ) then
  3438. taicpu(hp2).opcode := MovAligned
  3439. else
  3440. taicpu(hp2).opcode := MovUnaligned;
  3441. taicpu(hp2).opsize := S_XMM;
  3442. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3443. if ((TargetRef.offset mod 16) = 0) and
  3444. (
  3445. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3446. (TargetRef.base = current_procinfo.framepointer) or
  3447. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3448. ) then
  3449. taicpu(hp3).opcode := MovAligned
  3450. else
  3451. taicpu(hp3).opcode := MovUnaligned;
  3452. taicpu(hp3).opsize := S_XMM;
  3453. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3454. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3455. RemoveInstruction(hp1);
  3456. RemoveCurrentP(p, hp2);
  3457. Result := True;
  3458. Exit;
  3459. end;
  3460. end;
  3461. end;
  3462. end;
  3463. end;
  3464. {$endif x86_64}
  3465. end;
  3466. else
  3467. { The write target should be a reg or a ref }
  3468. InternalError(2021091601);
  3469. end;
  3470. else
  3471. ;
  3472. end
  3473. else
  3474. { %treg is used afterwards, but all eventualities
  3475. other than the first MOV instruction being a constant
  3476. are covered by DeepMOVOpt, so only check for that }
  3477. if (taicpu(p).oper[0]^.typ = top_const) and
  3478. (
  3479. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3480. not (cs_opt_size in current_settings.optimizerswitches) or
  3481. (taicpu(hp1).opsize = S_B)
  3482. ) and
  3483. (
  3484. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3485. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3486. ) then
  3487. begin
  3488. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3489. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3490. end;
  3491. end;
  3492. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3493. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3494. { mov reg1, mem1 or mov mem1, reg1
  3495. mov mem2, reg2 mov reg2, mem2}
  3496. begin
  3497. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3498. { mov reg1, mem1 or mov mem1, reg1
  3499. mov mem2, reg1 mov reg2, mem1}
  3500. begin
  3501. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3502. { Removes the second statement from
  3503. mov reg1, mem1/reg2
  3504. mov mem1/reg2, reg1 }
  3505. begin
  3506. if taicpu(p).oper[0]^.typ=top_reg then
  3507. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3508. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3509. RemoveInstruction(hp1);
  3510. Result:=true;
  3511. exit;
  3512. end
  3513. else
  3514. begin
  3515. TransferUsedRegs(TmpUsedRegs);
  3516. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3517. if (taicpu(p).oper[1]^.typ = top_ref) and
  3518. { mov reg1, mem1
  3519. mov mem2, reg1 }
  3520. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3521. GetNextInstruction(hp1, hp2) and
  3522. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3523. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3524. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3525. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3526. { change to
  3527. mov reg1, mem1 mov reg1, mem1
  3528. mov mem2, reg1 cmp reg1, mem2
  3529. cmp mem1, reg1
  3530. }
  3531. begin
  3532. RemoveInstruction(hp2);
  3533. taicpu(hp1).opcode := A_CMP;
  3534. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3535. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3536. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3537. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3538. end;
  3539. end;
  3540. end
  3541. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3542. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3543. begin
  3544. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3545. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3546. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3547. end
  3548. else
  3549. begin
  3550. TransferUsedRegs(TmpUsedRegs);
  3551. if GetNextInstruction(hp1, hp2) and
  3552. MatchOpType(taicpu(p),top_ref,top_reg) and
  3553. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3554. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3555. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3556. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3557. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3558. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3559. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3560. { mov mem1, %reg1
  3561. mov %reg1, mem2
  3562. mov mem2, reg2
  3563. to:
  3564. mov mem1, reg2
  3565. mov reg2, mem2}
  3566. begin
  3567. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3568. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3569. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3570. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3571. RemoveInstruction(hp2);
  3572. Result := True;
  3573. end
  3574. {$ifdef i386}
  3575. { this is enabled for i386 only, as the rules to create the reg sets below
  3576. are too complicated for x86-64, so this makes this code too error prone
  3577. on x86-64
  3578. }
  3579. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3580. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3581. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3582. { mov mem1, reg1 mov mem1, reg1
  3583. mov reg1, mem2 mov reg1, mem2
  3584. mov mem2, reg2 mov mem2, reg1
  3585. to: to:
  3586. mov mem1, reg1 mov mem1, reg1
  3587. mov mem1, reg2 mov reg1, mem2
  3588. mov reg1, mem2
  3589. or (if mem1 depends on reg1
  3590. and/or if mem2 depends on reg2)
  3591. to:
  3592. mov mem1, reg1
  3593. mov reg1, mem2
  3594. mov reg1, reg2
  3595. }
  3596. begin
  3597. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3598. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3599. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3600. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3601. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3602. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3603. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3604. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3605. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3606. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3607. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3608. end
  3609. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3610. begin
  3611. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3612. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3613. end
  3614. else
  3615. begin
  3616. RemoveInstruction(hp2);
  3617. end
  3618. {$endif i386}
  3619. ;
  3620. end;
  3621. end
  3622. { movl [mem1],reg1
  3623. movl [mem1],reg2
  3624. to
  3625. movl [mem1],reg1
  3626. movl reg1,reg2
  3627. }
  3628. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3629. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3630. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3631. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3632. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3633. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3634. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3635. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3636. begin
  3637. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3638. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3639. end;
  3640. { movl const1,[mem1]
  3641. movl [mem1],reg1
  3642. to
  3643. movl const1,reg1
  3644. movl reg1,[mem1]
  3645. }
  3646. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3647. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3648. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3649. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3650. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3651. begin
  3652. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3653. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3654. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3655. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3656. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3657. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3658. Result:=true;
  3659. exit;
  3660. end;
  3661. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3662. { Change:
  3663. movl %reg1,%reg2
  3664. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3665. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3666. To:
  3667. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3668. movl x(%reg1),%reg1
  3669. movl %reg1,%regX
  3670. }
  3671. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3672. begin
  3673. p_SourceReg := taicpu(p).oper[0]^.reg;
  3674. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3675. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3676. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3677. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3678. GetNextInstruction(hp1, hp2) and
  3679. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3680. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3681. begin
  3682. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3683. if RegInRef(p_TargetReg, SourceRef) and
  3684. { If %reg1 also appears in the second reference, then it will
  3685. not refer to the same memory block as the first reference }
  3686. not RegInRef(p_SourceReg, SourceRef) then
  3687. begin
  3688. { Check to see if the references match if %reg2 is changed to %reg1 }
  3689. if SourceRef.base = p_TargetReg then
  3690. SourceRef.base := p_SourceReg;
  3691. if SourceRef.index = p_TargetReg then
  3692. SourceRef.index := p_SourceReg;
  3693. { RefsEqual also checks to ensure both references are non-volatile }
  3694. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3695. begin
  3696. taicpu(hp2).loadreg(0, p_SourceReg);
  3697. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3698. Result := True;
  3699. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3700. begin
  3701. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3702. RemoveCurrentP(p, hp1);
  3703. Exit;
  3704. end
  3705. else
  3706. begin
  3707. { Check to see if %reg2 is no longer in use }
  3708. TransferUsedRegs(TmpUsedRegs);
  3709. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3710. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3711. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3712. begin
  3713. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3714. RemoveCurrentP(p, hp1);
  3715. Exit;
  3716. end;
  3717. end;
  3718. { If we reach this point, p and hp1 weren't actually modified,
  3719. so we can do a bit more work on this pass }
  3720. end;
  3721. end;
  3722. end;
  3723. end;
  3724. end;
  3725. { search further than the next instruction for a mov (as long as it's not a jump) }
  3726. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3727. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3728. (taicpu(p).oper[1]^.typ = top_reg) and
  3729. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3730. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3731. begin
  3732. { we work with hp2 here, so hp1 can be still used later on when
  3733. checking for GetNextInstruction_p }
  3734. hp3 := hp1;
  3735. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3736. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3737. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3738. TransferUsedRegs(TmpUsedRegs);
  3739. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3740. if NotFirstIteration then
  3741. JumpTracking := TLinkedList.Create
  3742. else
  3743. JumpTracking := nil;
  3744. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3745. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3746. (hp2.typ=ait_instruction) do
  3747. begin
  3748. case taicpu(hp2).opcode of
  3749. A_POP:
  3750. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3751. begin
  3752. if not CrossJump and
  3753. not RegUsedBetween(p_TargetReg, p, hp2) then
  3754. begin
  3755. { We can remove the original MOV since the register
  3756. wasn't used between it and its popping from the stack }
  3757. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3758. RemoveCurrentp(p, hp1);
  3759. Result := True;
  3760. JumpTracking.Free;
  3761. Exit;
  3762. end;
  3763. { Can't go any further }
  3764. Break;
  3765. end;
  3766. A_MOV:
  3767. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3768. ((taicpu(p).oper[0]^.typ=top_const) or
  3769. ((taicpu(p).oper[0]^.typ=top_reg) and
  3770. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3771. )
  3772. ) then
  3773. begin
  3774. { we have
  3775. mov x, %treg
  3776. mov %treg, y
  3777. }
  3778. { We don't need to call UpdateUsedRegs for every instruction between
  3779. p and hp2 because the register we're concerned about will not
  3780. become deallocated (otherwise GetNextInstructionUsingReg would
  3781. have stopped at an earlier instruction). [Kit] }
  3782. TempRegUsed :=
  3783. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3784. RegReadByInstruction(p_TargetReg, hp3) or
  3785. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3786. case taicpu(p).oper[0]^.typ Of
  3787. top_reg:
  3788. begin
  3789. { change
  3790. mov %reg, %treg
  3791. mov %treg, y
  3792. to
  3793. mov %reg, y
  3794. }
  3795. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3796. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3797. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3798. begin
  3799. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3800. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3801. if TempRegUsed then
  3802. begin
  3803. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3804. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3805. { Set the start of the next GetNextInstructionUsingRegCond search
  3806. to start at the entry right before hp2 (which is about to be removed) }
  3807. hp3 := tai(hp2.Previous);
  3808. RemoveInstruction(hp2);
  3809. { See if there's more we can optimise }
  3810. Continue;
  3811. end
  3812. else
  3813. begin
  3814. RemoveInstruction(hp2);
  3815. { We can remove the original MOV too }
  3816. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3817. RemoveCurrentP(p, hp1);
  3818. Result:=true;
  3819. JumpTracking.Free;
  3820. Exit;
  3821. end;
  3822. end
  3823. else
  3824. begin
  3825. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3826. taicpu(hp2).loadReg(0, p_SourceReg);
  3827. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3828. { Check to see if the register also appears in the reference }
  3829. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3830. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  3831. { Don't remove the first instruction if the temporary register is in use }
  3832. if not TempRegUsed and
  3833. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3834. not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  3835. begin
  3836. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3837. RemoveCurrentP(p, hp1);
  3838. Result:=true;
  3839. JumpTracking.Free;
  3840. Exit;
  3841. end;
  3842. { No need to set Result to True here. If there's another instruction later
  3843. on that can be optimised, it will be detected when the main Pass 1 loop
  3844. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3845. end;
  3846. end;
  3847. top_const:
  3848. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3849. begin
  3850. { change
  3851. mov const, %treg
  3852. mov %treg, y
  3853. to
  3854. mov const, y
  3855. }
  3856. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3857. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3858. begin
  3859. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3860. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3861. if TempRegUsed then
  3862. begin
  3863. { Don't remove the first instruction if the temporary register is in use }
  3864. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3865. { No need to set Result to True. If there's another instruction later on
  3866. that can be optimised, it will be detected when the main Pass 1 loop
  3867. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3868. end
  3869. else
  3870. begin
  3871. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3872. RemoveCurrentP(p, hp1);
  3873. Result:=true;
  3874. Exit;
  3875. end;
  3876. end;
  3877. end;
  3878. else
  3879. Internalerror(2019103001);
  3880. end;
  3881. end
  3882. else
  3883. if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  3884. begin
  3885. if not CrossJump and
  3886. not RegUsedBetween(p_TargetReg, p, hp2) and
  3887. not RegReadByInstruction(p_TargetReg, hp2) then
  3888. begin
  3889. { Register is not used before it is overwritten }
  3890. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3891. RemoveCurrentp(p, hp1);
  3892. Result := True;
  3893. Exit;
  3894. end;
  3895. if (taicpu(p).oper[0]^.typ = top_const) and
  3896. (taicpu(hp2).oper[0]^.typ = top_const) then
  3897. begin
  3898. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3899. begin
  3900. { Same value - register hasn't changed }
  3901. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3902. RemoveInstruction(hp2);
  3903. Result := True;
  3904. { See if there's more we can optimise }
  3905. Continue;
  3906. end;
  3907. end;
  3908. end;
  3909. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  3910. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  3911. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  3912. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  3913. begin
  3914. {
  3915. Change from:
  3916. mov ###, %reg
  3917. ...
  3918. movs/z %reg,%reg (Same register, just different sizes)
  3919. To:
  3920. movs/z ###, %reg (Longer version)
  3921. ...
  3922. (remove)
  3923. }
  3924. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  3925. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  3926. { Keep the first instruction as mov if ### is a constant }
  3927. if taicpu(p).oper[0]^.typ = top_const then
  3928. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  3929. else
  3930. begin
  3931. taicpu(p).opcode := taicpu(hp2).opcode;
  3932. taicpu(p).opsize := taicpu(hp2).opsize;
  3933. end;
  3934. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  3935. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  3936. RemoveInstruction(hp2);
  3937. Result := True;
  3938. JumpTracking.Free;
  3939. Exit;
  3940. end;
  3941. else
  3942. { Move down to the MatchOpType if-block below };
  3943. end;
  3944. { Also catches MOV/S/Z instructions that aren't modified }
  3945. if taicpu(p).oper[0]^.typ = top_reg then
  3946. begin
  3947. p_SourceReg := taicpu(p).oper[0]^.reg;
  3948. if
  3949. not RegModifiedByInstruction(p_SourceReg, hp3) and
  3950. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  3951. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  3952. begin
  3953. Result := True;
  3954. { Just in case something didn't get modified (e.g. an
  3955. implicit register). Also, if it does read from this
  3956. register, then there's no longer an advantage to
  3957. changing the register on subsequent instructions.}
  3958. if not RegReadByInstruction(p_TargetReg, hp2) then
  3959. begin
  3960. { If a conditional jump was crossed, do not delete
  3961. the original MOV no matter what }
  3962. if not CrossJump and
  3963. { RegEndOfLife returns True if the register is
  3964. deallocated before the next instruction or has
  3965. been loaded with a new value }
  3966. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  3967. begin
  3968. { We can remove the original MOV }
  3969. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  3970. RemoveCurrentp(p, hp1);
  3971. JumpTracking.Free;
  3972. Result := True;
  3973. Exit;
  3974. end;
  3975. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  3976. begin
  3977. { See if there's more we can optimise }
  3978. hp3 := hp2;
  3979. Continue;
  3980. end;
  3981. end;
  3982. end;
  3983. end;
  3984. { Break out of the while loop under normal circumstances }
  3985. Break;
  3986. end;
  3987. JumpTracking.Free;
  3988. end;
  3989. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  3990. (taicpu(p).oper[1]^.typ = top_reg) and
  3991. (taicpu(p).opsize = S_L) and
  3992. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  3993. (hp2.typ = ait_instruction) and
  3994. (taicpu(hp2).opcode = A_AND) and
  3995. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  3996. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3997. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  3998. ) then
  3999. begin
  4000. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4001. begin
  4002. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4003. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4004. begin
  4005. { Optimize out:
  4006. mov x, %reg
  4007. and ffffffffh, %reg
  4008. }
  4009. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4010. RemoveInstruction(hp2);
  4011. Result:=true;
  4012. exit;
  4013. end;
  4014. end;
  4015. end;
  4016. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4017. x >= RetOffset) as it doesn't do anything (it writes either to a
  4018. parameter or to the temporary storage room for the function
  4019. result)
  4020. }
  4021. if IsExitCode(hp1) and
  4022. (taicpu(p).oper[1]^.typ = top_ref) and
  4023. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4024. (
  4025. (
  4026. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4027. not (
  4028. assigned(current_procinfo.procdef.funcretsym) and
  4029. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4030. )
  4031. ) or
  4032. { Also discard writes to the stack that are below the base pointer,
  4033. as this is temporary storage rather than a function result on the
  4034. stack, say. }
  4035. (
  4036. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4037. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4038. )
  4039. ) then
  4040. begin
  4041. RemoveCurrentp(p, hp1);
  4042. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4043. RemoveLastDeallocForFuncRes(p);
  4044. Result:=true;
  4045. exit;
  4046. end;
  4047. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4048. begin
  4049. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4050. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4051. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4052. begin
  4053. { change
  4054. mov reg1, mem1
  4055. test/cmp x, mem1
  4056. to
  4057. mov reg1, mem1
  4058. test/cmp x, reg1
  4059. }
  4060. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4061. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4062. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4063. Result := True;
  4064. Exit;
  4065. end;
  4066. if DoMovCmpMemOpt(p, hp1, True) then
  4067. begin
  4068. Result := True;
  4069. Exit;
  4070. end;
  4071. end;
  4072. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4073. { If the flags register is in use, don't change the instruction to an
  4074. ADD otherwise this will scramble the flags. [Kit] }
  4075. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  4076. begin
  4077. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  4078. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  4079. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  4080. ) or
  4081. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  4082. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  4083. )
  4084. ) then
  4085. { mov reg1,ref
  4086. lea reg2,[reg1,reg2]
  4087. to
  4088. add reg2,ref}
  4089. begin
  4090. TransferUsedRegs(TmpUsedRegs);
  4091. { reg1 may not be used afterwards }
  4092. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4093. begin
  4094. Taicpu(hp1).opcode:=A_ADD;
  4095. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  4096. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  4097. RemoveCurrentp(p, hp1);
  4098. result:=true;
  4099. exit;
  4100. end;
  4101. end;
  4102. { If the LEA instruction can be converted into an arithmetic instruction,
  4103. it may be possible to then fold it in the next optimisation, otherwise
  4104. there's nothing more that can be optimised here. }
  4105. if not ConvertLEA(taicpu(hp1)) then
  4106. Exit;
  4107. end;
  4108. if (taicpu(p).oper[1]^.typ = top_reg) and
  4109. (hp1.typ = ait_instruction) and
  4110. GetNextInstruction(hp1, hp2) and
  4111. MatchInstruction(hp2,A_MOV,[]) and
  4112. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4113. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4114. (
  4115. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4116. {$ifdef x86_64}
  4117. or
  4118. (
  4119. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4120. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4121. )
  4122. {$endif x86_64}
  4123. ) then
  4124. begin
  4125. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4126. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4127. { change movsX/movzX reg/ref, reg2
  4128. add/sub/or/... reg3/$const, reg2
  4129. mov reg2 reg/ref
  4130. dealloc reg2
  4131. to
  4132. add/sub/or/... reg3/$const, reg/ref }
  4133. begin
  4134. TransferUsedRegs(TmpUsedRegs);
  4135. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4136. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4137. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4138. begin
  4139. { by example:
  4140. movswl %si,%eax movswl %si,%eax p
  4141. decl %eax addl %edx,%eax hp1
  4142. movw %ax,%si movw %ax,%si hp2
  4143. ->
  4144. movswl %si,%eax movswl %si,%eax p
  4145. decw %eax addw %edx,%eax hp1
  4146. movw %ax,%si movw %ax,%si hp2
  4147. }
  4148. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4149. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4150. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4151. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4152. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4153. {
  4154. ->
  4155. movswl %si,%eax movswl %si,%eax p
  4156. decw %si addw %dx,%si hp1
  4157. movw %ax,%si movw %ax,%si hp2
  4158. }
  4159. case taicpu(hp1).ops of
  4160. 1:
  4161. begin
  4162. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4163. if taicpu(hp1).oper[0]^.typ=top_reg then
  4164. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4165. end;
  4166. 2:
  4167. begin
  4168. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4169. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4170. (taicpu(hp1).opcode<>A_SHL) and
  4171. (taicpu(hp1).opcode<>A_SHR) and
  4172. (taicpu(hp1).opcode<>A_SAR) then
  4173. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4174. end;
  4175. else
  4176. internalerror(2008042701);
  4177. end;
  4178. {
  4179. ->
  4180. decw %si addw %dx,%si p
  4181. }
  4182. RemoveInstruction(hp2);
  4183. RemoveCurrentP(p, hp1);
  4184. Result:=True;
  4185. Exit;
  4186. end;
  4187. end;
  4188. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4189. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4190. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4191. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4192. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4193. )
  4194. {$ifdef i386}
  4195. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4196. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4197. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4198. {$endif i386}
  4199. then
  4200. { change movsX/movzX reg/ref, reg2
  4201. add/sub/or/... regX/$const, reg2
  4202. mov reg2, reg3
  4203. dealloc reg2
  4204. to
  4205. movsX/movzX reg/ref, reg3
  4206. add/sub/or/... reg3/$const, reg3
  4207. }
  4208. begin
  4209. TransferUsedRegs(TmpUsedRegs);
  4210. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4211. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4212. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4213. begin
  4214. { by example:
  4215. movswl %si,%eax movswl %si,%eax p
  4216. decl %eax addl %edx,%eax hp1
  4217. movw %ax,%si movw %ax,%si hp2
  4218. ->
  4219. movswl %si,%eax movswl %si,%eax p
  4220. decw %eax addw %edx,%eax hp1
  4221. movw %ax,%si movw %ax,%si hp2
  4222. }
  4223. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4224. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4225. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4226. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4227. { limit size of constants as well to avoid assembler errors, but
  4228. check opsize to avoid overflow when left shifting the 1 }
  4229. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4230. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4231. {$ifdef x86_64}
  4232. { Be careful of, for example:
  4233. movl %reg1,%reg2
  4234. addl %reg3,%reg2
  4235. movq %reg2,%reg4
  4236. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4237. }
  4238. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4239. begin
  4240. taicpu(hp2).changeopsize(S_L);
  4241. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4242. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4243. end;
  4244. {$endif x86_64}
  4245. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4246. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4247. if taicpu(p).oper[0]^.typ=top_reg then
  4248. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4249. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4250. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4251. {
  4252. ->
  4253. movswl %si,%eax movswl %si,%eax p
  4254. decw %si addw %dx,%si hp1
  4255. movw %ax,%si movw %ax,%si hp2
  4256. }
  4257. case taicpu(hp1).ops of
  4258. 1:
  4259. begin
  4260. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4261. if taicpu(hp1).oper[0]^.typ=top_reg then
  4262. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4263. end;
  4264. 2:
  4265. begin
  4266. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4267. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4268. (taicpu(hp1).opcode<>A_SHL) and
  4269. (taicpu(hp1).opcode<>A_SHR) and
  4270. (taicpu(hp1).opcode<>A_SAR) then
  4271. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4272. end;
  4273. else
  4274. internalerror(2018111801);
  4275. end;
  4276. {
  4277. ->
  4278. decw %si addw %dx,%si p
  4279. }
  4280. RemoveInstruction(hp2);
  4281. end;
  4282. end;
  4283. end;
  4284. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4285. GetNextInstruction(hp1, hp2) and
  4286. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4287. MatchOperand(Taicpu(p).oper[0]^,0) and
  4288. (Taicpu(p).oper[1]^.typ = top_reg) and
  4289. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4290. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4291. { mov reg1,0
  4292. bts reg1,operand1 --> mov reg1,operand2
  4293. or reg1,operand2 bts reg1,operand1}
  4294. begin
  4295. Taicpu(hp2).opcode:=A_MOV;
  4296. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4297. asml.remove(hp1);
  4298. insertllitem(hp2,hp2.next,hp1);
  4299. RemoveCurrentp(p, hp1);
  4300. Result:=true;
  4301. exit;
  4302. end;
  4303. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4304. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4305. GetNextInstruction(hp1, hp2) and
  4306. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4307. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4308. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4309. { change
  4310. mov reg1,reg2
  4311. sub reg3,reg2
  4312. cmp reg3,reg1
  4313. into
  4314. mov reg1,reg2
  4315. sub reg3,reg2
  4316. }
  4317. begin
  4318. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4319. RemoveInstruction(hp2);
  4320. Result:=true;
  4321. exit;
  4322. end;
  4323. {
  4324. mov ref,reg0
  4325. <op> reg0,reg1
  4326. dealloc reg0
  4327. to
  4328. <op> ref,reg1
  4329. }
  4330. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4331. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4332. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4333. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4334. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4335. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4336. begin
  4337. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4338. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4339. RemoveCurrentp(p, hp1);
  4340. Result:=true;
  4341. exit;
  4342. end;
  4343. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4344. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4345. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4346. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4347. begin
  4348. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4349. {$ifdef x86_64}
  4350. { Convert:
  4351. movq x(ref),%reg64
  4352. shrq y,%reg64
  4353. To:
  4354. movl x+4(ref),%reg32
  4355. shrl y-32,%reg32 (Remove if y = 32)
  4356. }
  4357. if (taicpu(p).opsize = S_Q) and
  4358. (taicpu(hp1).opcode = A_SHR) and
  4359. (taicpu(hp1).oper[0]^.val >= 32) then
  4360. begin
  4361. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4362. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4363. { Convert to 32-bit }
  4364. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4365. taicpu(p).opsize := S_L;
  4366. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4367. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4368. if (taicpu(hp1).oper[0]^.val = 32) then
  4369. begin
  4370. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4371. RemoveInstruction(hp1);
  4372. end
  4373. else
  4374. begin
  4375. { This will potentially open up more arithmetic operations since
  4376. the peephole optimizer now has a big hint that only the lower
  4377. 32 bits are currently in use (and opcodes are smaller in size) }
  4378. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4379. taicpu(hp1).opsize := S_L;
  4380. Dec(taicpu(hp1).oper[0]^.val, 32);
  4381. DebugMsg(SPeepholeOptimization + PreMessage +
  4382. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4383. end;
  4384. Result := True;
  4385. Exit;
  4386. end;
  4387. {$endif x86_64}
  4388. { Convert:
  4389. movl x(ref),%reg
  4390. shrl $24,%reg
  4391. To:
  4392. movzbl x+3(ref),%reg
  4393. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4394. Also accept sar instead of shr, but convert to movsx instead of movzx
  4395. }
  4396. if taicpu(hp1).opcode = A_SHR then
  4397. MovUnaligned := A_MOVZX
  4398. else
  4399. MovUnaligned := A_MOVSX;
  4400. NewSize := S_NO;
  4401. NewOffset := 0;
  4402. case taicpu(p).opsize of
  4403. S_B:
  4404. { No valid combinations };
  4405. S_W:
  4406. if (taicpu(hp1).oper[0]^.val = 8) then
  4407. begin
  4408. NewSize := S_BW;
  4409. NewOffset := 1;
  4410. end;
  4411. S_L:
  4412. case taicpu(hp1).oper[0]^.val of
  4413. 16:
  4414. begin
  4415. NewSize := S_WL;
  4416. NewOffset := 2;
  4417. end;
  4418. 24:
  4419. begin
  4420. NewSize := S_BL;
  4421. NewOffset := 3;
  4422. end;
  4423. else
  4424. ;
  4425. end;
  4426. {$ifdef x86_64}
  4427. S_Q:
  4428. case taicpu(hp1).oper[0]^.val of
  4429. 32:
  4430. begin
  4431. if taicpu(hp1).opcode = A_SAR then
  4432. begin
  4433. { 32-bit to 64-bit is a distinct instruction }
  4434. MovUnaligned := A_MOVSXD;
  4435. NewSize := S_LQ;
  4436. NewOffset := 4;
  4437. end
  4438. else
  4439. { Should have been handled by MovShr2Mov above }
  4440. InternalError(2022081811);
  4441. end;
  4442. 48:
  4443. begin
  4444. NewSize := S_WQ;
  4445. NewOffset := 6;
  4446. end;
  4447. 56:
  4448. begin
  4449. NewSize := S_BQ;
  4450. NewOffset := 7;
  4451. end;
  4452. else
  4453. ;
  4454. end;
  4455. {$endif x86_64}
  4456. else
  4457. InternalError(2022081810);
  4458. end;
  4459. if (NewSize <> S_NO) and
  4460. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4461. begin
  4462. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4463. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4464. debug_op2str(MovUnaligned);
  4465. {$ifdef x86_64}
  4466. if MovUnaligned <> A_MOVSXD then
  4467. { Don't add size suffix for MOVSXD }
  4468. {$endif x86_64}
  4469. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4470. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4471. taicpu(p).opcode := MovUnaligned;
  4472. taicpu(p).opsize := NewSize;
  4473. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4474. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4475. RemoveInstruction(hp1);
  4476. Result := True;
  4477. Exit;
  4478. end;
  4479. end;
  4480. { Backward optimisation shared with OptPass2MOV }
  4481. if FuncMov2Func(p, hp1) then
  4482. begin
  4483. Result := True;
  4484. Exit;
  4485. end;
  4486. end;
  4487. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4488. var
  4489. hp1 : tai;
  4490. begin
  4491. Result:=false;
  4492. if taicpu(p).ops <> 2 then
  4493. exit;
  4494. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4495. GetNextInstruction(p,hp1) then
  4496. begin
  4497. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4498. (taicpu(hp1).ops = 2) then
  4499. begin
  4500. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4501. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4502. { movXX reg1, mem1 or movXX mem1, reg1
  4503. movXX mem2, reg2 movXX reg2, mem2}
  4504. begin
  4505. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4506. { movXX reg1, mem1 or movXX mem1, reg1
  4507. movXX mem2, reg1 movXX reg2, mem1}
  4508. begin
  4509. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4510. begin
  4511. { Removes the second statement from
  4512. movXX reg1, mem1/reg2
  4513. movXX mem1/reg2, reg1
  4514. }
  4515. if taicpu(p).oper[0]^.typ=top_reg then
  4516. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4517. { Removes the second statement from
  4518. movXX mem1/reg1, reg2
  4519. movXX reg2, mem1/reg1
  4520. }
  4521. if (taicpu(p).oper[1]^.typ=top_reg) and
  4522. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4523. begin
  4524. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4525. RemoveInstruction(hp1);
  4526. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4527. Result:=true;
  4528. exit;
  4529. end
  4530. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4531. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4532. begin
  4533. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4534. RemoveInstruction(hp1);
  4535. Result:=true;
  4536. exit;
  4537. end;
  4538. end
  4539. end;
  4540. end;
  4541. end;
  4542. end;
  4543. end;
  4544. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4545. var
  4546. hp1 : tai;
  4547. begin
  4548. result:=false;
  4549. { replace
  4550. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4551. MovX %mreg2,%mreg1
  4552. dealloc %mreg2
  4553. by
  4554. <Op>X %mreg2,%mreg1
  4555. ?
  4556. }
  4557. if GetNextInstruction(p,hp1) and
  4558. { we mix single and double opperations here because we assume that the compiler
  4559. generates vmovapd only after double operations and vmovaps only after single operations }
  4560. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4561. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4562. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4563. (taicpu(p).oper[0]^.typ=top_reg) then
  4564. begin
  4565. TransferUsedRegs(TmpUsedRegs);
  4566. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4567. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4568. begin
  4569. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4570. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4571. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4572. RemoveInstruction(hp1);
  4573. result:=true;
  4574. end;
  4575. end;
  4576. end;
  4577. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4578. var
  4579. hp1, p_label, p_dist, hp1_dist: tai;
  4580. JumpLabel, JumpLabel_dist: TAsmLabel;
  4581. FirstValue, SecondValue: TCGInt;
  4582. TempBool: Boolean;
  4583. begin
  4584. Result := False;
  4585. if (taicpu(p).oper[0]^.typ = top_const) and
  4586. (taicpu(p).oper[0]^.val <> -1) then
  4587. begin
  4588. { Convert unsigned maximum constants to -1 to aid optimisation }
  4589. case taicpu(p).opsize of
  4590. S_B:
  4591. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4592. begin
  4593. taicpu(p).oper[0]^.val := -1;
  4594. Result := True;
  4595. Exit;
  4596. end;
  4597. S_W:
  4598. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4599. begin
  4600. taicpu(p).oper[0]^.val := -1;
  4601. Result := True;
  4602. Exit;
  4603. end;
  4604. S_L:
  4605. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4606. begin
  4607. taicpu(p).oper[0]^.val := -1;
  4608. Result := True;
  4609. Exit;
  4610. end;
  4611. {$ifdef x86_64}
  4612. S_Q:
  4613. { Storing anything greater than $7FFFFFFF is not possible so do
  4614. nothing };
  4615. {$endif x86_64}
  4616. else
  4617. InternalError(2021121001);
  4618. end;
  4619. end;
  4620. if GetNextInstruction(p, hp1) and
  4621. TrySwapMovCmp(p, hp1) then
  4622. begin
  4623. Result := True;
  4624. Exit;
  4625. end;
  4626. if MatchInstruction(hp1, A_Jcc, []) then
  4627. begin
  4628. TempBool := True;
  4629. if DoJumpOptimizations(hp1, TempBool) or
  4630. not TempBool then
  4631. begin
  4632. Result := True;
  4633. if Assigned(hp1) then
  4634. begin
  4635. if (hp1.typ in [ait_align]) then
  4636. SkipAligns(hp1, hp1);
  4637. { CollapseZeroDistJump will be set to the label after the
  4638. jump if it optimises, whether or not it's live or dead }
  4639. if (hp1.typ in [ait_label]) and
  4640. not (tai_label(hp1).labsym.is_used) then
  4641. GetNextInstruction(hp1, hp1);
  4642. end;
  4643. TransferUsedRegs(TmpUsedRegs);
  4644. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4645. if not Assigned(hp1) or
  4646. (
  4647. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  4648. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  4649. ) then
  4650. begin
  4651. { No more conditional jumps; conditional statement is no longer required }
  4652. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  4653. RemoveCurrentP(p);
  4654. end;
  4655. Exit;
  4656. end;
  4657. end;
  4658. { Search for:
  4659. test $x,(reg/ref)
  4660. jne @lbl1
  4661. test $y,(reg/ref) (same register or reference)
  4662. jne @lbl1
  4663. Change to:
  4664. test $(x or y),(reg/ref)
  4665. jne @lbl1
  4666. (Note, this doesn't work with je instead of jne)
  4667. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4668. Also search for:
  4669. test $x,(reg/ref)
  4670. je @lbl1
  4671. test $y,(reg/ref)
  4672. je/jne @lbl2
  4673. If (x or y) = x, then the second jump is deterministic
  4674. }
  4675. if (
  4676. (
  4677. (taicpu(p).oper[0]^.typ = top_const) or
  4678. (
  4679. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4680. (taicpu(p).oper[0]^.typ = top_reg) and
  4681. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4682. )
  4683. ) and
  4684. MatchInstruction(hp1, A_JCC, [])
  4685. ) then
  4686. begin
  4687. if (taicpu(p).oper[0]^.typ = top_reg) and
  4688. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4689. FirstValue := -1
  4690. else
  4691. FirstValue := taicpu(p).oper[0]^.val;
  4692. { If we have several test/jne's in a row, it might be the case that
  4693. the second label doesn't go to the same location, but the one
  4694. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4695. so accommodate for this with a while loop.
  4696. }
  4697. hp1_dist := hp1;
  4698. if GetNextInstruction(hp1, p_dist) and
  4699. (p_dist.typ = ait_instruction) and
  4700. (
  4701. (
  4702. (taicpu(p_dist).opcode = A_TEST) and
  4703. (
  4704. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4705. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4706. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4707. )
  4708. ) or
  4709. (
  4710. { cmp 0,%reg = test %reg,%reg }
  4711. (taicpu(p_dist).opcode = A_CMP) and
  4712. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4713. )
  4714. ) and
  4715. { Make sure the destination operands are actually the same }
  4716. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4717. GetNextInstruction(p_dist, hp1_dist) and
  4718. MatchInstruction(hp1_dist, A_JCC, []) then
  4719. begin
  4720. if
  4721. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4722. (
  4723. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4724. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4725. ) then
  4726. SecondValue := -1
  4727. else
  4728. SecondValue := taicpu(p_dist).oper[0]^.val;
  4729. { If both of the TEST constants are identical, delete the second
  4730. TEST that is unnecessary. }
  4731. if (FirstValue = SecondValue) then
  4732. begin
  4733. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4734. RemoveInstruction(p_dist);
  4735. { Don't let the flags register become deallocated and reallocated between the jumps }
  4736. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4737. Result := True;
  4738. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4739. begin
  4740. { Since the second jump's condition is a subset of the first, we
  4741. know it will never branch because the first jump dominates it.
  4742. Get it out of the way now rather than wait for the jump
  4743. optimisations for a speed boost. }
  4744. if IsJumpToLabel(taicpu(hp1_dist)) then
  4745. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4746. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4747. RemoveInstruction(hp1_dist);
  4748. end
  4749. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4750. begin
  4751. { If the inverse of the first condition is a subset of the second,
  4752. the second one will definitely branch if the first one doesn't }
  4753. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4754. MakeUnconditional(taicpu(hp1_dist));
  4755. RemoveDeadCodeAfterJump(hp1_dist);
  4756. end;
  4757. Exit;
  4758. end;
  4759. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4760. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4761. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4762. then the second jump will never branch, so it can also be
  4763. removed regardless of where it goes }
  4764. (
  4765. (FirstValue = -1) or
  4766. (SecondValue = -1) or
  4767. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4768. ) then
  4769. begin
  4770. { Same jump location... can be a register since nothing's changed }
  4771. { If any of the entries are equivalent to test %reg,%reg, then the
  4772. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  4773. taicpu(p).loadconst(0, FirstValue or SecondValue);
  4774. if IsJumpToLabel(taicpu(hp1_dist)) then
  4775. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4776. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  4777. RemoveInstruction(hp1_dist);
  4778. { Only remove the second test if no jumps or other conditional instructions follow }
  4779. TransferUsedRegs(TmpUsedRegs);
  4780. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4781. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4782. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  4783. RemoveInstruction(p_dist);
  4784. Result := True;
  4785. Exit;
  4786. end;
  4787. end;
  4788. end;
  4789. { Search for:
  4790. test %reg,%reg
  4791. j(c1) @lbl1
  4792. ...
  4793. @lbl:
  4794. test %reg,%reg (same register)
  4795. j(c2) @lbl2
  4796. If c2 is a subset of c1, change to:
  4797. test %reg,%reg
  4798. j(c1) @lbl2
  4799. (@lbl1 may become a dead label as a result)
  4800. }
  4801. if (taicpu(p).oper[1]^.typ = top_reg) and
  4802. (taicpu(p).oper[0]^.typ = top_reg) and
  4803. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  4804. MatchInstruction(hp1, A_JCC, []) and
  4805. IsJumpToLabel(taicpu(hp1)) then
  4806. begin
  4807. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4808. p_label := nil;
  4809. if Assigned(JumpLabel) then
  4810. p_label := getlabelwithsym(JumpLabel);
  4811. if Assigned(p_label) and
  4812. GetNextInstruction(p_label, p_dist) and
  4813. MatchInstruction(p_dist, A_TEST, []) and
  4814. { It's fine if the second test uses smaller sub-registers }
  4815. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  4816. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  4817. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  4818. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  4819. GetNextInstruction(p_dist, hp1_dist) and
  4820. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4821. begin
  4822. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4823. if JumpLabel = JumpLabel_dist then
  4824. { This is an infinite loop }
  4825. Exit;
  4826. { Best optimisation when the first condition is a subset (or equal) of the second }
  4827. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  4828. begin
  4829. { Any registers used here will already be allocated }
  4830. if Assigned(JumpLabel) then
  4831. JumpLabel.DecRefs;
  4832. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  4833. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  4834. Result := True;
  4835. Exit;
  4836. end;
  4837. end;
  4838. end;
  4839. end;
  4840. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  4841. var
  4842. hp1, hp2: tai;
  4843. ActiveReg: TRegister;
  4844. OldOffset: asizeint;
  4845. ThisConst: TCGInt;
  4846. function RegDeallocated: Boolean;
  4847. begin
  4848. TransferUsedRegs(TmpUsedRegs);
  4849. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4850. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4851. end;
  4852. begin
  4853. result:=false;
  4854. hp1 := nil;
  4855. { replace
  4856. addX const,%reg1
  4857. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4858. dealloc %reg1
  4859. by
  4860. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  4861. }
  4862. if MatchOpType(taicpu(p),top_const,top_reg) then
  4863. begin
  4864. ActiveReg := taicpu(p).oper[1]^.reg;
  4865. { Ensures the entire register was updated }
  4866. if (taicpu(p).opsize >= S_L) and
  4867. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  4868. MatchInstruction(hp1,A_LEA,[]) and
  4869. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  4870. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  4871. (
  4872. { Cover the case where the register in the reference is also the destination register }
  4873. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  4874. (
  4875. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  4876. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  4877. RegDeallocated
  4878. )
  4879. ) then
  4880. begin
  4881. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  4882. {$push}
  4883. {$R-}{$Q-}
  4884. { Explicitly disable overflow checking for these offset calculation
  4885. as those do not matter for the final result }
  4886. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  4887. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  4888. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  4889. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4890. {$pop}
  4891. {$ifdef x86_64}
  4892. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  4893. begin
  4894. { Overflow; abort }
  4895. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  4896. end
  4897. else
  4898. {$endif x86_64}
  4899. begin
  4900. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  4901. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  4902. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  4903. RemoveCurrentP(p, hp1)
  4904. else
  4905. RemoveCurrentP(p);
  4906. result:=true;
  4907. Exit;
  4908. end;
  4909. end;
  4910. if (
  4911. { Save calling GetNextInstructionUsingReg again }
  4912. Assigned(hp1) or
  4913. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  4914. ) and
  4915. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  4916. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  4917. begin
  4918. if taicpu(hp1).oper[0]^.typ = top_const then
  4919. begin
  4920. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  4921. if taicpu(hp1).opcode = A_ADD then
  4922. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  4923. else
  4924. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  4925. Result := True;
  4926. { Handle any overflows }
  4927. case taicpu(p).opsize of
  4928. S_B:
  4929. taicpu(p).oper[0]^.val := ThisConst and $FF;
  4930. S_W:
  4931. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  4932. S_L:
  4933. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  4934. {$ifdef x86_64}
  4935. S_Q:
  4936. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  4937. { Overflow; abort }
  4938. Result := False
  4939. else
  4940. taicpu(p).oper[0]^.val := ThisConst;
  4941. {$endif x86_64}
  4942. else
  4943. InternalError(2021102610);
  4944. end;
  4945. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  4946. if Result then
  4947. begin
  4948. if (taicpu(p).oper[0]^.val < 0) and
  4949. (
  4950. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  4951. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  4952. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  4953. ) then
  4954. begin
  4955. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  4956. taicpu(p).opcode := A_SUB;
  4957. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  4958. end
  4959. else
  4960. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  4961. RemoveInstruction(hp1);
  4962. end;
  4963. end
  4964. else
  4965. begin
  4966. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  4967. TransferUsedRegs(TmpUsedRegs);
  4968. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4969. hp2 := p;
  4970. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  4971. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  4972. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  4973. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  4974. begin
  4975. { Move the constant addition to after the reg/ref addition to improve optimisation }
  4976. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  4977. Asml.Remove(p);
  4978. Asml.InsertAfter(p, hp1);
  4979. p := hp1;
  4980. Result := True;
  4981. Exit;
  4982. end;
  4983. end;
  4984. end;
  4985. if DoArithCombineOpt(p) then
  4986. Result:=true;
  4987. end;
  4988. end;
  4989. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  4990. var
  4991. hp1: tai;
  4992. ref: Integer;
  4993. saveref: treference;
  4994. Multiple: TCGInt;
  4995. Adjacent: Boolean;
  4996. begin
  4997. Result:=false;
  4998. { play save and throw an error if LEA uses a seg register prefix,
  4999. this is most likely an error somewhere else }
  5000. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5001. internalerror(2022022001);
  5002. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5003. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5004. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5005. (
  5006. { do not mess with leas accessing the stack pointer
  5007. unless it's a null operation }
  5008. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5009. (
  5010. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5011. (taicpu(p).oper[0]^.ref^.offset = 0)
  5012. )
  5013. ) and
  5014. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5015. begin
  5016. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5017. begin
  5018. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5019. begin
  5020. taicpu(p).opcode := A_MOV;
  5021. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5022. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5023. end
  5024. else
  5025. begin
  5026. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5027. RemoveCurrentP(p);
  5028. end;
  5029. Result:=true;
  5030. exit;
  5031. end
  5032. else if (
  5033. { continue to use lea to adjust the stack pointer,
  5034. it is the recommended way, but only if not optimizing for size }
  5035. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5036. (cs_opt_size in current_settings.optimizerswitches)
  5037. ) and
  5038. { If the flags register is in use, don't change the instruction
  5039. to an ADD otherwise this will scramble the flags. [Kit] }
  5040. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5041. ConvertLEA(taicpu(p)) then
  5042. begin
  5043. Result:=true;
  5044. exit;
  5045. end;
  5046. end;
  5047. { Don't optimise if the stack or frame pointer is the destination register }
  5048. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5049. Exit;
  5050. if GetNextInstruction(p,hp1) and
  5051. (hp1.typ=ait_instruction) then
  5052. begin
  5053. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5054. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5055. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5056. begin
  5057. TransferUsedRegs(TmpUsedRegs);
  5058. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5059. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5060. begin
  5061. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5062. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5063. RemoveInstruction(hp1);
  5064. result:=true;
  5065. exit;
  5066. end;
  5067. end;
  5068. { changes
  5069. lea <ref1>, reg1
  5070. <op> ...,<ref. with reg1>,...
  5071. to
  5072. <op> ...,<ref1>,... }
  5073. { find a reference which uses reg1 }
  5074. 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
  5075. ref:=0
  5076. 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
  5077. ref:=1
  5078. else
  5079. ref:=-1;
  5080. if (ref<>-1) and
  5081. { reg1 must be either the base or the index }
  5082. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5083. begin
  5084. { reg1 can be removed from the reference }
  5085. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5086. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5087. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5088. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5089. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5090. else
  5091. Internalerror(2019111201);
  5092. { check if the can insert all data of the lea into the second instruction }
  5093. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5094. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5095. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5096. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5097. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5098. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5099. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5100. {$ifdef x86_64}
  5101. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5102. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5103. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5104. )
  5105. {$endif x86_64}
  5106. then
  5107. begin
  5108. { reg1 might not used by the second instruction after it is remove from the reference }
  5109. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5110. begin
  5111. TransferUsedRegs(TmpUsedRegs);
  5112. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5113. { reg1 is not updated so it might not be used afterwards }
  5114. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5115. begin
  5116. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5117. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5118. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5119. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5120. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5121. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5122. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5123. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5124. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5125. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5126. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5127. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5128. RemoveCurrentP(p, hp1);
  5129. result:=true;
  5130. exit;
  5131. end
  5132. end;
  5133. end;
  5134. { recover }
  5135. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5136. end;
  5137. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5138. if Adjacent or
  5139. { Check further ahead (up to 2 instructions ahead for -O2) }
  5140. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5141. begin
  5142. { Check common LEA/LEA conditions }
  5143. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5144. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  5145. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5146. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5147. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5148. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5149. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5150. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5151. (
  5152. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5153. calling it (since it calls GetNextInstruction) }
  5154. Adjacent or
  5155. (
  5156. (
  5157. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5158. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5159. ) and (
  5160. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5161. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5162. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5163. )
  5164. )
  5165. ) then
  5166. begin
  5167. { changes
  5168. lea (regX,scale), reg1
  5169. lea offset(reg1,reg1), reg1
  5170. to
  5171. lea offset(regX,scale*2), reg1
  5172. and
  5173. lea (regX,scale1), reg1
  5174. lea offset(reg1,scale2), reg1
  5175. to
  5176. lea offset(regX,scale1*scale2), reg1
  5177. ... so long as the final scale does not exceed 8
  5178. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5179. }
  5180. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5181. (taicpu(p).oper[0]^.ref^.offset = 0) and
  5182. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5183. (
  5184. (
  5185. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5186. ) or (
  5187. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5188. (
  5189. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5190. (
  5191. { RegUsedBetween always returns False if p and hp1 are adjacent }
  5192. Adjacent or
  5193. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  5194. )
  5195. )
  5196. )
  5197. ) and (
  5198. (
  5199. { lea (reg1,scale2), reg1 variant }
  5200. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  5201. (
  5202. (
  5203. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5204. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5205. ) or (
  5206. { lea (regX,regX), reg1 variant }
  5207. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5208. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5209. )
  5210. )
  5211. ) or (
  5212. { lea (reg1,reg1), reg1 variant }
  5213. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5214. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5215. )
  5216. ) then
  5217. begin
  5218. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5219. { Make everything homogeneous to make calculations easier }
  5220. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5221. begin
  5222. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5223. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5224. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5225. else
  5226. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5227. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5228. end;
  5229. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  5230. begin
  5231. { Just to prevent miscalculations }
  5232. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5233. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5234. else
  5235. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  5236. end
  5237. else
  5238. begin
  5239. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5240. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  5241. end;
  5242. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5243. RemoveCurrentP(p);
  5244. result:=true;
  5245. exit;
  5246. end
  5247. { changes
  5248. lea offset1(regX), reg1
  5249. lea offset2(reg1), reg1
  5250. to
  5251. lea offset1+offset2(regX), reg1 }
  5252. else if
  5253. (
  5254. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5255. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5256. ) or (
  5257. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5258. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5259. (
  5260. (
  5261. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5262. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5263. ) or (
  5264. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5265. (
  5266. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5267. (
  5268. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5269. (
  5270. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5271. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5272. )
  5273. )
  5274. )
  5275. )
  5276. )
  5277. ) then
  5278. begin
  5279. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5280. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5281. begin
  5282. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5283. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5284. { if the register is used as index and base, we have to increase for base as well
  5285. and adapt base }
  5286. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5287. begin
  5288. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5289. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5290. end;
  5291. end
  5292. else
  5293. begin
  5294. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5295. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5296. end;
  5297. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5298. begin
  5299. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5300. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5301. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5302. end;
  5303. RemoveCurrentP(p);
  5304. result:=true;
  5305. exit;
  5306. end;
  5307. end;
  5308. { Change:
  5309. leal/q $x(%reg1),%reg2
  5310. ...
  5311. shll/q $y,%reg2
  5312. To:
  5313. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5314. }
  5315. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5316. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5317. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5318. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5319. (taicpu(hp1).oper[0]^.val <= 3) then
  5320. begin
  5321. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5322. TransferUsedRegs(TmpUsedRegs);
  5323. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5324. if
  5325. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5326. (this works even if scalefactor is zero) }
  5327. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5328. { Ensure offset doesn't go out of bounds }
  5329. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5330. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5331. (
  5332. (
  5333. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5334. (
  5335. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5336. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5337. (
  5338. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5339. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5340. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5341. )
  5342. )
  5343. ) or (
  5344. (
  5345. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5346. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5347. ) and
  5348. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5349. )
  5350. ) then
  5351. begin
  5352. repeat
  5353. with taicpu(p).oper[0]^.ref^ do
  5354. begin
  5355. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5356. if index = base then
  5357. begin
  5358. if Multiple > 4 then
  5359. { Optimisation will no longer work because resultant
  5360. scale factor will exceed 8 }
  5361. Break;
  5362. base := NR_NO;
  5363. scalefactor := 2;
  5364. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5365. end
  5366. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5367. begin
  5368. { Scale factor only works on the index register }
  5369. index := base;
  5370. base := NR_NO;
  5371. end;
  5372. { For safety }
  5373. if scalefactor <= 1 then
  5374. begin
  5375. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5376. scalefactor := Multiple;
  5377. end
  5378. else
  5379. begin
  5380. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5381. scalefactor := scalefactor * Multiple;
  5382. end;
  5383. offset := offset * Multiple;
  5384. end;
  5385. RemoveInstruction(hp1);
  5386. Result := True;
  5387. Exit;
  5388. { This repeat..until loop exists for the benefit of Break }
  5389. until True;
  5390. end;
  5391. end;
  5392. end;
  5393. end;
  5394. end;
  5395. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  5396. var
  5397. hp1 : tai;
  5398. SubInstr: Boolean;
  5399. ThisConst: TCGInt;
  5400. const
  5401. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  5402. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  5403. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  5404. begin
  5405. Result := False;
  5406. if taicpu(p).oper[0]^.typ <> top_const then
  5407. { Should have been confirmed before calling }
  5408. InternalError(2021102601);
  5409. SubInstr := (taicpu(p).opcode = A_SUB);
  5410. if GetLastInstruction(p, hp1) and
  5411. (hp1.typ = ait_instruction) and
  5412. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5413. begin
  5414. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  5415. { Bad size }
  5416. InternalError(2022042001);
  5417. case taicpu(hp1).opcode Of
  5418. A_INC:
  5419. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5420. begin
  5421. if SubInstr then
  5422. ThisConst := taicpu(p).oper[0]^.val - 1
  5423. else
  5424. ThisConst := taicpu(p).oper[0]^.val + 1;
  5425. end
  5426. else
  5427. Exit;
  5428. A_DEC:
  5429. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5430. begin
  5431. if SubInstr then
  5432. ThisConst := taicpu(p).oper[0]^.val + 1
  5433. else
  5434. ThisConst := taicpu(p).oper[0]^.val - 1;
  5435. end
  5436. else
  5437. Exit;
  5438. A_SUB:
  5439. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5440. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5441. begin
  5442. if SubInstr then
  5443. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5444. else
  5445. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5446. end
  5447. else
  5448. Exit;
  5449. A_ADD:
  5450. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5451. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5452. begin
  5453. if SubInstr then
  5454. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  5455. else
  5456. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5457. end
  5458. else
  5459. Exit;
  5460. else
  5461. Exit;
  5462. end;
  5463. { Check that the values are in range }
  5464. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  5465. { Overflow; abort }
  5466. Exit;
  5467. if (ThisConst = 0) then
  5468. begin
  5469. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5470. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5471. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  5472. RemoveInstruction(hp1);
  5473. hp1 := tai(p.next);
  5474. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5475. if not GetLastInstruction(hp1, p) then
  5476. p := hp1;
  5477. end
  5478. else
  5479. begin
  5480. if taicpu(hp1).opercnt=1 then
  5481. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5482. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  5483. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5484. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  5485. else
  5486. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5487. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5488. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5489. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  5490. RemoveInstruction(hp1);
  5491. taicpu(p).loadconst(0, ThisConst);
  5492. end;
  5493. Result := True;
  5494. end;
  5495. end;
  5496. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  5497. begin
  5498. Result := False;
  5499. if UpdateTmpUsedRegs then
  5500. TransferUsedRegs(TmpUsedRegs);
  5501. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5502. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5503. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5504. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5505. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5506. (
  5507. (
  5508. (taicpu(hp1).opcode = A_TEST)
  5509. ) or (
  5510. (taicpu(hp1).opcode = A_CMP) and
  5511. { A sanity check more than anything }
  5512. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5513. )
  5514. ) then
  5515. begin
  5516. { change
  5517. mov mem, %reg
  5518. cmp/test x, %reg / test %reg,%reg
  5519. (reg deallocated)
  5520. to
  5521. cmp/test x, mem / cmp 0, mem
  5522. }
  5523. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5524. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5525. begin
  5526. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5527. if (taicpu(hp1).opcode = A_TEST) and
  5528. (
  5529. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5530. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5531. ) then
  5532. begin
  5533. taicpu(hp1).opcode := A_CMP;
  5534. taicpu(hp1).loadconst(0, 0);
  5535. end;
  5536. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  5537. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  5538. RemoveCurrentP(p, hp1);
  5539. Result := True;
  5540. Exit;
  5541. end;
  5542. end;
  5543. end;
  5544. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  5545. var
  5546. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  5547. ThisReg, SecondReg: TRegister;
  5548. JumpLoc: TAsmLabel;
  5549. NewSize: TOpSize;
  5550. begin
  5551. Result := False;
  5552. {
  5553. Convert:
  5554. j<c> .L1
  5555. .L2:
  5556. mov 1,reg
  5557. jmp .L3 (or ret, although it might not be a RET yet)
  5558. .L1:
  5559. mov 0,reg
  5560. jmp .L3 (or ret)
  5561. ( As long as .L3 <> .L1 or .L2)
  5562. To:
  5563. mov 0,reg
  5564. set<not(c)> reg
  5565. jmp .L3 (or ret)
  5566. .L2:
  5567. mov 1,reg
  5568. jmp .L3 (or ret)
  5569. .L1:
  5570. mov 0,reg
  5571. jmp .L3 (or ret)
  5572. }
  5573. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  5574. Exit;
  5575. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  5576. if GetNextInstruction(hp_label, hp2) and
  5577. MatchInstruction(hp2,A_MOV,[]) and
  5578. (taicpu(hp2).oper[0]^.typ = top_const) and
  5579. (
  5580. (
  5581. (taicpu(hp2).oper[1]^.typ = top_reg)
  5582. {$ifdef i386}
  5583. { Under i386, ESI, EDI, EBP and ESP
  5584. don't have an 8-bit representation }
  5585. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5586. {$endif i386}
  5587. ) or (
  5588. {$ifdef i386}
  5589. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  5590. {$endif i386}
  5591. (taicpu(hp2).opsize = S_B)
  5592. )
  5593. ) and
  5594. GetNextInstruction(hp2, hp3) and
  5595. MatchInstruction(hp3, A_JMP, A_RET, []) and
  5596. (
  5597. (taicpu(hp3).opcode=A_RET) or
  5598. (
  5599. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  5600. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  5601. )
  5602. ) and
  5603. GetNextInstruction(hp3, hp4) and
  5604. SkipAligns(hp4, hp4) and
  5605. (hp4.typ=ait_label) and
  5606. (tai_label(hp4).labsym=JumpLoc) and
  5607. (
  5608. not (cs_opt_size in current_settings.optimizerswitches) or
  5609. { If the initial jump is the label's only reference, then it will
  5610. become a dead label if the other conditions are met and hence
  5611. remove at least 2 instructions, including a jump }
  5612. (JumpLoc.getrefs = 1)
  5613. ) and
  5614. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  5615. that will be optimised out }
  5616. GetNextInstruction(hp4, hp5) and
  5617. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  5618. (taicpu(hp5).oper[0]^.typ = top_const) and
  5619. (
  5620. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  5621. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  5622. ) and
  5623. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  5624. GetNextInstruction(hp5,hp6) and
  5625. (
  5626. (hp6.typ<>ait_label) or
  5627. SkipLabels(hp6, hp6)
  5628. ) and
  5629. (hp6.typ=ait_instruction) then
  5630. begin
  5631. { First, let's look at the two jumps that are hp3 and hp6 }
  5632. if not
  5633. (
  5634. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5635. (
  5636. (taicpu(hp6).opcode=A_RET) or
  5637. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5638. )
  5639. ) then
  5640. { If condition is False, then the JMP/RET instructions matched conventionally }
  5641. begin
  5642. { See if one of the jumps can be instantly converted into a RET }
  5643. if (taicpu(hp3).opcode=A_JMP) then
  5644. begin
  5645. { Reuse hp5 }
  5646. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  5647. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  5648. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  5649. Exit;
  5650. if MatchInstruction(hp5, A_RET, []) then
  5651. begin
  5652. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  5653. ConvertJumpToRET(hp3, hp5);
  5654. Result := True;
  5655. end
  5656. else
  5657. Exit;
  5658. end;
  5659. if (taicpu(hp6).opcode=A_JMP) then
  5660. begin
  5661. { Reuse hp5 }
  5662. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  5663. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  5664. Exit;
  5665. if MatchInstruction(hp5, A_RET, []) then
  5666. begin
  5667. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  5668. ConvertJumpToRET(hp6, hp5);
  5669. Result := True;
  5670. end
  5671. else
  5672. Exit;
  5673. end;
  5674. if not
  5675. (
  5676. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5677. (
  5678. (taicpu(hp6).opcode=A_RET) or
  5679. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5680. )
  5681. ) then
  5682. { Still doesn't match }
  5683. Exit;
  5684. end;
  5685. if (taicpu(hp2).oper[0]^.val = 1) then
  5686. begin
  5687. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5688. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  5689. end
  5690. else
  5691. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  5692. if taicpu(hp2).opsize=S_B then
  5693. begin
  5694. if taicpu(hp2).oper[1]^.typ = top_reg then
  5695. begin
  5696. SecondReg := taicpu(hp2).oper[1]^.reg;
  5697. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  5698. end
  5699. else
  5700. begin
  5701. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  5702. SecondReg := NR_NO;
  5703. end;
  5704. hp_pos := p;
  5705. hp_allocstart := hp4;
  5706. end
  5707. else
  5708. begin
  5709. { Will be a register because the size can't be S_B otherwise }
  5710. SecondReg:=taicpu(hp2).oper[1]^.reg;
  5711. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  5712. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  5713. if (cs_opt_size in current_settings.optimizerswitches) then
  5714. begin
  5715. { Favour using MOVZX when optimising for size }
  5716. case taicpu(hp2).opsize of
  5717. S_W:
  5718. NewSize := S_BW;
  5719. S_L:
  5720. NewSize := S_BL;
  5721. {$ifdef x86_64}
  5722. S_Q:
  5723. begin
  5724. NewSize := S_BL;
  5725. { Will implicitly zero-extend to 64-bit }
  5726. setsubreg(SecondReg, R_SUBD);
  5727. end;
  5728. {$endif x86_64}
  5729. else
  5730. InternalError(2022101301);
  5731. end;
  5732. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  5733. { Inserting it right before p will guarantee that the flags are also tracked }
  5734. Asml.InsertBefore(hp5, p);
  5735. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  5736. hp_pos := hp5;
  5737. hp_allocstart := hp4;
  5738. end
  5739. else
  5740. begin
  5741. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  5742. { Inserting it right before p will guarantee that the flags are also tracked }
  5743. Asml.InsertBefore(hp5, p);
  5744. hp_pos := p;
  5745. hp_allocstart := hp5;
  5746. end;
  5747. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  5748. end;
  5749. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  5750. taicpu(hp4).condition := taicpu(p).condition;
  5751. asml.InsertBefore(hp4, hp_pos);
  5752. if taicpu(hp3).is_jmp then
  5753. begin
  5754. JumpLoc.decrefs;
  5755. MakeUnconditional(taicpu(p));
  5756. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  5757. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  5758. end
  5759. else
  5760. ConvertJumpToRET(p, hp3);
  5761. if SecondReg <> NR_NO then
  5762. { Ensure the destination register is allocated over this region }
  5763. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  5764. if (JumpLoc.getrefs = 0) then
  5765. RemoveDeadCodeAfterJump(hp3);
  5766. Result:=true;
  5767. exit;
  5768. end;
  5769. end;
  5770. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  5771. var
  5772. hp1, hp2: tai;
  5773. ActiveReg: TRegister;
  5774. OldOffset: asizeint;
  5775. ThisConst: TCGInt;
  5776. function RegDeallocated: Boolean;
  5777. begin
  5778. TransferUsedRegs(TmpUsedRegs);
  5779. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5780. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5781. end;
  5782. begin
  5783. Result:=false;
  5784. hp1 := nil;
  5785. { replace
  5786. subX const,%reg1
  5787. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5788. dealloc %reg1
  5789. by
  5790. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  5791. }
  5792. if MatchOpType(taicpu(p),top_const,top_reg) then
  5793. begin
  5794. ActiveReg := taicpu(p).oper[1]^.reg;
  5795. { Ensures the entire register was updated }
  5796. if (taicpu(p).opsize >= S_L) and
  5797. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5798. MatchInstruction(hp1,A_LEA,[]) and
  5799. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5800. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5801. (
  5802. { Cover the case where the register in the reference is also the destination register }
  5803. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5804. (
  5805. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5806. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5807. RegDeallocated
  5808. )
  5809. ) then
  5810. begin
  5811. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5812. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5813. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5814. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5815. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5816. {$ifdef x86_64}
  5817. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5818. begin
  5819. { Overflow; abort }
  5820. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5821. end
  5822. else
  5823. {$endif x86_64}
  5824. begin
  5825. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  5826. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5827. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5828. RemoveCurrentP(p, hp1)
  5829. else
  5830. RemoveCurrentP(p);
  5831. result:=true;
  5832. Exit;
  5833. end;
  5834. end;
  5835. if (
  5836. { Save calling GetNextInstructionUsingReg again }
  5837. Assigned(hp1) or
  5838. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5839. ) and
  5840. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  5841. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5842. begin
  5843. if taicpu(hp1).oper[0]^.typ = top_const then
  5844. begin
  5845. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  5846. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5847. Result := True;
  5848. { Handle any overflows }
  5849. case taicpu(p).opsize of
  5850. S_B:
  5851. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5852. S_W:
  5853. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5854. S_L:
  5855. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5856. {$ifdef x86_64}
  5857. S_Q:
  5858. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5859. { Overflow; abort }
  5860. Result := False
  5861. else
  5862. taicpu(p).oper[0]^.val := ThisConst;
  5863. {$endif x86_64}
  5864. else
  5865. InternalError(2021102611);
  5866. end;
  5867. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5868. if Result then
  5869. begin
  5870. if (taicpu(p).oper[0]^.val < 0) and
  5871. (
  5872. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5873. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5874. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5875. ) then
  5876. begin
  5877. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  5878. taicpu(p).opcode := A_SUB;
  5879. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5880. end
  5881. else
  5882. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  5883. RemoveInstruction(hp1);
  5884. end;
  5885. end
  5886. else
  5887. begin
  5888. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  5889. TransferUsedRegs(TmpUsedRegs);
  5890. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5891. hp2 := p;
  5892. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5893. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5894. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5895. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5896. begin
  5897. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  5898. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  5899. Asml.Remove(p);
  5900. Asml.InsertAfter(p, hp1);
  5901. p := hp1;
  5902. Result := True;
  5903. Exit;
  5904. end;
  5905. end;
  5906. end;
  5907. { * change "subl $2, %esp; pushw x" to "pushl x"}
  5908. { * change "sub/add const1, reg" or "dec reg" followed by
  5909. "sub const2, reg" to one "sub ..., reg" }
  5910. {$ifdef i386}
  5911. if (taicpu(p).oper[0]^.val = 2) and
  5912. (ActiveReg = NR_ESP) and
  5913. { Don't do the sub/push optimization if the sub }
  5914. { comes from setting up the stack frame (JM) }
  5915. (not(GetLastInstruction(p,hp1)) or
  5916. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  5917. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  5918. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  5919. begin
  5920. hp1 := tai(p.next);
  5921. while Assigned(hp1) and
  5922. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  5923. not RegReadByInstruction(NR_ESP,hp1) and
  5924. not RegModifiedByInstruction(NR_ESP,hp1) do
  5925. hp1 := tai(hp1.next);
  5926. if Assigned(hp1) and
  5927. MatchInstruction(hp1,A_PUSH,[S_W]) then
  5928. begin
  5929. taicpu(hp1).changeopsize(S_L);
  5930. if taicpu(hp1).oper[0]^.typ=top_reg then
  5931. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  5932. hp1 := tai(p.next);
  5933. RemoveCurrentp(p, hp1);
  5934. Result:=true;
  5935. exit;
  5936. end;
  5937. end;
  5938. {$endif i386}
  5939. if DoArithCombineOpt(p) then
  5940. Result:=true;
  5941. end;
  5942. end;
  5943. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  5944. var
  5945. TmpBool1,TmpBool2 : Boolean;
  5946. tmpref : treference;
  5947. hp1,hp2: tai;
  5948. mask, shiftval: tcgint;
  5949. begin
  5950. Result:=false;
  5951. { All these optimisations work on "shl/sal const,%reg" }
  5952. if not MatchOpType(taicpu(p),top_const,top_reg) then
  5953. Exit;
  5954. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  5955. (taicpu(p).oper[0]^.val <= 3) then
  5956. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  5957. begin
  5958. { should we check the next instruction? }
  5959. TmpBool1 := True;
  5960. { have we found an add/sub which could be
  5961. integrated in the lea? }
  5962. TmpBool2 := False;
  5963. reference_reset(tmpref,2,[]);
  5964. TmpRef.index := taicpu(p).oper[1]^.reg;
  5965. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5966. while TmpBool1 and
  5967. GetNextInstruction(p, hp1) and
  5968. (tai(hp1).typ = ait_instruction) and
  5969. ((((taicpu(hp1).opcode = A_ADD) or
  5970. (taicpu(hp1).opcode = A_SUB)) and
  5971. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  5972. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  5973. (((taicpu(hp1).opcode = A_INC) or
  5974. (taicpu(hp1).opcode = A_DEC)) and
  5975. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5976. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  5977. ((taicpu(hp1).opcode = A_LEA) and
  5978. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5979. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  5980. (not GetNextInstruction(hp1,hp2) or
  5981. not instrReadsFlags(hp2)) Do
  5982. begin
  5983. TmpBool1 := False;
  5984. if taicpu(hp1).opcode=A_LEA then
  5985. begin
  5986. if (TmpRef.base = NR_NO) and
  5987. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  5988. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  5989. { Segment register isn't a concern here }
  5990. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  5991. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  5992. begin
  5993. TmpBool1 := True;
  5994. TmpBool2 := True;
  5995. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  5996. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  5997. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  5998. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  5999. RemoveInstruction(hp1);
  6000. end
  6001. end
  6002. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6003. begin
  6004. TmpBool1 := True;
  6005. TmpBool2 := True;
  6006. case taicpu(hp1).opcode of
  6007. A_ADD:
  6008. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6009. A_SUB:
  6010. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6011. else
  6012. internalerror(2019050536);
  6013. end;
  6014. RemoveInstruction(hp1);
  6015. end
  6016. else
  6017. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6018. (((taicpu(hp1).opcode = A_ADD) and
  6019. (TmpRef.base = NR_NO)) or
  6020. (taicpu(hp1).opcode = A_INC) or
  6021. (taicpu(hp1).opcode = A_DEC)) then
  6022. begin
  6023. TmpBool1 := True;
  6024. TmpBool2 := True;
  6025. case taicpu(hp1).opcode of
  6026. A_ADD:
  6027. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6028. A_INC:
  6029. inc(TmpRef.offset);
  6030. A_DEC:
  6031. dec(TmpRef.offset);
  6032. else
  6033. internalerror(2019050535);
  6034. end;
  6035. RemoveInstruction(hp1);
  6036. end;
  6037. end;
  6038. if TmpBool2
  6039. {$ifndef x86_64}
  6040. or
  6041. ((current_settings.optimizecputype < cpu_Pentium2) and
  6042. (taicpu(p).oper[0]^.val <= 3) and
  6043. not(cs_opt_size in current_settings.optimizerswitches))
  6044. {$endif x86_64}
  6045. then
  6046. begin
  6047. if not(TmpBool2) and
  6048. (taicpu(p).oper[0]^.val=1) then
  6049. begin
  6050. taicpu(p).opcode := A_ADD;
  6051. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6052. end
  6053. else
  6054. begin
  6055. taicpu(p).opcode := A_LEA;
  6056. taicpu(p).loadref(0, TmpRef);
  6057. end;
  6058. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6059. Result := True;
  6060. end;
  6061. end
  6062. {$ifndef x86_64}
  6063. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6064. begin
  6065. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6066. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6067. (unlike shl, which is only Tairable in the U pipe) }
  6068. if taicpu(p).oper[0]^.val=1 then
  6069. begin
  6070. taicpu(p).opcode := A_ADD;
  6071. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6072. Result := True;
  6073. end
  6074. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6075. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6076. else if (taicpu(p).opsize = S_L) and
  6077. (taicpu(p).oper[0]^.val<= 3) then
  6078. begin
  6079. reference_reset(tmpref,2,[]);
  6080. TmpRef.index := taicpu(p).oper[1]^.reg;
  6081. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6082. taicpu(p).opcode := A_LEA;
  6083. taicpu(p).loadref(0, TmpRef);
  6084. Result := True;
  6085. end;
  6086. end
  6087. {$endif x86_64}
  6088. else if
  6089. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6090. (
  6091. (
  6092. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6093. SetAndTest(hp1, hp2)
  6094. {$ifdef x86_64}
  6095. ) or
  6096. (
  6097. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6098. GetNextInstruction(hp1, hp2) and
  6099. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6100. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6101. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6102. {$endif x86_64}
  6103. )
  6104. ) and
  6105. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6106. begin
  6107. { Change:
  6108. shl x, %reg1
  6109. mov -(1<<x), %reg2
  6110. and %reg2, %reg1
  6111. Or:
  6112. shl x, %reg1
  6113. and -(1<<x), %reg1
  6114. To just:
  6115. shl x, %reg1
  6116. Since the and operation only zeroes bits that are already zero from the shl operation
  6117. }
  6118. case taicpu(p).oper[0]^.val of
  6119. 8:
  6120. mask:=$FFFFFFFFFFFFFF00;
  6121. 16:
  6122. mask:=$FFFFFFFFFFFF0000;
  6123. 32:
  6124. mask:=$FFFFFFFF00000000;
  6125. 63:
  6126. { Constant pre-calculated to prevent overflow errors with Int64 }
  6127. mask:=$8000000000000000;
  6128. else
  6129. begin
  6130. if taicpu(p).oper[0]^.val >= 64 then
  6131. { Shouldn't happen realistically, since the register
  6132. is guaranteed to be set to zero at this point }
  6133. mask := 0
  6134. else
  6135. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6136. end;
  6137. end;
  6138. if taicpu(hp1).oper[0]^.val = mask then
  6139. begin
  6140. { Everything checks out, perform the optimisation, as long as
  6141. the FLAGS register isn't being used}
  6142. TransferUsedRegs(TmpUsedRegs);
  6143. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6144. {$ifdef x86_64}
  6145. if (hp1 <> hp2) then
  6146. begin
  6147. { "shl/mov/and" version }
  6148. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6149. { Don't do the optimisation if the FLAGS register is in use }
  6150. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6151. begin
  6152. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6153. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6154. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6155. begin
  6156. RemoveInstruction(hp1);
  6157. Result := True;
  6158. end;
  6159. { Only set Result to True if the 'mov' instruction was removed }
  6160. RemoveInstruction(hp2);
  6161. end;
  6162. end
  6163. else
  6164. {$endif x86_64}
  6165. begin
  6166. { "shl/and" version }
  6167. { Don't do the optimisation if the FLAGS register is in use }
  6168. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6169. begin
  6170. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6171. RemoveInstruction(hp1);
  6172. Result := True;
  6173. end;
  6174. end;
  6175. Exit;
  6176. end
  6177. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6178. begin
  6179. { Even if the mask doesn't allow for its removal, we might be
  6180. able to optimise the mask for the "shl/and" version, which
  6181. may permit other peephole optimisations }
  6182. {$ifdef DEBUG_AOPTCPU}
  6183. mask := taicpu(hp1).oper[0]^.val and mask;
  6184. if taicpu(hp1).oper[0]^.val <> mask then
  6185. begin
  6186. DebugMsg(
  6187. SPeepholeOptimization +
  6188. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6189. ' to $' + debug_tostr(mask) +
  6190. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6191. taicpu(hp1).oper[0]^.val := mask;
  6192. end;
  6193. {$else DEBUG_AOPTCPU}
  6194. { If debugging is off, just set the operand even if it's the same }
  6195. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6196. {$endif DEBUG_AOPTCPU}
  6197. end;
  6198. end;
  6199. {
  6200. change
  6201. shl/sal const,reg
  6202. <op> ...(...,reg,1),...
  6203. into
  6204. <op> ...(...,reg,1 shl const),...
  6205. if const in 1..3
  6206. }
  6207. if MatchOpType(taicpu(p), top_const, top_reg) and
  6208. (taicpu(p).oper[0]^.val in [1..3]) and
  6209. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6210. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6211. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6212. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6213. MatchOpType(taicpu(hp1),top_ref))
  6214. ) and
  6215. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6216. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6217. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6218. begin
  6219. TransferUsedRegs(TmpUsedRegs);
  6220. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6221. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6222. begin
  6223. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6224. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6225. RemoveCurrentP(p);
  6226. Result:=true;
  6227. exit;
  6228. end;
  6229. end;
  6230. if MatchOpType(taicpu(p), top_const, top_reg) and
  6231. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6232. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  6233. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6234. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  6235. begin
  6236. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  6237. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  6238. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  6239. {$ifdef x86_64}
  6240. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  6241. {$endif x86_64}
  6242. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  6243. begin
  6244. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  6245. taicpu(hp1).opcode:=A_MOV;
  6246. taicpu(hp1).oper[0]^.val:=0;
  6247. end
  6248. else
  6249. begin
  6250. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  6251. taicpu(hp1).oper[0]^.val:=shiftval;
  6252. end;
  6253. RemoveCurrentP(p);
  6254. Result:=true;
  6255. exit;
  6256. end;
  6257. end;
  6258. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6259. begin
  6260. case shr_size of
  6261. S_B:
  6262. { No valid combinations }
  6263. Result := False;
  6264. S_W:
  6265. Result := (Shift >= 8) and (movz_size = S_BW);
  6266. S_L:
  6267. Result :=
  6268. (Shift >= 24) { Any opsize is valid for this shift } or
  6269. ((Shift >= 16) and (movz_size = S_WL));
  6270. {$ifdef x86_64}
  6271. S_Q:
  6272. Result :=
  6273. (Shift >= 56) { Any opsize is valid for this shift } or
  6274. ((Shift >= 48) and (movz_size = S_WL));
  6275. {$endif x86_64}
  6276. else
  6277. InternalError(2022081510);
  6278. end;
  6279. end;
  6280. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6281. var
  6282. hp1, hp2: tai;
  6283. Shift: TCGInt;
  6284. LimitSize: Topsize;
  6285. DoNotMerge: Boolean;
  6286. begin
  6287. Result := False;
  6288. { All these optimisations work on "shr const,%reg" }
  6289. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6290. Exit;
  6291. DoNotMerge := False;
  6292. Shift := taicpu(p).oper[0]^.val;
  6293. LimitSize := taicpu(p).opsize;
  6294. hp1 := p;
  6295. repeat
  6296. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6297. Exit;
  6298. case taicpu(hp1).opcode of
  6299. A_TEST, A_CMP, A_Jcc:
  6300. { Skip over conditional jumps and relevant comparisons }
  6301. Continue;
  6302. A_MOVZX:
  6303. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6304. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6305. begin
  6306. { Since the original register is being read as is, subsequent
  6307. SHRs must not be merged at this point }
  6308. DoNotMerge := True;
  6309. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6310. begin
  6311. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6312. begin
  6313. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6314. taicpu(hp1).opcode := A_MOV;
  6315. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6316. case taicpu(hp1).opsize of
  6317. S_BW:
  6318. taicpu(hp1).opsize := S_W;
  6319. S_BL, S_WL:
  6320. taicpu(hp1).opsize := S_L;
  6321. else
  6322. InternalError(2022081503);
  6323. end;
  6324. { p itself hasn't changed, so no need to set Result to True }
  6325. Include(OptsToCheck, aoc_ForceNewIteration);
  6326. { See if there's anything afterwards that can be
  6327. optimised, since the input register hasn't changed }
  6328. Continue;
  6329. end;
  6330. { NOTE: If the MOVZX instruction reads and writes the same
  6331. register, defer this to the post-peephole optimisation stage }
  6332. Exit;
  6333. end;
  6334. end;
  6335. A_SHL, A_SAL, A_SHR:
  6336. if (taicpu(hp1).opsize <= LimitSize) and
  6337. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6338. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  6339. begin
  6340. { Make sure the sizes don't exceed the register size limit
  6341. (measured by the shift value falling below the limit) }
  6342. if taicpu(hp1).opsize < LimitSize then
  6343. LimitSize := taicpu(hp1).opsize;
  6344. if taicpu(hp1).opcode = A_SHR then
  6345. Inc(Shift, taicpu(hp1).oper[0]^.val)
  6346. else
  6347. begin
  6348. Dec(Shift, taicpu(hp1).oper[0]^.val);
  6349. DoNotMerge := True;
  6350. end;
  6351. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  6352. Exit;
  6353. { Since we've established that the combined shift is within
  6354. limits, we can actually combine the adjacent SHR
  6355. instructions even if they're different sizes }
  6356. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  6357. begin
  6358. hp2 := tai(hp1.Previous);
  6359. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  6360. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  6361. RemoveInstruction(hp1);
  6362. hp1 := hp2;
  6363. { Though p has changed, only the constant has, and its
  6364. effects can still be detected on the next iteration of
  6365. the repeat..until loop }
  6366. Include(OptsToCheck, aoc_ForceNewIteration);
  6367. end;
  6368. { Move onto the next instruction }
  6369. Continue;
  6370. end;
  6371. else
  6372. ;
  6373. end;
  6374. Break;
  6375. until False;
  6376. end;
  6377. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  6378. var
  6379. CurrentRef: TReference;
  6380. FullReg: TRegister;
  6381. hp1, hp2: tai;
  6382. begin
  6383. Result := False;
  6384. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  6385. Exit;
  6386. { We assume you've checked if the operand is actually a reference by
  6387. this point. If it isn't, you'll most likely get an access violation }
  6388. CurrentRef := first_mov.oper[1]^.ref^;
  6389. { Memory must be aligned }
  6390. if (CurrentRef.offset mod 4) <> 0 then
  6391. Exit;
  6392. Inc(CurrentRef.offset);
  6393. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6394. if MatchOperand(second_mov.oper[0]^, 0) and
  6395. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  6396. GetNextInstruction(second_mov, hp1) and
  6397. (hp1.typ = ait_instruction) and
  6398. (taicpu(hp1).opcode = A_MOV) and
  6399. MatchOpType(taicpu(hp1), top_const, top_ref) and
  6400. (taicpu(hp1).oper[0]^.val = 0) then
  6401. begin
  6402. Inc(CurrentRef.offset);
  6403. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  6404. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  6405. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  6406. begin
  6407. case taicpu(hp1).opsize of
  6408. S_B:
  6409. if GetNextInstruction(hp1, hp2) and
  6410. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  6411. MatchOpType(taicpu(hp2), top_const, top_ref) and
  6412. (taicpu(hp2).oper[0]^.val = 0) then
  6413. begin
  6414. Inc(CurrentRef.offset);
  6415. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6416. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  6417. (taicpu(hp2).opsize = S_B) then
  6418. begin
  6419. RemoveInstruction(hp1);
  6420. RemoveInstruction(hp2);
  6421. first_mov.opsize := S_L;
  6422. if first_mov.oper[0]^.typ = top_reg then
  6423. begin
  6424. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  6425. { Reuse second_mov as a MOVZX instruction }
  6426. second_mov.opcode := A_MOVZX;
  6427. second_mov.opsize := S_BL;
  6428. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6429. second_mov.loadreg(1, FullReg);
  6430. first_mov.oper[0]^.reg := FullReg;
  6431. asml.Remove(second_mov);
  6432. asml.InsertBefore(second_mov, first_mov);
  6433. end
  6434. else
  6435. { It's a value }
  6436. begin
  6437. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  6438. RemoveInstruction(second_mov);
  6439. end;
  6440. Result := True;
  6441. Exit;
  6442. end;
  6443. end;
  6444. S_W:
  6445. begin
  6446. RemoveInstruction(hp1);
  6447. first_mov.opsize := S_L;
  6448. if first_mov.oper[0]^.typ = top_reg then
  6449. begin
  6450. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  6451. { Reuse second_mov as a MOVZX instruction }
  6452. second_mov.opcode := A_MOVZX;
  6453. second_mov.opsize := S_BL;
  6454. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6455. second_mov.loadreg(1, FullReg);
  6456. first_mov.oper[0]^.reg := FullReg;
  6457. asml.Remove(second_mov);
  6458. asml.InsertBefore(second_mov, first_mov);
  6459. end
  6460. else
  6461. { It's a value }
  6462. begin
  6463. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  6464. RemoveInstruction(second_mov);
  6465. end;
  6466. Result := True;
  6467. Exit;
  6468. end;
  6469. else
  6470. ;
  6471. end;
  6472. end;
  6473. end;
  6474. end;
  6475. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  6476. { returns true if a "continue" should be done after this optimization }
  6477. var
  6478. hp1, hp2, hp3: tai;
  6479. begin
  6480. Result := false;
  6481. hp3 := nil;
  6482. if MatchOpType(taicpu(p),top_ref) and
  6483. GetNextInstruction(p, hp1) and
  6484. (hp1.typ = ait_instruction) and
  6485. (((taicpu(hp1).opcode = A_FLD) and
  6486. (taicpu(p).opcode = A_FSTP)) or
  6487. ((taicpu(p).opcode = A_FISTP) and
  6488. (taicpu(hp1).opcode = A_FILD))) and
  6489. MatchOpType(taicpu(hp1),top_ref) and
  6490. (taicpu(hp1).opsize = taicpu(p).opsize) and
  6491. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6492. begin
  6493. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  6494. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  6495. GetNextInstruction(hp1, hp2) and
  6496. (((hp2.typ = ait_instruction) and
  6497. IsExitCode(hp2) and
  6498. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6499. not(assigned(current_procinfo.procdef.funcretsym) and
  6500. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  6501. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  6502. { fstp <temp>
  6503. fld <temp>
  6504. <dealloc> <temp>
  6505. }
  6506. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6507. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6508. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  6509. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6510. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  6511. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  6512. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  6513. )
  6514. )
  6515. ) then
  6516. begin
  6517. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  6518. RemoveInstruction(hp1);
  6519. RemoveCurrentP(p, hp2);
  6520. { first case: exit code }
  6521. if hp2.typ = ait_instruction then
  6522. RemoveLastDeallocForFuncRes(p);
  6523. Result := true;
  6524. end
  6525. else
  6526. { we can do this only in fast math mode as fstp is rounding ...
  6527. ... still disabled as it breaks the compiler and/or rtl }
  6528. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  6529. { ... or if another fstp equal to the first one follows }
  6530. GetNextInstruction(hp1,hp2) and
  6531. (hp2.typ = ait_instruction) and
  6532. (taicpu(p).opcode=taicpu(hp2).opcode) and
  6533. (taicpu(p).opsize=taicpu(hp2).opsize) then
  6534. begin
  6535. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6536. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6537. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  6538. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6539. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6540. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  6541. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  6542. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  6543. ) then
  6544. begin
  6545. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  6546. RemoveCurrentP(p,hp2);
  6547. RemoveInstruction(hp1);
  6548. Result := true;
  6549. end
  6550. else if { fst can't store an extended/comp value }
  6551. (taicpu(p).opsize <> S_FX) and
  6552. (taicpu(p).opsize <> S_IQ) then
  6553. begin
  6554. if (taicpu(p).opcode = A_FSTP) then
  6555. taicpu(p).opcode := A_FST
  6556. else
  6557. taicpu(p).opcode := A_FIST;
  6558. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  6559. RemoveInstruction(hp1);
  6560. Result := true;
  6561. end;
  6562. end;
  6563. end;
  6564. end;
  6565. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  6566. var
  6567. hp1, hp2, hp3: tai;
  6568. begin
  6569. result:=false;
  6570. if MatchOpType(taicpu(p),top_reg) and
  6571. GetNextInstruction(p, hp1) and
  6572. (hp1.typ = Ait_Instruction) and
  6573. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6574. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  6575. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  6576. { change to
  6577. fld reg fxxx reg,st
  6578. fxxxp st, st1 (hp1)
  6579. Remark: non commutative operations must be reversed!
  6580. }
  6581. begin
  6582. case taicpu(hp1).opcode Of
  6583. A_FMULP,A_FADDP,
  6584. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6585. begin
  6586. case taicpu(hp1).opcode Of
  6587. A_FADDP: taicpu(hp1).opcode := A_FADD;
  6588. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  6589. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  6590. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  6591. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  6592. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  6593. else
  6594. internalerror(2019050534);
  6595. end;
  6596. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  6597. taicpu(hp1).oper[1]^.reg := NR_ST;
  6598. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  6599. RemoveCurrentP(p, hp1);
  6600. Result:=true;
  6601. exit;
  6602. end;
  6603. else
  6604. ;
  6605. end;
  6606. end
  6607. else
  6608. if MatchOpType(taicpu(p),top_ref) and
  6609. GetNextInstruction(p, hp2) and
  6610. (hp2.typ = Ait_Instruction) and
  6611. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  6612. (taicpu(p).opsize in [S_FS, S_FL]) and
  6613. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  6614. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  6615. if GetLastInstruction(p, hp1) and
  6616. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  6617. MatchOpType(taicpu(hp1),top_ref) and
  6618. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6619. if ((taicpu(hp2).opcode = A_FMULP) or
  6620. (taicpu(hp2).opcode = A_FADDP)) then
  6621. { change to
  6622. fld/fst mem1 (hp1) fld/fst mem1
  6623. fld mem1 (p) fadd/
  6624. faddp/ fmul st, st
  6625. fmulp st, st1 (hp2) }
  6626. begin
  6627. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  6628. RemoveCurrentP(p, hp1);
  6629. if (taicpu(hp2).opcode = A_FADDP) then
  6630. taicpu(hp2).opcode := A_FADD
  6631. else
  6632. taicpu(hp2).opcode := A_FMUL;
  6633. taicpu(hp2).oper[1]^.reg := NR_ST;
  6634. end
  6635. else
  6636. { change to
  6637. fld/fst mem1 (hp1) fld/fst mem1
  6638. fld mem1 (p) fld st
  6639. }
  6640. begin
  6641. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  6642. taicpu(p).changeopsize(S_FL);
  6643. taicpu(p).loadreg(0,NR_ST);
  6644. end
  6645. else
  6646. begin
  6647. case taicpu(hp2).opcode Of
  6648. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6649. { change to
  6650. fld/fst mem1 (hp1) fld/fst mem1
  6651. fld mem2 (p) fxxx mem2
  6652. fxxxp st, st1 (hp2) }
  6653. begin
  6654. case taicpu(hp2).opcode Of
  6655. A_FADDP: taicpu(p).opcode := A_FADD;
  6656. A_FMULP: taicpu(p).opcode := A_FMUL;
  6657. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  6658. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  6659. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  6660. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  6661. else
  6662. internalerror(2019050533);
  6663. end;
  6664. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  6665. RemoveInstruction(hp2);
  6666. end
  6667. else
  6668. ;
  6669. end
  6670. end
  6671. end;
  6672. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  6673. begin
  6674. Result := condition_in(cond1, cond2) or
  6675. { Not strictly subsets due to the actual flags checked, but because we're
  6676. comparing integers, E is a subset of AE and GE and their aliases }
  6677. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  6678. end;
  6679. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  6680. var
  6681. v: TCGInt;
  6682. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  6683. FirstMatch, TempBool: Boolean;
  6684. NewReg: TRegister;
  6685. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  6686. begin
  6687. Result:=false;
  6688. { All these optimisations need a next instruction }
  6689. if not GetNextInstruction(p, hp1) then
  6690. Exit;
  6691. { Search for:
  6692. cmp ###,###
  6693. j(c1) @lbl1
  6694. ...
  6695. @lbl:
  6696. cmp ###,### (same comparison as above)
  6697. j(c2) @lbl2
  6698. If c1 is a subset of c2, change to:
  6699. cmp ###,###
  6700. j(c1) @lbl2
  6701. (@lbl1 may become a dead label as a result)
  6702. }
  6703. { Also handle cases where there are multiple jumps in a row }
  6704. p_jump := hp1;
  6705. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  6706. begin
  6707. if IsJumpToLabel(taicpu(p_jump)) then
  6708. begin
  6709. { Do jump optimisations first in case the condition becomes
  6710. unnecessary }
  6711. TempBool := True;
  6712. if DoJumpOptimizations(p_jump, TempBool) or
  6713. not TempBool then
  6714. begin
  6715. if Assigned(p_jump) then
  6716. begin
  6717. hp1 := p_jump;
  6718. if (p_jump.typ in [ait_align]) then
  6719. SkipAligns(p_jump, p_jump);
  6720. { CollapseZeroDistJump will be set to the label after the
  6721. jump if it optimises, whether or not it's live or dead }
  6722. if (p_jump.typ in [ait_label]) and
  6723. not (tai_label(p_jump).labsym.is_used) then
  6724. GetNextInstruction(p_jump, p_jump);
  6725. end;
  6726. TransferUsedRegs(TmpUsedRegs);
  6727. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6728. if not Assigned(p_jump) or
  6729. (
  6730. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  6731. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  6732. ) then
  6733. begin
  6734. { No more conditional jumps; conditional statement is no longer required }
  6735. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  6736. RemoveCurrentP(p);
  6737. Result := True;
  6738. Exit;
  6739. end;
  6740. hp1 := p_jump;
  6741. Include(OptsToCheck, aoc_ForceNewIteration);
  6742. Continue;
  6743. end;
  6744. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  6745. if GetNextInstruction(p_jump, hp2) and
  6746. (
  6747. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  6748. not TempBool
  6749. ) then
  6750. begin
  6751. hp1 := p_jump;
  6752. Include(OptsToCheck, aoc_ForceNewIteration);
  6753. Continue;
  6754. end;
  6755. p_label := nil;
  6756. if Assigned(JumpLabel) then
  6757. p_label := getlabelwithsym(JumpLabel);
  6758. if Assigned(p_label) and
  6759. GetNextInstruction(p_label, p_dist) and
  6760. MatchInstruction(p_dist, A_CMP, []) and
  6761. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  6762. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  6763. GetNextInstruction(p_dist, hp1_dist) and
  6764. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  6765. begin
  6766. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  6767. if JumpLabel = JumpLabel_dist then
  6768. { This is an infinite loop }
  6769. Exit;
  6770. { Best optimisation when the first condition is a subset (or equal) of the second }
  6771. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  6772. begin
  6773. { Any registers used here will already be allocated }
  6774. if Assigned(JumpLabel) then
  6775. JumpLabel.DecRefs;
  6776. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  6777. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  6778. Result := True;
  6779. { Don't exit yet. Since p and p_jump haven't actually been
  6780. removed, we can check for more on this iteration }
  6781. end
  6782. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  6783. GetNextInstruction(hp1_dist, hp1_label) and
  6784. SkipAligns(hp1_label, hp1_label) and
  6785. (hp1_label.typ = ait_label) then
  6786. begin
  6787. JumpLabel_far := tai_label(hp1_label).labsym;
  6788. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  6789. { This is an infinite loop }
  6790. Exit;
  6791. if Assigned(JumpLabel_far) then
  6792. begin
  6793. { In this situation, if the first jump branches, the second one will never,
  6794. branch so change the destination label to after the second jump }
  6795. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  6796. if Assigned(JumpLabel) then
  6797. JumpLabel.DecRefs;
  6798. JumpLabel_far.IncRefs;
  6799. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  6800. Result := True;
  6801. { Don't exit yet. Since p and p_jump haven't actually been
  6802. removed, we can check for more on this iteration }
  6803. Continue;
  6804. end;
  6805. end;
  6806. end;
  6807. end;
  6808. { Search for:
  6809. cmp ###,###
  6810. j(c1) @lbl1
  6811. cmp ###,### (same as first)
  6812. Remove second cmp
  6813. }
  6814. if GetNextInstruction(p_jump, hp2) and
  6815. (
  6816. (
  6817. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  6818. (
  6819. (
  6820. MatchOpType(taicpu(p), top_const, top_reg) and
  6821. MatchOpType(taicpu(hp2), top_const, top_reg) and
  6822. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  6823. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6824. ) or (
  6825. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  6826. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  6827. )
  6828. )
  6829. ) or (
  6830. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  6831. MatchOperand(taicpu(p).oper[0]^, 0) and
  6832. (taicpu(p).oper[1]^.typ = top_reg) and
  6833. MatchInstruction(hp2, A_TEST, []) and
  6834. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6835. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  6836. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6837. )
  6838. ) then
  6839. begin
  6840. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  6841. RemoveInstruction(hp2);
  6842. Result := True;
  6843. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  6844. end;
  6845. GetNextInstruction(p_jump, p_jump);
  6846. end;
  6847. {
  6848. Try to optimise the following:
  6849. cmp $x,### ($x and $y can be registers or constants)
  6850. je @lbl1 (only reference)
  6851. cmp $y,### (### are identical)
  6852. @Lbl:
  6853. sete %reg1
  6854. Change to:
  6855. cmp $x,###
  6856. sete %reg2 (allocate new %reg2)
  6857. cmp $y,###
  6858. sete %reg1
  6859. orb %reg2,%reg1
  6860. (dealloc %reg2)
  6861. This adds an instruction (so don't perform under -Os), but it removes
  6862. a conditional branch.
  6863. }
  6864. if not (cs_opt_size in current_settings.optimizerswitches) and
  6865. (
  6866. (hp1 = p_jump) or
  6867. GetNextInstruction(p, hp1)
  6868. ) and
  6869. MatchInstruction(hp1, A_Jcc, []) and
  6870. IsJumpToLabel(taicpu(hp1)) and
  6871. (taicpu(hp1).condition in [C_E, C_Z]) and
  6872. GetNextInstruction(hp1, hp2) and
  6873. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  6874. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  6875. { The first operand of CMP instructions can only be a register or
  6876. immediate anyway, so no need to check }
  6877. GetNextInstruction(hp2, p_label) and
  6878. (
  6879. (p_label.typ = ait_label) or
  6880. (
  6881. { Sometimes there's a zero-distance jump before the label, so deal with it here
  6882. to potentially cut down on the iterations of Pass 1 }
  6883. MatchInstruction(p_label, A_Jcc, []) and
  6884. IsJumpToLabel(taicpu(p_label)) and
  6885. { Use p_dist to hold the jump briefly }
  6886. SetAndTest(p_label, p_dist) and
  6887. GetNextInstruction(p_dist, p_label) and
  6888. (p_label.typ = ait_label) and
  6889. (tai_label(p_label).labsym.getrefs >= 2) and
  6890. (JumpTargetOp(taicpu(p_dist))^.ref^.symbol = tai_label(p_label).labsym) and
  6891. { We might as well collapse the jump now }
  6892. CollapseZeroDistJump(p_dist, tai_label(p_label).labsym)
  6893. )
  6894. ) and
  6895. (tai_label(p_label).labsym.getrefs = 1) and
  6896. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  6897. GetNextInstruction(p_label, p_dist) and
  6898. MatchInstruction(p_dist, A_SETcc, []) and
  6899. (taicpu(p_dist).condition in [C_E, C_Z]) and
  6900. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  6901. { Get the instruction after the SETcc instruction so we can
  6902. allocate a new register over the entire range }
  6903. GetNextInstruction(p_dist, hp1_dist) then
  6904. begin
  6905. TransferUsedRegs(TmpUsedRegs);
  6906. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6907. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6908. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  6909. // UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  6910. { RegUsedAfterInstruction modifies TmpUsedRegs }
  6911. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  6912. begin
  6913. { Register can appear in p if it's not used afterwards, so only
  6914. allocate between hp1 and hp1_dist }
  6915. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, p_dist);
  6916. if NewReg <> NR_NO then
  6917. begin
  6918. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  6919. { Change the jump instruction into a SETcc instruction }
  6920. taicpu(hp1).opcode := A_SETcc;
  6921. taicpu(hp1).opsize := S_B;
  6922. taicpu(hp1).loadreg(0, NewReg);
  6923. { This is now a dead label }
  6924. tai_label(p_label).labsym.decrefs;
  6925. { Prefer adding before the next instruction so the FLAGS
  6926. register is deallocated first }
  6927. hp2 := taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg);
  6928. taicpu(hp2).fileinfo := taicpu(p_dist).fileinfo;
  6929. AsmL.InsertBefore(
  6930. hp2,
  6931. hp1_dist
  6932. );
  6933. { Make sure the new register is in use over the new instruction
  6934. (long-winded, but things work best when the FLAGS register
  6935. is not allocated here) }
  6936. AllocRegBetween(NewReg, p_dist, hp2, TmpUsedRegs);
  6937. Result := True;
  6938. { Don't exit yet, as p wasn't changed and hp1, while
  6939. modified, is still intact and might be optimised by the
  6940. SETcc optimisation below }
  6941. end;
  6942. end;
  6943. end;
  6944. if taicpu(p).oper[0]^.typ = top_const then
  6945. begin
  6946. if (taicpu(p).oper[0]^.val = 0) and
  6947. (taicpu(p).oper[1]^.typ = top_reg) and
  6948. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  6949. begin
  6950. hp2 := p;
  6951. FirstMatch := True;
  6952. { When dealing with "cmp $0,%reg", only ZF and SF contain
  6953. anything meaningful once it's converted to "test %reg,%reg";
  6954. additionally, some jumps will always (or never) branch, so
  6955. evaluate every jump immediately following the
  6956. comparison, optimising the conditions if possible.
  6957. Similarly with SETcc... those that are always set to 0 or 1
  6958. are changed to MOV instructions }
  6959. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  6960. (
  6961. GetNextInstruction(hp2, hp1) and
  6962. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  6963. ) do
  6964. begin
  6965. FirstMatch := False;
  6966. case taicpu(hp1).condition of
  6967. C_B, C_C, C_NAE, C_O:
  6968. { For B/NAE:
  6969. Will never branch since an unsigned integer can never be below zero
  6970. For C/O:
  6971. Result cannot overflow because 0 is being subtracted
  6972. }
  6973. begin
  6974. if taicpu(hp1).opcode = A_Jcc then
  6975. begin
  6976. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  6977. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  6978. RemoveInstruction(hp1);
  6979. { Since hp1 was deleted, hp2 must not be updated }
  6980. Continue;
  6981. end
  6982. else
  6983. begin
  6984. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  6985. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  6986. taicpu(hp1).opcode := A_MOV;
  6987. taicpu(hp1).ops := 2;
  6988. taicpu(hp1).condition := C_None;
  6989. taicpu(hp1).opsize := S_B;
  6990. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6991. taicpu(hp1).loadconst(0, 0);
  6992. end;
  6993. end;
  6994. C_BE, C_NA:
  6995. begin
  6996. { Will only branch if equal to zero }
  6997. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  6998. taicpu(hp1).condition := C_E;
  6999. end;
  7000. C_A, C_NBE:
  7001. begin
  7002. { Will only branch if not equal to zero }
  7003. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7004. taicpu(hp1).condition := C_NE;
  7005. end;
  7006. C_AE, C_NB, C_NC, C_NO:
  7007. begin
  7008. { Will always branch }
  7009. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7010. if taicpu(hp1).opcode = A_Jcc then
  7011. begin
  7012. MakeUnconditional(taicpu(hp1));
  7013. { Any jumps/set that follow will now be dead code }
  7014. RemoveDeadCodeAfterJump(taicpu(hp1));
  7015. Break;
  7016. end
  7017. else
  7018. begin
  7019. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7020. taicpu(hp1).opcode := A_MOV;
  7021. taicpu(hp1).ops := 2;
  7022. taicpu(hp1).condition := C_None;
  7023. taicpu(hp1).opsize := S_B;
  7024. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7025. taicpu(hp1).loadconst(0, 1);
  7026. end;
  7027. end;
  7028. C_None:
  7029. InternalError(2020012201);
  7030. C_P, C_PE, C_NP, C_PO:
  7031. { We can't handle parity checks and they should never be generated
  7032. after a general-purpose CMP (it's used in some floating-point
  7033. comparisons that don't use CMP) }
  7034. InternalError(2020012202);
  7035. else
  7036. { Zero/Equality, Sign, their complements and all of the
  7037. signed comparisons do not need to be converted };
  7038. end;
  7039. hp2 := hp1;
  7040. end;
  7041. { Convert the instruction to a TEST }
  7042. taicpu(p).opcode := A_TEST;
  7043. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7044. Result := True;
  7045. Exit;
  7046. end
  7047. else if (taicpu(p).oper[0]^.val = 1) and
  7048. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7049. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7050. begin
  7051. { Convert; To:
  7052. cmp $1,r/m cmp $0,r/m
  7053. jl @lbl jle @lbl
  7054. (Also do inverted conditions)
  7055. }
  7056. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7057. taicpu(p).oper[0]^.val := 0;
  7058. if taicpu(hp1).condition in [C_L, C_NGE] then
  7059. taicpu(hp1).condition := C_LE
  7060. else
  7061. taicpu(hp1).condition := C_NLE;
  7062. { If the instruction is now "cmp $0,%reg", convert it to a
  7063. TEST (and effectively do the work of the "cmp $0,%reg" in
  7064. the block above)
  7065. }
  7066. if (taicpu(p).oper[1]^.typ = top_reg) then
  7067. begin
  7068. taicpu(p).opcode := A_TEST;
  7069. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7070. end;
  7071. Result := True;
  7072. Exit;
  7073. end
  7074. else if (taicpu(p).oper[1]^.typ = top_reg)
  7075. {$ifdef x86_64}
  7076. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7077. {$endif x86_64}
  7078. then
  7079. begin
  7080. { cmp register,$8000 neg register
  7081. je target --> jo target
  7082. .... only if register is deallocated before jump.}
  7083. case Taicpu(p).opsize of
  7084. S_B: v:=$80;
  7085. S_W: v:=$8000;
  7086. S_L: v:=qword($80000000);
  7087. else
  7088. internalerror(2013112905);
  7089. end;
  7090. if (taicpu(p).oper[0]^.val=v) and
  7091. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7092. (Taicpu(hp1).condition in [C_E,C_NE]) then
  7093. begin
  7094. TransferUsedRegs(TmpUsedRegs);
  7095. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  7096. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  7097. begin
  7098. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  7099. Taicpu(p).opcode:=A_NEG;
  7100. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  7101. Taicpu(p).clearop(1);
  7102. Taicpu(p).ops:=1;
  7103. if Taicpu(hp1).condition=C_E then
  7104. Taicpu(hp1).condition:=C_O
  7105. else
  7106. Taicpu(hp1).condition:=C_NO;
  7107. Result:=true;
  7108. exit;
  7109. end;
  7110. end;
  7111. end;
  7112. end;
  7113. if TrySwapMovCmp(p, hp1) then
  7114. begin
  7115. Result := True;
  7116. Exit;
  7117. end;
  7118. end;
  7119. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  7120. var
  7121. hp1: tai;
  7122. begin
  7123. {
  7124. remove the second (v)pxor from
  7125. pxor reg,reg
  7126. ...
  7127. pxor reg,reg
  7128. }
  7129. Result:=false;
  7130. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7131. MatchOpType(taicpu(p),top_reg,top_reg) and
  7132. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7133. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7134. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7135. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7136. begin
  7137. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7138. RemoveInstruction(hp1);
  7139. Result:=true;
  7140. Exit;
  7141. end
  7142. {
  7143. replace
  7144. pxor reg1,reg1
  7145. movapd/s reg1,reg2
  7146. dealloc reg1
  7147. by
  7148. pxor reg2,reg2
  7149. }
  7150. else if GetNextInstruction(p,hp1) and
  7151. { we mix single and double opperations here because we assume that the compiler
  7152. generates vmovapd only after double operations and vmovaps only after single operations }
  7153. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7154. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7155. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7156. (taicpu(p).oper[0]^.typ=top_reg) then
  7157. begin
  7158. TransferUsedRegs(TmpUsedRegs);
  7159. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7160. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7161. begin
  7162. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7163. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7164. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7165. RemoveInstruction(hp1);
  7166. result:=true;
  7167. end;
  7168. end;
  7169. end;
  7170. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7171. var
  7172. hp1: tai;
  7173. begin
  7174. {
  7175. remove the second (v)pxor from
  7176. (v)pxor reg,reg
  7177. ...
  7178. (v)pxor reg,reg
  7179. }
  7180. Result:=false;
  7181. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7182. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7183. begin
  7184. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7185. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7186. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7187. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7188. begin
  7189. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7190. RemoveInstruction(hp1);
  7191. Result:=true;
  7192. Exit;
  7193. end;
  7194. {$ifdef x86_64}
  7195. {
  7196. replace
  7197. vpxor reg1,reg1,reg1
  7198. vmov reg,mem
  7199. by
  7200. movq $0,mem
  7201. }
  7202. if GetNextInstruction(p,hp1) and
  7203. MatchInstruction(hp1,A_VMOVSD,[]) and
  7204. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7205. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7206. begin
  7207. TransferUsedRegs(TmpUsedRegs);
  7208. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7209. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7210. begin
  7211. taicpu(hp1).loadconst(0,0);
  7212. taicpu(hp1).opcode:=A_MOV;
  7213. taicpu(hp1).opsize:=S_Q;
  7214. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7215. RemoveCurrentP(p);
  7216. result:=true;
  7217. Exit;
  7218. end;
  7219. end;
  7220. {$endif x86_64}
  7221. end
  7222. {
  7223. replace
  7224. vpxor reg1,reg1,reg2
  7225. by
  7226. vpxor reg2,reg2,reg2
  7227. to avoid unncessary data dependencies
  7228. }
  7229. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7230. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7231. begin
  7232. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7233. { avoid unncessary data dependency }
  7234. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7235. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7236. result:=true;
  7237. exit;
  7238. end;
  7239. Result:=OptPass1VOP(p);
  7240. end;
  7241. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7242. var
  7243. hp1 : tai;
  7244. begin
  7245. result:=false;
  7246. { replace
  7247. IMul const,%mreg1,%mreg2
  7248. Mov %reg2,%mreg3
  7249. dealloc %mreg3
  7250. by
  7251. Imul const,%mreg1,%mreg23
  7252. }
  7253. if (taicpu(p).ops=3) and
  7254. GetNextInstruction(p,hp1) and
  7255. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7256. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7257. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7258. begin
  7259. TransferUsedRegs(TmpUsedRegs);
  7260. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7261. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7262. begin
  7263. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7264. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7265. RemoveInstruction(hp1);
  7266. result:=true;
  7267. end;
  7268. end;
  7269. end;
  7270. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7271. var
  7272. hp1 : tai;
  7273. begin
  7274. result:=false;
  7275. { replace
  7276. IMul %reg0,%reg1,%reg2
  7277. Mov %reg2,%reg3
  7278. dealloc %reg2
  7279. by
  7280. Imul %reg0,%reg1,%reg3
  7281. }
  7282. if GetNextInstruction(p,hp1) and
  7283. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7284. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7285. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7286. begin
  7287. TransferUsedRegs(TmpUsedRegs);
  7288. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7289. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7290. begin
  7291. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7292. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  7293. RemoveInstruction(hp1);
  7294. result:=true;
  7295. end;
  7296. end;
  7297. end;
  7298. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  7299. var
  7300. hp1: tai;
  7301. begin
  7302. Result:=false;
  7303. { get rid of
  7304. (v)cvtss2sd reg0,<reg1,>reg2
  7305. (v)cvtss2sd reg2,<reg2,>reg0
  7306. }
  7307. if GetNextInstruction(p,hp1) and
  7308. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  7309. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  7310. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  7311. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  7312. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  7313. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7314. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7315. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  7316. )
  7317. ) then
  7318. begin
  7319. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7320. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  7321. begin
  7322. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  7323. RemoveCurrentP(p);
  7324. RemoveInstruction(hp1);
  7325. end
  7326. else
  7327. begin
  7328. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  7329. if taicpu(hp1).opcode=A_CVTSD2SS then
  7330. begin
  7331. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7332. taicpu(p).opcode:=A_MOVAPS;
  7333. end
  7334. else
  7335. begin
  7336. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  7337. taicpu(p).opcode:=A_VMOVAPS;
  7338. end;
  7339. taicpu(p).ops:=2;
  7340. RemoveInstruction(hp1);
  7341. end;
  7342. Result:=true;
  7343. Exit;
  7344. end;
  7345. end;
  7346. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  7347. var
  7348. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  7349. ThisReg: TRegister;
  7350. begin
  7351. Result := False;
  7352. if not GetNextInstruction(p,hp1) then
  7353. Exit;
  7354. {
  7355. convert
  7356. j<c> .L1
  7357. mov 1,reg
  7358. jmp .L2
  7359. .L1
  7360. mov 0,reg
  7361. .L2
  7362. into
  7363. mov 0,reg
  7364. set<not(c)> reg
  7365. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7366. would destroy the flag contents
  7367. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  7368. executed at the same time as a previous comparison.
  7369. set<not(c)> reg
  7370. movzx reg, reg
  7371. }
  7372. if MatchInstruction(hp1,A_MOV,[]) and
  7373. (taicpu(hp1).oper[0]^.typ = top_const) and
  7374. (
  7375. (
  7376. (taicpu(hp1).oper[1]^.typ = top_reg)
  7377. {$ifdef i386}
  7378. { Under i386, ESI, EDI, EBP and ESP
  7379. don't have an 8-bit representation }
  7380. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7381. {$endif i386}
  7382. ) or (
  7383. {$ifdef i386}
  7384. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  7385. {$endif i386}
  7386. (taicpu(hp1).opsize = S_B)
  7387. )
  7388. ) and
  7389. GetNextInstruction(hp1,hp2) and
  7390. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7391. GetNextInstruction(hp2,hp3) and
  7392. SkipAligns(hp3, hp3) and
  7393. (hp3.typ=ait_label) and
  7394. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7395. GetNextInstruction(hp3,hp4) and
  7396. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  7397. (taicpu(hp4).oper[0]^.typ = top_const) and
  7398. (
  7399. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  7400. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  7401. ) and
  7402. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7403. GetNextInstruction(hp4,hp5) and
  7404. SkipAligns(hp5, hp5) and
  7405. (hp5.typ=ait_label) and
  7406. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  7407. begin
  7408. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7409. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7410. tai_label(hp3).labsym.DecRefs;
  7411. { If this isn't the only reference to the middle label, we can
  7412. still make a saving - only that the first jump and everything
  7413. that follows will remain. }
  7414. if (tai_label(hp3).labsym.getrefs = 0) then
  7415. begin
  7416. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7417. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  7418. else
  7419. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  7420. { remove jump, first label and second MOV (also catching any aligns) }
  7421. repeat
  7422. if not GetNextInstruction(hp2, hp3) then
  7423. InternalError(2021040810);
  7424. RemoveInstruction(hp2);
  7425. hp2 := hp3;
  7426. until hp2 = hp5;
  7427. { Don't decrement reference count before the removal loop
  7428. above, otherwise GetNextInstruction won't stop on the
  7429. the label }
  7430. tai_label(hp5).labsym.DecRefs;
  7431. end
  7432. else
  7433. begin
  7434. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7435. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  7436. else
  7437. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  7438. end;
  7439. taicpu(p).opcode:=A_SETcc;
  7440. taicpu(p).opsize:=S_B;
  7441. taicpu(p).is_jmp:=False;
  7442. if taicpu(hp1).opsize=S_B then
  7443. begin
  7444. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  7445. if taicpu(hp1).oper[1]^.typ = top_reg then
  7446. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  7447. RemoveInstruction(hp1);
  7448. end
  7449. else
  7450. begin
  7451. { Will be a register because the size can't be S_B otherwise }
  7452. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  7453. taicpu(p).loadreg(0, ThisReg);
  7454. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  7455. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  7456. begin
  7457. case taicpu(hp1).opsize of
  7458. S_W:
  7459. taicpu(hp1).opsize := S_BW;
  7460. S_L:
  7461. taicpu(hp1).opsize := S_BL;
  7462. {$ifdef x86_64}
  7463. S_Q:
  7464. begin
  7465. taicpu(hp1).opsize := S_BL;
  7466. { Change the destination register to 32-bit }
  7467. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  7468. end;
  7469. {$endif x86_64}
  7470. else
  7471. InternalError(2021040820);
  7472. end;
  7473. taicpu(hp1).opcode := A_MOVZX;
  7474. taicpu(hp1).loadreg(0, ThisReg);
  7475. end
  7476. else
  7477. begin
  7478. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  7479. { hp1 is already a MOV instruction with the correct register }
  7480. taicpu(hp1).loadconst(0, 0);
  7481. { Inserting it right before p will guarantee that the flags are also tracked }
  7482. asml.Remove(hp1);
  7483. asml.InsertBefore(hp1, p);
  7484. end;
  7485. end;
  7486. Result:=true;
  7487. exit;
  7488. end
  7489. else if (hp1.typ = ait_label) then
  7490. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  7491. end;
  7492. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  7493. var
  7494. hp1, hp2, hp3: tai;
  7495. SourceRef, TargetRef: TReference;
  7496. CurrentReg: TRegister;
  7497. begin
  7498. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  7499. if not UseAVX then
  7500. InternalError(2021100501);
  7501. Result := False;
  7502. { Look for the following to simplify:
  7503. vmovdqa/u x(mem1), %xmmreg
  7504. vmovdqa/u %xmmreg, y(mem2)
  7505. vmovdqa/u x+16(mem1), %xmmreg
  7506. vmovdqa/u %xmmreg, y+16(mem2)
  7507. Change to:
  7508. vmovdqa/u x(mem1), %ymmreg
  7509. vmovdqa/u %ymmreg, y(mem2)
  7510. vpxor %ymmreg, %ymmreg, %ymmreg
  7511. ( The VPXOR instruction is to zero the upper half, thus removing the
  7512. need to call the potentially expensive VZEROUPPER instruction. Other
  7513. peephole optimisations can remove VPXOR if it's unnecessary )
  7514. }
  7515. TransferUsedRegs(TmpUsedRegs);
  7516. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7517. { NOTE: In the optimisations below, if the references dictate that an
  7518. aligned move is possible (i.e. VMOVDQA), the existing instructions
  7519. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  7520. if (taicpu(p).opsize = S_XMM) and
  7521. MatchOpType(taicpu(p), top_ref, top_reg) and
  7522. GetNextInstruction(p, hp1) and
  7523. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7524. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  7525. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  7526. begin
  7527. SourceRef := taicpu(p).oper[0]^.ref^;
  7528. TargetRef := taicpu(hp1).oper[1]^.ref^;
  7529. if GetNextInstruction(hp1, hp2) and
  7530. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7531. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  7532. begin
  7533. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  7534. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7535. Inc(SourceRef.offset, 16);
  7536. { Reuse the register in the first block move }
  7537. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  7538. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  7539. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  7540. begin
  7541. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7542. Inc(TargetRef.offset, 16);
  7543. if GetNextInstruction(hp2, hp3) and
  7544. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7545. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7546. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7547. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7548. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7549. begin
  7550. { Update the register tracking to the new size }
  7551. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  7552. { Remember that the offsets are 16 ahead }
  7553. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7554. if not (
  7555. ((SourceRef.offset mod 32) = 16) and
  7556. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7557. ) then
  7558. taicpu(p).opcode := A_VMOVDQU;
  7559. taicpu(p).opsize := S_YMM;
  7560. taicpu(p).oper[1]^.reg := CurrentReg;
  7561. if not (
  7562. ((TargetRef.offset mod 32) = 16) and
  7563. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7564. ) then
  7565. taicpu(hp1).opcode := A_VMOVDQU;
  7566. taicpu(hp1).opsize := S_YMM;
  7567. taicpu(hp1).oper[0]^.reg := CurrentReg;
  7568. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  7569. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7570. if (pi_uses_ymm in current_procinfo.flags) then
  7571. RemoveInstruction(hp2)
  7572. else
  7573. begin
  7574. taicpu(hp2).opcode := A_VPXOR;
  7575. taicpu(hp2).opsize := S_YMM;
  7576. taicpu(hp2).loadreg(0, CurrentReg);
  7577. taicpu(hp2).loadreg(1, CurrentReg);
  7578. taicpu(hp2).loadreg(2, CurrentReg);
  7579. taicpu(hp2).ops := 3;
  7580. end;
  7581. RemoveInstruction(hp3);
  7582. Result := True;
  7583. Exit;
  7584. end;
  7585. end
  7586. else
  7587. begin
  7588. { See if the next references are 16 less rather than 16 greater }
  7589. Dec(SourceRef.offset, 32); { -16 the other way }
  7590. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  7591. begin
  7592. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7593. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  7594. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  7595. GetNextInstruction(hp2, hp3) and
  7596. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  7597. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7598. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7599. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7600. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7601. begin
  7602. { Update the register tracking to the new size }
  7603. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  7604. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  7605. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7606. if not(
  7607. ((SourceRef.offset mod 32) = 0) and
  7608. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7609. ) then
  7610. taicpu(hp2).opcode := A_VMOVDQU;
  7611. taicpu(hp2).opsize := S_YMM;
  7612. taicpu(hp2).oper[1]^.reg := CurrentReg;
  7613. if not (
  7614. ((TargetRef.offset mod 32) = 0) and
  7615. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7616. ) then
  7617. taicpu(hp3).opcode := A_VMOVDQU;
  7618. taicpu(hp3).opsize := S_YMM;
  7619. taicpu(hp3).oper[0]^.reg := CurrentReg;
  7620. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  7621. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7622. if (pi_uses_ymm in current_procinfo.flags) then
  7623. RemoveInstruction(hp1)
  7624. else
  7625. begin
  7626. taicpu(hp1).opcode := A_VPXOR;
  7627. taicpu(hp1).opsize := S_YMM;
  7628. taicpu(hp1).loadreg(0, CurrentReg);
  7629. taicpu(hp1).loadreg(1, CurrentReg);
  7630. taicpu(hp1).loadreg(2, CurrentReg);
  7631. taicpu(hp1).ops := 3;
  7632. Asml.Remove(hp1);
  7633. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  7634. end;
  7635. RemoveCurrentP(p, hp2);
  7636. Result := True;
  7637. Exit;
  7638. end;
  7639. end;
  7640. end;
  7641. end;
  7642. end;
  7643. end;
  7644. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  7645. var
  7646. hp2, hp3, first_assignment: tai;
  7647. IncCount, OperIdx: Integer;
  7648. OrigLabel: TAsmLabel;
  7649. begin
  7650. Count := 0;
  7651. Result := False;
  7652. first_assignment := nil;
  7653. if (LoopCount >= 20) then
  7654. begin
  7655. { Guard against infinite loops }
  7656. Exit;
  7657. end;
  7658. if (taicpu(p).oper[0]^.typ <> top_ref) or
  7659. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  7660. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  7661. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  7662. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  7663. Exit;
  7664. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  7665. {
  7666. change
  7667. jmp .L1
  7668. ...
  7669. .L1:
  7670. mov ##, ## ( multiple movs possible )
  7671. jmp/ret
  7672. into
  7673. mov ##, ##
  7674. jmp/ret
  7675. }
  7676. if not Assigned(hp1) then
  7677. begin
  7678. hp1 := GetLabelWithSym(OrigLabel);
  7679. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  7680. Exit;
  7681. end;
  7682. hp2 := hp1;
  7683. while Assigned(hp2) do
  7684. begin
  7685. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  7686. SkipLabels(hp2,hp2);
  7687. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  7688. Break;
  7689. case taicpu(hp2).opcode of
  7690. A_MOVSD:
  7691. begin
  7692. if taicpu(hp2).ops = 0 then
  7693. { Wrong MOVSD }
  7694. Break;
  7695. Inc(Count);
  7696. if Count >= 5 then
  7697. { Too many to be worthwhile }
  7698. Break;
  7699. GetNextInstruction(hp2, hp2);
  7700. Continue;
  7701. end;
  7702. A_MOV,
  7703. A_MOVD,
  7704. A_MOVQ,
  7705. A_MOVSX,
  7706. {$ifdef x86_64}
  7707. A_MOVSXD,
  7708. {$endif x86_64}
  7709. A_MOVZX,
  7710. A_MOVAPS,
  7711. A_MOVUPS,
  7712. A_MOVSS,
  7713. A_MOVAPD,
  7714. A_MOVUPD,
  7715. A_MOVDQA,
  7716. A_MOVDQU,
  7717. A_VMOVSS,
  7718. A_VMOVAPS,
  7719. A_VMOVUPS,
  7720. A_VMOVSD,
  7721. A_VMOVAPD,
  7722. A_VMOVUPD,
  7723. A_VMOVDQA,
  7724. A_VMOVDQU:
  7725. begin
  7726. Inc(Count);
  7727. if Count >= 5 then
  7728. { Too many to be worthwhile }
  7729. Break;
  7730. GetNextInstruction(hp2, hp2);
  7731. Continue;
  7732. end;
  7733. A_JMP:
  7734. begin
  7735. { Guard against infinite loops }
  7736. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  7737. Exit;
  7738. { Analyse this jump first in case it also duplicates assignments }
  7739. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  7740. begin
  7741. { Something did change! }
  7742. Result := True;
  7743. Inc(Count, IncCount);
  7744. if Count >= 5 then
  7745. begin
  7746. { Too many to be worthwhile }
  7747. Exit;
  7748. end;
  7749. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  7750. Break;
  7751. end;
  7752. Result := True;
  7753. Break;
  7754. end;
  7755. A_RET:
  7756. begin
  7757. Result := True;
  7758. Break;
  7759. end;
  7760. else
  7761. Break;
  7762. end;
  7763. end;
  7764. if Result then
  7765. begin
  7766. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  7767. if Count = 0 then
  7768. begin
  7769. Result := False;
  7770. Exit;
  7771. end;
  7772. hp3 := p;
  7773. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  7774. while True do
  7775. begin
  7776. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  7777. SkipLabels(hp1,hp1);
  7778. if (hp1.typ <> ait_instruction) then
  7779. InternalError(2021040720);
  7780. case taicpu(hp1).opcode of
  7781. A_JMP:
  7782. begin
  7783. { Change the original jump to the new destination }
  7784. OrigLabel.decrefs;
  7785. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  7786. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  7787. { Set p to the first duplicated assignment so it can get optimised if needs be }
  7788. if not Assigned(first_assignment) then
  7789. InternalError(2021040810)
  7790. else
  7791. p := first_assignment;
  7792. Exit;
  7793. end;
  7794. A_RET:
  7795. begin
  7796. { Now change the jump into a RET instruction }
  7797. ConvertJumpToRET(p, hp1);
  7798. { Set p to the first duplicated assignment so it can get optimised if needs be }
  7799. if not Assigned(first_assignment) then
  7800. InternalError(2021040811)
  7801. else
  7802. p := first_assignment;
  7803. Exit;
  7804. end;
  7805. else
  7806. begin
  7807. { Duplicate the MOV instruction }
  7808. hp3:=tai(hp1.getcopy);
  7809. if first_assignment = nil then
  7810. first_assignment := hp3;
  7811. asml.InsertBefore(hp3, p);
  7812. { Make sure the compiler knows about any final registers written here }
  7813. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  7814. with taicpu(hp3).oper[OperIdx]^ do
  7815. begin
  7816. case typ of
  7817. top_ref:
  7818. begin
  7819. if (ref^.base <> NR_NO) and
  7820. (getsupreg(ref^.base) <> RS_ESP) and
  7821. (getsupreg(ref^.base) <> RS_EBP)
  7822. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  7823. then
  7824. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  7825. if (ref^.index <> NR_NO) and
  7826. (getsupreg(ref^.index) <> RS_ESP) and
  7827. (getsupreg(ref^.index) <> RS_EBP)
  7828. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  7829. (ref^.index <> ref^.base) then
  7830. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  7831. end;
  7832. top_reg:
  7833. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  7834. else
  7835. ;
  7836. end;
  7837. end;
  7838. end;
  7839. end;
  7840. if not GetNextInstruction(hp1, hp1) then
  7841. { Should have dropped out earlier }
  7842. InternalError(2021040710);
  7843. end;
  7844. end;
  7845. end;
  7846. const
  7847. WriteOp: array[0..3] of set of TInsChange = (
  7848. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  7849. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  7850. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  7851. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  7852. RegWriteFlags: array[0..7] of set of TInsChange = (
  7853. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  7854. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  7855. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  7856. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  7857. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  7858. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  7859. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  7860. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  7861. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  7862. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  7863. var
  7864. hp2: tai;
  7865. X: Integer;
  7866. begin
  7867. { If we have something like:
  7868. op ###,###
  7869. mov ###,###
  7870. Try to move the MOV instruction to before OP as long as OP and MOV don't
  7871. interfere in regards to what they write to.
  7872. NOTE: p must be a 2-operand instruction
  7873. }
  7874. Result := False;
  7875. if (hp1.typ <> ait_instruction) or
  7876. taicpu(hp1).is_jmp or
  7877. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  7878. Exit;
  7879. { NOP is a pipeline fence, likely marking the beginning of the function
  7880. epilogue, so drop out. Similarly, drop out if POP or RET are
  7881. encountered }
  7882. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  7883. Exit;
  7884. if (taicpu(hp1).opcode = A_MOVSD) and
  7885. (taicpu(hp1).ops = 0) then
  7886. { Wrong MOVSD }
  7887. Exit;
  7888. { Check for writes to specific registers first }
  7889. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  7890. for X := 0 to 7 do
  7891. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  7892. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  7893. Exit;
  7894. for X := 0 to taicpu(hp1).ops - 1 do
  7895. begin
  7896. { Check to see if this operand writes to something }
  7897. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  7898. { And matches something in the CMP/TEST instruction }
  7899. (
  7900. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  7901. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  7902. (
  7903. { If it's a register, make sure the register written to doesn't
  7904. appear in the cmp instruction as part of a reference }
  7905. (taicpu(hp1).oper[X]^.typ = top_reg) and
  7906. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  7907. )
  7908. ) then
  7909. Exit;
  7910. end;
  7911. { Check p to make sure it doesn't write to something that affects hp1 }
  7912. { Check for writes to specific registers first }
  7913. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  7914. for X := 0 to 7 do
  7915. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  7916. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  7917. Exit;
  7918. for X := 0 to taicpu(p).ops - 1 do
  7919. begin
  7920. { Check to see if this operand writes to something }
  7921. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  7922. { And matches something in hp1 }
  7923. (taicpu(p).oper[X]^.typ = top_reg) and
  7924. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  7925. Exit;
  7926. end;
  7927. { The instruction can be safely moved }
  7928. asml.Remove(hp1);
  7929. { Try to insert before the FLAGS register is allocated, so "mov $0,%reg"
  7930. can be optimised into "xor %reg,%reg" later }
  7931. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  7932. asml.InsertBefore(hp1, hp2)
  7933. { Failing that, try to insert after the last instructions where the
  7934. FLAGS register is not yet in use }
  7935. else if GetLastInstruction(p, hp2) and
  7936. (
  7937. (hp2.typ <> ait_instruction) or
  7938. { Don't insert after an instruction that uses the flags when p doesn't use them }
  7939. RegInInstruction(NR_DEFAULTFLAGS, p) or
  7940. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  7941. ) then
  7942. asml.InsertAfter(hp1, hp2)
  7943. else
  7944. { Note, if p.Previous is nil (even if it should logically never be the
  7945. case), FindRegAllocBackward immediately exits with False and so we
  7946. safely land here (we can't just pass p because FindRegAllocBackward
  7947. immediately exits on an instruction). [Kit] }
  7948. asml.InsertBefore(hp1, p);
  7949. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  7950. { We can't trust UsedRegs because we're looking backwards, although we
  7951. know the registers are allocated after p at the very least, so manually
  7952. create tai_regalloc objects if needed }
  7953. for X := 0 to taicpu(hp1).ops - 1 do
  7954. case taicpu(hp1).oper[X]^.typ of
  7955. top_reg:
  7956. begin
  7957. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  7958. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  7959. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  7960. end;
  7961. top_ref:
  7962. begin
  7963. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  7964. begin
  7965. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  7966. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  7967. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  7968. end;
  7969. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  7970. begin
  7971. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  7972. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  7973. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  7974. end;
  7975. end;
  7976. else
  7977. ;
  7978. end;
  7979. Result := True;
  7980. end;
  7981. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  7982. var
  7983. hp2: tai;
  7984. X: Integer;
  7985. begin
  7986. { If we have something like:
  7987. cmp ###,%reg1
  7988. mov 0,%reg2
  7989. And no modified registers are shared, move the instruction to before
  7990. the comparison as this means it can be optimised without worrying
  7991. about the FLAGS register. (CMP/MOV is generated by
  7992. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  7993. As long as the second instruction doesn't use the flags or one of the
  7994. registers used by CMP or TEST (also check any references that use the
  7995. registers), then it can be moved prior to the comparison.
  7996. }
  7997. Result := False;
  7998. if not TrySwapMovOp(p, hp1) then
  7999. Exit;
  8000. if taicpu(hp1).opcode = A_LEA then
  8001. { The flags will be overwritten by the CMP/TEST instruction }
  8002. ConvertLEA(taicpu(hp1));
  8003. Result := True;
  8004. { Can we move it one further back? }
  8005. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8006. { Check to see if CMP/TEST is a comparison against zero }
  8007. (
  8008. (
  8009. (taicpu(p).opcode = A_CMP) and
  8010. MatchOperand(taicpu(p).oper[0]^, 0)
  8011. ) or
  8012. (
  8013. (taicpu(p).opcode = A_TEST) and
  8014. (
  8015. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8016. MatchOperand(taicpu(p).oper[0]^, -1)
  8017. )
  8018. )
  8019. ) and
  8020. { These instructions set the zero flag if the result is zero }
  8021. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  8022. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  8023. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  8024. TrySwapMovOp(hp2, hp1);
  8025. end;
  8026. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  8027. function IsXCHGAcceptable: Boolean; inline;
  8028. begin
  8029. { Always accept if optimising for size }
  8030. Result := (cs_opt_size in current_settings.optimizerswitches) or
  8031. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  8032. than 3, so it becomes a saving compared to three MOVs with two of
  8033. them able to execute simultaneously. [Kit] }
  8034. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  8035. end;
  8036. var
  8037. NewRef: TReference;
  8038. hp1, hp2, hp3, hp4: Tai;
  8039. {$ifndef x86_64}
  8040. OperIdx: Integer;
  8041. {$endif x86_64}
  8042. NewInstr : Taicpu;
  8043. NewAligh : Tai_align;
  8044. DestLabel: TAsmLabel;
  8045. function TryMovArith2Lea(InputInstr: tai): Boolean;
  8046. var
  8047. NextInstr: tai;
  8048. begin
  8049. Result := False;
  8050. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  8051. if not GetNextInstruction(InputInstr, NextInstr) or
  8052. (
  8053. { The FLAGS register isn't always tracked properly, so do not
  8054. perform this optimisation if a conditional statement follows }
  8055. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  8056. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  8057. ) then
  8058. begin
  8059. reference_reset(NewRef, 1, []);
  8060. NewRef.base := taicpu(p).oper[0]^.reg;
  8061. NewRef.scalefactor := 1;
  8062. if taicpu(InputInstr).opcode = A_ADD then
  8063. begin
  8064. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  8065. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  8066. end
  8067. else
  8068. begin
  8069. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  8070. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  8071. end;
  8072. taicpu(p).opcode := A_LEA;
  8073. taicpu(p).loadref(0, NewRef);
  8074. RemoveInstruction(InputInstr);
  8075. Result := True;
  8076. end;
  8077. end;
  8078. begin
  8079. Result:=false;
  8080. { This optimisation adds an instruction, so only do it for speed }
  8081. if not (cs_opt_size in current_settings.optimizerswitches) and
  8082. MatchOpType(taicpu(p), top_const, top_reg) and
  8083. (taicpu(p).oper[0]^.val = 0) then
  8084. begin
  8085. { To avoid compiler warning }
  8086. DestLabel := nil;
  8087. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  8088. InternalError(2021040750);
  8089. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  8090. Exit;
  8091. case hp1.typ of
  8092. ait_align,
  8093. ait_label:
  8094. begin
  8095. { Change:
  8096. mov $0,%reg mov $0,%reg
  8097. @Lbl1: @Lbl1:
  8098. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  8099. je @Lbl2 jne @Lbl2
  8100. To: To:
  8101. mov $0,%reg mov $0,%reg
  8102. jmp @Lbl2 jmp @Lbl3
  8103. (align) (align)
  8104. @Lbl1: @Lbl1:
  8105. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  8106. je @Lbl2 je @Lbl2
  8107. @Lbl3: <-- Only if label exists
  8108. (Not if it's optimised for size)
  8109. }
  8110. if not SkipAligns(hp1, hp1) or not GetNextInstruction(hp1, hp2) then
  8111. Exit;
  8112. if (hp2.typ = ait_instruction) and
  8113. (
  8114. { Register sizes must exactly match }
  8115. (
  8116. (taicpu(hp2).opcode = A_CMP) and
  8117. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  8118. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8119. ) or (
  8120. (taicpu(hp2).opcode = A_TEST) and
  8121. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8122. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8123. )
  8124. ) and GetNextInstruction(hp2, hp3) and
  8125. (hp3.typ = ait_instruction) and
  8126. (taicpu(hp3).opcode = A_JCC) and
  8127. (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
  8128. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  8129. begin
  8130. { Check condition of jump }
  8131. { Always true? }
  8132. if condition_in(C_E, taicpu(hp3).condition) then
  8133. begin
  8134. { Copy label symbol and obtain matching label entry for the
  8135. conditional jump, as this will be our destination}
  8136. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  8137. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  8138. Result := True;
  8139. end
  8140. { Always false? }
  8141. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  8142. begin
  8143. { This is only worth it if there's a jump to take }
  8144. case hp2.typ of
  8145. ait_instruction:
  8146. begin
  8147. if taicpu(hp2).opcode = A_JMP then
  8148. begin
  8149. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8150. { An unconditional jump follows the conditional jump which will always be false,
  8151. so use this jump's destination for the new jump }
  8152. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  8153. Result := True;
  8154. end
  8155. else if taicpu(hp2).opcode = A_JCC then
  8156. begin
  8157. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8158. if condition_in(C_E, taicpu(hp2).condition) then
  8159. begin
  8160. { A second conditional jump follows the conditional jump which will always be false,
  8161. while the second jump is always True, so use this jump's destination for the new jump }
  8162. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  8163. Result := True;
  8164. end;
  8165. { Don't risk it if the jump isn't always true (Result remains False) }
  8166. end;
  8167. end;
  8168. else
  8169. { If anything else don't optimise };
  8170. end;
  8171. end;
  8172. if Result then
  8173. begin
  8174. { Just so we have something to insert as a paremeter}
  8175. reference_reset(NewRef, 1, []);
  8176. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  8177. { Now actually load the correct parameter (this also
  8178. increases the reference count) }
  8179. NewInstr.loadsymbol(0, DestLabel, 0);
  8180. if (cs_opt_level3 in current_settings.optimizerswitches) then
  8181. begin
  8182. { Get instruction before original label (may not be p under -O3) }
  8183. if not GetLastInstruction(hp1, hp2) then
  8184. { Shouldn't fail here }
  8185. InternalError(2021040701);
  8186. { Before the aligns too }
  8187. while (hp2.typ = ait_align) do
  8188. if not GetLastInstruction(hp2, hp2) then
  8189. { Shouldn't fail here }
  8190. InternalError(2021040702);
  8191. end
  8192. else
  8193. hp2 := p;
  8194. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  8195. AsmL.InsertAfter(NewInstr, hp2);
  8196. { Add new alignment field }
  8197. (* AsmL.InsertAfter(
  8198. cai_align.create_max(
  8199. current_settings.alignment.jumpalign,
  8200. current_settings.alignment.jumpalignskipmax
  8201. ),
  8202. NewInstr
  8203. ); *)
  8204. end;
  8205. Exit;
  8206. end;
  8207. end;
  8208. else
  8209. ;
  8210. end;
  8211. end;
  8212. if not GetNextInstruction(p, hp1) then
  8213. Exit;
  8214. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  8215. and DoMovCmpMemOpt(p, hp1, True) then
  8216. begin
  8217. Result := True;
  8218. Exit;
  8219. end
  8220. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  8221. begin
  8222. { Sometimes the MOVs that OptPass2JMP produces can be improved
  8223. further, but we can't just put this jump optimisation in pass 1
  8224. because it tends to perform worse when conditional jumps are
  8225. nearby (e.g. when converting CMOV instructions). [Kit] }
  8226. if OptPass2JMP(hp1) then
  8227. { call OptPass1MOV once to potentially merge any MOVs that were created }
  8228. Result := OptPass1MOV(p)
  8229. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  8230. returned True and the instruction is still a MOV, thus checking
  8231. the optimisations below }
  8232. { If OptPass2JMP returned False, no optimisations were done to
  8233. the jump and there are no further optimisations that can be done
  8234. to the MOV instruction on this pass }
  8235. end
  8236. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8237. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  8238. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8239. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8240. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8241. begin
  8242. { Change:
  8243. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  8244. addl/q $x,%reg2 subl/q $x,%reg2
  8245. To:
  8246. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  8247. }
  8248. if (taicpu(hp1).oper[0]^.typ = top_const) and
  8249. { be lazy, checking separately for sub would be slightly better }
  8250. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  8251. begin
  8252. TransferUsedRegs(TmpUsedRegs);
  8253. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8254. if TryMovArith2Lea(hp1) then
  8255. begin
  8256. Result := True;
  8257. Exit;
  8258. end
  8259. end
  8260. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  8261. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  8262. { Same as above, but also adds or subtracts to %reg2 in between.
  8263. It's still valid as long as the flags aren't in use }
  8264. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8265. MatchOpType(taicpu(hp2), top_const, top_reg) and
  8266. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  8267. { be lazy, checking separately for sub would be slightly better }
  8268. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  8269. begin
  8270. TransferUsedRegs(TmpUsedRegs);
  8271. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8272. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8273. if TryMovArith2Lea(hp2) then
  8274. begin
  8275. Result := True;
  8276. Exit;
  8277. end;
  8278. end;
  8279. end
  8280. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8281. {$ifdef x86_64}
  8282. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  8283. {$else x86_64}
  8284. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  8285. {$endif x86_64}
  8286. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8287. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  8288. { mov reg1, reg2 mov reg1, reg2
  8289. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  8290. begin
  8291. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  8292. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  8293. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  8294. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  8295. TransferUsedRegs(TmpUsedRegs);
  8296. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8297. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  8298. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  8299. then
  8300. begin
  8301. RemoveCurrentP(p, hp1);
  8302. Result:=true;
  8303. end;
  8304. exit;
  8305. end
  8306. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8307. IsXCHGAcceptable and
  8308. { XCHG doesn't support 8-byte registers }
  8309. (taicpu(p).opsize <> S_B) and
  8310. MatchInstruction(hp1, A_MOV, []) and
  8311. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8312. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  8313. GetNextInstruction(hp1, hp2) and
  8314. MatchInstruction(hp2, A_MOV, []) and
  8315. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  8316. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8317. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  8318. begin
  8319. { mov %reg1,%reg2
  8320. mov %reg3,%reg1 -> xchg %reg3,%reg1
  8321. mov %reg2,%reg3
  8322. (%reg2 not used afterwards)
  8323. Note that xchg takes 3 cycles to execute, and generally mov's take
  8324. only one cycle apiece, but the first two mov's can be executed in
  8325. parallel, only taking 2 cycles overall. Older processors should
  8326. therefore only optimise for size. [Kit]
  8327. }
  8328. TransferUsedRegs(TmpUsedRegs);
  8329. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8330. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8331. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  8332. begin
  8333. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  8334. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  8335. taicpu(hp1).opcode := A_XCHG;
  8336. RemoveCurrentP(p, hp1);
  8337. RemoveInstruction(hp2);
  8338. Result := True;
  8339. Exit;
  8340. end;
  8341. end
  8342. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8343. MatchInstruction(hp1, A_SAR, []) then
  8344. begin
  8345. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  8346. begin
  8347. { the use of %edx also covers the opsize being S_L }
  8348. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  8349. begin
  8350. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  8351. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  8352. (taicpu(p).oper[1]^.reg = NR_EDX) then
  8353. begin
  8354. { Change:
  8355. movl %eax,%edx
  8356. sarl $31,%edx
  8357. To:
  8358. cltd
  8359. }
  8360. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  8361. RemoveInstruction(hp1);
  8362. taicpu(p).opcode := A_CDQ;
  8363. taicpu(p).opsize := S_NO;
  8364. taicpu(p).clearop(1);
  8365. taicpu(p).clearop(0);
  8366. taicpu(p).ops:=0;
  8367. Result := True;
  8368. end
  8369. else if (cs_opt_size in current_settings.optimizerswitches) and
  8370. (taicpu(p).oper[0]^.reg = NR_EDX) and
  8371. (taicpu(p).oper[1]^.reg = NR_EAX) then
  8372. begin
  8373. { Change:
  8374. movl %edx,%eax
  8375. sarl $31,%edx
  8376. To:
  8377. movl %edx,%eax
  8378. cltd
  8379. Note that this creates a dependency between the two instructions,
  8380. so only perform if optimising for size.
  8381. }
  8382. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  8383. taicpu(hp1).opcode := A_CDQ;
  8384. taicpu(hp1).opsize := S_NO;
  8385. taicpu(hp1).clearop(1);
  8386. taicpu(hp1).clearop(0);
  8387. taicpu(hp1).ops:=0;
  8388. end;
  8389. {$ifndef x86_64}
  8390. end
  8391. { Don't bother if CMOV is supported, because a more optimal
  8392. sequence would have been generated for the Abs() intrinsic }
  8393. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  8394. { the use of %eax also covers the opsize being S_L }
  8395. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  8396. (taicpu(p).oper[0]^.reg = NR_EAX) and
  8397. (taicpu(p).oper[1]^.reg = NR_EDX) and
  8398. GetNextInstruction(hp1, hp2) and
  8399. MatchInstruction(hp2, A_XOR, [S_L]) and
  8400. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  8401. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  8402. GetNextInstruction(hp2, hp3) and
  8403. MatchInstruction(hp3, A_SUB, [S_L]) and
  8404. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  8405. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  8406. begin
  8407. { Change:
  8408. movl %eax,%edx
  8409. sarl $31,%eax
  8410. xorl %eax,%edx
  8411. subl %eax,%edx
  8412. (Instruction that uses %edx)
  8413. (%eax deallocated)
  8414. (%edx deallocated)
  8415. To:
  8416. cltd
  8417. xorl %edx,%eax <-- Note the registers have swapped
  8418. subl %edx,%eax
  8419. (Instruction that uses %eax) <-- %eax rather than %edx
  8420. }
  8421. TransferUsedRegs(TmpUsedRegs);
  8422. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8423. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8424. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8425. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  8426. begin
  8427. if GetNextInstruction(hp3, hp4) and
  8428. not RegModifiedByInstruction(NR_EDX, hp4) and
  8429. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  8430. begin
  8431. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  8432. taicpu(p).opcode := A_CDQ;
  8433. taicpu(p).clearop(1);
  8434. taicpu(p).clearop(0);
  8435. taicpu(p).ops:=0;
  8436. RemoveInstruction(hp1);
  8437. taicpu(hp2).loadreg(0, NR_EDX);
  8438. taicpu(hp2).loadreg(1, NR_EAX);
  8439. taicpu(hp3).loadreg(0, NR_EDX);
  8440. taicpu(hp3).loadreg(1, NR_EAX);
  8441. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  8442. { Convert references in the following instruction (hp4) from %edx to %eax }
  8443. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  8444. with taicpu(hp4).oper[OperIdx]^ do
  8445. case typ of
  8446. top_reg:
  8447. if getsupreg(reg) = RS_EDX then
  8448. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8449. top_ref:
  8450. begin
  8451. if getsupreg(reg) = RS_EDX then
  8452. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8453. if getsupreg(reg) = RS_EDX then
  8454. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8455. end;
  8456. else
  8457. ;
  8458. end;
  8459. end;
  8460. end;
  8461. {$else x86_64}
  8462. end;
  8463. end
  8464. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  8465. { the use of %rdx also covers the opsize being S_Q }
  8466. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  8467. begin
  8468. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  8469. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  8470. (taicpu(p).oper[1]^.reg = NR_RDX) then
  8471. begin
  8472. { Change:
  8473. movq %rax,%rdx
  8474. sarq $63,%rdx
  8475. To:
  8476. cqto
  8477. }
  8478. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  8479. RemoveInstruction(hp1);
  8480. taicpu(p).opcode := A_CQO;
  8481. taicpu(p).opsize := S_NO;
  8482. taicpu(p).clearop(1);
  8483. taicpu(p).clearop(0);
  8484. taicpu(p).ops:=0;
  8485. Result := True;
  8486. end
  8487. else if (cs_opt_size in current_settings.optimizerswitches) and
  8488. (taicpu(p).oper[0]^.reg = NR_RDX) and
  8489. (taicpu(p).oper[1]^.reg = NR_RAX) then
  8490. begin
  8491. { Change:
  8492. movq %rdx,%rax
  8493. sarq $63,%rdx
  8494. To:
  8495. movq %rdx,%rax
  8496. cqto
  8497. Note that this creates a dependency between the two instructions,
  8498. so only perform if optimising for size.
  8499. }
  8500. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  8501. taicpu(hp1).opcode := A_CQO;
  8502. taicpu(hp1).opsize := S_NO;
  8503. taicpu(hp1).clearop(1);
  8504. taicpu(hp1).clearop(0);
  8505. taicpu(hp1).ops:=0;
  8506. {$endif x86_64}
  8507. end;
  8508. end;
  8509. end
  8510. else if MatchInstruction(hp1, A_MOV, []) and
  8511. (taicpu(hp1).oper[1]^.typ = top_reg) then
  8512. { Though "GetNextInstruction" could be factored out, along with
  8513. the instructions that depend on hp2, it is an expensive call that
  8514. should be delayed for as long as possible, hence we do cheaper
  8515. checks first that are likely to be False. [Kit] }
  8516. begin
  8517. if (
  8518. (
  8519. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  8520. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  8521. (
  8522. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8523. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  8524. )
  8525. ) or
  8526. (
  8527. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  8528. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  8529. (
  8530. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8531. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  8532. )
  8533. )
  8534. ) and
  8535. GetNextInstruction(hp1, hp2) and
  8536. MatchInstruction(hp2, A_SAR, []) and
  8537. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  8538. begin
  8539. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  8540. begin
  8541. { Change:
  8542. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  8543. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  8544. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  8545. To:
  8546. movl r/m,%eax <- Note the change in register
  8547. cltd
  8548. }
  8549. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  8550. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  8551. taicpu(p).loadreg(1, NR_EAX);
  8552. taicpu(hp1).opcode := A_CDQ;
  8553. taicpu(hp1).clearop(1);
  8554. taicpu(hp1).clearop(0);
  8555. taicpu(hp1).ops:=0;
  8556. RemoveInstruction(hp2);
  8557. (*
  8558. {$ifdef x86_64}
  8559. end
  8560. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  8561. { This code sequence does not get generated - however it might become useful
  8562. if and when 128-bit signed integer types make an appearance, so the code
  8563. is kept here for when it is eventually needed. [Kit] }
  8564. (
  8565. (
  8566. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  8567. (
  8568. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8569. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  8570. )
  8571. ) or
  8572. (
  8573. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  8574. (
  8575. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8576. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  8577. )
  8578. )
  8579. ) and
  8580. GetNextInstruction(hp1, hp2) and
  8581. MatchInstruction(hp2, A_SAR, [S_Q]) and
  8582. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  8583. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  8584. begin
  8585. { Change:
  8586. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  8587. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  8588. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  8589. To:
  8590. movq r/m,%rax <- Note the change in register
  8591. cqto
  8592. }
  8593. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  8594. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  8595. taicpu(p).loadreg(1, NR_RAX);
  8596. taicpu(hp1).opcode := A_CQO;
  8597. taicpu(hp1).clearop(1);
  8598. taicpu(hp1).clearop(0);
  8599. taicpu(hp1).ops:=0;
  8600. RemoveInstruction(hp2);
  8601. {$endif x86_64}
  8602. *)
  8603. end;
  8604. end;
  8605. {$ifdef x86_64}
  8606. end
  8607. else if (taicpu(p).opsize = S_L) and
  8608. (taicpu(p).oper[1]^.typ = top_reg) and
  8609. (
  8610. MatchInstruction(hp1, A_MOV,[]) and
  8611. (taicpu(hp1).opsize = S_L) and
  8612. (taicpu(hp1).oper[1]^.typ = top_reg)
  8613. ) and (
  8614. GetNextInstruction(hp1, hp2) and
  8615. (tai(hp2).typ=ait_instruction) and
  8616. (taicpu(hp2).opsize = S_Q) and
  8617. (
  8618. (
  8619. MatchInstruction(hp2, A_ADD,[]) and
  8620. (taicpu(hp2).opsize = S_Q) and
  8621. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  8622. (
  8623. (
  8624. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8625. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8626. ) or (
  8627. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8628. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8629. )
  8630. )
  8631. ) or (
  8632. MatchInstruction(hp2, A_LEA,[]) and
  8633. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  8634. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  8635. (
  8636. (
  8637. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8638. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8639. ) or (
  8640. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8641. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  8642. )
  8643. ) and (
  8644. (
  8645. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8646. ) or (
  8647. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8648. )
  8649. )
  8650. )
  8651. )
  8652. ) and (
  8653. GetNextInstruction(hp2, hp3) and
  8654. MatchInstruction(hp3, A_SHR,[]) and
  8655. (taicpu(hp3).opsize = S_Q) and
  8656. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  8657. (taicpu(hp3).oper[0]^.val = 1) and
  8658. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  8659. ) then
  8660. begin
  8661. { Change movl x, reg1d movl x, reg1d
  8662. movl y, reg2d movl y, reg2d
  8663. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  8664. shrq $1, reg1q shrq $1, reg1q
  8665. ( reg1d and reg2d can be switched around in the first two instructions )
  8666. To movl x, reg1d
  8667. addl y, reg1d
  8668. rcrl $1, reg1d
  8669. This corresponds to the common expression (x + y) shr 1, where
  8670. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  8671. smaller code, but won't account for x + y causing an overflow). [Kit]
  8672. }
  8673. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  8674. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  8675. { Change first MOV command to have the same register as the final output }
  8676. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  8677. else
  8678. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  8679. { Change second MOV command to an ADD command. This is easier than
  8680. converting the existing command because it means we don't have to
  8681. touch 'y', which might be a complicated reference, and also the
  8682. fact that the third command might either be ADD or LEA. [Kit] }
  8683. taicpu(hp1).opcode := A_ADD;
  8684. { Delete old ADD/LEA instruction }
  8685. RemoveInstruction(hp2);
  8686. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  8687. taicpu(hp3).opcode := A_RCR;
  8688. taicpu(hp3).changeopsize(S_L);
  8689. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  8690. {$endif x86_64}
  8691. end;
  8692. if FuncMov2Func(p, hp1) then
  8693. begin
  8694. Result := True;
  8695. Exit;
  8696. end;
  8697. end;
  8698. {$push}
  8699. {$q-}{$r-}
  8700. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  8701. var
  8702. ThisReg: TRegister;
  8703. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  8704. TargetSubReg: TSubRegister;
  8705. hp1, hp2: tai;
  8706. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  8707. { Store list of found instructions so we don't have to call
  8708. GetNextInstructionUsingReg multiple times }
  8709. InstrList: array of taicpu;
  8710. InstrMax, Index: Integer;
  8711. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  8712. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  8713. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  8714. WorkingValue: TCgInt;
  8715. PreMessage: string;
  8716. { Data flow analysis }
  8717. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  8718. BitwiseOnly, OrXorUsed,
  8719. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  8720. function CheckOverflowConditions: Boolean;
  8721. begin
  8722. Result := True;
  8723. if (TestValSignedMax > SignedUpperLimit) then
  8724. UpperSignedOverflow := True;
  8725. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  8726. LowerSignedOverflow := True;
  8727. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  8728. LowerUnsignedOverflow := True;
  8729. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  8730. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  8731. begin
  8732. { Absolute overflow }
  8733. Result := False;
  8734. Exit;
  8735. end;
  8736. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  8737. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  8738. ShiftDownOverflow := True;
  8739. if (TestValMin < 0) or (TestValMax < 0) then
  8740. begin
  8741. LowerUnsignedOverflow := True;
  8742. UpperUnsignedOverflow := True;
  8743. end;
  8744. end;
  8745. function AdjustInitialLoadAndSize: Boolean;
  8746. begin
  8747. Result := False;
  8748. if not p_removed then
  8749. begin
  8750. if TargetSize = MinSize then
  8751. begin
  8752. { Convert the input MOVZX to a MOV }
  8753. if (taicpu(p).oper[0]^.typ = top_reg) and
  8754. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  8755. begin
  8756. { Or remove it completely! }
  8757. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  8758. RemoveCurrentP(p);
  8759. p_removed := True;
  8760. end
  8761. else
  8762. begin
  8763. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  8764. taicpu(p).opcode := A_MOV;
  8765. taicpu(p).oper[1]^.reg := ThisReg;
  8766. taicpu(p).opsize := TargetSize;
  8767. end;
  8768. Result := True;
  8769. end
  8770. else if TargetSize <> MaxSize then
  8771. begin
  8772. case MaxSize of
  8773. S_L:
  8774. if TargetSize = S_W then
  8775. begin
  8776. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  8777. taicpu(p).opsize := S_BW;
  8778. taicpu(p).oper[1]^.reg := ThisReg;
  8779. Result := True;
  8780. end
  8781. else
  8782. InternalError(2020112341);
  8783. S_W:
  8784. if TargetSize = S_L then
  8785. begin
  8786. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  8787. taicpu(p).opsize := S_BL;
  8788. taicpu(p).oper[1]^.reg := ThisReg;
  8789. Result := True;
  8790. end
  8791. else
  8792. InternalError(2020112342);
  8793. else
  8794. ;
  8795. end;
  8796. end
  8797. else if not hp1_removed and not RegInUse then
  8798. begin
  8799. { If we have something like:
  8800. movzbl (oper),%regd
  8801. add x, %regd
  8802. movzbl %regb, %regd
  8803. We can reduce the register size to the input of the final
  8804. movzbl instruction. Overflows won't have any effect.
  8805. }
  8806. if (taicpu(p).opsize in [S_BW, S_BL]) and
  8807. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  8808. begin
  8809. TargetSize := S_B;
  8810. setsubreg(ThisReg, R_SUBL);
  8811. Result := True;
  8812. end
  8813. else if (taicpu(p).opsize = S_WL) and
  8814. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  8815. begin
  8816. TargetSize := S_W;
  8817. setsubreg(ThisReg, R_SUBW);
  8818. Result := True;
  8819. end;
  8820. if Result then
  8821. begin
  8822. { Convert the input MOVZX to a MOV }
  8823. if (taicpu(p).oper[0]^.typ = top_reg) and
  8824. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  8825. begin
  8826. { Or remove it completely! }
  8827. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  8828. RemoveCurrentP(p);
  8829. p_removed := True;
  8830. end
  8831. else
  8832. begin
  8833. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  8834. taicpu(p).opcode := A_MOV;
  8835. taicpu(p).oper[1]^.reg := ThisReg;
  8836. taicpu(p).opsize := TargetSize;
  8837. end;
  8838. end;
  8839. end;
  8840. end;
  8841. end;
  8842. procedure AdjustFinalLoad;
  8843. begin
  8844. if not LowerUnsignedOverflow then
  8845. begin
  8846. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  8847. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  8848. begin
  8849. { Convert the output MOVZX to a MOV }
  8850. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8851. begin
  8852. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  8853. if (MinSize = S_B) or
  8854. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  8855. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  8856. begin
  8857. { Remove it completely! }
  8858. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  8859. { Be careful; if p = hp1 and p was also removed, p
  8860. will become a dangling pointer }
  8861. if p = hp1 then
  8862. begin
  8863. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  8864. p_removed := True;
  8865. end
  8866. else
  8867. RemoveInstruction(hp1);
  8868. hp1_removed := True;
  8869. end;
  8870. end
  8871. else
  8872. begin
  8873. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  8874. taicpu(hp1).opcode := A_MOV;
  8875. taicpu(hp1).oper[0]^.reg := ThisReg;
  8876. taicpu(hp1).opsize := TargetSize;
  8877. end;
  8878. end
  8879. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  8880. begin
  8881. { Need to change the size of the output }
  8882. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  8883. taicpu(hp1).oper[0]^.reg := ThisReg;
  8884. taicpu(hp1).opsize := S_BL;
  8885. end;
  8886. end;
  8887. end;
  8888. function CompressInstructions: Boolean;
  8889. var
  8890. LocalIndex: Integer;
  8891. begin
  8892. Result := False;
  8893. { The objective here is to try to find a combination that
  8894. removes one of the MOV/Z instructions. }
  8895. if (
  8896. (taicpu(p).oper[0]^.typ <> top_reg) or
  8897. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  8898. ) and
  8899. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8900. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8901. begin
  8902. { Make a preference to remove the second MOVZX instruction }
  8903. case taicpu(hp1).opsize of
  8904. S_BL, S_WL:
  8905. begin
  8906. TargetSize := S_L;
  8907. TargetSubReg := R_SUBD;
  8908. end;
  8909. S_BW:
  8910. begin
  8911. TargetSize := S_W;
  8912. TargetSubReg := R_SUBW;
  8913. end;
  8914. else
  8915. InternalError(2020112302);
  8916. end;
  8917. end
  8918. else
  8919. begin
  8920. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  8921. begin
  8922. { Exceeded lower bound but not upper bound }
  8923. TargetSize := MaxSize;
  8924. end
  8925. else if not LowerUnsignedOverflow then
  8926. begin
  8927. { Size didn't exceed lower bound }
  8928. TargetSize := MinSize;
  8929. end
  8930. else
  8931. Exit;
  8932. end;
  8933. case TargetSize of
  8934. S_B:
  8935. TargetSubReg := R_SUBL;
  8936. S_W:
  8937. TargetSubReg := R_SUBW;
  8938. S_L:
  8939. TargetSubReg := R_SUBD;
  8940. else
  8941. InternalError(2020112350);
  8942. end;
  8943. { Update the register to its new size }
  8944. setsubreg(ThisReg, TargetSubReg);
  8945. RegInUse := False;
  8946. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8947. begin
  8948. { Check to see if the active register is used afterwards;
  8949. if not, we can change it and make a saving. }
  8950. TransferUsedRegs(TmpUsedRegs);
  8951. { The target register may be marked as in use to cross
  8952. a jump to a distant label, so exclude it }
  8953. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  8954. hp2 := p;
  8955. repeat
  8956. { Explicitly check for the excluded register (don't include the first
  8957. instruction as it may be reading from here }
  8958. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  8959. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  8960. begin
  8961. RegInUse := True;
  8962. Break;
  8963. end;
  8964. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  8965. if not GetNextInstruction(hp2, hp2) then
  8966. InternalError(2020112340);
  8967. until (hp2 = hp1);
  8968. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  8969. { We might still be able to get away with this }
  8970. RegInUse := not
  8971. (
  8972. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  8973. (hp2.typ = ait_instruction) and
  8974. (
  8975. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8976. instruction that doesn't actually contain ThisReg }
  8977. (cs_opt_level3 in current_settings.optimizerswitches) or
  8978. RegInInstruction(ThisReg, hp2)
  8979. ) and
  8980. RegLoadedWithNewValue(ThisReg, hp2)
  8981. );
  8982. if not RegInUse then
  8983. begin
  8984. { Force the register size to the same as this instruction so it can be removed}
  8985. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  8986. begin
  8987. TargetSize := S_L;
  8988. TargetSubReg := R_SUBD;
  8989. end
  8990. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  8991. begin
  8992. TargetSize := S_W;
  8993. TargetSubReg := R_SUBW;
  8994. end;
  8995. ThisReg := taicpu(hp1).oper[1]^.reg;
  8996. setsubreg(ThisReg, TargetSubReg);
  8997. RegChanged := True;
  8998. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  8999. TransferUsedRegs(TmpUsedRegs);
  9000. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  9001. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  9002. if p = hp1 then
  9003. begin
  9004. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9005. p_removed := True;
  9006. end
  9007. else
  9008. RemoveInstruction(hp1);
  9009. hp1_removed := True;
  9010. { Instruction will become "mov %reg,%reg" }
  9011. if not p_removed and (taicpu(p).opcode = A_MOV) and
  9012. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  9013. begin
  9014. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  9015. RemoveCurrentP(p);
  9016. p_removed := True;
  9017. end
  9018. else
  9019. taicpu(p).oper[1]^.reg := ThisReg;
  9020. Result := True;
  9021. end
  9022. else
  9023. begin
  9024. if TargetSize <> MaxSize then
  9025. begin
  9026. { Since the register is in use, we have to force it to
  9027. MaxSize otherwise part of it may become undefined later on }
  9028. TargetSize := MaxSize;
  9029. case TargetSize of
  9030. S_B:
  9031. TargetSubReg := R_SUBL;
  9032. S_W:
  9033. TargetSubReg := R_SUBW;
  9034. S_L:
  9035. TargetSubReg := R_SUBD;
  9036. else
  9037. InternalError(2020112351);
  9038. end;
  9039. setsubreg(ThisReg, TargetSubReg);
  9040. end;
  9041. AdjustFinalLoad;
  9042. end;
  9043. end
  9044. else
  9045. AdjustFinalLoad;
  9046. Result := AdjustInitialLoadAndSize or Result;
  9047. { Now go through every instruction we found and change the
  9048. size. If TargetSize = MaxSize, then almost no changes are
  9049. needed and Result can remain False if it hasn't been set
  9050. yet.
  9051. If RegChanged is True, then the register requires changing
  9052. and so the point about TargetSize = MaxSize doesn't apply. }
  9053. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  9054. begin
  9055. for LocalIndex := 0 to InstrMax do
  9056. begin
  9057. { If p_removed is true, then the original MOV/Z was removed
  9058. and removing the AND instruction may not be safe if it
  9059. appears first }
  9060. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  9061. InternalError(2020112310);
  9062. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  9063. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  9064. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  9065. InstrList[LocalIndex].opsize := TargetSize;
  9066. end;
  9067. Result := True;
  9068. end;
  9069. end;
  9070. begin
  9071. Result := False;
  9072. p_removed := False;
  9073. hp1_removed := False;
  9074. ThisReg := taicpu(p).oper[1]^.reg;
  9075. { Check for:
  9076. movs/z ###,%ecx (or %cx or %rcx)
  9077. ...
  9078. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9079. (dealloc %ecx)
  9080. Change to:
  9081. mov ###,%cl (if ### = %cl, then remove completely)
  9082. ...
  9083. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9084. }
  9085. if (getsupreg(ThisReg) = RS_ECX) and
  9086. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  9087. (hp1.typ = ait_instruction) and
  9088. (
  9089. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9090. instruction that doesn't actually contain ECX }
  9091. (cs_opt_level3 in current_settings.optimizerswitches) or
  9092. RegInInstruction(NR_ECX, hp1) or
  9093. (
  9094. { It's common for the shift/rotate's read/write register to be
  9095. initialised in between, so under -O2 and under, search ahead
  9096. one more instruction
  9097. }
  9098. GetNextInstruction(hp1, hp1) and
  9099. (hp1.typ = ait_instruction) and
  9100. RegInInstruction(NR_ECX, hp1)
  9101. )
  9102. ) and
  9103. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  9104. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  9105. begin
  9106. TransferUsedRegs(TmpUsedRegs);
  9107. hp2 := p;
  9108. repeat
  9109. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9110. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  9111. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  9112. begin
  9113. case taicpu(p).opsize of
  9114. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9115. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  9116. begin
  9117. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  9118. RemoveCurrentP(p);
  9119. end
  9120. else
  9121. begin
  9122. taicpu(p).opcode := A_MOV;
  9123. taicpu(p).opsize := S_B;
  9124. taicpu(p).oper[1]^.reg := NR_CL;
  9125. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  9126. end;
  9127. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9128. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  9129. begin
  9130. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  9131. RemoveCurrentP(p);
  9132. end
  9133. else
  9134. begin
  9135. taicpu(p).opcode := A_MOV;
  9136. taicpu(p).opsize := S_W;
  9137. taicpu(p).oper[1]^.reg := NR_CX;
  9138. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  9139. end;
  9140. {$ifdef x86_64}
  9141. S_LQ:
  9142. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  9143. begin
  9144. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  9145. RemoveCurrentP(p);
  9146. end
  9147. else
  9148. begin
  9149. taicpu(p).opcode := A_MOV;
  9150. taicpu(p).opsize := S_L;
  9151. taicpu(p).oper[1]^.reg := NR_ECX;
  9152. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  9153. end;
  9154. {$endif x86_64}
  9155. else
  9156. InternalError(2021120401);
  9157. end;
  9158. Result := True;
  9159. Exit;
  9160. end;
  9161. end;
  9162. { This is anything but quick! }
  9163. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  9164. Exit;
  9165. SetLength(InstrList, 0);
  9166. InstrMax := -1;
  9167. case taicpu(p).opsize of
  9168. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9169. begin
  9170. {$if defined(i386) or defined(i8086)}
  9171. { If the target size is 8-bit, make sure we can actually encode it }
  9172. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  9173. Exit;
  9174. {$endif i386 or i8086}
  9175. LowerLimit := $FF;
  9176. SignedLowerLimit := $7F;
  9177. SignedLowerLimitBottom := -128;
  9178. MinSize := S_B;
  9179. if taicpu(p).opsize = S_BW then
  9180. begin
  9181. MaxSize := S_W;
  9182. UpperLimit := $FFFF;
  9183. SignedUpperLimit := $7FFF;
  9184. SignedUpperLimitBottom := -32768;
  9185. end
  9186. else
  9187. begin
  9188. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  9189. MaxSize := S_L;
  9190. UpperLimit := $FFFFFFFF;
  9191. SignedUpperLimit := $7FFFFFFF;
  9192. SignedUpperLimitBottom := -2147483648;
  9193. end;
  9194. end;
  9195. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9196. begin
  9197. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  9198. LowerLimit := $FFFF;
  9199. SignedLowerLimit := $7FFF;
  9200. SignedLowerLimitBottom := -32768;
  9201. UpperLimit := $FFFFFFFF;
  9202. SignedUpperLimit := $7FFFFFFF;
  9203. SignedUpperLimitBottom := -2147483648;
  9204. MinSize := S_W;
  9205. MaxSize := S_L;
  9206. end;
  9207. {$ifdef x86_64}
  9208. S_LQ:
  9209. begin
  9210. { Both the lower and upper limits are set to 32-bit. If a limit
  9211. is breached, then optimisation is impossible }
  9212. LowerLimit := $FFFFFFFF;
  9213. SignedLowerLimit := $7FFFFFFF;
  9214. SignedLowerLimitBottom := -2147483648;
  9215. UpperLimit := $FFFFFFFF;
  9216. SignedUpperLimit := $7FFFFFFF;
  9217. SignedUpperLimitBottom := -2147483648;
  9218. MinSize := S_L;
  9219. MaxSize := S_L;
  9220. end;
  9221. {$endif x86_64}
  9222. else
  9223. InternalError(2020112301);
  9224. end;
  9225. TestValMin := 0;
  9226. TestValMax := LowerLimit;
  9227. TestValSignedMax := SignedLowerLimit;
  9228. TryShiftDownLimit := LowerLimit;
  9229. TryShiftDown := S_NO;
  9230. ShiftDownOverflow := False;
  9231. RegChanged := False;
  9232. BitwiseOnly := True;
  9233. OrXorUsed := False;
  9234. UpperSignedOverflow := False;
  9235. LowerSignedOverflow := False;
  9236. UpperUnsignedOverflow := False;
  9237. LowerUnsignedOverflow := False;
  9238. hp1 := p;
  9239. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  9240. (hp1.typ = ait_instruction) and
  9241. (
  9242. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9243. instruction that doesn't actually contain ThisReg }
  9244. (cs_opt_level3 in current_settings.optimizerswitches) or
  9245. { This allows this Movx optimisation to work through the SETcc instructions
  9246. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9247. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9248. skip over these SETcc instructions). }
  9249. (taicpu(hp1).opcode = A_SETcc) or
  9250. RegInInstruction(ThisReg, hp1)
  9251. ) do
  9252. begin
  9253. case taicpu(hp1).opcode of
  9254. A_INC,A_DEC:
  9255. begin
  9256. { Has to be an exact match on the register }
  9257. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  9258. Break;
  9259. if taicpu(hp1).opcode = A_INC then
  9260. begin
  9261. Inc(TestValMin);
  9262. Inc(TestValMax);
  9263. Inc(TestValSignedMax);
  9264. end
  9265. else
  9266. begin
  9267. Dec(TestValMin);
  9268. Dec(TestValMax);
  9269. Dec(TestValSignedMax);
  9270. end;
  9271. end;
  9272. A_TEST, A_CMP:
  9273. begin
  9274. if (
  9275. { Too high a risk of non-linear behaviour that breaks DFA
  9276. here, unless it's cmp $0,%reg, which is equivalent to
  9277. test %reg,%reg }
  9278. OrXorUsed and
  9279. (taicpu(hp1).opcode = A_CMP) and
  9280. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  9281. ) or
  9282. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9283. { Has to be an exact match on the register }
  9284. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9285. (
  9286. { Permit "test %reg,%reg" }
  9287. (taicpu(hp1).opcode = A_TEST) and
  9288. (taicpu(hp1).oper[0]^.typ = top_reg) and
  9289. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  9290. ) or
  9291. (taicpu(hp1).oper[0]^.typ <> top_const) or
  9292. { Make sure the comparison value is not smaller than the
  9293. smallest allowed signed value for the minimum size (e.g.
  9294. -128 for 8-bit) }
  9295. not (
  9296. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  9297. { Is it in the negative range? }
  9298. (
  9299. (taicpu(hp1).oper[0]^.val < 0) and
  9300. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  9301. )
  9302. ) then
  9303. Break;
  9304. { Check to see if the active register is used afterwards }
  9305. TransferUsedRegs(TmpUsedRegs);
  9306. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  9307. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9308. begin
  9309. { Make sure the comparison or any previous instructions
  9310. hasn't pushed the test values outside of the range of
  9311. MinSize }
  9312. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9313. begin
  9314. { Exceeded lower bound but not upper bound }
  9315. Exit;
  9316. end
  9317. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  9318. begin
  9319. { Size didn't exceed lower bound }
  9320. TargetSize := MinSize;
  9321. end
  9322. else
  9323. Break;
  9324. case TargetSize of
  9325. S_B:
  9326. TargetSubReg := R_SUBL;
  9327. S_W:
  9328. TargetSubReg := R_SUBW;
  9329. S_L:
  9330. TargetSubReg := R_SUBD;
  9331. else
  9332. InternalError(2021051002);
  9333. end;
  9334. if TargetSize <> MaxSize then
  9335. begin
  9336. { Update the register to its new size }
  9337. setsubreg(ThisReg, TargetSubReg);
  9338. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  9339. taicpu(hp1).oper[1]^.reg := ThisReg;
  9340. taicpu(hp1).opsize := TargetSize;
  9341. { Convert the input MOVZX to a MOV if necessary }
  9342. AdjustInitialLoadAndSize;
  9343. if (InstrMax >= 0) then
  9344. begin
  9345. for Index := 0 to InstrMax do
  9346. begin
  9347. { If p_removed is true, then the original MOV/Z was removed
  9348. and removing the AND instruction may not be safe if it
  9349. appears first }
  9350. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  9351. InternalError(2020112311);
  9352. if InstrList[Index].oper[0]^.typ = top_reg then
  9353. InstrList[Index].oper[0]^.reg := ThisReg;
  9354. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  9355. InstrList[Index].opsize := MinSize;
  9356. end;
  9357. end;
  9358. Result := True;
  9359. end;
  9360. Exit;
  9361. end;
  9362. end;
  9363. A_SETcc:
  9364. begin
  9365. { This allows this Movx optimisation to work through the SETcc instructions
  9366. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9367. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9368. skip over these SETcc instructions). }
  9369. if (cs_opt_level3 in current_settings.optimizerswitches) or
  9370. { Of course, break out if the current register is used }
  9371. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  9372. Break
  9373. else
  9374. { We must use Continue so the instruction doesn't get added
  9375. to InstrList }
  9376. Continue;
  9377. end;
  9378. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  9379. begin
  9380. if
  9381. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9382. { Has to be an exact match on the register }
  9383. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  9384. (
  9385. (
  9386. (taicpu(hp1).oper[0]^.typ = top_const) and
  9387. (
  9388. (
  9389. (taicpu(hp1).opcode = A_SHL) and
  9390. (
  9391. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  9392. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  9393. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  9394. )
  9395. ) or (
  9396. (taicpu(hp1).opcode <> A_SHL) and
  9397. (
  9398. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9399. { Is it in the negative range? }
  9400. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  9401. )
  9402. )
  9403. )
  9404. ) or (
  9405. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  9406. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  9407. )
  9408. ) then
  9409. Break;
  9410. { Only process OR and XOR if there are only bitwise operations,
  9411. since otherwise they can too easily fool the data flow
  9412. analysis (they can cause non-linear behaviour) }
  9413. case taicpu(hp1).opcode of
  9414. A_ADD:
  9415. begin
  9416. if OrXorUsed then
  9417. { Too high a risk of non-linear behaviour that breaks DFA here }
  9418. Break
  9419. else
  9420. BitwiseOnly := False;
  9421. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9422. begin
  9423. TestValMin := TestValMin * 2;
  9424. TestValMax := TestValMax * 2;
  9425. TestValSignedMax := TestValSignedMax * 2;
  9426. end
  9427. else
  9428. begin
  9429. WorkingValue := taicpu(hp1).oper[0]^.val;
  9430. TestValMin := TestValMin + WorkingValue;
  9431. TestValMax := TestValMax + WorkingValue;
  9432. TestValSignedMax := TestValSignedMax + WorkingValue;
  9433. end;
  9434. end;
  9435. A_SUB:
  9436. begin
  9437. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9438. begin
  9439. TestValMin := 0;
  9440. TestValMax := 0;
  9441. TestValSignedMax := 0;
  9442. end
  9443. else
  9444. begin
  9445. if OrXorUsed then
  9446. { Too high a risk of non-linear behaviour that breaks DFA here }
  9447. Break
  9448. else
  9449. BitwiseOnly := False;
  9450. WorkingValue := taicpu(hp1).oper[0]^.val;
  9451. TestValMin := TestValMin - WorkingValue;
  9452. TestValMax := TestValMax - WorkingValue;
  9453. TestValSignedMax := TestValSignedMax - WorkingValue;
  9454. end;
  9455. end;
  9456. A_AND:
  9457. if (taicpu(hp1).oper[0]^.typ = top_const) then
  9458. begin
  9459. { we might be able to go smaller if AND appears first }
  9460. if InstrMax = -1 then
  9461. case MinSize of
  9462. S_B:
  9463. ;
  9464. S_W:
  9465. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9466. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9467. begin
  9468. TryShiftDown := S_B;
  9469. TryShiftDownLimit := $FF;
  9470. end;
  9471. S_L:
  9472. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9473. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9474. begin
  9475. TryShiftDown := S_B;
  9476. TryShiftDownLimit := $FF;
  9477. end
  9478. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  9479. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  9480. begin
  9481. TryShiftDown := S_W;
  9482. TryShiftDownLimit := $FFFF;
  9483. end;
  9484. else
  9485. InternalError(2020112320);
  9486. end;
  9487. WorkingValue := taicpu(hp1).oper[0]^.val;
  9488. TestValMin := TestValMin and WorkingValue;
  9489. TestValMax := TestValMax and WorkingValue;
  9490. TestValSignedMax := TestValSignedMax and WorkingValue;
  9491. end;
  9492. A_OR:
  9493. begin
  9494. if not BitwiseOnly then
  9495. Break;
  9496. OrXorUsed := True;
  9497. WorkingValue := taicpu(hp1).oper[0]^.val;
  9498. TestValMin := TestValMin or WorkingValue;
  9499. TestValMax := TestValMax or WorkingValue;
  9500. TestValSignedMax := TestValSignedMax or WorkingValue;
  9501. end;
  9502. A_XOR:
  9503. begin
  9504. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9505. begin
  9506. TestValMin := 0;
  9507. TestValMax := 0;
  9508. TestValSignedMax := 0;
  9509. end
  9510. else
  9511. begin
  9512. if not BitwiseOnly then
  9513. Break;
  9514. OrXorUsed := True;
  9515. WorkingValue := taicpu(hp1).oper[0]^.val;
  9516. TestValMin := TestValMin xor WorkingValue;
  9517. TestValMax := TestValMax xor WorkingValue;
  9518. TestValSignedMax := TestValSignedMax xor WorkingValue;
  9519. end;
  9520. end;
  9521. A_SHL:
  9522. begin
  9523. BitwiseOnly := False;
  9524. WorkingValue := taicpu(hp1).oper[0]^.val;
  9525. TestValMin := TestValMin shl WorkingValue;
  9526. TestValMax := TestValMax shl WorkingValue;
  9527. TestValSignedMax := TestValSignedMax shl WorkingValue;
  9528. end;
  9529. A_SHR,
  9530. { The first instruction was MOVZX, so the value won't be negative }
  9531. A_SAR:
  9532. begin
  9533. if InstrMax <> -1 then
  9534. BitwiseOnly := False
  9535. else
  9536. { we might be able to go smaller if SHR appears first }
  9537. case MinSize of
  9538. S_B:
  9539. ;
  9540. S_W:
  9541. if (taicpu(hp1).oper[0]^.val >= 8) then
  9542. begin
  9543. TryShiftDown := S_B;
  9544. TryShiftDownLimit := $FF;
  9545. TryShiftDownSignedLimit := $7F;
  9546. TryShiftDownSignedLimitLower := -128;
  9547. end;
  9548. S_L:
  9549. if (taicpu(hp1).oper[0]^.val >= 24) then
  9550. begin
  9551. TryShiftDown := S_B;
  9552. TryShiftDownLimit := $FF;
  9553. TryShiftDownSignedLimit := $7F;
  9554. TryShiftDownSignedLimitLower := -128;
  9555. end
  9556. else if (taicpu(hp1).oper[0]^.val >= 16) then
  9557. begin
  9558. TryShiftDown := S_W;
  9559. TryShiftDownLimit := $FFFF;
  9560. TryShiftDownSignedLimit := $7FFF;
  9561. TryShiftDownSignedLimitLower := -32768;
  9562. end;
  9563. else
  9564. InternalError(2020112321);
  9565. end;
  9566. WorkingValue := taicpu(hp1).oper[0]^.val;
  9567. if taicpu(hp1).opcode = A_SAR then
  9568. begin
  9569. TestValMin := SarInt64(TestValMin, WorkingValue);
  9570. TestValMax := SarInt64(TestValMax, WorkingValue);
  9571. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  9572. end
  9573. else
  9574. begin
  9575. TestValMin := TestValMin shr WorkingValue;
  9576. TestValMax := TestValMax shr WorkingValue;
  9577. TestValSignedMax := TestValSignedMax shr WorkingValue;
  9578. end;
  9579. end;
  9580. else
  9581. InternalError(2020112303);
  9582. end;
  9583. end;
  9584. (*
  9585. A_IMUL:
  9586. case taicpu(hp1).ops of
  9587. 2:
  9588. begin
  9589. if not MatchOpType(hp1, top_reg, top_reg) or
  9590. { Has to be an exact match on the register }
  9591. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  9592. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  9593. Break;
  9594. TestValMin := TestValMin * TestValMin;
  9595. TestValMax := TestValMax * TestValMax;
  9596. TestValSignedMax := TestValSignedMax * TestValMax;
  9597. end;
  9598. 3:
  9599. begin
  9600. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9601. { Has to be an exact match on the register }
  9602. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9603. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9604. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9605. { Is it in the negative range? }
  9606. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9607. Break;
  9608. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  9609. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  9610. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  9611. end;
  9612. else
  9613. Break;
  9614. end;
  9615. A_IDIV:
  9616. case taicpu(hp1).ops of
  9617. 3:
  9618. begin
  9619. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9620. { Has to be an exact match on the register }
  9621. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9622. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9623. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9624. { Is it in the negative range? }
  9625. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9626. Break;
  9627. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  9628. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  9629. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  9630. end;
  9631. else
  9632. Break;
  9633. end;
  9634. *)
  9635. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  9636. begin
  9637. { If there are no instructions in between, then we might be able to make a saving }
  9638. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  9639. Break;
  9640. { We have something like:
  9641. movzbw %dl,%dx
  9642. ...
  9643. movswl %dx,%edx
  9644. Change the latter to a zero-extension then enter the
  9645. A_MOVZX case branch.
  9646. }
  9647. {$ifdef x86_64}
  9648. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9649. begin
  9650. { this becomes a zero extension from 32-bit to 64-bit, but
  9651. the upper 32 bits are already zero, so just delete the
  9652. instruction }
  9653. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  9654. RemoveInstruction(hp1);
  9655. Result := True;
  9656. Exit;
  9657. end
  9658. else
  9659. {$endif x86_64}
  9660. begin
  9661. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  9662. taicpu(hp1).opcode := A_MOVZX;
  9663. {$ifdef x86_64}
  9664. case taicpu(hp1).opsize of
  9665. S_BQ:
  9666. begin
  9667. taicpu(hp1).opsize := S_BL;
  9668. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9669. end;
  9670. S_WQ:
  9671. begin
  9672. taicpu(hp1).opsize := S_WL;
  9673. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9674. end;
  9675. S_LQ:
  9676. begin
  9677. taicpu(hp1).opcode := A_MOV;
  9678. taicpu(hp1).opsize := S_L;
  9679. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9680. { In this instance, we need to break out because the
  9681. instruction is no longer MOVZX or MOVSXD }
  9682. Result := True;
  9683. Exit;
  9684. end;
  9685. else
  9686. ;
  9687. end;
  9688. {$endif x86_64}
  9689. Result := CompressInstructions;
  9690. Exit;
  9691. end;
  9692. end;
  9693. A_MOVZX:
  9694. begin
  9695. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  9696. Break;
  9697. if (InstrMax = -1) then
  9698. begin
  9699. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  9700. begin
  9701. { Optimise around i40003 }
  9702. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  9703. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  9704. {$ifndef x86_64}
  9705. and (
  9706. (taicpu(p).oper[0]^.typ <> top_reg) or
  9707. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  9708. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  9709. )
  9710. {$endif not x86_64}
  9711. then
  9712. begin
  9713. if (taicpu(p).oper[0]^.typ = top_reg) then
  9714. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  9715. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  9716. taicpu(p).opsize := S_BL;
  9717. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  9718. RemoveInstruction(hp1);
  9719. Result := True;
  9720. Exit;
  9721. end;
  9722. end
  9723. else
  9724. begin
  9725. { Will return false if the second parameter isn't ThisReg
  9726. (can happen on -O2 and under) }
  9727. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9728. begin
  9729. { The two MOVZX instructions are adjacent, so remove the first one }
  9730. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  9731. RemoveCurrentP(p);
  9732. Result := True;
  9733. Exit;
  9734. end;
  9735. Break;
  9736. end;
  9737. end;
  9738. Result := CompressInstructions;
  9739. Exit;
  9740. end;
  9741. else
  9742. { This includes ADC, SBB and IDIV }
  9743. Break;
  9744. end;
  9745. if not CheckOverflowConditions then
  9746. Break;
  9747. { Contains highest index (so instruction count - 1) }
  9748. Inc(InstrMax);
  9749. if InstrMax > High(InstrList) then
  9750. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  9751. InstrList[InstrMax] := taicpu(hp1);
  9752. end;
  9753. end;
  9754. {$pop}
  9755. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  9756. var
  9757. hp1 : tai;
  9758. begin
  9759. Result:=false;
  9760. if (taicpu(p).ops >= 2) and
  9761. ((taicpu(p).oper[0]^.typ = top_const) or
  9762. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  9763. (taicpu(p).oper[1]^.typ = top_reg) and
  9764. ((taicpu(p).ops = 2) or
  9765. ((taicpu(p).oper[2]^.typ = top_reg) and
  9766. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  9767. GetLastInstruction(p,hp1) and
  9768. MatchInstruction(hp1,A_MOV,[]) and
  9769. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9770. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9771. begin
  9772. TransferUsedRegs(TmpUsedRegs);
  9773. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  9774. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  9775. { change
  9776. mov reg1,reg2
  9777. imul y,reg2 to imul y,reg1,reg2 }
  9778. begin
  9779. taicpu(p).ops := 3;
  9780. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  9781. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  9782. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  9783. RemoveInstruction(hp1);
  9784. result:=true;
  9785. end;
  9786. end;
  9787. end;
  9788. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  9789. var
  9790. ThisLabel: TAsmLabel;
  9791. begin
  9792. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  9793. ThisLabel.decrefs;
  9794. taicpu(p).condition := C_None;
  9795. taicpu(p).opcode := A_RET;
  9796. taicpu(p).is_jmp := false;
  9797. taicpu(p).ops := taicpu(ret_p).ops;
  9798. case taicpu(ret_p).ops of
  9799. 0:
  9800. taicpu(p).clearop(0);
  9801. 1:
  9802. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  9803. else
  9804. internalerror(2016041301);
  9805. end;
  9806. { If the original label is now dead, it might turn out that the label
  9807. immediately follows p. As a result, everything beyond it, which will
  9808. be just some final register configuration and a RET instruction, is
  9809. now dead code. [Kit] }
  9810. { NOTE: This is much faster than introducing a OptPass2RET routine and
  9811. running RemoveDeadCodeAfterJump for each RET instruction, because
  9812. this optimisation rarely happens and most RETs appear at the end of
  9813. routines where there is nothing that can be stripped. [Kit] }
  9814. if not ThisLabel.is_used then
  9815. RemoveDeadCodeAfterJump(p);
  9816. end;
  9817. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  9818. var
  9819. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  9820. Unconditional, PotentialModified: Boolean;
  9821. OperPtr: POper;
  9822. NewRef: TReference;
  9823. InstrList: array of taicpu;
  9824. InstrMax, Index: Integer;
  9825. const
  9826. {$ifdef DEBUG_AOPTCPU}
  9827. SNoFlags: shortstring = ' so the flags aren''t modified';
  9828. {$else DEBUG_AOPTCPU}
  9829. SNoFlags = '';
  9830. {$endif DEBUG_AOPTCPU}
  9831. begin
  9832. Result:=false;
  9833. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  9834. begin
  9835. if MatchInstruction(hp1, A_TEST, [S_B]) and
  9836. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9837. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9838. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9839. GetNextInstruction(hp1, hp2) and
  9840. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  9841. { Change from: To:
  9842. set(C) %reg j(~C) label
  9843. test %reg,%reg/cmp $0,%reg
  9844. je label
  9845. set(C) %reg j(C) label
  9846. test %reg,%reg/cmp $0,%reg
  9847. jne label
  9848. (Also do something similar with sete/setne instead of je/jne)
  9849. }
  9850. begin
  9851. { Before we do anything else, we need to check the instructions
  9852. in between SETcc and TEST to make sure they don't modify the
  9853. FLAGS register - if -O2 or under, there won't be any
  9854. instructions between SET and TEST }
  9855. TransferUsedRegs(TmpUsedRegs);
  9856. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9857. if (cs_opt_level3 in current_settings.optimizerswitches) then
  9858. begin
  9859. next := p;
  9860. SetLength(InstrList, 0);
  9861. InstrMax := -1;
  9862. PotentialModified := False;
  9863. { Make a note of every instruction that modifies the FLAGS
  9864. register }
  9865. while GetNextInstruction(next, next) and (next <> hp1) do
  9866. begin
  9867. if next.typ <> ait_instruction then
  9868. { GetNextInstructionUsingReg should have returned False }
  9869. InternalError(2021051701);
  9870. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  9871. begin
  9872. case taicpu(next).opcode of
  9873. A_SETcc,
  9874. A_CMOVcc,
  9875. A_Jcc:
  9876. begin
  9877. if PotentialModified then
  9878. { Not safe because the flags were modified earlier }
  9879. Exit
  9880. else
  9881. { Condition is the same as the initial SETcc, so this is safe
  9882. (don't add to instruction list though) }
  9883. Continue;
  9884. end;
  9885. A_ADD:
  9886. begin
  9887. if (taicpu(next).opsize = S_B) or
  9888. { LEA doesn't support 8-bit operands }
  9889. (taicpu(next).oper[1]^.typ <> top_reg) or
  9890. { Must write to a register }
  9891. (taicpu(next).oper[0]^.typ = top_ref) then
  9892. { Require a constant or a register }
  9893. Exit;
  9894. PotentialModified := True;
  9895. end;
  9896. A_SUB:
  9897. begin
  9898. if (taicpu(next).opsize = S_B) or
  9899. { LEA doesn't support 8-bit operands }
  9900. (taicpu(next).oper[1]^.typ <> top_reg) or
  9901. { Must write to a register }
  9902. (taicpu(next).oper[0]^.typ <> top_const) or
  9903. (taicpu(next).oper[0]^.val = $80000000) then
  9904. { Can't subtract a register with LEA - also
  9905. check that the value isn't -2^31, as this
  9906. can't be negated }
  9907. Exit;
  9908. PotentialModified := True;
  9909. end;
  9910. A_SAL,
  9911. A_SHL:
  9912. begin
  9913. if (taicpu(next).opsize = S_B) or
  9914. { LEA doesn't support 8-bit operands }
  9915. (taicpu(next).oper[1]^.typ <> top_reg) or
  9916. { Must write to a register }
  9917. (taicpu(next).oper[0]^.typ <> top_const) or
  9918. (taicpu(next).oper[0]^.val < 0) or
  9919. (taicpu(next).oper[0]^.val > 3) then
  9920. Exit;
  9921. PotentialModified := True;
  9922. end;
  9923. A_IMUL:
  9924. begin
  9925. if (taicpu(next).ops <> 3) or
  9926. (taicpu(next).oper[1]^.typ <> top_reg) or
  9927. { Must write to a register }
  9928. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  9929. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  9930. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  9931. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  9932. Exit
  9933. else
  9934. PotentialModified := True;
  9935. end;
  9936. else
  9937. { Don't know how to change this, so abort }
  9938. Exit;
  9939. end;
  9940. { Contains highest index (so instruction count - 1) }
  9941. Inc(InstrMax);
  9942. if InstrMax > High(InstrList) then
  9943. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  9944. InstrList[InstrMax] := taicpu(next);
  9945. end;
  9946. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  9947. end;
  9948. if not Assigned(next) or (next <> hp1) then
  9949. { It should be equal to hp1 }
  9950. InternalError(2021051702);
  9951. { Cycle through each instruction and check to see if we can
  9952. change them to versions that don't modify the flags }
  9953. if (InstrMax >= 0) then
  9954. begin
  9955. for Index := 0 to InstrMax do
  9956. case InstrList[Index].opcode of
  9957. A_ADD:
  9958. begin
  9959. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  9960. InstrList[Index].opcode := A_LEA;
  9961. reference_reset(NewRef, 1, []);
  9962. NewRef.base := InstrList[Index].oper[1]^.reg;
  9963. if InstrList[Index].oper[0]^.typ = top_reg then
  9964. begin
  9965. NewRef.index := InstrList[Index].oper[0]^.reg;
  9966. NewRef.scalefactor := 1;
  9967. end
  9968. else
  9969. NewRef.offset := InstrList[Index].oper[0]^.val;
  9970. InstrList[Index].loadref(0, NewRef);
  9971. end;
  9972. A_SUB:
  9973. begin
  9974. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  9975. InstrList[Index].opcode := A_LEA;
  9976. reference_reset(NewRef, 1, []);
  9977. NewRef.base := InstrList[Index].oper[1]^.reg;
  9978. NewRef.offset := -InstrList[Index].oper[0]^.val;
  9979. InstrList[Index].loadref(0, NewRef);
  9980. end;
  9981. A_SHL,
  9982. A_SAL:
  9983. begin
  9984. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  9985. InstrList[Index].opcode := A_LEA;
  9986. reference_reset(NewRef, 1, []);
  9987. NewRef.index := InstrList[Index].oper[1]^.reg;
  9988. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  9989. InstrList[Index].loadref(0, NewRef);
  9990. end;
  9991. A_IMUL:
  9992. begin
  9993. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  9994. InstrList[Index].opcode := A_LEA;
  9995. reference_reset(NewRef, 1, []);
  9996. NewRef.index := InstrList[Index].oper[1]^.reg;
  9997. case InstrList[Index].oper[0]^.val of
  9998. 2, 4, 8:
  9999. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  10000. else {3, 5 and 9}
  10001. begin
  10002. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  10003. NewRef.base := InstrList[Index].oper[1]^.reg;
  10004. end;
  10005. end;
  10006. InstrList[Index].loadref(0, NewRef);
  10007. end;
  10008. else
  10009. InternalError(2021051710);
  10010. end;
  10011. end;
  10012. { Mark the FLAGS register as used across this whole block }
  10013. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  10014. end;
  10015. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10016. JumpC := taicpu(hp2).condition;
  10017. Unconditional := False;
  10018. if conditions_equal(JumpC, C_E) then
  10019. SetC := inverse_cond(taicpu(p).condition)
  10020. else if conditions_equal(JumpC, C_NE) then
  10021. SetC := taicpu(p).condition
  10022. else
  10023. { We've got something weird here (and inefficent) }
  10024. begin
  10025. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  10026. SetC := C_NONE;
  10027. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  10028. if condition_in(C_AE, JumpC) then
  10029. Unconditional := True
  10030. else
  10031. { Not sure what to do with this jump - drop out }
  10032. Exit;
  10033. end;
  10034. RemoveInstruction(hp1);
  10035. if Unconditional then
  10036. MakeUnconditional(taicpu(hp2))
  10037. else
  10038. begin
  10039. if SetC = C_NONE then
  10040. InternalError(2018061402);
  10041. taicpu(hp2).SetCondition(SetC);
  10042. end;
  10043. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  10044. TmpUsedRegs }
  10045. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  10046. begin
  10047. RemoveCurrentp(p, hp2);
  10048. if taicpu(hp2).opcode = A_SETcc then
  10049. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  10050. else
  10051. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  10052. end
  10053. else
  10054. if taicpu(hp2).opcode = A_SETcc then
  10055. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  10056. else
  10057. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  10058. Result := True;
  10059. end
  10060. else if
  10061. { Make sure the instructions are adjacent }
  10062. (
  10063. not (cs_opt_level3 in current_settings.optimizerswitches) or
  10064. GetNextInstruction(p, hp1)
  10065. ) and
  10066. MatchInstruction(hp1, A_MOV, [S_B]) and
  10067. { Writing to memory is allowed }
  10068. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  10069. begin
  10070. {
  10071. Watch out for sequences such as:
  10072. set(c)b %regb
  10073. movb %regb,(ref)
  10074. movb $0,1(ref)
  10075. movb $0,2(ref)
  10076. movb $0,3(ref)
  10077. Much more efficient to turn it into:
  10078. movl $0,%regl
  10079. set(c)b %regb
  10080. movl %regl,(ref)
  10081. Or:
  10082. set(c)b %regb
  10083. movzbl %regb,%regl
  10084. movl %regl,(ref)
  10085. }
  10086. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  10087. GetNextInstruction(hp1, hp2) and
  10088. MatchInstruction(hp2, A_MOV, [S_B]) and
  10089. (taicpu(hp2).oper[1]^.typ = top_ref) and
  10090. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  10091. begin
  10092. { Don't do anything else except set Result to True }
  10093. end
  10094. else
  10095. begin
  10096. if taicpu(p).oper[0]^.typ = top_reg then
  10097. begin
  10098. TransferUsedRegs(TmpUsedRegs);
  10099. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10100. end;
  10101. { If it's not a register, it's a memory address }
  10102. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  10103. begin
  10104. { Even if the register is still in use, we can minimise the
  10105. pipeline stall by changing the MOV into another SETcc. }
  10106. taicpu(hp1).opcode := A_SETcc;
  10107. taicpu(hp1).condition := taicpu(p).condition;
  10108. if taicpu(hp1).oper[1]^.typ = top_ref then
  10109. begin
  10110. { Swapping the operand pointers like this is probably a
  10111. bit naughty, but it is far faster than using loadoper
  10112. to transfer the reference from oper[1] to oper[0] if
  10113. you take into account the extra procedure calls and
  10114. the memory allocation and deallocation required }
  10115. OperPtr := taicpu(hp1).oper[1];
  10116. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  10117. taicpu(hp1).oper[0] := OperPtr;
  10118. end
  10119. else
  10120. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  10121. taicpu(hp1).clearop(1);
  10122. taicpu(hp1).ops := 1;
  10123. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  10124. end
  10125. else
  10126. begin
  10127. if taicpu(hp1).oper[1]^.typ = top_reg then
  10128. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  10129. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  10130. RemoveInstruction(hp1);
  10131. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  10132. end
  10133. end;
  10134. Result := True;
  10135. end;
  10136. end;
  10137. end;
  10138. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  10139. var
  10140. hp1: tai;
  10141. Count: Integer;
  10142. OrigLabel: TAsmLabel;
  10143. begin
  10144. result := False;
  10145. { Sometimes, the optimisations below can permit this }
  10146. RemoveDeadCodeAfterJump(p);
  10147. 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
  10148. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  10149. begin
  10150. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10151. { Also a side-effect of optimisations }
  10152. if CollapseZeroDistJump(p, OrigLabel) then
  10153. begin
  10154. Result := True;
  10155. Exit;
  10156. end;
  10157. hp1 := GetLabelWithSym(OrigLabel);
  10158. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  10159. begin
  10160. if taicpu(hp1).opcode = A_RET then
  10161. begin
  10162. {
  10163. change
  10164. jmp .L1
  10165. ...
  10166. .L1:
  10167. ret
  10168. into
  10169. ret
  10170. }
  10171. begin
  10172. ConvertJumpToRET(p, hp1);
  10173. result:=true;
  10174. end;
  10175. end
  10176. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  10177. not (cs_opt_size in current_settings.optimizerswitches) and
  10178. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  10179. begin
  10180. Result := True;
  10181. Exit;
  10182. end;
  10183. end;
  10184. end;
  10185. end;
  10186. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  10187. begin
  10188. CanBeCMOV:=assigned(p) and
  10189. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  10190. { we can't use cmov ref,reg because
  10191. ref could be nil and cmov still throws an exception
  10192. if ref=nil but the mov isn't done (FK)
  10193. or ((taicpu(p).oper[0]^.typ = top_ref) and
  10194. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  10195. }
  10196. (taicpu(p).oper[1]^.typ = top_reg) and
  10197. (
  10198. (taicpu(p).oper[0]^.typ = top_reg) or
  10199. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  10200. it is not expected that this can cause a seg. violation }
  10201. (
  10202. (taicpu(p).oper[0]^.typ = top_ref) and
  10203. IsRefSafe(taicpu(p).oper[0]^.ref)
  10204. )
  10205. );
  10206. end;
  10207. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  10208. var
  10209. hp1,hp2: tai;
  10210. {$ifndef i8086}
  10211. hp3,hp4,hpmov2, hp5: tai;
  10212. l : Longint;
  10213. condition : TAsmCond;
  10214. {$endif i8086}
  10215. carryadd_opcode : TAsmOp;
  10216. symbol: TAsmSymbol;
  10217. increg, tmpreg: TRegister;
  10218. begin
  10219. result:=false;
  10220. if GetNextInstruction(p,hp1) then
  10221. begin
  10222. if (hp1.typ=ait_label) then
  10223. begin
  10224. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  10225. Exit;
  10226. end
  10227. else if (hp1.typ<>ait_instruction) then
  10228. Exit;
  10229. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10230. if (
  10231. (
  10232. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  10233. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  10234. (Taicpu(hp1).oper[0]^.val=1)
  10235. ) or
  10236. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  10237. ) and
  10238. GetNextInstruction(hp1,hp2) and
  10239. SkipAligns(hp2, hp2) and
  10240. (hp2.typ = ait_label) and
  10241. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  10242. { jb @@1 cmc
  10243. inc/dec operand --> adc/sbb operand,0
  10244. @@1:
  10245. ... and ...
  10246. jnb @@1
  10247. inc/dec operand --> adc/sbb operand,0
  10248. @@1: }
  10249. begin
  10250. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  10251. begin
  10252. case taicpu(hp1).opcode of
  10253. A_INC,
  10254. A_ADD:
  10255. carryadd_opcode:=A_ADC;
  10256. A_DEC,
  10257. A_SUB:
  10258. carryadd_opcode:=A_SBB;
  10259. else
  10260. InternalError(2021011001);
  10261. end;
  10262. Taicpu(p).clearop(0);
  10263. Taicpu(p).ops:=0;
  10264. Taicpu(p).is_jmp:=false;
  10265. Taicpu(p).opcode:=A_CMC;
  10266. Taicpu(p).condition:=C_NONE;
  10267. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  10268. Taicpu(hp1).ops:=2;
  10269. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10270. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10271. else
  10272. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10273. Taicpu(hp1).loadconst(0,0);
  10274. Taicpu(hp1).opcode:=carryadd_opcode;
  10275. result:=true;
  10276. exit;
  10277. end
  10278. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  10279. begin
  10280. case taicpu(hp1).opcode of
  10281. A_INC,
  10282. A_ADD:
  10283. carryadd_opcode:=A_ADC;
  10284. A_DEC,
  10285. A_SUB:
  10286. carryadd_opcode:=A_SBB;
  10287. else
  10288. InternalError(2021011002);
  10289. end;
  10290. Taicpu(hp1).ops:=2;
  10291. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  10292. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10293. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10294. else
  10295. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10296. Taicpu(hp1).loadconst(0,0);
  10297. Taicpu(hp1).opcode:=carryadd_opcode;
  10298. RemoveCurrentP(p, hp1);
  10299. result:=true;
  10300. exit;
  10301. end
  10302. {
  10303. jcc @@1 setcc tmpreg
  10304. inc/dec/add/sub operand -> (movzx tmpreg)
  10305. @@1: add/sub tmpreg,operand
  10306. While this increases code size slightly, it makes the code much faster if the
  10307. jump is unpredictable
  10308. }
  10309. else if not(cs_opt_size in current_settings.optimizerswitches) then
  10310. begin
  10311. { search for an available register which is volatile }
  10312. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  10313. if increg <> NR_NO then
  10314. begin
  10315. { We don't need to check if tmpreg is in hp1 or not, because
  10316. it will be marked as in use at p (if not, this is
  10317. indictive of a compiler bug). }
  10318. TAsmLabel(symbol).decrefs;
  10319. Taicpu(p).clearop(0);
  10320. Taicpu(p).ops:=1;
  10321. Taicpu(p).is_jmp:=false;
  10322. Taicpu(p).opcode:=A_SETcc;
  10323. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  10324. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  10325. Taicpu(p).loadreg(0,increg);
  10326. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  10327. begin
  10328. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  10329. R_SUBW:
  10330. begin
  10331. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  10332. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  10333. end;
  10334. R_SUBD:
  10335. begin
  10336. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10337. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10338. end;
  10339. {$ifdef x86_64}
  10340. R_SUBQ:
  10341. begin
  10342. { MOVZX doesn't have a 64-bit variant, because
  10343. the 32-bit version implicitly zeroes the
  10344. upper 32-bits of the destination register }
  10345. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10346. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10347. setsubreg(tmpreg, R_SUBQ);
  10348. end;
  10349. {$endif x86_64}
  10350. else
  10351. Internalerror(2020030601);
  10352. end;
  10353. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  10354. asml.InsertAfter(hp2,p);
  10355. end
  10356. else
  10357. tmpreg := increg;
  10358. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  10359. begin
  10360. Taicpu(hp1).ops:=2;
  10361. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  10362. end;
  10363. Taicpu(hp1).loadreg(0,tmpreg);
  10364. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  10365. Result := True;
  10366. { p is no longer a Jcc instruction, so exit }
  10367. Exit;
  10368. end;
  10369. end;
  10370. end;
  10371. { Detect the following:
  10372. jmp<cond> @Lbl1
  10373. jmp @Lbl2
  10374. ...
  10375. @Lbl1:
  10376. ret
  10377. Change to:
  10378. jmp<inv_cond> @Lbl2
  10379. ret
  10380. }
  10381. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  10382. begin
  10383. hp2:=getlabelwithsym(TAsmLabel(symbol));
  10384. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  10385. MatchInstruction(hp2,A_RET,[S_NO]) then
  10386. begin
  10387. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  10388. { Change label address to that of the unconditional jump }
  10389. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  10390. TAsmLabel(symbol).DecRefs;
  10391. taicpu(hp1).opcode := A_RET;
  10392. taicpu(hp1).is_jmp := false;
  10393. taicpu(hp1).ops := taicpu(hp2).ops;
  10394. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  10395. case taicpu(hp2).ops of
  10396. 0:
  10397. taicpu(hp1).clearop(0);
  10398. 1:
  10399. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  10400. else
  10401. internalerror(2016041302);
  10402. end;
  10403. end;
  10404. {$ifndef i8086}
  10405. end
  10406. {
  10407. convert
  10408. j<c> .L1
  10409. mov 1,reg
  10410. jmp .L2
  10411. .L1
  10412. mov 0,reg
  10413. .L2
  10414. into
  10415. mov 0,reg
  10416. set<not(c)> reg
  10417. take care of alignment and that the mov 0,reg is not converted into a xor as this
  10418. would destroy the flag contents
  10419. }
  10420. else if MatchInstruction(hp1,A_MOV,[]) and
  10421. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10422. {$ifdef i386}
  10423. (
  10424. { Under i386, ESI, EDI, EBP and ESP
  10425. don't have an 8-bit representation }
  10426. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  10427. ) and
  10428. {$endif i386}
  10429. (taicpu(hp1).oper[0]^.val=1) and
  10430. GetNextInstruction(hp1,hp2) and
  10431. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  10432. GetNextInstruction(hp2,hp3) and
  10433. { skip align }
  10434. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  10435. (hp3.typ=ait_label) and
  10436. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  10437. (tai_label(hp3).labsym.getrefs=1) and
  10438. GetNextInstruction(hp3,hp4) and
  10439. MatchInstruction(hp4,A_MOV,[]) and
  10440. MatchOpType(taicpu(hp4),top_const,top_reg) and
  10441. (taicpu(hp4).oper[0]^.val=0) and
  10442. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  10443. GetNextInstruction(hp4,hp5) and
  10444. (hp5.typ=ait_label) and
  10445. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  10446. (tai_label(hp5).labsym.getrefs=1) then
  10447. begin
  10448. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  10449. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  10450. { remove last label }
  10451. RemoveInstruction(hp5);
  10452. { remove second label }
  10453. RemoveInstruction(hp3);
  10454. { if align is present remove it }
  10455. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  10456. RemoveInstruction(hp3);
  10457. { remove jmp }
  10458. RemoveInstruction(hp2);
  10459. if taicpu(hp1).opsize=S_B then
  10460. RemoveInstruction(hp1)
  10461. else
  10462. taicpu(hp1).loadconst(0,0);
  10463. taicpu(hp4).opcode:=A_SETcc;
  10464. taicpu(hp4).opsize:=S_B;
  10465. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  10466. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  10467. taicpu(hp4).opercnt:=1;
  10468. taicpu(hp4).ops:=1;
  10469. taicpu(hp4).freeop(1);
  10470. RemoveCurrentP(p);
  10471. Result:=true;
  10472. exit;
  10473. end
  10474. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  10475. begin
  10476. { check for
  10477. jCC xxx
  10478. <several movs>
  10479. xxx:
  10480. Also spot:
  10481. Jcc xxx
  10482. <several movs>
  10483. jmp xxx
  10484. Change to:
  10485. <several cmovs with inverted condition>
  10486. jmp xxx
  10487. }
  10488. l:=0;
  10489. while assigned(hp1) and
  10490. CanBeCMOV(hp1) and
  10491. { stop on labels }
  10492. not(hp1.typ=ait_label) do
  10493. begin
  10494. inc(l);
  10495. hp5 := hp1;
  10496. GetNextInstruction(hp1,hp1);
  10497. end;
  10498. if assigned(hp1) then
  10499. begin
  10500. TransferUsedRegs(TmpUsedRegs);
  10501. if (
  10502. MatchInstruction(hp1, A_JMP, []) and
  10503. (JumpTargetOp(taicpu(hp1))^.typ=top_ref) and
  10504. (JumpTargetOp(taicpu(hp1))^.ref^.symbol=symbol)
  10505. ) or
  10506. FindLabel(tasmlabel(symbol),hp1) then
  10507. begin
  10508. if (l<=4) and (l>0) then
  10509. begin
  10510. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  10511. condition:=inverse_cond(taicpu(p).condition);
  10512. UpdateUsedRegs(tai(p.next));
  10513. GetNextInstruction(p,hp1);
  10514. repeat
  10515. if not Assigned(hp1) then
  10516. InternalError(2018062900);
  10517. taicpu(hp1).opcode:=A_CMOVcc;
  10518. taicpu(hp1).condition:=condition;
  10519. UpdateUsedRegs(tai(hp1.next));
  10520. GetNextInstruction(hp1,hp1);
  10521. until not(CanBeCMOV(hp1));
  10522. { Remember what hp1 is in case there's multiple aligns to get rid of }
  10523. hp2 := hp1;
  10524. repeat
  10525. if not Assigned(hp2) then
  10526. InternalError(2018062910);
  10527. case hp2.typ of
  10528. ait_label:
  10529. { What we expected - break out of the loop (it won't be a dead label at the top of
  10530. a cluster because that was optimised at an earlier stage) }
  10531. Break;
  10532. ait_align:
  10533. { Go to the next entry until a label is found (may be multiple aligns before it) }
  10534. begin
  10535. hp2 := tai(hp2.Next);
  10536. Continue;
  10537. end;
  10538. ait_instruction:
  10539. begin
  10540. if taicpu(hp2).opcode<>A_JMP then
  10541. InternalError(2018062912);
  10542. { This is the Jcc @Lbl; <several movs>; JMP @Lbl variant }
  10543. Break;
  10544. end
  10545. else
  10546. begin
  10547. { Might be a comment or temporary allocation entry }
  10548. if not (hp2.typ in SkipInstr) then
  10549. InternalError(2018062911);
  10550. hp2 := tai(hp2.Next);
  10551. Continue;
  10552. end;
  10553. end;
  10554. until False;
  10555. { Now we can safely decrement the reference count }
  10556. tasmlabel(symbol).decrefs;
  10557. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  10558. { Remove the original jump }
  10559. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  10560. if hp2.typ=ait_instruction then
  10561. begin
  10562. p:=hp2;
  10563. Result:=True;
  10564. end
  10565. else
  10566. begin
  10567. UpdateUsedRegs(tai(hp2.next));
  10568. Result:=GetNextInstruction(hp2, p); { Instruction after the label }
  10569. { Remove the label if this is its final reference }
  10570. if (tasmlabel(symbol).getrefs=0) then
  10571. StripLabelFast(hp1);
  10572. end;
  10573. exit;
  10574. end;
  10575. end
  10576. else
  10577. begin
  10578. { check further for
  10579. jCC xxx
  10580. <several movs 1>
  10581. jmp yyy
  10582. xxx:
  10583. <several movs 2>
  10584. yyy:
  10585. }
  10586. { hp2 points to jmp yyy }
  10587. hp2:=hp1;
  10588. { skip hp1 to xxx (or an align right before it) }
  10589. GetNextInstruction(hp1, hp1);
  10590. if assigned(hp2) and
  10591. assigned(hp1) and
  10592. (l<=3) and
  10593. (hp2.typ=ait_instruction) and
  10594. (taicpu(hp2).is_jmp) and
  10595. (taicpu(hp2).condition=C_None) and
  10596. { real label and jump, no further references to the
  10597. label are allowed }
  10598. (tasmlabel(symbol).getrefs=1) and
  10599. FindLabel(tasmlabel(symbol),hp1) then
  10600. begin
  10601. l:=0;
  10602. { skip hp1 to <several moves 2> }
  10603. if (hp1.typ = ait_align) then
  10604. GetNextInstruction(hp1, hp1);
  10605. GetNextInstruction(hp1, hpmov2);
  10606. hp1 := hpmov2;
  10607. while assigned(hp1) and
  10608. CanBeCMOV(hp1) do
  10609. begin
  10610. inc(l);
  10611. hp5 := hp1;
  10612. GetNextInstruction(hp1, hp1);
  10613. end;
  10614. { hp1 points to yyy (or an align right before it) }
  10615. hp3 := hp1;
  10616. if assigned(hp1) and
  10617. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  10618. begin
  10619. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  10620. condition:=inverse_cond(taicpu(p).condition);
  10621. UpdateUsedRegs(tai(p.next));
  10622. GetNextInstruction(p,hp1);
  10623. repeat
  10624. taicpu(hp1).opcode:=A_CMOVcc;
  10625. taicpu(hp1).condition:=condition;
  10626. UpdateUsedRegs(tai(hp1.next));
  10627. GetNextInstruction(hp1,hp1);
  10628. until not(assigned(hp1)) or
  10629. not(CanBeCMOV(hp1));
  10630. condition:=inverse_cond(condition);
  10631. if GetLastInstruction(hpmov2,hp1) then
  10632. UpdateUsedRegs(tai(hp1.next));
  10633. hp1 := hpmov2;
  10634. { hp1 is now at <several movs 2> }
  10635. while Assigned(hp1) and CanBeCMOV(hp1) do
  10636. begin
  10637. taicpu(hp1).opcode:=A_CMOVcc;
  10638. taicpu(hp1).condition:=condition;
  10639. UpdateUsedRegs(tai(hp1.next));
  10640. GetNextInstruction(hp1,hp1);
  10641. end;
  10642. hp1 := p;
  10643. { Get first instruction after label }
  10644. UpdateUsedRegs(tai(hp3.next));
  10645. GetNextInstruction(hp3, p);
  10646. if assigned(p) and (hp3.typ = ait_align) then
  10647. GetNextInstruction(p, p);
  10648. { Don't dereference yet, as doing so will cause
  10649. GetNextInstruction to skip the label and
  10650. optional align marker. [Kit] }
  10651. GetNextInstruction(hp2, hp4);
  10652. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  10653. { remove jCC }
  10654. RemoveInstruction(hp1);
  10655. { Now we can safely decrement it }
  10656. tasmlabel(symbol).decrefs;
  10657. { Remove label xxx (it will have a ref of zero due to the initial check }
  10658. StripLabelFast(hp4);
  10659. { remove jmp }
  10660. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  10661. RemoveInstruction(hp2);
  10662. { As before, now we can safely decrement it }
  10663. tasmlabel(symbol).decrefs;
  10664. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  10665. if tasmlabel(symbol).getrefs = 0 then
  10666. StripLabelFast(hp3);
  10667. if Assigned(p) then
  10668. result:=true;
  10669. exit;
  10670. end;
  10671. end;
  10672. end;
  10673. end;
  10674. {$endif i8086}
  10675. end;
  10676. end;
  10677. end;
  10678. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  10679. var
  10680. hp1,hp2,hp3: tai;
  10681. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  10682. NewSize: TOpSize;
  10683. NewRegSize: TSubRegister;
  10684. Limit: TCgInt;
  10685. SwapOper: POper;
  10686. begin
  10687. result:=false;
  10688. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  10689. GetNextInstruction(p,hp1) and
  10690. (hp1.typ = ait_instruction);
  10691. if reg_and_hp1_is_instr and
  10692. (
  10693. (taicpu(hp1).opcode <> A_LEA) or
  10694. { If the LEA instruction can be converted into an arithmetic instruction,
  10695. it may be possible to then fold it. }
  10696. (
  10697. { If the flags register is in use, don't change the instruction
  10698. to an ADD otherwise this will scramble the flags. [Kit] }
  10699. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  10700. ConvertLEA(taicpu(hp1))
  10701. )
  10702. ) and
  10703. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  10704. GetNextInstruction(hp1,hp2) and
  10705. MatchInstruction(hp2,A_MOV,[]) and
  10706. (taicpu(hp2).oper[0]^.typ = top_reg) and
  10707. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  10708. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  10709. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  10710. {$ifdef i386}
  10711. { not all registers have byte size sub registers on i386 }
  10712. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  10713. {$endif i386}
  10714. (((taicpu(hp1).ops=2) and
  10715. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  10716. ((taicpu(hp1).ops=1) and
  10717. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  10718. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  10719. begin
  10720. { change movsX/movzX reg/ref, reg2
  10721. add/sub/or/... reg3/$const, reg2
  10722. mov reg2 reg/ref
  10723. to add/sub/or/... reg3/$const, reg/ref }
  10724. { by example:
  10725. movswl %si,%eax movswl %si,%eax p
  10726. decl %eax addl %edx,%eax hp1
  10727. movw %ax,%si movw %ax,%si hp2
  10728. ->
  10729. movswl %si,%eax movswl %si,%eax p
  10730. decw %eax addw %edx,%eax hp1
  10731. movw %ax,%si movw %ax,%si hp2
  10732. }
  10733. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  10734. {
  10735. ->
  10736. movswl %si,%eax movswl %si,%eax p
  10737. decw %si addw %dx,%si hp1
  10738. movw %ax,%si movw %ax,%si hp2
  10739. }
  10740. case taicpu(hp1).ops of
  10741. 1:
  10742. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  10743. 2:
  10744. begin
  10745. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  10746. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10747. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  10748. end;
  10749. else
  10750. internalerror(2008042702);
  10751. end;
  10752. {
  10753. ->
  10754. decw %si addw %dx,%si p
  10755. }
  10756. DebugMsg(SPeepholeOptimization + 'var3',p);
  10757. RemoveCurrentP(p, hp1);
  10758. RemoveInstruction(hp2);
  10759. Result := True;
  10760. Exit;
  10761. end;
  10762. if reg_and_hp1_is_instr and
  10763. (taicpu(hp1).opcode = A_MOV) and
  10764. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10765. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  10766. {$ifdef x86_64}
  10767. { check for implicit extension to 64 bit }
  10768. or
  10769. ((taicpu(p).opsize in [S_BL,S_WL]) and
  10770. (taicpu(hp1).opsize=S_Q) and
  10771. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  10772. )
  10773. {$endif x86_64}
  10774. )
  10775. then
  10776. begin
  10777. { change
  10778. movx %reg1,%reg2
  10779. mov %reg2,%reg3
  10780. dealloc %reg2
  10781. into
  10782. movx %reg,%reg3
  10783. }
  10784. TransferUsedRegs(TmpUsedRegs);
  10785. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10786. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  10787. begin
  10788. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  10789. {$ifdef x86_64}
  10790. if (taicpu(p).opsize in [S_BL,S_WL]) and
  10791. (taicpu(hp1).opsize=S_Q) then
  10792. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  10793. else
  10794. {$endif x86_64}
  10795. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  10796. RemoveInstruction(hp1);
  10797. Result := True;
  10798. Exit;
  10799. end;
  10800. end;
  10801. if reg_and_hp1_is_instr and
  10802. ((taicpu(hp1).opcode=A_MOV) or
  10803. (taicpu(hp1).opcode=A_ADD) or
  10804. (taicpu(hp1).opcode=A_SUB) or
  10805. (taicpu(hp1).opcode=A_CMP) or
  10806. (taicpu(hp1).opcode=A_OR) or
  10807. (taicpu(hp1).opcode=A_XOR) or
  10808. (taicpu(hp1).opcode=A_AND)
  10809. ) and
  10810. (taicpu(hp1).oper[1]^.typ = top_reg) then
  10811. begin
  10812. AndTest := (taicpu(hp1).opcode=A_AND) and
  10813. GetNextInstruction(hp1, hp2) and
  10814. (hp2.typ = ait_instruction) and
  10815. (
  10816. (
  10817. (taicpu(hp2).opcode=A_TEST) and
  10818. (
  10819. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  10820. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  10821. (
  10822. { If the AND and TEST instructions share a constant, this is also valid }
  10823. (taicpu(hp1).oper[0]^.typ = top_const) and
  10824. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  10825. )
  10826. ) and
  10827. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  10828. ) or
  10829. (
  10830. (taicpu(hp2).opcode=A_CMP) and
  10831. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  10832. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  10833. )
  10834. );
  10835. { change
  10836. movx (oper),%reg2
  10837. and $x,%reg2
  10838. test %reg2,%reg2
  10839. dealloc %reg2
  10840. into
  10841. op %reg1,%reg3
  10842. if the second op accesses only the bits stored in reg1
  10843. }
  10844. if ((taicpu(p).oper[0]^.typ=top_reg) or
  10845. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  10846. (taicpu(hp1).oper[0]^.typ = top_const) and
  10847. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  10848. AndTest then
  10849. begin
  10850. { Check if the AND constant is in range }
  10851. case taicpu(p).opsize of
  10852. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10853. begin
  10854. NewSize := S_B;
  10855. Limit := $FF;
  10856. end;
  10857. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10858. begin
  10859. NewSize := S_W;
  10860. Limit := $FFFF;
  10861. end;
  10862. {$ifdef x86_64}
  10863. S_LQ:
  10864. begin
  10865. NewSize := S_L;
  10866. Limit := $FFFFFFFF;
  10867. end;
  10868. {$endif x86_64}
  10869. else
  10870. InternalError(2021120303);
  10871. end;
  10872. if (
  10873. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  10874. { Check for negative operands }
  10875. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  10876. ) and
  10877. GetNextInstruction(hp2,hp3) and
  10878. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  10879. (taicpu(hp3).condition in [C_E,C_NE]) then
  10880. begin
  10881. TransferUsedRegs(TmpUsedRegs);
  10882. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10883. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  10884. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  10885. begin
  10886. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  10887. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  10888. taicpu(hp1).opcode := A_TEST;
  10889. taicpu(hp1).opsize := NewSize;
  10890. RemoveInstruction(hp2);
  10891. RemoveCurrentP(p, hp1);
  10892. Result:=true;
  10893. exit;
  10894. end;
  10895. end;
  10896. end;
  10897. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  10898. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  10899. (taicpu(hp1).opsize=S_B)) or
  10900. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  10901. (taicpu(hp1).opsize=S_W))
  10902. {$ifdef x86_64}
  10903. or ((taicpu(p).opsize=S_LQ) and
  10904. (taicpu(hp1).opsize=S_L))
  10905. {$endif x86_64}
  10906. ) and
  10907. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  10908. begin
  10909. { change
  10910. movx %reg1,%reg2
  10911. op %reg2,%reg3
  10912. dealloc %reg2
  10913. into
  10914. op %reg1,%reg3
  10915. if the second op accesses only the bits stored in reg1
  10916. }
  10917. TransferUsedRegs(TmpUsedRegs);
  10918. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10919. if AndTest then
  10920. begin
  10921. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10922. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  10923. end
  10924. else
  10925. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  10926. if not RegUsed then
  10927. begin
  10928. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  10929. if taicpu(p).oper[0]^.typ=top_reg then
  10930. begin
  10931. case taicpu(hp1).opsize of
  10932. S_B:
  10933. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  10934. S_W:
  10935. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  10936. S_L:
  10937. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  10938. else
  10939. Internalerror(2020102301);
  10940. end;
  10941. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  10942. end
  10943. else
  10944. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  10945. RemoveCurrentP(p);
  10946. if AndTest then
  10947. RemoveInstruction(hp2);
  10948. result:=true;
  10949. exit;
  10950. end;
  10951. end
  10952. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  10953. (
  10954. { Bitwise operations only }
  10955. (taicpu(hp1).opcode=A_AND) or
  10956. (taicpu(hp1).opcode=A_TEST) or
  10957. (
  10958. (taicpu(hp1).oper[0]^.typ = top_const) and
  10959. (
  10960. (taicpu(hp1).opcode=A_OR) or
  10961. (taicpu(hp1).opcode=A_XOR)
  10962. )
  10963. )
  10964. ) and
  10965. (
  10966. (taicpu(hp1).oper[0]^.typ = top_const) or
  10967. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  10968. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  10969. ) then
  10970. begin
  10971. { change
  10972. movx %reg2,%reg2
  10973. op const,%reg2
  10974. into
  10975. op const,%reg2 (smaller version)
  10976. movx %reg2,%reg2
  10977. also change
  10978. movx %reg1,%reg2
  10979. and/test (oper),%reg2
  10980. dealloc %reg2
  10981. into
  10982. and/test (oper),%reg1
  10983. }
  10984. case taicpu(p).opsize of
  10985. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10986. begin
  10987. NewSize := S_B;
  10988. NewRegSize := R_SUBL;
  10989. Limit := $FF;
  10990. end;
  10991. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10992. begin
  10993. NewSize := S_W;
  10994. NewRegSize := R_SUBW;
  10995. Limit := $FFFF;
  10996. end;
  10997. {$ifdef x86_64}
  10998. S_LQ:
  10999. begin
  11000. NewSize := S_L;
  11001. NewRegSize := R_SUBD;
  11002. Limit := $FFFFFFFF;
  11003. end;
  11004. {$endif x86_64}
  11005. else
  11006. Internalerror(2021120302);
  11007. end;
  11008. TransferUsedRegs(TmpUsedRegs);
  11009. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11010. if AndTest then
  11011. begin
  11012. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11013. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  11014. end
  11015. else
  11016. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  11017. if
  11018. (
  11019. (taicpu(p).opcode = A_MOVZX) and
  11020. (
  11021. (taicpu(hp1).opcode=A_AND) or
  11022. (taicpu(hp1).opcode=A_TEST)
  11023. ) and
  11024. not (
  11025. { If both are references, then the final instruction will have
  11026. both operands as references, which is not allowed }
  11027. (taicpu(p).oper[0]^.typ = top_ref) and
  11028. (taicpu(hp1).oper[0]^.typ = top_ref)
  11029. ) and
  11030. not RegUsed
  11031. ) or
  11032. (
  11033. (
  11034. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  11035. not RegUsed
  11036. ) and
  11037. (taicpu(p).oper[0]^.typ = top_reg) and
  11038. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11039. (taicpu(hp1).oper[0]^.typ = top_const) and
  11040. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  11041. ) then
  11042. begin
  11043. {$if defined(i386) or defined(i8086)}
  11044. { If the target size is 8-bit, make sure we can actually encode it }
  11045. 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
  11046. Exit;
  11047. {$endif i386 or i8086}
  11048. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  11049. taicpu(hp1).opsize := NewSize;
  11050. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  11051. if AndTest then
  11052. begin
  11053. RemoveInstruction(hp2);
  11054. if not RegUsed then
  11055. begin
  11056. taicpu(hp1).opcode := A_TEST;
  11057. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  11058. begin
  11059. { Make sure the reference is the second operand }
  11060. SwapOper := taicpu(hp1).oper[0];
  11061. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  11062. taicpu(hp1).oper[1] := SwapOper;
  11063. end;
  11064. end;
  11065. end;
  11066. case taicpu(hp1).oper[0]^.typ of
  11067. top_reg:
  11068. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  11069. top_const:
  11070. { For the AND/TEST case }
  11071. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  11072. else
  11073. ;
  11074. end;
  11075. if RegUsed then
  11076. begin
  11077. AsmL.Remove(p);
  11078. AsmL.InsertAfter(p, hp1);
  11079. p := hp1;
  11080. end
  11081. else
  11082. RemoveCurrentP(p, hp1);
  11083. result:=true;
  11084. exit;
  11085. end;
  11086. end;
  11087. end;
  11088. if reg_and_hp1_is_instr and
  11089. (taicpu(p).oper[0]^.typ = top_reg) and
  11090. (
  11091. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  11092. ) and
  11093. (taicpu(hp1).oper[0]^.typ = top_const) and
  11094. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11095. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  11096. { Minimum shift value allowed is the bit difference between the sizes }
  11097. (taicpu(hp1).oper[0]^.val >=
  11098. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  11099. 8 * (
  11100. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  11101. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  11102. )
  11103. ) then
  11104. begin
  11105. { For:
  11106. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  11107. shl/sal ##, %reg1
  11108. Remove the movsx/movzx instruction if the shift overwrites the
  11109. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  11110. }
  11111. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  11112. RemoveCurrentP(p, hp1);
  11113. Result := True;
  11114. Exit;
  11115. end
  11116. else if reg_and_hp1_is_instr and
  11117. (taicpu(p).oper[0]^.typ = top_reg) and
  11118. (
  11119. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  11120. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  11121. ) and
  11122. (taicpu(hp1).oper[0]^.typ = top_const) and
  11123. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11124. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  11125. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  11126. (taicpu(hp1).oper[0]^.val <
  11127. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  11128. 8 * (
  11129. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  11130. )
  11131. ) then
  11132. begin
  11133. { For:
  11134. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  11135. sar ##, %reg1 shr ##, %reg1
  11136. Move the shift to before the movx instruction if the shift value
  11137. is not too large.
  11138. }
  11139. asml.Remove(hp1);
  11140. asml.InsertBefore(hp1, p);
  11141. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  11142. case taicpu(p).opsize of
  11143. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  11144. taicpu(hp1).opsize := S_B;
  11145. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  11146. taicpu(hp1).opsize := S_W;
  11147. {$ifdef x86_64}
  11148. S_LQ:
  11149. taicpu(hp1).opsize := S_L;
  11150. {$endif}
  11151. else
  11152. InternalError(2020112401);
  11153. end;
  11154. if (taicpu(hp1).opcode = A_SHR) then
  11155. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  11156. else
  11157. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  11158. Result := True;
  11159. end;
  11160. if reg_and_hp1_is_instr and
  11161. (taicpu(p).oper[0]^.typ = top_reg) and
  11162. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11163. (
  11164. (taicpu(hp1).opcode = taicpu(p).opcode)
  11165. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  11166. {$ifdef x86_64}
  11167. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  11168. {$endif x86_64}
  11169. ) then
  11170. begin
  11171. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  11172. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  11173. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  11174. begin
  11175. {
  11176. For example:
  11177. movzbw %al,%ax
  11178. movzwl %ax,%eax
  11179. Compress into:
  11180. movzbl %al,%eax
  11181. }
  11182. RegUsed := False;
  11183. case taicpu(p).opsize of
  11184. S_BW:
  11185. case taicpu(hp1).opsize of
  11186. S_WL:
  11187. begin
  11188. taicpu(p).opsize := S_BL;
  11189. RegUsed := True;
  11190. end;
  11191. {$ifdef x86_64}
  11192. S_WQ:
  11193. begin
  11194. if taicpu(p).opcode = A_MOVZX then
  11195. begin
  11196. taicpu(p).opsize := S_BL;
  11197. { 64-bit zero extension is implicit, so change to the 32-bit register }
  11198. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11199. end
  11200. else
  11201. taicpu(p).opsize := S_BQ;
  11202. RegUsed := True;
  11203. end;
  11204. {$endif x86_64}
  11205. else
  11206. ;
  11207. end;
  11208. {$ifdef x86_64}
  11209. S_BL:
  11210. case taicpu(hp1).opsize of
  11211. S_LQ:
  11212. begin
  11213. if taicpu(p).opcode = A_MOVZX then
  11214. begin
  11215. taicpu(p).opsize := S_BL;
  11216. { 64-bit zero extension is implicit, so change to the 32-bit register }
  11217. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11218. end
  11219. else
  11220. taicpu(p).opsize := S_BQ;
  11221. RegUsed := True;
  11222. end;
  11223. else
  11224. ;
  11225. end;
  11226. S_WL:
  11227. case taicpu(hp1).opsize of
  11228. S_LQ:
  11229. begin
  11230. if taicpu(p).opcode = A_MOVZX then
  11231. begin
  11232. taicpu(p).opsize := S_WL;
  11233. { 64-bit zero extension is implicit, so change to the 32-bit register }
  11234. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11235. end
  11236. else
  11237. taicpu(p).opsize := S_WQ;
  11238. RegUsed := True;
  11239. end;
  11240. else
  11241. ;
  11242. end;
  11243. {$endif x86_64}
  11244. else
  11245. ;
  11246. end;
  11247. if RegUsed then
  11248. begin
  11249. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  11250. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  11251. RemoveInstruction(hp1);
  11252. Result := True;
  11253. Exit;
  11254. end;
  11255. end;
  11256. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  11257. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  11258. GetNextInstruction(hp1, hp2) and
  11259. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  11260. (
  11261. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  11262. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  11263. {$ifdef x86_64}
  11264. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  11265. {$endif x86_64}
  11266. ) and
  11267. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  11268. (
  11269. (
  11270. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  11271. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  11272. ) or
  11273. (
  11274. { Only allow the operands in reverse order for TEST instructions }
  11275. (taicpu(hp2).opcode = A_TEST) and
  11276. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  11277. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  11278. )
  11279. ) then
  11280. begin
  11281. {
  11282. For example:
  11283. movzbl %al,%eax
  11284. movzbl (ref),%edx
  11285. andl %edx,%eax
  11286. (%edx deallocated)
  11287. Change to:
  11288. andb (ref),%al
  11289. movzbl %al,%eax
  11290. Rules are:
  11291. - First two instructions have the same opcode and opsize
  11292. - First instruction's operands are the same super-register
  11293. - Second instruction operates on a different register
  11294. - Third instruction is AND, OR, XOR or TEST
  11295. - Third instruction's operands are the destination registers of the first two instructions
  11296. - Third instruction writes to the destination register of the first instruction (except with TEST)
  11297. - Second instruction's destination register is deallocated afterwards
  11298. }
  11299. TransferUsedRegs(TmpUsedRegs);
  11300. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11301. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  11302. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  11303. begin
  11304. case taicpu(p).opsize of
  11305. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11306. NewSize := S_B;
  11307. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11308. NewSize := S_W;
  11309. {$ifdef x86_64}
  11310. S_LQ:
  11311. NewSize := S_L;
  11312. {$endif x86_64}
  11313. else
  11314. InternalError(2021120301);
  11315. end;
  11316. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  11317. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  11318. taicpu(hp2).opsize := NewSize;
  11319. RemoveInstruction(hp1);
  11320. { With TEST, it's best to keep the MOVX instruction at the top }
  11321. if (taicpu(hp2).opcode <> A_TEST) then
  11322. begin
  11323. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  11324. asml.Remove(p);
  11325. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  11326. asml.InsertAfter(p, hp2);
  11327. p := hp2;
  11328. end
  11329. else
  11330. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  11331. Result := True;
  11332. Exit;
  11333. end;
  11334. end;
  11335. end;
  11336. if taicpu(p).opcode=A_MOVZX then
  11337. begin
  11338. { removes superfluous And's after movzx's }
  11339. if reg_and_hp1_is_instr and
  11340. (taicpu(hp1).opcode = A_AND) and
  11341. MatchOpType(taicpu(hp1),top_const,top_reg) and
  11342. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  11343. {$ifdef x86_64}
  11344. { check for implicit extension to 64 bit }
  11345. or
  11346. ((taicpu(p).opsize in [S_BL,S_WL]) and
  11347. (taicpu(hp1).opsize=S_Q) and
  11348. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  11349. )
  11350. {$endif x86_64}
  11351. )
  11352. then
  11353. begin
  11354. case taicpu(p).opsize Of
  11355. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11356. if (taicpu(hp1).oper[0]^.val = $ff) then
  11357. begin
  11358. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  11359. RemoveInstruction(hp1);
  11360. Result:=true;
  11361. exit;
  11362. end;
  11363. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11364. if (taicpu(hp1).oper[0]^.val = $ffff) then
  11365. begin
  11366. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  11367. RemoveInstruction(hp1);
  11368. Result:=true;
  11369. exit;
  11370. end;
  11371. {$ifdef x86_64}
  11372. S_LQ:
  11373. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  11374. begin
  11375. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  11376. RemoveInstruction(hp1);
  11377. Result:=true;
  11378. exit;
  11379. end;
  11380. {$endif x86_64}
  11381. else
  11382. ;
  11383. end;
  11384. { we cannot get rid of the and, but can we get rid of the movz ?}
  11385. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  11386. begin
  11387. case taicpu(p).opsize Of
  11388. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11389. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  11390. begin
  11391. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  11392. RemoveCurrentP(p,hp1);
  11393. Result:=true;
  11394. exit;
  11395. end;
  11396. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11397. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  11398. begin
  11399. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  11400. RemoveCurrentP(p,hp1);
  11401. Result:=true;
  11402. exit;
  11403. end;
  11404. {$ifdef x86_64}
  11405. S_LQ:
  11406. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  11407. begin
  11408. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  11409. RemoveCurrentP(p,hp1);
  11410. Result:=true;
  11411. exit;
  11412. end;
  11413. {$endif x86_64}
  11414. else
  11415. ;
  11416. end;
  11417. end;
  11418. end;
  11419. { changes some movzx constructs to faster synonyms (all examples
  11420. are given with eax/ax, but are also valid for other registers)}
  11421. if MatchOpType(taicpu(p),top_reg,top_reg) then
  11422. begin
  11423. case taicpu(p).opsize of
  11424. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  11425. (the machine code is equivalent to movzbl %al,%eax), but the
  11426. code generator still generates that assembler instruction and
  11427. it is silently converted. This should probably be checked.
  11428. [Kit] }
  11429. S_BW:
  11430. begin
  11431. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  11432. (
  11433. not IsMOVZXAcceptable
  11434. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  11435. or (
  11436. (cs_opt_size in current_settings.optimizerswitches) and
  11437. (taicpu(p).oper[1]^.reg = NR_AX)
  11438. )
  11439. ) then
  11440. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  11441. begin
  11442. DebugMsg(SPeepholeOptimization + 'var7',p);
  11443. taicpu(p).opcode := A_AND;
  11444. taicpu(p).changeopsize(S_W);
  11445. taicpu(p).loadConst(0,$ff);
  11446. Result := True;
  11447. end
  11448. else if not IsMOVZXAcceptable and
  11449. GetNextInstruction(p, hp1) and
  11450. (tai(hp1).typ = ait_instruction) and
  11451. (taicpu(hp1).opcode = A_AND) and
  11452. MatchOpType(taicpu(hp1),top_const,top_reg) and
  11453. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  11454. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  11455. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  11456. begin
  11457. DebugMsg(SPeepholeOptimization + 'var8',p);
  11458. taicpu(p).opcode := A_MOV;
  11459. taicpu(p).changeopsize(S_W);
  11460. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  11461. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  11462. Result := True;
  11463. end;
  11464. end;
  11465. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  11466. S_BL:
  11467. if not IsMOVZXAcceptable then
  11468. begin
  11469. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  11470. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  11471. begin
  11472. DebugMsg(SPeepholeOptimization + 'var9',p);
  11473. taicpu(p).opcode := A_AND;
  11474. taicpu(p).changeopsize(S_L);
  11475. taicpu(p).loadConst(0,$ff);
  11476. Result := True;
  11477. end
  11478. else if GetNextInstruction(p, hp1) and
  11479. (tai(hp1).typ = ait_instruction) and
  11480. (taicpu(hp1).opcode = A_AND) and
  11481. MatchOpType(taicpu(hp1),top_const,top_reg) and
  11482. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  11483. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  11484. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  11485. begin
  11486. DebugMsg(SPeepholeOptimization + 'var10',p);
  11487. taicpu(p).opcode := A_MOV;
  11488. taicpu(p).changeopsize(S_L);
  11489. { do not use R_SUBWHOLE
  11490. as movl %rdx,%eax
  11491. is invalid in assembler PM }
  11492. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  11493. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  11494. Result := True;
  11495. end;
  11496. end;
  11497. {$endif i8086}
  11498. S_WL:
  11499. if not IsMOVZXAcceptable then
  11500. begin
  11501. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  11502. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  11503. begin
  11504. DebugMsg(SPeepholeOptimization + 'var11',p);
  11505. taicpu(p).opcode := A_AND;
  11506. taicpu(p).changeopsize(S_L);
  11507. taicpu(p).loadConst(0,$ffff);
  11508. Result := True;
  11509. end
  11510. else if GetNextInstruction(p, hp1) and
  11511. (tai(hp1).typ = ait_instruction) and
  11512. (taicpu(hp1).opcode = A_AND) and
  11513. (taicpu(hp1).oper[0]^.typ = top_const) and
  11514. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11515. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  11516. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  11517. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  11518. begin
  11519. DebugMsg(SPeepholeOptimization + 'var12',p);
  11520. taicpu(p).opcode := A_MOV;
  11521. taicpu(p).changeopsize(S_L);
  11522. { do not use R_SUBWHOLE
  11523. as movl %rdx,%eax
  11524. is invalid in assembler PM }
  11525. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  11526. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  11527. Result := True;
  11528. end;
  11529. end;
  11530. else
  11531. InternalError(2017050705);
  11532. end;
  11533. end
  11534. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  11535. begin
  11536. if GetNextInstruction(p, hp1) and
  11537. (tai(hp1).typ = ait_instruction) and
  11538. (taicpu(hp1).opcode = A_AND) and
  11539. MatchOpType(taicpu(hp1),top_const,top_reg) and
  11540. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  11541. begin
  11542. //taicpu(p).opcode := A_MOV;
  11543. case taicpu(p).opsize Of
  11544. S_BL:
  11545. begin
  11546. DebugMsg(SPeepholeOptimization + 'var13',p);
  11547. taicpu(hp1).changeopsize(S_L);
  11548. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  11549. end;
  11550. S_WL:
  11551. begin
  11552. DebugMsg(SPeepholeOptimization + 'var14',p);
  11553. taicpu(hp1).changeopsize(S_L);
  11554. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  11555. end;
  11556. S_BW:
  11557. begin
  11558. DebugMsg(SPeepholeOptimization + 'var15',p);
  11559. taicpu(hp1).changeopsize(S_W);
  11560. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  11561. end;
  11562. else
  11563. Internalerror(2017050704)
  11564. end;
  11565. Result := True;
  11566. end;
  11567. end;
  11568. end;
  11569. end;
  11570. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  11571. var
  11572. hp1, hp2 : tai;
  11573. MaskLength : Cardinal;
  11574. MaskedBits : TCgInt;
  11575. ActiveReg : TRegister;
  11576. begin
  11577. Result:=false;
  11578. { There are no optimisations for reference targets }
  11579. if (taicpu(p).oper[1]^.typ <> top_reg) then
  11580. Exit;
  11581. while GetNextInstruction(p, hp1) and
  11582. (hp1.typ = ait_instruction) do
  11583. begin
  11584. if (taicpu(p).oper[0]^.typ = top_const) then
  11585. begin
  11586. case taicpu(hp1).opcode of
  11587. A_AND:
  11588. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  11589. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  11590. { the second register must contain the first one, so compare their subreg types }
  11591. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  11592. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  11593. { change
  11594. and const1, reg
  11595. and const2, reg
  11596. to
  11597. and (const1 and const2), reg
  11598. }
  11599. begin
  11600. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  11601. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  11602. RemoveCurrentP(p, hp1);
  11603. Result:=true;
  11604. exit;
  11605. end;
  11606. A_CMP:
  11607. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  11608. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  11609. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  11610. { Just check that the condition on the next instruction is compatible }
  11611. GetNextInstruction(hp1, hp2) and
  11612. (hp2.typ = ait_instruction) and
  11613. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  11614. then
  11615. { change
  11616. and 2^n, reg
  11617. cmp 2^n, reg
  11618. j(c) / set(c) / cmov(c) (c is equal or not equal)
  11619. to
  11620. and 2^n, reg
  11621. test reg, reg
  11622. j(~c) / set(~c) / cmov(~c)
  11623. }
  11624. begin
  11625. { Keep TEST instruction in, rather than remove it, because
  11626. it may trigger other optimisations such as MovAndTest2Test }
  11627. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  11628. taicpu(hp1).opcode := A_TEST;
  11629. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  11630. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  11631. Result := True;
  11632. Exit;
  11633. end;
  11634. A_MOVZX:
  11635. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11636. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  11637. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  11638. (
  11639. (
  11640. (taicpu(p).opsize=S_W) and
  11641. (taicpu(hp1).opsize=S_BW)
  11642. ) or
  11643. (
  11644. (taicpu(p).opsize=S_L) and
  11645. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  11646. )
  11647. {$ifdef x86_64}
  11648. or
  11649. (
  11650. (taicpu(p).opsize=S_Q) and
  11651. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  11652. )
  11653. {$endif x86_64}
  11654. ) then
  11655. begin
  11656. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  11657. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  11658. ) or
  11659. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  11660. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  11661. then
  11662. begin
  11663. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  11664. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  11665. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  11666. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  11667. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  11668. }
  11669. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  11670. RemoveInstruction(hp1);
  11671. { See if there are other optimisations possible }
  11672. Continue;
  11673. end;
  11674. end;
  11675. A_SHL:
  11676. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  11677. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  11678. begin
  11679. {$ifopt R+}
  11680. {$define RANGE_WAS_ON}
  11681. {$R-}
  11682. {$endif}
  11683. { get length of potential and mask }
  11684. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  11685. { really a mask? }
  11686. {$ifdef RANGE_WAS_ON}
  11687. {$R+}
  11688. {$endif}
  11689. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  11690. { unmasked part shifted out? }
  11691. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  11692. begin
  11693. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  11694. RemoveCurrentP(p, hp1);
  11695. Result:=true;
  11696. exit;
  11697. end;
  11698. end;
  11699. A_SHR:
  11700. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  11701. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  11702. (taicpu(hp1).oper[0]^.val <= 63) then
  11703. begin
  11704. { Does SHR combined with the AND cover all the bits?
  11705. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  11706. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  11707. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  11708. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  11709. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  11710. begin
  11711. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  11712. RemoveCurrentP(p, hp1);
  11713. Result := True;
  11714. Exit;
  11715. end;
  11716. end;
  11717. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  11718. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  11719. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  11720. begin
  11721. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  11722. (
  11723. (
  11724. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  11725. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  11726. ) or (
  11727. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  11728. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  11729. {$ifdef x86_64}
  11730. ) or (
  11731. (taicpu(hp1).opsize = S_LQ) and
  11732. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  11733. {$endif x86_64}
  11734. )
  11735. ) then
  11736. begin
  11737. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  11738. begin
  11739. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  11740. RemoveInstruction(hp1);
  11741. { See if there are other optimisations possible }
  11742. Continue;
  11743. end;
  11744. { The super-registers are the same though.
  11745. Note that this change by itself doesn't improve
  11746. code speed, but it opens up other optimisations. }
  11747. {$ifdef x86_64}
  11748. { Convert 64-bit register to 32-bit }
  11749. case taicpu(hp1).opsize of
  11750. S_BQ:
  11751. begin
  11752. taicpu(hp1).opsize := S_BL;
  11753. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  11754. end;
  11755. S_WQ:
  11756. begin
  11757. taicpu(hp1).opsize := S_WL;
  11758. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  11759. end
  11760. else
  11761. ;
  11762. end;
  11763. {$endif x86_64}
  11764. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  11765. taicpu(hp1).opcode := A_MOVZX;
  11766. { See if there are other optimisations possible }
  11767. Continue;
  11768. end;
  11769. end;
  11770. else
  11771. ;
  11772. end;
  11773. end
  11774. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  11775. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  11776. begin
  11777. {$ifdef x86_64}
  11778. if (taicpu(p).opsize = S_Q) then
  11779. begin
  11780. { Never necessary }
  11781. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  11782. RemoveCurrentP(p, hp1);
  11783. Result := True;
  11784. Exit;
  11785. end;
  11786. {$endif x86_64}
  11787. { Forward check to determine necessity of and %reg,%reg }
  11788. TransferUsedRegs(TmpUsedRegs);
  11789. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11790. { Saves on a bunch of dereferences }
  11791. ActiveReg := taicpu(p).oper[1]^.reg;
  11792. case taicpu(hp1).opcode of
  11793. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  11794. if (
  11795. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11796. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11797. ) and
  11798. (
  11799. (taicpu(hp1).opcode <> A_MOV) or
  11800. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  11801. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  11802. ) and
  11803. not (
  11804. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  11805. (taicpu(hp1).opcode = A_MOV) and
  11806. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  11807. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  11808. ) and
  11809. (
  11810. (
  11811. (taicpu(hp1).oper[0]^.typ = top_reg) and
  11812. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  11813. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  11814. ) or
  11815. (
  11816. {$ifdef x86_64}
  11817. (
  11818. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  11819. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  11820. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  11821. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  11822. ) and
  11823. {$endif x86_64}
  11824. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  11825. )
  11826. ) then
  11827. begin
  11828. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  11829. RemoveCurrentP(p, hp1);
  11830. Result := True;
  11831. Exit;
  11832. end;
  11833. A_ADD,
  11834. A_AND,
  11835. A_BSF,
  11836. A_BSR,
  11837. A_BTC,
  11838. A_BTR,
  11839. A_BTS,
  11840. A_OR,
  11841. A_SUB,
  11842. A_XOR:
  11843. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  11844. if (
  11845. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11846. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11847. ) and
  11848. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  11849. begin
  11850. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  11851. RemoveCurrentP(p, hp1);
  11852. Result := True;
  11853. Exit;
  11854. end;
  11855. A_CMP,
  11856. A_TEST:
  11857. if (
  11858. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11859. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11860. ) and
  11861. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  11862. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  11863. begin
  11864. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  11865. RemoveCurrentP(p, hp1);
  11866. Result := True;
  11867. Exit;
  11868. end;
  11869. A_BSWAP,
  11870. A_NEG,
  11871. A_NOT:
  11872. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  11873. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  11874. begin
  11875. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  11876. RemoveCurrentP(p, hp1);
  11877. Result := True;
  11878. Exit;
  11879. end;
  11880. else
  11881. ;
  11882. end;
  11883. end;
  11884. if (taicpu(hp1).is_jmp) and
  11885. (taicpu(hp1).opcode<>A_JMP) and
  11886. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  11887. begin
  11888. { change
  11889. and x, reg
  11890. jxx
  11891. to
  11892. test x, reg
  11893. jxx
  11894. if reg is deallocated before the
  11895. jump, but only if it's a conditional jump (PFV)
  11896. }
  11897. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  11898. taicpu(p).opcode := A_TEST;
  11899. Exit;
  11900. end;
  11901. Break;
  11902. end;
  11903. { Lone AND tests }
  11904. if (taicpu(p).oper[0]^.typ = top_const) then
  11905. begin
  11906. {
  11907. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  11908. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  11909. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  11910. }
  11911. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  11912. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  11913. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  11914. begin
  11915. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  11916. if taicpu(p).opsize = S_L then
  11917. begin
  11918. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  11919. Result := True;
  11920. end;
  11921. end;
  11922. end;
  11923. { Backward check to determine necessity of and %reg,%reg }
  11924. if (taicpu(p).oper[0]^.typ = top_reg) and
  11925. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  11926. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11927. GetLastInstruction(p, hp2) and
  11928. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  11929. { Check size of adjacent instruction to determine if the AND is
  11930. effectively a null operation }
  11931. (
  11932. (taicpu(p).opsize = taicpu(hp2).opsize) or
  11933. { Note: Don't include S_Q }
  11934. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  11935. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  11936. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  11937. ) then
  11938. begin
  11939. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  11940. { If GetNextInstruction returned False, hp1 will be nil }
  11941. RemoveCurrentP(p, hp1);
  11942. Result := True;
  11943. Exit;
  11944. end;
  11945. end;
  11946. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  11947. var
  11948. hp1, hp2: tai;
  11949. NewRef: TReference;
  11950. Distance: Cardinal;
  11951. TempTracking: TAllUsedRegs;
  11952. { This entire nested function is used in an if-statement below, but we
  11953. want to avoid all the used reg transfers and GetNextInstruction calls
  11954. until we really have to check }
  11955. function MemRegisterNotUsedLater: Boolean; inline;
  11956. var
  11957. hp2: tai;
  11958. begin
  11959. TransferUsedRegs(TmpUsedRegs);
  11960. hp2 := p;
  11961. repeat
  11962. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  11963. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  11964. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  11965. end;
  11966. begin
  11967. Result := False;
  11968. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  11969. (taicpu(p).oper[1]^.typ = top_reg) then
  11970. begin
  11971. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  11972. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  11973. (hp1.typ <> ait_instruction) or
  11974. not
  11975. (
  11976. (cs_opt_level3 in current_settings.optimizerswitches) or
  11977. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  11978. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  11979. ) then
  11980. Exit;
  11981. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  11982. addq $x, %rax
  11983. movq %rax, %rdx
  11984. sarq $63, %rdx
  11985. (%rax still in use)
  11986. ...letting OptPass2ADD run its course (and without -Os) will produce:
  11987. leaq $x(%rax),%rdx
  11988. addq $x, %rax
  11989. sarq $63, %rdx
  11990. ...which is okay since it breaks the dependency chain between
  11991. addq and movq, but if OptPass2MOV is called first:
  11992. addq $x, %rax
  11993. cqto
  11994. ...which is better in all ways, taking only 2 cycles to execute
  11995. and much smaller in code size.
  11996. }
  11997. { The extra register tracking is quite strenuous }
  11998. if (cs_opt_level2 in current_settings.optimizerswitches) and
  11999. MatchInstruction(hp1, A_MOV, []) then
  12000. begin
  12001. { Update the register tracking to the MOV instruction }
  12002. CopyUsedRegs(TempTracking);
  12003. hp2 := p;
  12004. repeat
  12005. UpdateUsedRegs(tai(hp2.Next));
  12006. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12007. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  12008. OptPass2ADD get called again }
  12009. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  12010. begin
  12011. { Reset the tracking to the current instruction }
  12012. RestoreUsedRegs(TempTracking);
  12013. ReleaseUsedRegs(TempTracking);
  12014. Result := True;
  12015. Exit;
  12016. end;
  12017. { Reset the tracking to the current instruction }
  12018. RestoreUsedRegs(TempTracking);
  12019. ReleaseUsedRegs(TempTracking);
  12020. { If OptPass2MOV returned True, we don't need to set Result to
  12021. True if hp1 didn't change because the ADD instruction didn't
  12022. get modified and we'll be evaluating hp1 again when the
  12023. peephole optimizer reaches it }
  12024. end;
  12025. { Change:
  12026. add %reg2,%reg1
  12027. (%reg2 not modified in between)
  12028. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  12029. To:
  12030. mov/s/z #(%reg1,%reg2),%reg1
  12031. }
  12032. if (taicpu(p).oper[0]^.typ = top_reg) and
  12033. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  12034. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  12035. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  12036. (
  12037. (
  12038. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  12039. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  12040. { r/esp cannot be an index }
  12041. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  12042. ) or (
  12043. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  12044. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  12045. )
  12046. ) and (
  12047. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  12048. (
  12049. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  12050. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  12051. MemRegisterNotUsedLater
  12052. )
  12053. ) then
  12054. begin
  12055. if (
  12056. { Instructions are guaranteed to be adjacent on -O2 and under }
  12057. (cs_opt_level3 in current_settings.optimizerswitches) and
  12058. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  12059. ) then
  12060. begin
  12061. { If the other register is used in between, move the MOV
  12062. instruction to right after the ADD instruction so a
  12063. saving can still be made }
  12064. Asml.Remove(hp1);
  12065. Asml.InsertAfter(hp1, p);
  12066. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  12067. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  12068. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  12069. RemoveCurrentp(p, hp1);
  12070. end
  12071. else
  12072. begin
  12073. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  12074. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  12075. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  12076. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  12077. if (cs_opt_level3 in current_settings.optimizerswitches) then
  12078. { hp1 may not be the immediate next instruction under -O3 }
  12079. RemoveCurrentp(p)
  12080. else
  12081. RemoveCurrentp(p, hp1);
  12082. end;
  12083. Result := True;
  12084. Exit;
  12085. end;
  12086. { Change:
  12087. addl/q $x,%reg1
  12088. movl/q %reg1,%reg2
  12089. To:
  12090. leal/q $x(%reg1),%reg2
  12091. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  12092. Breaks the dependency chain.
  12093. }
  12094. if (taicpu(p).oper[0]^.typ = top_const) and
  12095. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  12096. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12097. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  12098. (
  12099. { Instructions are guaranteed to be adjacent on -O2 and under }
  12100. not (cs_opt_level3 in current_settings.optimizerswitches) or
  12101. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  12102. ) then
  12103. begin
  12104. TransferUsedRegs(TmpUsedRegs);
  12105. hp2 := p;
  12106. repeat
  12107. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  12108. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12109. if (
  12110. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  12111. not (cs_opt_size in current_settings.optimizerswitches) or
  12112. (
  12113. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  12114. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  12115. )
  12116. ) then
  12117. begin
  12118. { Change the MOV instruction to a LEA instruction, and update the
  12119. first operand }
  12120. reference_reset(NewRef, 1, []);
  12121. NewRef.base := taicpu(p).oper[1]^.reg;
  12122. NewRef.scalefactor := 1;
  12123. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  12124. taicpu(hp1).opcode := A_LEA;
  12125. taicpu(hp1).loadref(0, NewRef);
  12126. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  12127. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  12128. begin
  12129. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  12130. { Move what is now the LEA instruction to before the ADD instruction }
  12131. Asml.Remove(hp1);
  12132. Asml.InsertBefore(hp1, p);
  12133. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  12134. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  12135. p := hp1;
  12136. end
  12137. else
  12138. begin
  12139. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  12140. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  12141. if (cs_opt_level3 in current_settings.optimizerswitches) then
  12142. { hp1 may not be the immediate next instruction under -O3 }
  12143. RemoveCurrentp(p)
  12144. else
  12145. RemoveCurrentp(p, hp1);
  12146. end;
  12147. Result := True;
  12148. end;
  12149. end;
  12150. end;
  12151. end;
  12152. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  12153. var
  12154. SubReg: TSubRegister;
  12155. begin
  12156. Result:=false;
  12157. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  12158. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  12159. with taicpu(p).oper[0]^.ref^ do
  12160. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  12161. begin
  12162. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  12163. begin
  12164. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  12165. taicpu(p).opcode := A_ADD;
  12166. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  12167. Result := True;
  12168. end
  12169. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  12170. begin
  12171. if (base <> NR_NO) then
  12172. begin
  12173. if (scalefactor <= 1) then
  12174. begin
  12175. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  12176. taicpu(p).opcode := A_ADD;
  12177. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  12178. Result := True;
  12179. end;
  12180. end
  12181. else
  12182. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  12183. if (scalefactor in [2, 4, 8]) then
  12184. begin
  12185. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  12186. taicpu(p).loadconst(0, BsrByte(scalefactor));
  12187. taicpu(p).opcode := A_SHL;
  12188. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  12189. Result := True;
  12190. end;
  12191. end;
  12192. end;
  12193. end;
  12194. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  12195. var
  12196. hp1, hp2: tai;
  12197. NewRef: TReference;
  12198. Distance: Cardinal;
  12199. TempTracking: TAllUsedRegs;
  12200. begin
  12201. Result := False;
  12202. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  12203. MatchOpType(taicpu(p),top_const,top_reg) then
  12204. begin
  12205. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  12206. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  12207. (hp1.typ <> ait_instruction) or
  12208. not
  12209. (
  12210. (cs_opt_level3 in current_settings.optimizerswitches) or
  12211. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  12212. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  12213. ) then
  12214. Exit;
  12215. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  12216. subq $x, %rax
  12217. movq %rax, %rdx
  12218. sarq $63, %rdx
  12219. (%rax still in use)
  12220. ...letting OptPass2SUB run its course (and without -Os) will produce:
  12221. leaq $-x(%rax),%rdx
  12222. movq $x, %rax
  12223. sarq $63, %rdx
  12224. ...which is okay since it breaks the dependency chain between
  12225. subq and movq, but if OptPass2MOV is called first:
  12226. subq $x, %rax
  12227. cqto
  12228. ...which is better in all ways, taking only 2 cycles to execute
  12229. and much smaller in code size.
  12230. }
  12231. { The extra register tracking is quite strenuous }
  12232. if (cs_opt_level2 in current_settings.optimizerswitches) and
  12233. MatchInstruction(hp1, A_MOV, []) then
  12234. begin
  12235. { Update the register tracking to the MOV instruction }
  12236. CopyUsedRegs(TempTracking);
  12237. hp2 := p;
  12238. repeat
  12239. UpdateUsedRegs(tai(hp2.Next));
  12240. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12241. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  12242. OptPass2SUB get called again }
  12243. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  12244. begin
  12245. { Reset the tracking to the current instruction }
  12246. RestoreUsedRegs(TempTracking);
  12247. ReleaseUsedRegs(TempTracking);
  12248. Result := True;
  12249. Exit;
  12250. end;
  12251. { Reset the tracking to the current instruction }
  12252. RestoreUsedRegs(TempTracking);
  12253. ReleaseUsedRegs(TempTracking);
  12254. { If OptPass2MOV returned True, we don't need to set Result to
  12255. True if hp1 didn't change because the SUB instruction didn't
  12256. get modified and we'll be evaluating hp1 again when the
  12257. peephole optimizer reaches it }
  12258. end;
  12259. { Change:
  12260. subl/q $x,%reg1
  12261. movl/q %reg1,%reg2
  12262. To:
  12263. leal/q $-x(%reg1),%reg2
  12264. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  12265. Breaks the dependency chain and potentially permits the removal of
  12266. a CMP instruction if one follows.
  12267. }
  12268. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  12269. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12270. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  12271. (
  12272. { Instructions are guaranteed to be adjacent on -O2 and under }
  12273. not (cs_opt_level3 in current_settings.optimizerswitches) or
  12274. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  12275. ) then
  12276. begin
  12277. TransferUsedRegs(TmpUsedRegs);
  12278. hp2 := p;
  12279. repeat
  12280. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  12281. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12282. if (
  12283. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  12284. not (cs_opt_size in current_settings.optimizerswitches) or
  12285. (
  12286. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  12287. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  12288. )
  12289. ) then
  12290. begin
  12291. { Change the MOV instruction to a LEA instruction, and update the
  12292. first operand }
  12293. reference_reset(NewRef, 1, []);
  12294. NewRef.base := taicpu(p).oper[1]^.reg;
  12295. NewRef.scalefactor := 1;
  12296. NewRef.offset := -taicpu(p).oper[0]^.val;
  12297. taicpu(hp1).opcode := A_LEA;
  12298. taicpu(hp1).loadref(0, NewRef);
  12299. TransferUsedRegs(TmpUsedRegs);
  12300. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12301. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  12302. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  12303. begin
  12304. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  12305. { Move what is now the LEA instruction to before the SUB instruction }
  12306. Asml.Remove(hp1);
  12307. Asml.InsertBefore(hp1, p);
  12308. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  12309. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  12310. p := hp1;
  12311. end
  12312. else
  12313. begin
  12314. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  12315. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  12316. if (cs_opt_level3 in current_settings.optimizerswitches) then
  12317. { hp1 may not be the immediate next instruction under -O3 }
  12318. RemoveCurrentp(p)
  12319. else
  12320. RemoveCurrentp(p, hp1);
  12321. end;
  12322. Result := True;
  12323. end;
  12324. end;
  12325. end;
  12326. end;
  12327. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  12328. begin
  12329. { we can skip all instructions not messing with the stack pointer }
  12330. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  12331. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  12332. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  12333. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  12334. ({(taicpu(hp1).ops=0) or }
  12335. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  12336. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  12337. ) and }
  12338. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  12339. )
  12340. ) do
  12341. GetNextInstruction(hp1,hp1);
  12342. Result:=assigned(hp1);
  12343. end;
  12344. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  12345. var
  12346. hp1, hp2, hp3, hp4, hp5: tai;
  12347. begin
  12348. Result:=false;
  12349. hp5:=nil;
  12350. { replace
  12351. leal(q) x(<stackpointer>),<stackpointer>
  12352. call procname
  12353. leal(q) -x(<stackpointer>),<stackpointer>
  12354. ret
  12355. by
  12356. jmp procname
  12357. but do it only on level 4 because it destroys stack back traces
  12358. }
  12359. if (cs_opt_level4 in current_settings.optimizerswitches) and
  12360. MatchOpType(taicpu(p),top_ref,top_reg) and
  12361. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  12362. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  12363. { the -8 or -24 are not required, but bail out early if possible,
  12364. higher values are unlikely }
  12365. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  12366. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  12367. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  12368. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  12369. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  12370. GetNextInstruction(p, hp1) and
  12371. { Take a copy of hp1 }
  12372. SetAndTest(hp1, hp4) and
  12373. { trick to skip label }
  12374. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  12375. SkipSimpleInstructions(hp1) and
  12376. MatchInstruction(hp1,A_CALL,[S_NO]) and
  12377. GetNextInstruction(hp1, hp2) and
  12378. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  12379. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  12380. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  12381. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  12382. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  12383. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  12384. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  12385. { Segment register will be NR_NO }
  12386. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  12387. GetNextInstruction(hp2, hp3) and
  12388. { trick to skip label }
  12389. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  12390. (MatchInstruction(hp3,A_RET,[S_NO]) or
  12391. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  12392. SetAndTest(hp3,hp5) and
  12393. GetNextInstruction(hp3,hp3) and
  12394. MatchInstruction(hp3,A_RET,[S_NO])
  12395. )
  12396. ) and
  12397. (taicpu(hp3).ops=0) then
  12398. begin
  12399. taicpu(hp1).opcode := A_JMP;
  12400. taicpu(hp1).is_jmp := true;
  12401. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  12402. RemoveCurrentP(p, hp4);
  12403. RemoveInstruction(hp2);
  12404. RemoveInstruction(hp3);
  12405. if Assigned(hp5) then
  12406. begin
  12407. AsmL.Remove(hp5);
  12408. ASmL.InsertBefore(hp5,hp1)
  12409. end;
  12410. Result:=true;
  12411. end;
  12412. end;
  12413. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  12414. {$ifdef x86_64}
  12415. var
  12416. hp1, hp2, hp3, hp4, hp5: tai;
  12417. {$endif x86_64}
  12418. begin
  12419. Result:=false;
  12420. {$ifdef x86_64}
  12421. hp5:=nil;
  12422. { replace
  12423. push %rax
  12424. call procname
  12425. pop %rcx
  12426. ret
  12427. by
  12428. jmp procname
  12429. but do it only on level 4 because it destroys stack back traces
  12430. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  12431. for all supported calling conventions
  12432. }
  12433. if (cs_opt_level4 in current_settings.optimizerswitches) and
  12434. MatchOpType(taicpu(p),top_reg) and
  12435. (taicpu(p).oper[0]^.reg=NR_RAX) and
  12436. GetNextInstruction(p, hp1) and
  12437. { Take a copy of hp1 }
  12438. SetAndTest(hp1, hp4) and
  12439. { trick to skip label }
  12440. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  12441. SkipSimpleInstructions(hp1) and
  12442. MatchInstruction(hp1,A_CALL,[S_NO]) and
  12443. GetNextInstruction(hp1, hp2) and
  12444. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  12445. MatchOpType(taicpu(hp2),top_reg) and
  12446. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  12447. GetNextInstruction(hp2, hp3) and
  12448. { trick to skip label }
  12449. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  12450. (MatchInstruction(hp3,A_RET,[S_NO]) or
  12451. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  12452. SetAndTest(hp3,hp5) and
  12453. GetNextInstruction(hp3,hp3) and
  12454. MatchInstruction(hp3,A_RET,[S_NO])
  12455. )
  12456. ) and
  12457. (taicpu(hp3).ops=0) then
  12458. begin
  12459. taicpu(hp1).opcode := A_JMP;
  12460. taicpu(hp1).is_jmp := true;
  12461. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  12462. RemoveCurrentP(p, hp4);
  12463. RemoveInstruction(hp2);
  12464. RemoveInstruction(hp3);
  12465. if Assigned(hp5) then
  12466. begin
  12467. AsmL.Remove(hp5);
  12468. ASmL.InsertBefore(hp5,hp1)
  12469. end;
  12470. Result:=true;
  12471. end;
  12472. {$endif x86_64}
  12473. end;
  12474. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  12475. var
  12476. Value, RegName: string;
  12477. begin
  12478. Result:=false;
  12479. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  12480. begin
  12481. case taicpu(p).oper[0]^.val of
  12482. 0:
  12483. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  12484. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  12485. begin
  12486. { change "mov $0,%reg" into "xor %reg,%reg" }
  12487. taicpu(p).opcode := A_XOR;
  12488. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  12489. Result := True;
  12490. {$ifdef x86_64}
  12491. end
  12492. else if (taicpu(p).opsize = S_Q) then
  12493. begin
  12494. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  12495. { The actual optimization }
  12496. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  12497. taicpu(p).changeopsize(S_L);
  12498. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  12499. Result := True;
  12500. end;
  12501. $1..$FFFFFFFF:
  12502. begin
  12503. { Code size reduction by J. Gareth "Kit" Moreton }
  12504. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  12505. case taicpu(p).opsize of
  12506. S_Q:
  12507. begin
  12508. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  12509. Value := debug_tostr(taicpu(p).oper[0]^.val);
  12510. { The actual optimization }
  12511. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  12512. taicpu(p).changeopsize(S_L);
  12513. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  12514. Result := True;
  12515. end;
  12516. else
  12517. { Do nothing };
  12518. end;
  12519. {$endif x86_64}
  12520. end;
  12521. -1:
  12522. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  12523. if (cs_opt_size in current_settings.optimizerswitches) and
  12524. (taicpu(p).opsize <> S_B) and
  12525. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  12526. begin
  12527. { change "mov $-1,%reg" into "or $-1,%reg" }
  12528. { NOTES:
  12529. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  12530. - This operation creates a false dependency on the register, so only do it when optimising for size
  12531. - 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
  12532. }
  12533. taicpu(p).opcode := A_OR;
  12534. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  12535. Result := True;
  12536. end;
  12537. else
  12538. { Do nothing };
  12539. end;
  12540. end;
  12541. end;
  12542. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  12543. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  12544. begin
  12545. Result := False;
  12546. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  12547. Exit;
  12548. { For sizes less than S_L, the byte size is equal or larger with BTx,
  12549. so don't bother optimising }
  12550. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  12551. Exit;
  12552. if (taicpu(p).oper[0]^.typ <> top_const) or
  12553. { If the value can fit into an 8-bit signed integer, a smaller
  12554. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  12555. falls within this range }
  12556. (
  12557. (taicpu(p).oper[0]^.val > -128) and
  12558. (taicpu(p).oper[0]^.val <= 127)
  12559. ) then
  12560. Exit;
  12561. { If we're optimising for size, this is acceptable }
  12562. if (cs_opt_size in current_settings.optimizerswitches) then
  12563. Exit(True);
  12564. if (taicpu(p).oper[1]^.typ = top_reg) and
  12565. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  12566. Exit(True);
  12567. if (taicpu(p).oper[1]^.typ <> top_reg) and
  12568. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  12569. Exit(True);
  12570. end;
  12571. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  12572. var
  12573. hp1: tai;
  12574. Value: TCGInt;
  12575. begin
  12576. Result := False;
  12577. if MatchOpType(taicpu(p), top_const, top_reg) then
  12578. begin
  12579. { Detect:
  12580. andw x, %ax (0 <= x < $8000)
  12581. ...
  12582. movzwl %ax,%eax
  12583. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  12584. }
  12585. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  12586. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  12587. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  12588. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  12589. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  12590. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  12591. begin
  12592. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  12593. taicpu(hp1).opcode := A_CWDE;
  12594. taicpu(hp1).clearop(0);
  12595. taicpu(hp1).clearop(1);
  12596. taicpu(hp1).ops := 0;
  12597. { A change was made, but not with p, so move forward 1 }
  12598. p := tai(p.Next);
  12599. Result := True;
  12600. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  12601. end;
  12602. end;
  12603. { If "not x" is a power of 2 (popcnt = 1), change:
  12604. and $x, %reg/ref
  12605. To:
  12606. btr lb(x), %reg/ref
  12607. }
  12608. if IsBTXAcceptable(p) and
  12609. (
  12610. { Make sure a TEST doesn't follow that plays with the register }
  12611. not GetNextInstruction(p, hp1) or
  12612. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  12613. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  12614. ) then
  12615. begin
  12616. {$push}{$R-}{$Q-}
  12617. { Value is a sign-extended 32-bit integer - just correct it
  12618. if it's represented as an unsigned value. Also, IsBTXAcceptable
  12619. checks to see if this operand is an immediate. }
  12620. Value := not taicpu(p).oper[0]^.val;
  12621. {$pop}
  12622. {$ifdef x86_64}
  12623. if taicpu(p).opsize = S_L then
  12624. {$endif x86_64}
  12625. Value := Value and $FFFFFFFF;
  12626. if (PopCnt(QWord(Value)) = 1) then
  12627. begin
  12628. 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);
  12629. taicpu(p).opcode := A_BTR;
  12630. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  12631. Result := True;
  12632. Exit;
  12633. end;
  12634. end;
  12635. end;
  12636. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  12637. begin
  12638. Result := False;
  12639. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  12640. Exit;
  12641. { Convert:
  12642. movswl %ax,%eax -> cwtl
  12643. movslq %eax,%rax -> cdqe
  12644. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  12645. refer to the same opcode and depends only on the assembler's
  12646. current operand-size attribute. [Kit]
  12647. }
  12648. with taicpu(p) do
  12649. case opsize of
  12650. S_WL:
  12651. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  12652. begin
  12653. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  12654. opcode := A_CWDE;
  12655. clearop(0);
  12656. clearop(1);
  12657. ops := 0;
  12658. Result := True;
  12659. end;
  12660. {$ifdef x86_64}
  12661. S_LQ:
  12662. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  12663. begin
  12664. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  12665. opcode := A_CDQE;
  12666. clearop(0);
  12667. clearop(1);
  12668. ops := 0;
  12669. Result := True;
  12670. end;
  12671. {$endif x86_64}
  12672. else
  12673. ;
  12674. end;
  12675. end;
  12676. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  12677. var
  12678. hp1, hp2: tai;
  12679. IdentityMask, Shift: TCGInt;
  12680. LimitSize: Topsize;
  12681. DoNotMerge: Boolean;
  12682. begin
  12683. Result := False;
  12684. { All these optimisations work on "shr const,%reg" }
  12685. if not MatchOpType(taicpu(p), top_const, top_reg) then
  12686. Exit;
  12687. DoNotMerge := False;
  12688. Shift := taicpu(p).oper[0]^.val;
  12689. LimitSize := taicpu(p).opsize;
  12690. hp1 := p;
  12691. repeat
  12692. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  12693. Break;
  12694. { Detect:
  12695. shr x, %reg
  12696. and y, %reg
  12697. If and y, %reg doesn't actually change the value of %reg (e.g. with
  12698. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  12699. }
  12700. case taicpu(hp1).opcode of
  12701. A_AND:
  12702. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  12703. MatchOpType(taicpu(hp1), top_const, top_reg) and
  12704. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12705. begin
  12706. { Make sure the FLAGS register isn't in use }
  12707. TransferUsedRegs(TmpUsedRegs);
  12708. hp2 := p;
  12709. repeat
  12710. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  12711. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12712. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  12713. begin
  12714. { Generate the identity mask }
  12715. case taicpu(p).opsize of
  12716. S_B:
  12717. IdentityMask := $FF shr Shift;
  12718. S_W:
  12719. IdentityMask := $FFFF shr Shift;
  12720. S_L:
  12721. IdentityMask := $FFFFFFFF shr Shift;
  12722. {$ifdef x86_64}
  12723. S_Q:
  12724. { We need to force the operands to be unsigned 64-bit
  12725. integers otherwise the wrong value is generated }
  12726. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  12727. {$endif x86_64}
  12728. else
  12729. InternalError(2022081501);
  12730. end;
  12731. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  12732. begin
  12733. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  12734. { All the possible 1 bits are covered, so we can remove the AND }
  12735. hp2 := tai(hp1.Previous);
  12736. RemoveInstruction(hp1);
  12737. { p wasn't actually changed, so don't set Result to True,
  12738. but a change was nonetheless made elsewhere }
  12739. Include(OptsToCheck, aoc_ForceNewIteration);
  12740. { Do another pass in case other AND or MOVZX instructions
  12741. follow }
  12742. hp1 := hp2;
  12743. Continue;
  12744. end;
  12745. end;
  12746. end;
  12747. A_TEST, A_CMP, A_Jcc:
  12748. { Skip over conditional jumps and relevant comparisons }
  12749. Continue;
  12750. A_MOVZX:
  12751. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  12752. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  12753. begin
  12754. { Since the original register is being read as is, subsequent
  12755. SHRs must not be merged at this point }
  12756. DoNotMerge := True;
  12757. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  12758. begin
  12759. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12760. begin
  12761. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  12762. { All the possible 1 bits are covered, so we can remove the AND }
  12763. hp2 := tai(hp1.Previous);
  12764. RemoveInstruction(hp1);
  12765. hp1 := hp2;
  12766. end
  12767. else { Different register target }
  12768. begin
  12769. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  12770. taicpu(hp1).opcode := A_MOV;
  12771. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  12772. case taicpu(hp1).opsize of
  12773. S_BW:
  12774. taicpu(hp1).opsize := S_W;
  12775. S_BL, S_WL:
  12776. taicpu(hp1).opsize := S_L;
  12777. else
  12778. InternalError(2022081503);
  12779. end;
  12780. end;
  12781. end
  12782. else if (Shift > 0) and
  12783. (taicpu(p).opsize = S_W) and
  12784. (taicpu(hp1).opsize = S_WL) and
  12785. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  12786. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  12787. begin
  12788. { Detect:
  12789. shr x, %ax (x > 0)
  12790. ...
  12791. movzwl %ax,%eax
  12792. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  12793. }
  12794. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  12795. taicpu(hp1).opcode := A_CWDE;
  12796. taicpu(hp1).clearop(0);
  12797. taicpu(hp1).clearop(1);
  12798. taicpu(hp1).ops := 0;
  12799. end;
  12800. { Move onto the next instruction }
  12801. Continue;
  12802. end;
  12803. A_SHL, A_SAL, A_SHR:
  12804. if (taicpu(hp1).opsize <= LimitSize) and
  12805. MatchOpType(taicpu(hp1), top_const, top_reg) and
  12806. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  12807. begin
  12808. { Make sure the sizes don't exceed the register size limit
  12809. (measured by the shift value falling below the limit) }
  12810. if taicpu(hp1).opsize < LimitSize then
  12811. LimitSize := taicpu(hp1).opsize;
  12812. if taicpu(hp1).opcode = A_SHR then
  12813. Inc(Shift, taicpu(hp1).oper[0]^.val)
  12814. else
  12815. begin
  12816. Dec(Shift, taicpu(hp1).oper[0]^.val);
  12817. DoNotMerge := True;
  12818. end;
  12819. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  12820. Break;
  12821. { Since we've established that the combined shift is within
  12822. limits, we can actually combine the adjacent SHR
  12823. instructions even if they're different sizes }
  12824. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  12825. begin
  12826. hp2 := tai(hp1.Previous);
  12827. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  12828. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  12829. RemoveInstruction(hp1);
  12830. hp1 := hp2;
  12831. end;
  12832. { Move onto the next instruction }
  12833. Continue;
  12834. end;
  12835. else
  12836. ;
  12837. end;
  12838. Break;
  12839. until False;
  12840. { Detect the following (looking backwards):
  12841. shr %cl,%reg
  12842. shr x, %reg
  12843. Swap the two SHR instructions to minimise a pipeline stall.
  12844. }
  12845. if GetLastInstruction(p, hp1) and
  12846. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  12847. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  12848. { First operand will be %cl }
  12849. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  12850. { Just to be sure }
  12851. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  12852. begin
  12853. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  12854. { Moving the entries this way ensures the register tracking remains correct }
  12855. Asml.Remove(p);
  12856. Asml.InsertBefore(p, hp1);
  12857. p := hp1;
  12858. { Don't set Result to True because the current instruction is now
  12859. "shr %cl,%reg" and there's nothing more we can do with it }
  12860. end;
  12861. end;
  12862. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  12863. var
  12864. hp1, hp2: tai;
  12865. Opposite, SecondOpposite: TAsmOp;
  12866. NewCond: TAsmCond;
  12867. begin
  12868. Result := False;
  12869. { Change:
  12870. add/sub 128,(dest)
  12871. To:
  12872. sub/add -128,(dest)
  12873. This generaally takes fewer bytes to encode because -128 can be stored
  12874. in a signed byte, whereas +128 cannot.
  12875. }
  12876. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  12877. begin
  12878. if taicpu(p).opcode = A_ADD then
  12879. Opposite := A_SUB
  12880. else
  12881. Opposite := A_ADD;
  12882. { Be careful if the flags are in use, because the CF flag inverts
  12883. when changing from ADD to SUB and vice versa }
  12884. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12885. GetNextInstruction(p, hp1) then
  12886. begin
  12887. TransferUsedRegs(TmpUsedRegs);
  12888. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  12889. hp2 := hp1;
  12890. { Scan ahead to check if everything's safe }
  12891. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  12892. begin
  12893. if (hp1.typ <> ait_instruction) then
  12894. { Probably unsafe since the flags are still in use }
  12895. Exit;
  12896. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  12897. { Stop searching at an unconditional jump }
  12898. Break;
  12899. if not
  12900. (
  12901. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  12902. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  12903. ) and
  12904. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  12905. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  12906. Exit;
  12907. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12908. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  12909. { Move to the next instruction }
  12910. GetNextInstruction(hp1, hp1);
  12911. end;
  12912. while Assigned(hp2) and (hp2 <> hp1) do
  12913. begin
  12914. NewCond := C_None;
  12915. case taicpu(hp2).condition of
  12916. C_A, C_NBE:
  12917. NewCond := C_BE;
  12918. C_B, C_C, C_NAE:
  12919. NewCond := C_AE;
  12920. C_AE, C_NB, C_NC:
  12921. NewCond := C_B;
  12922. C_BE, C_NA:
  12923. NewCond := C_A;
  12924. else
  12925. { No change needed };
  12926. end;
  12927. if NewCond <> C_None then
  12928. begin
  12929. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  12930. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  12931. taicpu(hp2).condition := NewCond;
  12932. end
  12933. else
  12934. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  12935. begin
  12936. { Because of the flipping of the carry bit, to ensure
  12937. the operation remains equivalent, ADC becomes SBB
  12938. and vice versa, and the constant is not-inverted.
  12939. If multiple ADCs or SBBs appear in a row, each one
  12940. changed causes the carry bit to invert, so they all
  12941. need to be flipped }
  12942. if taicpu(hp2).opcode = A_ADC then
  12943. SecondOpposite := A_SBB
  12944. else
  12945. SecondOpposite := A_ADC;
  12946. if taicpu(hp2).oper[0]^.typ <> top_const then
  12947. { Should have broken out of this optimisation already }
  12948. InternalError(2021112901);
  12949. 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]^) + ' -> ' +
  12950. 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);
  12951. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  12952. taicpu(hp2).opcode := SecondOpposite;
  12953. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  12954. end;
  12955. { Move to the next instruction }
  12956. GetNextInstruction(hp2, hp2);
  12957. end;
  12958. if (hp2 <> hp1) then
  12959. InternalError(2021111501);
  12960. end;
  12961. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  12962. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  12963. taicpu(p).opcode := Opposite;
  12964. taicpu(p).oper[0]^.val := -128;
  12965. { No further optimisations can be made on this instruction, so move
  12966. onto the next one to save time }
  12967. p := tai(p.Next);
  12968. UpdateUsedRegs(p);
  12969. Result := True;
  12970. Exit;
  12971. end;
  12972. { Detect:
  12973. add/sub %reg2,(dest)
  12974. add/sub x, (dest)
  12975. (dest can be a register or a reference)
  12976. Swap the instructions to minimise a pipeline stall. This reverses the
  12977. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  12978. optimisations could be made.
  12979. }
  12980. if (taicpu(p).oper[0]^.typ = top_reg) and
  12981. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  12982. (
  12983. (
  12984. (taicpu(p).oper[1]^.typ = top_reg) and
  12985. { We can try searching further ahead if we're writing to a register }
  12986. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  12987. ) or
  12988. (
  12989. (taicpu(p).oper[1]^.typ = top_ref) and
  12990. GetNextInstruction(p, hp1)
  12991. )
  12992. ) and
  12993. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  12994. (taicpu(hp1).oper[0]^.typ = top_const) and
  12995. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  12996. begin
  12997. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  12998. TransferUsedRegs(TmpUsedRegs);
  12999. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13000. hp2 := p;
  13001. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  13002. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  13003. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  13004. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  13005. begin
  13006. asml.remove(hp1);
  13007. asml.InsertBefore(hp1, p);
  13008. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  13009. Result := True;
  13010. end;
  13011. end;
  13012. end;
  13013. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  13014. begin
  13015. Result:=false;
  13016. { change "cmp $0, %reg" to "test %reg, %reg" }
  13017. if MatchOpType(taicpu(p),top_const,top_reg) and
  13018. (taicpu(p).oper[0]^.val = 0) then
  13019. begin
  13020. taicpu(p).opcode := A_TEST;
  13021. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  13022. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  13023. Result:=true;
  13024. end;
  13025. end;
  13026. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  13027. var
  13028. IsTestConstX, IsValid : Boolean;
  13029. hp1,hp2 : tai;
  13030. begin
  13031. Result:=false;
  13032. { If x is a power of 2 (popcnt = 1), change:
  13033. or $x, %reg/ref
  13034. To:
  13035. bts lb(x), %reg/ref
  13036. }
  13037. if (taicpu(p).opcode = A_OR) and
  13038. IsBTXAcceptable(p) and
  13039. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  13040. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  13041. (
  13042. { Don't optimise if a test instruction follows }
  13043. not GetNextInstruction(p, hp1) or
  13044. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  13045. ) then
  13046. begin
  13047. 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);
  13048. taicpu(p).opcode := A_BTS;
  13049. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  13050. Result := True;
  13051. Exit;
  13052. end;
  13053. { If x is a power of 2 (popcnt = 1), change:
  13054. test $x, %reg/ref
  13055. je / sete / cmove (or jne / setne)
  13056. To:
  13057. bt lb(x), %reg/ref
  13058. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  13059. }
  13060. if (taicpu(p).opcode = A_TEST) and
  13061. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  13062. (taicpu(p).oper[0]^.typ = top_const) and
  13063. (
  13064. (cs_opt_size in current_settings.optimizerswitches) or
  13065. (
  13066. (taicpu(p).oper[1]^.typ = top_reg) and
  13067. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  13068. ) or
  13069. (
  13070. (taicpu(p).oper[1]^.typ <> top_reg) and
  13071. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  13072. )
  13073. ) and
  13074. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  13075. { For sizes less than S_L, the byte size is equal or larger with BT,
  13076. so don't bother optimising }
  13077. (taicpu(p).opsize >= S_L) then
  13078. begin
  13079. IsValid := True;
  13080. { Check the next set of instructions, watching the FLAGS register
  13081. and the conditions used }
  13082. TransferUsedRegs(TmpUsedRegs);
  13083. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13084. hp1 := p;
  13085. hp2 := nil;
  13086. while GetNextInstruction(hp1, hp1) do
  13087. begin
  13088. if not Assigned(hp2) then
  13089. { The first instruction after TEST }
  13090. hp2 := hp1;
  13091. if (hp1.typ <> ait_instruction) then
  13092. begin
  13093. { If the flags are no longer in use, everything is fine }
  13094. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  13095. IsValid := False;
  13096. Break;
  13097. end;
  13098. case taicpu(hp1).condition of
  13099. C_None:
  13100. begin
  13101. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  13102. { Something is not quite normal, so play safe and don't change }
  13103. IsValid := False;
  13104. Break;
  13105. end;
  13106. C_E, C_Z, C_NE, C_NZ:
  13107. { This is fine };
  13108. else
  13109. begin
  13110. { Unsupported condition }
  13111. IsValid := False;
  13112. Break;
  13113. end;
  13114. end;
  13115. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13116. end;
  13117. if IsValid then
  13118. begin
  13119. while hp2 <> hp1 do
  13120. begin
  13121. case taicpu(hp2).condition of
  13122. C_Z, C_E:
  13123. taicpu(hp2).condition := C_NC;
  13124. C_NZ, C_NE:
  13125. taicpu(hp2).condition := C_C;
  13126. else
  13127. { Should not get this by this point }
  13128. InternalError(2022110701);
  13129. end;
  13130. GetNextInstruction(hp2, hp2);
  13131. end;
  13132. 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);
  13133. taicpu(p).opcode := A_BT;
  13134. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  13135. Result := True;
  13136. Exit;
  13137. end;
  13138. end;
  13139. { removes the line marked with (x) from the sequence
  13140. and/or/xor/add/sub/... $x, %y
  13141. test/or %y, %y | test $-1, %y (x)
  13142. j(n)z _Label
  13143. as the first instruction already adjusts the ZF
  13144. %y operand may also be a reference }
  13145. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  13146. MatchOperand(taicpu(p).oper[0]^,-1);
  13147. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  13148. GetLastInstruction(p, hp1) and
  13149. (tai(hp1).typ = ait_instruction) and
  13150. GetNextInstruction(p,hp2) and
  13151. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  13152. case taicpu(hp1).opcode Of
  13153. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  13154. { These two instructions set the zero flag if the result is zero }
  13155. A_POPCNT, A_LZCNT:
  13156. begin
  13157. if (
  13158. { With POPCNT, an input of zero will set the zero flag
  13159. because the population count of zero is zero }
  13160. (taicpu(hp1).opcode = A_POPCNT) and
  13161. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  13162. (
  13163. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  13164. { Faster than going through the second half of the 'or'
  13165. condition below }
  13166. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  13167. )
  13168. ) or (
  13169. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  13170. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  13171. { and in case of carry for A(E)/B(E)/C/NC }
  13172. (
  13173. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  13174. (
  13175. (taicpu(hp1).opcode <> A_ADD) and
  13176. (taicpu(hp1).opcode <> A_SUB) and
  13177. (taicpu(hp1).opcode <> A_LZCNT)
  13178. )
  13179. )
  13180. ) then
  13181. begin
  13182. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  13183. RemoveCurrentP(p, hp2);
  13184. Result:=true;
  13185. Exit;
  13186. end;
  13187. end;
  13188. A_SHL, A_SAL, A_SHR, A_SAR:
  13189. begin
  13190. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  13191. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  13192. { therefore, it's only safe to do this optimization for }
  13193. { shifts by a (nonzero) constant }
  13194. (taicpu(hp1).oper[0]^.typ = top_const) and
  13195. (taicpu(hp1).oper[0]^.val <> 0) and
  13196. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  13197. { and in case of carry for A(E)/B(E)/C/NC }
  13198. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  13199. begin
  13200. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  13201. RemoveCurrentP(p, hp2);
  13202. Result:=true;
  13203. Exit;
  13204. end;
  13205. end;
  13206. A_DEC, A_INC, A_NEG:
  13207. begin
  13208. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  13209. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  13210. { and in case of carry for A(E)/B(E)/C/NC }
  13211. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  13212. begin
  13213. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  13214. RemoveCurrentP(p, hp2);
  13215. Result:=true;
  13216. Exit;
  13217. end;
  13218. end;
  13219. A_ANDN, A_BZHI:
  13220. begin
  13221. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  13222. { Only the zero and sign flags are consistent with what the result is }
  13223. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  13224. begin
  13225. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  13226. RemoveCurrentP(p, hp2);
  13227. Result:=true;
  13228. Exit;
  13229. end;
  13230. end;
  13231. A_BEXTR:
  13232. begin
  13233. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  13234. { Only the zero flag is set }
  13235. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  13236. begin
  13237. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  13238. RemoveCurrentP(p, hp2);
  13239. Result:=true;
  13240. Exit;
  13241. end;
  13242. end;
  13243. else
  13244. ;
  13245. end; { case }
  13246. { change "test $-1,%reg" into "test %reg,%reg" }
  13247. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  13248. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  13249. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  13250. if MatchInstruction(p, A_OR, []) and
  13251. { Can only match if they're both registers }
  13252. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  13253. begin
  13254. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  13255. taicpu(p).opcode := A_TEST;
  13256. { No need to set Result to True, as we've done all the optimisations we can }
  13257. end;
  13258. end;
  13259. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  13260. var
  13261. hp1,hp3 : tai;
  13262. {$ifndef x86_64}
  13263. hp2 : taicpu;
  13264. {$endif x86_64}
  13265. begin
  13266. Result:=false;
  13267. hp3:=nil;
  13268. {$ifndef x86_64}
  13269. { don't do this on modern CPUs, this really hurts them due to
  13270. broken call/ret pairing }
  13271. if (current_settings.optimizecputype < cpu_Pentium2) and
  13272. not(cs_create_pic in current_settings.moduleswitches) and
  13273. GetNextInstruction(p, hp1) and
  13274. MatchInstruction(hp1,A_JMP,[S_NO]) and
  13275. MatchOpType(taicpu(hp1),top_ref) and
  13276. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  13277. begin
  13278. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  13279. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  13280. InsertLLItem(p.previous, p, hp2);
  13281. taicpu(p).opcode := A_JMP;
  13282. taicpu(p).is_jmp := true;
  13283. RemoveInstruction(hp1);
  13284. Result:=true;
  13285. end
  13286. else
  13287. {$endif x86_64}
  13288. { replace
  13289. call procname
  13290. ret
  13291. by
  13292. jmp procname
  13293. but do it only on level 4 because it destroys stack back traces
  13294. else if the subroutine is marked as no return, remove the ret
  13295. }
  13296. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  13297. (po_noreturn in current_procinfo.procdef.procoptions)) and
  13298. GetNextInstruction(p, hp1) and
  13299. (MatchInstruction(hp1,A_RET,[S_NO]) or
  13300. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  13301. SetAndTest(hp1,hp3) and
  13302. GetNextInstruction(hp1,hp1) and
  13303. MatchInstruction(hp1,A_RET,[S_NO])
  13304. )
  13305. ) and
  13306. (taicpu(hp1).ops=0) then
  13307. begin
  13308. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13309. { we might destroy stack alignment here if we do not do a call }
  13310. (target_info.stackalign<=sizeof(SizeUInt)) then
  13311. begin
  13312. taicpu(p).opcode := A_JMP;
  13313. taicpu(p).is_jmp := true;
  13314. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  13315. end
  13316. else
  13317. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  13318. RemoveInstruction(hp1);
  13319. if Assigned(hp3) then
  13320. begin
  13321. AsmL.Remove(hp3);
  13322. AsmL.InsertBefore(hp3,p)
  13323. end;
  13324. Result:=true;
  13325. end;
  13326. end;
  13327. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  13328. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  13329. begin
  13330. case OpSize of
  13331. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13332. Result := (Val <= $FF) and (Val >= -128);
  13333. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13334. Result := (Val <= $FFFF) and (Val >= -32768);
  13335. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  13336. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  13337. else
  13338. Result := True;
  13339. end;
  13340. end;
  13341. var
  13342. hp1, hp2 : tai;
  13343. SizeChange: Boolean;
  13344. PreMessage: string;
  13345. begin
  13346. Result := False;
  13347. if (taicpu(p).oper[0]^.typ = top_reg) and
  13348. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13349. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  13350. begin
  13351. { Change (using movzbl %al,%eax as an example):
  13352. movzbl %al, %eax movzbl %al, %eax
  13353. cmpl x, %eax testl %eax,%eax
  13354. To:
  13355. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  13356. movzbl %al, %eax movzbl %al, %eax
  13357. Smaller instruction and minimises pipeline stall as the CPU
  13358. doesn't have to wait for the register to get zero-extended. [Kit]
  13359. Also allow if the smaller of the two registers is being checked,
  13360. as this still removes the false dependency.
  13361. }
  13362. if
  13363. (
  13364. (
  13365. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  13366. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  13367. ) or (
  13368. { If MatchOperand returns True, they must both be registers }
  13369. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  13370. )
  13371. ) and
  13372. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  13373. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  13374. begin
  13375. 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);
  13376. asml.Remove(hp1);
  13377. asml.InsertBefore(hp1, p);
  13378. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  13379. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  13380. begin
  13381. taicpu(hp1).opcode := A_TEST;
  13382. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  13383. end;
  13384. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  13385. case taicpu(p).opsize of
  13386. S_BW, S_BL:
  13387. begin
  13388. SizeChange := taicpu(hp1).opsize <> S_B;
  13389. taicpu(hp1).changeopsize(S_B);
  13390. end;
  13391. S_WL:
  13392. begin
  13393. SizeChange := taicpu(hp1).opsize <> S_W;
  13394. taicpu(hp1).changeopsize(S_W);
  13395. end
  13396. else
  13397. InternalError(2020112701);
  13398. end;
  13399. UpdateUsedRegs(tai(p.Next));
  13400. { Check if the register is used aferwards - if not, we can
  13401. remove the movzx instruction completely }
  13402. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  13403. begin
  13404. { Hp1 is a better position than p for debugging purposes }
  13405. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  13406. RemoveCurrentp(p, hp1);
  13407. Result := True;
  13408. end;
  13409. if SizeChange then
  13410. DebugMsg(SPeepholeOptimization + PreMessage +
  13411. 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)
  13412. else
  13413. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  13414. Exit;
  13415. end;
  13416. { Change (using movzwl %ax,%eax as an example):
  13417. movzwl %ax, %eax
  13418. movb %al, (dest) (Register is smaller than read register in movz)
  13419. To:
  13420. movb %al, (dest) (Move one back to avoid a false dependency)
  13421. movzwl %ax, %eax
  13422. }
  13423. if (taicpu(hp1).opcode = A_MOV) and
  13424. (taicpu(hp1).oper[0]^.typ = top_reg) and
  13425. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  13426. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  13427. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  13428. begin
  13429. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  13430. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  13431. asml.Remove(hp1);
  13432. asml.InsertBefore(hp1, p);
  13433. if taicpu(hp1).oper[1]^.typ = top_reg then
  13434. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13435. { Check if the register is used aferwards - if not, we can
  13436. remove the movzx instruction completely }
  13437. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  13438. begin
  13439. { Hp1 is a better position than p for debugging purposes }
  13440. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  13441. RemoveCurrentp(p, hp1);
  13442. Result := True;
  13443. end;
  13444. Exit;
  13445. end;
  13446. end;
  13447. end;
  13448. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  13449. var
  13450. hp1: tai;
  13451. {$ifdef x86_64}
  13452. PreMessage, RegName: string;
  13453. {$endif x86_64}
  13454. begin
  13455. Result := False;
  13456. { If x is a power of 2 (popcnt = 1), change:
  13457. xor $x, %reg/ref
  13458. To:
  13459. btc lb(x), %reg/ref
  13460. }
  13461. if IsBTXAcceptable(p) and
  13462. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  13463. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  13464. (
  13465. { Don't optimise if a test instruction follows }
  13466. not GetNextInstruction(p, hp1) or
  13467. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  13468. ) then
  13469. begin
  13470. DebugMsg(SPeepholeOptimization + 'Changed XOR $0x' + hexstr(taicpu(p).oper[0]^.val, 2) + ' to BTC ' + debug_tostr(BsrQWord(taicpu(p).oper[0]^.val)) + ' to shrink instruction size (Xor2Btc)', p);
  13471. taicpu(p).opcode := A_BTC;
  13472. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  13473. Result := True;
  13474. Exit;
  13475. end;
  13476. {$ifdef x86_64}
  13477. { Code size reduction by J. Gareth "Kit" Moreton }
  13478. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  13479. as this removes the REX prefix }
  13480. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  13481. Exit;
  13482. if taicpu(p).oper[0]^.typ <> top_reg then
  13483. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  13484. InternalError(2018011500);
  13485. case taicpu(p).opsize of
  13486. S_Q:
  13487. begin
  13488. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  13489. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  13490. { The actual optimization }
  13491. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13492. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13493. taicpu(p).changeopsize(S_L);
  13494. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  13495. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  13496. end;
  13497. else
  13498. ;
  13499. end;
  13500. {$endif x86_64}
  13501. end;
  13502. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  13503. var
  13504. XReg: TRegister;
  13505. begin
  13506. Result := False;
  13507. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  13508. Smaller encoding and slightly faster on some platforms (also works for
  13509. ZMM-sized registers) }
  13510. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  13511. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  13512. begin
  13513. XReg := taicpu(p).oper[0]^.reg;
  13514. if (taicpu(p).oper[1]^.reg = XReg) then
  13515. begin
  13516. taicpu(p).changeopsize(S_XMM);
  13517. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  13518. if (cs_opt_size in current_settings.optimizerswitches) then
  13519. begin
  13520. { Change input registers to %xmm0 to reduce size. Note that
  13521. there's a risk of a false dependency doing this, so only
  13522. optimise for size here }
  13523. XReg := NR_XMM0;
  13524. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  13525. end
  13526. else
  13527. begin
  13528. setsubreg(XReg, R_SUBMMX);
  13529. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  13530. end;
  13531. taicpu(p).oper[0]^.reg := XReg;
  13532. taicpu(p).oper[1]^.reg := XReg;
  13533. Result := True;
  13534. end;
  13535. end;
  13536. end;
  13537. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  13538. var
  13539. OperIdx: Integer;
  13540. begin
  13541. for OperIdx := 0 to p.ops - 1 do
  13542. if p.oper[OperIdx]^.typ = top_ref then
  13543. optimize_ref(p.oper[OperIdx]^.ref^, False);
  13544. end;
  13545. end.