aoptx86.pas 549 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3
  33. );
  34. TX86AsmOptimizer = class(TAsmOptimizer)
  35. { some optimizations are very expensive to check, so the
  36. pre opt pass can be used to set some flags, depending on the found
  37. instructions if it is worth to check a certain optimization }
  38. OptsToCheck : set of TOptsToCheck;
  39. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  40. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  41. function RegReadByInstruction(reg : TRegister; hp : tai) : boolean;
  42. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  43. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  44. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  45. potentially allowing further optimisation (although it might need to know if
  46. it crossed a conditional jump. }
  47. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  48. {
  49. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  50. the use of a register by allocs/dealloc, so it can ignore calls.
  51. In the following example, GetNextInstructionUsingReg will return the second movq,
  52. GetNextInstructionUsingRegTrackingUse won't.
  53. movq %rdi,%rax
  54. # Register rdi released
  55. # Register rdi allocated
  56. movq %rax,%rdi
  57. While in this example:
  58. movq %rdi,%rax
  59. call proc
  60. movq %rdi,%rax
  61. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  62. won't.
  63. }
  64. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  65. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  66. private
  67. function SkipSimpleInstructions(var hp1: tai): Boolean;
  68. protected
  69. class function IsMOVZXAcceptable: Boolean; static; inline;
  70. { Attempts to allocate a volatile integer register for use between p and hp,
  71. using AUsedRegs for the current register usage information. Returns NR_NO
  72. if no free register could be found }
  73. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  74. { Attempts to allocate a volatile MM register for use between p and hp,
  75. using AUsedRegs for the current register usage information. Returns NR_NO
  76. if no free register could be found }
  77. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  78. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  79. function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  80. { checks whether reading the value in reg1 depends on the value of reg2. This
  81. is very similar to SuperRegisterEquals, except it takes into account that
  82. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  83. depend on the value in AH). }
  84. function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  85. { Replaces all references to AOldReg in a memory reference to ANewReg }
  86. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  87. { Replaces all references to AOldReg in an operand to ANewReg }
  88. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  89. { Replaces all references to AOldReg in an instruction to ANewReg,
  90. except where the register is being written }
  91. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  92. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  93. or writes to a global symbol }
  94. class function IsRefSafe(const ref: PReference): Boolean; static;
  95. { Returns true if the given MOV instruction can be safely converted to CMOV }
  96. class function CanBeCMOV(p : tai) : boolean; static;
  97. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  98. conversion was successful }
  99. function ConvertLEA(const p : taicpu): Boolean;
  100. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  101. procedure DebugMsg(const s : string; p : tai);inline;
  102. class function IsExitCode(p : tai) : boolean; static;
  103. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  104. procedure RemoveLastDeallocForFuncRes(p : tai);
  105. function DoSubAddOpt(var p : tai) : Boolean;
  106. function DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  107. function PrePeepholeOptSxx(var p : tai) : boolean;
  108. function PrePeepholeOptIMUL(var p : tai) : boolean;
  109. function PrePeepholeOptAND(var p : tai) : boolean;
  110. function OptPass1Test(var p: tai): boolean;
  111. function OptPass1Add(var p: tai): boolean;
  112. function OptPass1AND(var p : tai) : boolean;
  113. function OptPass1_V_MOVAP(var p : tai) : boolean;
  114. function OptPass1VOP(var p : tai) : boolean;
  115. function OptPass1MOV(var p : tai) : boolean;
  116. function OptPass1Movx(var p : tai) : boolean;
  117. function OptPass1MOVXX(var p : tai) : boolean;
  118. function OptPass1OP(var p : tai) : boolean;
  119. function OptPass1LEA(var p : tai) : boolean;
  120. function OptPass1Sub(var p : tai) : boolean;
  121. function OptPass1SHLSAL(var p : tai) : boolean;
  122. function OptPass1FSTP(var p : tai) : boolean;
  123. function OptPass1FLD(var p : tai) : boolean;
  124. function OptPass1Cmp(var p : tai) : boolean;
  125. function OptPass1PXor(var p : tai) : boolean;
  126. function OptPass1VPXor(var p: tai): boolean;
  127. function OptPass1Imul(var p : tai) : boolean;
  128. function OptPass1Jcc(var p : tai) : boolean;
  129. function OptPass1SHXX(var p: tai): boolean;
  130. function OptPass1VMOVDQ(var p: tai): Boolean;
  131. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  132. function OptPass2Movx(var p : tai): Boolean;
  133. function OptPass2MOV(var p : tai) : boolean;
  134. function OptPass2Imul(var p : tai) : boolean;
  135. function OptPass2Jmp(var p : tai) : boolean;
  136. function OptPass2Jcc(var p : tai) : boolean;
  137. function OptPass2Lea(var p: tai): Boolean;
  138. function OptPass2SUB(var p: tai): Boolean;
  139. function OptPass2ADD(var p : tai): Boolean;
  140. function OptPass2SETcc(var p : tai) : boolean;
  141. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  142. function PostPeepholeOptMov(var p : tai) : Boolean;
  143. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  144. {$ifdef x86_64} { These post-peephole optimisations only affect 64-bit registers. [Kit] }
  145. function PostPeepholeOptXor(var p : tai) : Boolean;
  146. {$endif x86_64}
  147. function PostPeepholeOptAnd(var p : tai) : boolean;
  148. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  149. function PostPeepholeOptCmp(var p : tai) : Boolean;
  150. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  151. function PostPeepholeOptCall(var p : tai) : Boolean;
  152. function PostPeepholeOptLea(var p : tai) : Boolean;
  153. function PostPeepholeOptPush(var p: tai): Boolean;
  154. function PostPeepholeOptShr(var p : tai) : boolean;
  155. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  156. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  157. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  158. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  159. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  160. { Processor-dependent reference optimisation }
  161. class procedure OptimizeRefs(var p: taicpu); static;
  162. end;
  163. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  164. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  165. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  166. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  167. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  168. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  169. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  170. {$if max_operands>2}
  171. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  172. {$endif max_operands>2}
  173. function RefsEqual(const r1, r2: treference): boolean;
  174. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  175. { returns true, if ref is a reference using only the registers passed as base and index
  176. and having an offset }
  177. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  178. implementation
  179. uses
  180. cutils,verbose,
  181. systems,
  182. globals,
  183. cpuinfo,
  184. procinfo,
  185. paramgr,
  186. aasmbase,
  187. aoptbase,aoptutils,
  188. symconst,symsym,
  189. cgx86,
  190. itcpugas;
  191. {$ifdef DEBUG_AOPTCPU}
  192. const
  193. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  194. {$else DEBUG_AOPTCPU}
  195. { Empty strings help the optimizer to remove string concatenations that won't
  196. ever appear to the user on release builds. [Kit] }
  197. const
  198. SPeepholeOptimization = '';
  199. {$endif DEBUG_AOPTCPU}
  200. LIST_STEP_SIZE = 4;
  201. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  202. begin
  203. result :=
  204. (instr.typ = ait_instruction) and
  205. (taicpu(instr).opcode = op) and
  206. ((opsize = []) or (taicpu(instr).opsize in opsize));
  207. end;
  208. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  209. begin
  210. result :=
  211. (instr.typ = ait_instruction) and
  212. ((taicpu(instr).opcode = op1) or
  213. (taicpu(instr).opcode = op2)
  214. ) and
  215. ((opsize = []) or (taicpu(instr).opsize in opsize));
  216. end;
  217. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  218. begin
  219. result :=
  220. (instr.typ = ait_instruction) and
  221. ((taicpu(instr).opcode = op1) or
  222. (taicpu(instr).opcode = op2) or
  223. (taicpu(instr).opcode = op3)
  224. ) and
  225. ((opsize = []) or (taicpu(instr).opsize in opsize));
  226. end;
  227. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  228. const opsize : topsizes) : boolean;
  229. var
  230. op : TAsmOp;
  231. begin
  232. result:=false;
  233. if (instr.typ <> ait_instruction) or
  234. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  235. exit;
  236. for op in ops do
  237. begin
  238. if taicpu(instr).opcode = op then
  239. begin
  240. result:=true;
  241. exit;
  242. end;
  243. end;
  244. end;
  245. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  246. begin
  247. result := (oper.typ = top_reg) and (oper.reg = reg);
  248. end;
  249. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  250. begin
  251. result := (oper.typ = top_const) and (oper.val = a);
  252. end;
  253. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  254. begin
  255. result := oper1.typ = oper2.typ;
  256. if result then
  257. case oper1.typ of
  258. top_const:
  259. Result:=oper1.val = oper2.val;
  260. top_reg:
  261. Result:=oper1.reg = oper2.reg;
  262. top_ref:
  263. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  264. else
  265. internalerror(2013102801);
  266. end
  267. end;
  268. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  269. begin
  270. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  271. if result then
  272. case oper1.typ of
  273. top_const:
  274. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  275. top_reg:
  276. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  277. top_ref:
  278. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  279. else
  280. internalerror(2020052401);
  281. end
  282. end;
  283. function RefsEqual(const r1, r2: treference): boolean;
  284. begin
  285. RefsEqual :=
  286. (r1.offset = r2.offset) and
  287. (r1.segment = r2.segment) and (r1.base = r2.base) and
  288. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  289. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  290. (r1.relsymbol = r2.relsymbol) and
  291. (r1.volatility=[]) and
  292. (r2.volatility=[]);
  293. end;
  294. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  295. begin
  296. Result:=(ref.offset=0) and
  297. (ref.scalefactor in [0,1]) and
  298. (ref.segment=NR_NO) and
  299. (ref.symbol=nil) and
  300. (ref.relsymbol=nil) and
  301. ((base=NR_INVALID) or
  302. (ref.base=base)) and
  303. ((index=NR_INVALID) or
  304. (ref.index=index)) and
  305. (ref.volatility=[]);
  306. end;
  307. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  308. begin
  309. Result:=(ref.scalefactor in [0,1]) and
  310. (ref.segment=NR_NO) and
  311. (ref.symbol=nil) and
  312. (ref.relsymbol=nil) and
  313. ((base=NR_INVALID) or
  314. (ref.base=base)) and
  315. ((index=NR_INVALID) or
  316. (ref.index=index)) and
  317. (ref.volatility=[]);
  318. end;
  319. function InstrReadsFlags(p: tai): boolean;
  320. begin
  321. InstrReadsFlags := true;
  322. case p.typ of
  323. ait_instruction:
  324. if InsProp[taicpu(p).opcode].Ch*
  325. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  326. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  327. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  328. exit;
  329. ait_label:
  330. exit;
  331. else
  332. ;
  333. end;
  334. InstrReadsFlags := false;
  335. end;
  336. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  337. begin
  338. Next:=Current;
  339. repeat
  340. Result:=GetNextInstruction(Next,Next);
  341. until not (Result) or
  342. not(cs_opt_level3 in current_settings.optimizerswitches) or
  343. (Next.typ<>ait_instruction) or
  344. RegInInstruction(reg,Next) or
  345. is_calljmp(taicpu(Next).opcode);
  346. end;
  347. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  348. begin
  349. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  350. Next := Current;
  351. repeat
  352. Result := GetNextInstruction(Next,Next);
  353. if Result and (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  354. if is_calljmpuncondret(taicpu(Next).opcode) then
  355. begin
  356. Result := False;
  357. Exit;
  358. end
  359. else
  360. CrossJump := True;
  361. until not Result or
  362. not (cs_opt_level3 in current_settings.optimizerswitches) or
  363. (Next.typ <> ait_instruction) or
  364. RegInInstruction(reg,Next);
  365. end;
  366. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  367. begin
  368. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  369. begin
  370. Result:=GetNextInstruction(Current,Next);
  371. exit;
  372. end;
  373. Next:=tai(Current.Next);
  374. Result:=false;
  375. while assigned(Next) do
  376. begin
  377. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  378. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  379. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  380. exit
  381. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  382. begin
  383. Result:=true;
  384. exit;
  385. end;
  386. Next:=tai(Next.Next);
  387. end;
  388. end;
  389. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  390. begin
  391. Result:=RegReadByInstruction(reg,hp);
  392. end;
  393. function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  394. var
  395. p: taicpu;
  396. opcount: longint;
  397. begin
  398. RegReadByInstruction := false;
  399. if hp.typ <> ait_instruction then
  400. exit;
  401. p := taicpu(hp);
  402. case p.opcode of
  403. A_CALL:
  404. regreadbyinstruction := true;
  405. A_IMUL:
  406. case p.ops of
  407. 1:
  408. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  409. (
  410. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  411. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  412. );
  413. 2,3:
  414. regReadByInstruction :=
  415. reginop(reg,p.oper[0]^) or
  416. reginop(reg,p.oper[1]^);
  417. else
  418. InternalError(2019112801);
  419. end;
  420. A_MUL:
  421. begin
  422. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  423. (
  424. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  425. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  426. );
  427. end;
  428. A_IDIV,A_DIV:
  429. begin
  430. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  431. (
  432. (getregtype(reg)=R_INTREGISTER) and
  433. (
  434. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  435. )
  436. );
  437. end;
  438. else
  439. begin
  440. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  441. begin
  442. RegReadByInstruction := false;
  443. exit;
  444. end;
  445. for opcount := 0 to p.ops-1 do
  446. if (p.oper[opCount]^.typ = top_ref) and
  447. RegInRef(reg,p.oper[opcount]^.ref^) then
  448. begin
  449. RegReadByInstruction := true;
  450. exit
  451. end;
  452. { special handling for SSE MOVSD }
  453. if (p.opcode=A_MOVSD) and (p.ops>0) then
  454. begin
  455. if p.ops<>2 then
  456. internalerror(2017042702);
  457. regReadByInstruction := reginop(reg,p.oper[0]^) or
  458. (
  459. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  460. );
  461. exit;
  462. end;
  463. with insprop[p.opcode] do
  464. begin
  465. case getregtype(reg) of
  466. R_INTREGISTER:
  467. begin
  468. case getsupreg(reg) of
  469. RS_EAX:
  470. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  471. begin
  472. RegReadByInstruction := true;
  473. exit
  474. end;
  475. RS_ECX:
  476. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  477. begin
  478. RegReadByInstruction := true;
  479. exit
  480. end;
  481. RS_EDX:
  482. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  483. begin
  484. RegReadByInstruction := true;
  485. exit
  486. end;
  487. RS_EBX:
  488. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  489. begin
  490. RegReadByInstruction := true;
  491. exit
  492. end;
  493. RS_ESP:
  494. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  495. begin
  496. RegReadByInstruction := true;
  497. exit
  498. end;
  499. RS_EBP:
  500. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  501. begin
  502. RegReadByInstruction := true;
  503. exit
  504. end;
  505. RS_ESI:
  506. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  507. begin
  508. RegReadByInstruction := true;
  509. exit
  510. end;
  511. RS_EDI:
  512. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  513. begin
  514. RegReadByInstruction := true;
  515. exit
  516. end;
  517. end;
  518. end;
  519. R_MMREGISTER:
  520. begin
  521. case getsupreg(reg) of
  522. RS_XMM0:
  523. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  524. begin
  525. RegReadByInstruction := true;
  526. exit
  527. end;
  528. end;
  529. end;
  530. else
  531. ;
  532. end;
  533. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  534. begin
  535. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  536. begin
  537. case p.condition of
  538. C_A,C_NBE, { CF=0 and ZF=0 }
  539. C_BE,C_NA: { CF=1 or ZF=1 }
  540. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  541. C_AE,C_NB,C_NC, { CF=0 }
  542. C_B,C_NAE,C_C: { CF=1 }
  543. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  544. C_NE,C_NZ, { ZF=0 }
  545. C_E,C_Z: { ZF=1 }
  546. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  547. C_G,C_NLE, { ZF=0 and SF=OF }
  548. C_LE,C_NG: { ZF=1 or SF<>OF }
  549. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  550. C_GE,C_NL, { SF=OF }
  551. C_L,C_NGE: { SF<>OF }
  552. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  553. C_NO, { OF=0 }
  554. C_O: { OF=1 }
  555. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  556. C_NP,C_PO, { PF=0 }
  557. C_P,C_PE: { PF=1 }
  558. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  559. C_NS, { SF=0 }
  560. C_S: { SF=1 }
  561. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  562. else
  563. internalerror(2017042701);
  564. end;
  565. if RegReadByInstruction then
  566. exit;
  567. end;
  568. case getsubreg(reg) of
  569. R_SUBW,R_SUBD,R_SUBQ:
  570. RegReadByInstruction :=
  571. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  572. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  573. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  574. R_SUBFLAGCARRY:
  575. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  576. R_SUBFLAGPARITY:
  577. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  578. R_SUBFLAGAUXILIARY:
  579. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  580. R_SUBFLAGZERO:
  581. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  582. R_SUBFLAGSIGN:
  583. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  584. R_SUBFLAGOVERFLOW:
  585. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  586. R_SUBFLAGINTERRUPT:
  587. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  588. R_SUBFLAGDIRECTION:
  589. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  590. else
  591. internalerror(2017042601);
  592. end;
  593. exit;
  594. end;
  595. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  596. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  597. (p.oper[0]^.reg=p.oper[1]^.reg) then
  598. exit;
  599. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  600. begin
  601. RegReadByInstruction := true;
  602. exit
  603. end;
  604. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  605. begin
  606. RegReadByInstruction := true;
  607. exit
  608. end;
  609. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  610. begin
  611. RegReadByInstruction := true;
  612. exit
  613. end;
  614. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  615. begin
  616. RegReadByInstruction := true;
  617. exit
  618. end;
  619. end;
  620. end;
  621. end;
  622. end;
  623. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  624. begin
  625. result:=false;
  626. if p1.typ<>ait_instruction then
  627. exit;
  628. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  629. exit(true);
  630. if (getregtype(reg)=R_INTREGISTER) and
  631. { change information for xmm movsd are not correct }
  632. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  633. begin
  634. case getsupreg(reg) of
  635. { RS_EAX = RS_RAX on x86-64 }
  636. RS_EAX:
  637. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  638. RS_ECX:
  639. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  640. RS_EDX:
  641. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  642. RS_EBX:
  643. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  644. RS_ESP:
  645. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  646. RS_EBP:
  647. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  648. RS_ESI:
  649. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  650. RS_EDI:
  651. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  652. else
  653. ;
  654. end;
  655. if result then
  656. exit;
  657. end
  658. else if getregtype(reg)=R_MMREGISTER then
  659. begin
  660. case getsupreg(reg) of
  661. RS_XMM0:
  662. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  663. else
  664. ;
  665. end;
  666. if result then
  667. exit;
  668. end
  669. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  670. begin
  671. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  672. exit(true);
  673. case getsubreg(reg) of
  674. R_SUBFLAGCARRY:
  675. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  676. R_SUBFLAGPARITY:
  677. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  678. R_SUBFLAGAUXILIARY:
  679. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  680. R_SUBFLAGZERO:
  681. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  682. R_SUBFLAGSIGN:
  683. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  684. R_SUBFLAGOVERFLOW:
  685. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  686. R_SUBFLAGINTERRUPT:
  687. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  688. R_SUBFLAGDIRECTION:
  689. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  690. R_SUBW,R_SUBD,R_SUBQ:
  691. { Everything except the direction bits }
  692. Result:=
  693. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  694. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  695. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  696. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  697. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  698. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  699. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  700. else
  701. ;
  702. end;
  703. if result then
  704. exit;
  705. end
  706. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  707. exit(true);
  708. Result:=inherited RegInInstruction(Reg, p1);
  709. end;
  710. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  711. const
  712. WriteOps: array[0..3] of set of TInsChange =
  713. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  714. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  715. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  716. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  717. var
  718. OperIdx: Integer;
  719. begin
  720. Result := False;
  721. if p1.typ <> ait_instruction then
  722. exit;
  723. with insprop[taicpu(p1).opcode] do
  724. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  725. begin
  726. case getsubreg(reg) of
  727. R_SUBW,R_SUBD,R_SUBQ:
  728. Result :=
  729. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  730. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  731. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  732. R_SUBFLAGCARRY:
  733. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  734. R_SUBFLAGPARITY:
  735. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  736. R_SUBFLAGAUXILIARY:
  737. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  738. R_SUBFLAGZERO:
  739. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  740. R_SUBFLAGSIGN:
  741. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  742. R_SUBFLAGOVERFLOW:
  743. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  744. R_SUBFLAGINTERRUPT:
  745. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  746. R_SUBFLAGDIRECTION:
  747. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  748. else
  749. internalerror(2017042602);
  750. end;
  751. exit;
  752. end;
  753. case taicpu(p1).opcode of
  754. A_CALL:
  755. { We could potentially set Result to False if the register in
  756. question is non-volatile for the subroutine's calling convention,
  757. but this would require detecting the calling convention in use and
  758. also assuming that the routine doesn't contain malformed assembly
  759. language, for example... so it could only be done under -O4 as it
  760. would be considered a side-effect. [Kit] }
  761. Result := True;
  762. A_MOVSD:
  763. { special handling for SSE MOVSD }
  764. if (taicpu(p1).ops>0) then
  765. begin
  766. if taicpu(p1).ops<>2 then
  767. internalerror(2017042703);
  768. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  769. end;
  770. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  771. so fix it here (FK)
  772. }
  773. A_VMOVSS,
  774. A_VMOVSD:
  775. begin
  776. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  777. exit;
  778. end;
  779. A_IMUL:
  780. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  781. else
  782. ;
  783. end;
  784. if Result then
  785. exit;
  786. with insprop[taicpu(p1).opcode] do
  787. begin
  788. if getregtype(reg)=R_INTREGISTER then
  789. begin
  790. case getsupreg(reg) of
  791. RS_EAX:
  792. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  793. begin
  794. Result := True;
  795. exit
  796. end;
  797. RS_ECX:
  798. if [Ch_WECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  799. begin
  800. Result := True;
  801. exit
  802. end;
  803. RS_EDX:
  804. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  805. begin
  806. Result := True;
  807. exit
  808. end;
  809. RS_EBX:
  810. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  811. begin
  812. Result := True;
  813. exit
  814. end;
  815. RS_ESP:
  816. if [Ch_WESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  817. begin
  818. Result := True;
  819. exit
  820. end;
  821. RS_EBP:
  822. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  823. begin
  824. Result := True;
  825. exit
  826. end;
  827. RS_ESI:
  828. if [Ch_WESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  829. begin
  830. Result := True;
  831. exit
  832. end;
  833. RS_EDI:
  834. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  835. begin
  836. Result := True;
  837. exit
  838. end;
  839. end;
  840. end;
  841. for OperIdx := 0 to taicpu(p1).ops - 1 do
  842. if (WriteOps[OperIdx]*Ch<>[]) and
  843. { The register doesn't get modified inside a reference }
  844. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  845. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  846. begin
  847. Result := true;
  848. exit
  849. end;
  850. end;
  851. end;
  852. {$ifdef DEBUG_AOPTCPU}
  853. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  854. begin
  855. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  856. end;
  857. function debug_tostr(i: tcgint): string; inline;
  858. begin
  859. Result := tostr(i);
  860. end;
  861. function debug_regname(r: TRegister): string; inline;
  862. begin
  863. Result := '%' + std_regname(r);
  864. end;
  865. { Debug output function - creates a string representation of an operator }
  866. function debug_operstr(oper: TOper): string;
  867. begin
  868. case oper.typ of
  869. top_const:
  870. Result := '$' + debug_tostr(oper.val);
  871. top_reg:
  872. Result := debug_regname(oper.reg);
  873. top_ref:
  874. begin
  875. if oper.ref^.offset <> 0 then
  876. Result := debug_tostr(oper.ref^.offset) + '('
  877. else
  878. Result := '(';
  879. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  880. begin
  881. Result := Result + debug_regname(oper.ref^.base);
  882. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  883. Result := Result + ',' + debug_regname(oper.ref^.index);
  884. end
  885. else
  886. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  887. Result := Result + debug_regname(oper.ref^.index);
  888. if (oper.ref^.scalefactor > 1) then
  889. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  890. else
  891. Result := Result + ')';
  892. end;
  893. else
  894. Result := '[UNKNOWN]';
  895. end;
  896. end;
  897. function debug_op2str(opcode: tasmop): string; inline;
  898. begin
  899. Result := std_op2str[opcode];
  900. end;
  901. function debug_opsize2str(opsize: topsize): string; inline;
  902. begin
  903. Result := gas_opsize2str[opsize];
  904. end;
  905. {$else DEBUG_AOPTCPU}
  906. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  907. begin
  908. end;
  909. function debug_tostr(i: tcgint): string; inline;
  910. begin
  911. Result := '';
  912. end;
  913. function debug_regname(r: TRegister): string; inline;
  914. begin
  915. Result := '';
  916. end;
  917. function debug_operstr(oper: TOper): string; inline;
  918. begin
  919. Result := '';
  920. end;
  921. function debug_op2str(opcode: tasmop): string; inline;
  922. begin
  923. Result := '';
  924. end;
  925. function debug_opsize2str(opsize: topsize): string; inline;
  926. begin
  927. Result := '';
  928. end;
  929. {$endif DEBUG_AOPTCPU}
  930. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  931. begin
  932. {$ifdef x86_64}
  933. { Always fine on x86-64 }
  934. Result := True;
  935. {$else x86_64}
  936. Result :=
  937. {$ifdef i8086}
  938. (current_settings.cputype >= cpu_386) and
  939. {$endif i8086}
  940. (
  941. { Always accept if optimising for size }
  942. (cs_opt_size in current_settings.optimizerswitches) or
  943. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  944. (current_settings.optimizecputype >= cpu_Pentium2)
  945. );
  946. {$endif x86_64}
  947. end;
  948. { Attempts to allocate a volatile integer register for use between p and hp,
  949. using AUsedRegs for the current register usage information. Returns NR_NO
  950. if no free register could be found }
  951. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  952. var
  953. RegSet: TCPURegisterSet;
  954. CurrentSuperReg: Integer;
  955. CurrentReg: TRegister;
  956. Currentp: tai;
  957. Breakout: Boolean;
  958. begin
  959. { TODO: Currently, only the volatile registers are checked - can this be extended to use any register the procedure has preserved? }
  960. Result := NR_NO;
  961. RegSet :=
  962. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  963. current_procinfo.saved_regs_int;
  964. for CurrentSuperReg in RegSet do
  965. begin
  966. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  967. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  968. {$if defined(i386) or defined(i8086)}
  969. { If the target size is 8-bit, make sure we can actually encode it }
  970. and (
  971. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  972. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  973. )
  974. {$endif i386 or i8086}
  975. then
  976. begin
  977. Currentp := p;
  978. Breakout := False;
  979. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  980. begin
  981. case Currentp.typ of
  982. ait_instruction:
  983. begin
  984. if RegInInstruction(CurrentReg, Currentp) then
  985. begin
  986. Breakout := True;
  987. Break;
  988. end;
  989. { Cannot allocate across an unconditional jump }
  990. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  991. Exit;
  992. end;
  993. ait_marker:
  994. { Don't try anything more if a marker is hit }
  995. Exit;
  996. ait_regalloc:
  997. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  998. begin
  999. Breakout := True;
  1000. Break;
  1001. end;
  1002. else
  1003. ;
  1004. end;
  1005. end;
  1006. if Breakout then
  1007. { Try the next register }
  1008. Continue;
  1009. { We have a free register available }
  1010. Result := CurrentReg;
  1011. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1012. Exit;
  1013. end;
  1014. end;
  1015. end;
  1016. { Attempts to allocate a volatile MM register for use between p and hp,
  1017. using AUsedRegs for the current register usage information. Returns NR_NO
  1018. if no free register could be found }
  1019. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1020. var
  1021. RegSet: TCPURegisterSet;
  1022. CurrentSuperReg: Integer;
  1023. CurrentReg: TRegister;
  1024. Currentp: tai;
  1025. Breakout: Boolean;
  1026. begin
  1027. { TODO: Currently, only the volatile registers are checked - can this be extended to use any register the procedure has preserved? }
  1028. Result := NR_NO;
  1029. RegSet :=
  1030. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1031. current_procinfo.saved_regs_mm;
  1032. for CurrentSuperReg in RegSet do
  1033. begin
  1034. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1035. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1036. begin
  1037. Currentp := p;
  1038. Breakout := False;
  1039. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1040. begin
  1041. case Currentp.typ of
  1042. ait_instruction:
  1043. begin
  1044. if RegInInstruction(CurrentReg, Currentp) then
  1045. begin
  1046. Breakout := True;
  1047. Break;
  1048. end;
  1049. { Cannot allocate across an unconditional jump }
  1050. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1051. Exit;
  1052. end;
  1053. ait_marker:
  1054. { Don't try anything more if a marker is hit }
  1055. Exit;
  1056. ait_regalloc:
  1057. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1058. begin
  1059. Breakout := True;
  1060. Break;
  1061. end;
  1062. else
  1063. ;
  1064. end;
  1065. end;
  1066. if Breakout then
  1067. { Try the next register }
  1068. Continue;
  1069. { We have a free register available }
  1070. Result := CurrentReg;
  1071. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1072. Exit;
  1073. end;
  1074. end;
  1075. end;
  1076. function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1077. begin
  1078. if not SuperRegistersEqual(reg1,reg2) then
  1079. exit(false);
  1080. if getregtype(reg1)<>R_INTREGISTER then
  1081. exit(true); {because SuperRegisterEqual is true}
  1082. case getsubreg(reg1) of
  1083. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1084. higher, it preserves the high bits, so the new value depends on
  1085. reg2's previous value. In other words, it is equivalent to doing:
  1086. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1087. R_SUBL:
  1088. exit(getsubreg(reg2)=R_SUBL);
  1089. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1090. higher, it actually does a:
  1091. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1092. R_SUBH:
  1093. exit(getsubreg(reg2)=R_SUBH);
  1094. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1095. bits of reg2:
  1096. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1097. R_SUBW:
  1098. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1099. { a write to R_SUBD always overwrites every other subregister,
  1100. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1101. R_SUBD,
  1102. R_SUBQ:
  1103. exit(true);
  1104. else
  1105. internalerror(2017042801);
  1106. end;
  1107. end;
  1108. function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1109. begin
  1110. if not SuperRegistersEqual(reg1,reg2) then
  1111. exit(false);
  1112. if getregtype(reg1)<>R_INTREGISTER then
  1113. exit(true); {because SuperRegisterEqual is true}
  1114. case getsubreg(reg1) of
  1115. R_SUBL:
  1116. exit(getsubreg(reg2)<>R_SUBH);
  1117. R_SUBH:
  1118. exit(getsubreg(reg2)<>R_SUBL);
  1119. R_SUBW,
  1120. R_SUBD,
  1121. R_SUBQ:
  1122. exit(true);
  1123. else
  1124. internalerror(2017042802);
  1125. end;
  1126. end;
  1127. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1128. var
  1129. hp1 : tai;
  1130. l : TCGInt;
  1131. begin
  1132. result:=false;
  1133. { changes the code sequence
  1134. shr/sar const1, x
  1135. shl const2, x
  1136. to
  1137. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1138. if GetNextInstruction(p, hp1) and
  1139. MatchInstruction(hp1,A_SHL,[]) and
  1140. (taicpu(p).oper[0]^.typ = top_const) and
  1141. (taicpu(hp1).oper[0]^.typ = top_const) and
  1142. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1143. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1144. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1145. begin
  1146. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1147. not(cs_opt_size in current_settings.optimizerswitches) then
  1148. begin
  1149. { shr/sar const1, %reg
  1150. shl const2, %reg
  1151. with const1 > const2 }
  1152. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1153. taicpu(hp1).opcode := A_AND;
  1154. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1155. case taicpu(p).opsize Of
  1156. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1157. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1158. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1159. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1160. else
  1161. Internalerror(2017050703)
  1162. end;
  1163. end
  1164. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1165. not(cs_opt_size in current_settings.optimizerswitches) then
  1166. begin
  1167. { shr/sar const1, %reg
  1168. shl const2, %reg
  1169. with const1 < const2 }
  1170. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1171. taicpu(p).opcode := A_AND;
  1172. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1173. case taicpu(p).opsize Of
  1174. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1175. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1176. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1177. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1178. else
  1179. Internalerror(2017050702)
  1180. end;
  1181. end
  1182. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1183. begin
  1184. { shr/sar const1, %reg
  1185. shl const2, %reg
  1186. with const1 = const2 }
  1187. taicpu(p).opcode := A_AND;
  1188. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1189. case taicpu(p).opsize Of
  1190. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1191. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1192. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1193. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1194. else
  1195. Internalerror(2017050701)
  1196. end;
  1197. RemoveInstruction(hp1);
  1198. end;
  1199. end;
  1200. end;
  1201. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1202. var
  1203. opsize : topsize;
  1204. hp1 : tai;
  1205. tmpref : treference;
  1206. ShiftValue : Cardinal;
  1207. BaseValue : TCGInt;
  1208. begin
  1209. result:=false;
  1210. opsize:=taicpu(p).opsize;
  1211. { changes certain "imul const, %reg"'s to lea sequences }
  1212. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1213. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1214. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1215. if (taicpu(p).oper[0]^.val = 1) then
  1216. if (taicpu(p).ops = 2) then
  1217. { remove "imul $1, reg" }
  1218. begin
  1219. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1220. Result := RemoveCurrentP(p);
  1221. end
  1222. else
  1223. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1224. begin
  1225. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1226. InsertLLItem(p.previous, p.next, hp1);
  1227. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1228. p.free;
  1229. p := hp1;
  1230. end
  1231. else if ((taicpu(p).ops <= 2) or
  1232. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1233. not(cs_opt_size in current_settings.optimizerswitches) and
  1234. (not(GetNextInstruction(p, hp1)) or
  1235. not((tai(hp1).typ = ait_instruction) and
  1236. ((taicpu(hp1).opcode=A_Jcc) and
  1237. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1238. begin
  1239. {
  1240. imul X, reg1, reg2 to
  1241. lea (reg1,reg1,Y), reg2
  1242. shl ZZ,reg2
  1243. imul XX, reg1 to
  1244. lea (reg1,reg1,YY), reg1
  1245. shl ZZ,reg2
  1246. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1247. it does not exist as a separate optimization target in FPC though.
  1248. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1249. at most two zeros
  1250. }
  1251. reference_reset(tmpref,1,[]);
  1252. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1253. begin
  1254. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1255. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1256. TmpRef.base := taicpu(p).oper[1]^.reg;
  1257. TmpRef.index := taicpu(p).oper[1]^.reg;
  1258. if not(BaseValue in [3,5,9]) then
  1259. Internalerror(2018110101);
  1260. TmpRef.ScaleFactor := BaseValue-1;
  1261. if (taicpu(p).ops = 2) then
  1262. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1263. else
  1264. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1265. AsmL.InsertAfter(hp1,p);
  1266. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1267. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1268. RemoveCurrentP(p, hp1);
  1269. if ShiftValue>0 then
  1270. AsmL.InsertAfter(taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg),hp1);
  1271. end;
  1272. end;
  1273. end;
  1274. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1275. begin
  1276. Result := False;
  1277. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1278. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1279. begin
  1280. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1281. taicpu(p).opcode := A_MOV;
  1282. Result := True;
  1283. end;
  1284. end;
  1285. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1286. var
  1287. p: taicpu absolute hp;
  1288. i: Integer;
  1289. begin
  1290. Result := False;
  1291. if not assigned(hp) or
  1292. (hp.typ <> ait_instruction) then
  1293. Exit;
  1294. // p := taicpu(hp);
  1295. Prefetch(insprop[p.opcode]);
  1296. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1297. with insprop[p.opcode] do
  1298. begin
  1299. case getsubreg(reg) of
  1300. R_SUBW,R_SUBD,R_SUBQ:
  1301. Result:=
  1302. RegLoadedWithNewValue(NR_CARRYFLAG,hp) and
  1303. RegLoadedWithNewValue(NR_PARITYFLAG,hp) and
  1304. RegLoadedWithNewValue(NR_AUXILIARYFLAG,hp) and
  1305. RegLoadedWithNewValue(NR_ZEROFLAG,hp) and
  1306. RegLoadedWithNewValue(NR_SIGNFLAG,hp) and
  1307. RegLoadedWithNewValue(NR_OVERFLOWFLAG,hp);
  1308. R_SUBFLAGCARRY:
  1309. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1310. R_SUBFLAGPARITY:
  1311. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1312. R_SUBFLAGAUXILIARY:
  1313. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1314. R_SUBFLAGZERO:
  1315. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1316. R_SUBFLAGSIGN:
  1317. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1318. R_SUBFLAGOVERFLOW:
  1319. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1320. R_SUBFLAGINTERRUPT:
  1321. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1322. R_SUBFLAGDIRECTION:
  1323. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1324. else
  1325. begin
  1326. writeln(getsubreg(reg));
  1327. internalerror(2017050501);
  1328. end;
  1329. end;
  1330. exit;
  1331. end;
  1332. { Handle special cases first }
  1333. case p.opcode of
  1334. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1335. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1336. begin
  1337. Result :=
  1338. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1339. (p.oper[1]^.typ = top_reg) and
  1340. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1341. (
  1342. (p.oper[0]^.typ = top_const) or
  1343. (
  1344. (p.oper[0]^.typ = top_reg) and
  1345. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1346. ) or (
  1347. (p.oper[0]^.typ = top_ref) and
  1348. not RegInRef(reg,p.oper[0]^.ref^)
  1349. )
  1350. );
  1351. end;
  1352. A_MUL, A_IMUL:
  1353. Result :=
  1354. (
  1355. (p.ops=3) and { IMUL only }
  1356. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1357. (
  1358. (
  1359. (p.oper[1]^.typ=top_reg) and
  1360. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1361. ) or (
  1362. (p.oper[1]^.typ=top_ref) and
  1363. not RegInRef(reg,p.oper[1]^.ref^)
  1364. )
  1365. )
  1366. ) or (
  1367. (
  1368. (p.ops=1) and
  1369. (
  1370. (
  1371. (
  1372. (p.oper[0]^.typ=top_reg) and
  1373. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1374. )
  1375. ) or (
  1376. (p.oper[0]^.typ=top_ref) and
  1377. not RegInRef(reg,p.oper[0]^.ref^)
  1378. )
  1379. ) and (
  1380. (
  1381. (p.opsize=S_B) and
  1382. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1383. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1384. ) or (
  1385. (p.opsize=S_W) and
  1386. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1387. ) or (
  1388. (p.opsize=S_L) and
  1389. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1390. {$ifdef x86_64}
  1391. ) or (
  1392. (p.opsize=S_Q) and
  1393. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1394. {$endif x86_64}
  1395. )
  1396. )
  1397. )
  1398. );
  1399. A_CBW:
  1400. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1401. {$ifndef x86_64}
  1402. A_LDS:
  1403. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1404. A_LES:
  1405. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1406. {$endif not x86_64}
  1407. A_LFS:
  1408. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1409. A_LGS:
  1410. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1411. A_LSS:
  1412. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1413. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1414. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1415. A_LODSB:
  1416. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1417. A_LODSW:
  1418. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1419. {$ifdef x86_64}
  1420. A_LODSQ:
  1421. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1422. {$endif x86_64}
  1423. A_LODSD:
  1424. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1425. A_FSTSW, A_FNSTSW:
  1426. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1427. else
  1428. begin
  1429. with insprop[p.opcode] do
  1430. begin
  1431. if (
  1432. { xor %reg,%reg etc. is classed as a new value }
  1433. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1434. MatchOpType(p, top_reg, top_reg) and
  1435. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1436. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1437. ) then
  1438. begin
  1439. Result := True;
  1440. Exit;
  1441. end;
  1442. { Make sure the entire register is overwritten }
  1443. if (getregtype(reg) = R_INTREGISTER) then
  1444. begin
  1445. if (p.ops > 0) then
  1446. begin
  1447. if RegInOp(reg, p.oper[0]^) then
  1448. begin
  1449. if (p.oper[0]^.typ = top_ref) then
  1450. begin
  1451. if RegInRef(reg, p.oper[0]^.ref^) then
  1452. begin
  1453. Result := False;
  1454. Exit;
  1455. end;
  1456. end
  1457. else if (p.oper[0]^.typ = top_reg) then
  1458. begin
  1459. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1460. begin
  1461. Result := False;
  1462. Exit;
  1463. end
  1464. else if ([Ch_WOp1]*Ch<>[]) then
  1465. begin
  1466. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1467. Result := True
  1468. else
  1469. begin
  1470. Result := False;
  1471. Exit;
  1472. end;
  1473. end;
  1474. end;
  1475. end;
  1476. if (p.ops > 1) then
  1477. begin
  1478. if RegInOp(reg, p.oper[1]^) then
  1479. begin
  1480. if (p.oper[1]^.typ = top_ref) then
  1481. begin
  1482. if RegInRef(reg, p.oper[1]^.ref^) then
  1483. begin
  1484. Result := False;
  1485. Exit;
  1486. end;
  1487. end
  1488. else if (p.oper[1]^.typ = top_reg) then
  1489. begin
  1490. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1491. begin
  1492. Result := False;
  1493. Exit;
  1494. end
  1495. else if ([Ch_WOp2]*Ch<>[]) then
  1496. begin
  1497. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1498. Result := True
  1499. else
  1500. begin
  1501. Result := False;
  1502. Exit;
  1503. end;
  1504. end;
  1505. end;
  1506. end;
  1507. if (p.ops > 2) then
  1508. begin
  1509. if RegInOp(reg, p.oper[2]^) then
  1510. begin
  1511. if (p.oper[2]^.typ = top_ref) then
  1512. begin
  1513. if RegInRef(reg, p.oper[2]^.ref^) then
  1514. begin
  1515. Result := False;
  1516. Exit;
  1517. end;
  1518. end
  1519. else if (p.oper[2]^.typ = top_reg) then
  1520. begin
  1521. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1522. begin
  1523. Result := False;
  1524. Exit;
  1525. end
  1526. else if ([Ch_WOp3]*Ch<>[]) then
  1527. begin
  1528. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1529. Result := True
  1530. else
  1531. begin
  1532. Result := False;
  1533. Exit;
  1534. end;
  1535. end;
  1536. end;
  1537. end;
  1538. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1539. begin
  1540. if (p.oper[3]^.typ = top_ref) then
  1541. begin
  1542. if RegInRef(reg, p.oper[3]^.ref^) then
  1543. begin
  1544. Result := False;
  1545. Exit;
  1546. end;
  1547. end
  1548. else if (p.oper[3]^.typ = top_reg) then
  1549. begin
  1550. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1551. begin
  1552. Result := False;
  1553. Exit;
  1554. end
  1555. else if ([Ch_WOp4]*Ch<>[]) then
  1556. begin
  1557. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1558. Result := True
  1559. else
  1560. begin
  1561. Result := False;
  1562. Exit;
  1563. end;
  1564. end;
  1565. end;
  1566. end;
  1567. end;
  1568. end;
  1569. end;
  1570. { Don't do these ones first in case an input operand is equal to an explicit output registers }
  1571. case getsupreg(reg) of
  1572. RS_EAX:
  1573. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1574. begin
  1575. Result := True;
  1576. Exit;
  1577. end;
  1578. RS_ECX:
  1579. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1580. begin
  1581. Result := True;
  1582. Exit;
  1583. end;
  1584. RS_EDX:
  1585. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1586. begin
  1587. Result := True;
  1588. Exit;
  1589. end;
  1590. RS_EBX:
  1591. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1592. begin
  1593. Result := True;
  1594. Exit;
  1595. end;
  1596. RS_ESP:
  1597. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1598. begin
  1599. Result := True;
  1600. Exit;
  1601. end;
  1602. RS_EBP:
  1603. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1604. begin
  1605. Result := True;
  1606. Exit;
  1607. end;
  1608. RS_ESI:
  1609. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1610. begin
  1611. Result := True;
  1612. Exit;
  1613. end;
  1614. RS_EDI:
  1615. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1616. begin
  1617. Result := True;
  1618. Exit;
  1619. end;
  1620. else
  1621. ;
  1622. end;
  1623. end;
  1624. end;
  1625. end;
  1626. end;
  1627. end;
  1628. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1629. var
  1630. hp2,hp3 : tai;
  1631. begin
  1632. { some x86-64 issue a NOP before the real exit code }
  1633. if MatchInstruction(p,A_NOP,[]) then
  1634. GetNextInstruction(p,p);
  1635. result:=assigned(p) and (p.typ=ait_instruction) and
  1636. ((taicpu(p).opcode = A_RET) or
  1637. ((taicpu(p).opcode=A_LEAVE) and
  1638. GetNextInstruction(p,hp2) and
  1639. MatchInstruction(hp2,A_RET,[S_NO])
  1640. ) or
  1641. (((taicpu(p).opcode=A_LEA) and
  1642. MatchOpType(taicpu(p),top_ref,top_reg) and
  1643. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1644. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1645. ) and
  1646. GetNextInstruction(p,hp2) and
  1647. MatchInstruction(hp2,A_RET,[S_NO])
  1648. ) or
  1649. ((((taicpu(p).opcode=A_MOV) and
  1650. MatchOpType(taicpu(p),top_reg,top_reg) and
  1651. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1652. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1653. ((taicpu(p).opcode=A_LEA) and
  1654. MatchOpType(taicpu(p),top_ref,top_reg) and
  1655. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1656. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1657. )
  1658. ) and
  1659. GetNextInstruction(p,hp2) and
  1660. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1661. MatchOpType(taicpu(hp2),top_reg) and
  1662. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1663. GetNextInstruction(hp2,hp3) and
  1664. MatchInstruction(hp3,A_RET,[S_NO])
  1665. )
  1666. );
  1667. end;
  1668. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1669. begin
  1670. isFoldableArithOp := False;
  1671. case hp1.opcode of
  1672. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1673. isFoldableArithOp :=
  1674. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1675. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1676. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1677. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1678. (taicpu(hp1).oper[1]^.reg = reg);
  1679. A_INC,A_DEC,A_NEG,A_NOT:
  1680. isFoldableArithOp :=
  1681. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1682. (taicpu(hp1).oper[0]^.reg = reg);
  1683. else
  1684. ;
  1685. end;
  1686. end;
  1687. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1688. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1689. var
  1690. hp2: tai;
  1691. begin
  1692. hp2 := p;
  1693. repeat
  1694. hp2 := tai(hp2.previous);
  1695. if assigned(hp2) and
  1696. (hp2.typ = ait_regalloc) and
  1697. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1698. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1699. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1700. begin
  1701. RemoveInstruction(hp2);
  1702. break;
  1703. end;
  1704. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1705. end;
  1706. begin
  1707. case current_procinfo.procdef.returndef.typ of
  1708. arraydef,recorddef,pointerdef,
  1709. stringdef,enumdef,procdef,objectdef,errordef,
  1710. filedef,setdef,procvardef,
  1711. classrefdef,forwarddef:
  1712. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1713. orddef:
  1714. if current_procinfo.procdef.returndef.size <> 0 then
  1715. begin
  1716. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1717. { for int64/qword }
  1718. if current_procinfo.procdef.returndef.size = 8 then
  1719. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1720. end;
  1721. else
  1722. ;
  1723. end;
  1724. end;
  1725. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1726. var
  1727. hp1,hp2 : tai;
  1728. begin
  1729. result:=false;
  1730. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1731. begin
  1732. { vmova* reg1,reg1
  1733. =>
  1734. <nop> }
  1735. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1736. begin
  1737. RemoveCurrentP(p);
  1738. result:=true;
  1739. exit;
  1740. end
  1741. else if GetNextInstruction(p,hp1) then
  1742. begin
  1743. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1744. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1745. begin
  1746. { vmova* reg1,reg2
  1747. vmova* reg2,reg3
  1748. dealloc reg2
  1749. =>
  1750. vmova* reg1,reg3 }
  1751. TransferUsedRegs(TmpUsedRegs);
  1752. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1753. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1754. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1755. begin
  1756. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1757. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1758. RemoveInstruction(hp1);
  1759. result:=true;
  1760. exit;
  1761. end
  1762. { special case:
  1763. vmova* reg1,<op>
  1764. vmova* <op>,reg1
  1765. =>
  1766. vmova* reg1,<op> }
  1767. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1768. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1769. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1770. ) then
  1771. begin
  1772. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1773. RemoveInstruction(hp1);
  1774. result:=true;
  1775. exit;
  1776. end
  1777. end
  1778. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  1779. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  1780. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  1781. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  1782. ) and
  1783. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1784. begin
  1785. { vmova* reg1,reg2
  1786. vmovs* reg2,<op>
  1787. dealloc reg2
  1788. =>
  1789. vmovs* reg1,reg3 }
  1790. TransferUsedRegs(TmpUsedRegs);
  1791. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1792. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1793. begin
  1794. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  1795. taicpu(p).opcode:=taicpu(hp1).opcode;
  1796. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1797. RemoveInstruction(hp1);
  1798. result:=true;
  1799. exit;
  1800. end
  1801. end;
  1802. end;
  1803. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  1804. begin
  1805. if MatchInstruction(hp1,[A_VFMADDPD,
  1806. A_VFMADD132PD,
  1807. A_VFMADD132PS,
  1808. A_VFMADD132SD,
  1809. A_VFMADD132SS,
  1810. A_VFMADD213PD,
  1811. A_VFMADD213PS,
  1812. A_VFMADD213SD,
  1813. A_VFMADD213SS,
  1814. A_VFMADD231PD,
  1815. A_VFMADD231PS,
  1816. A_VFMADD231SD,
  1817. A_VFMADD231SS,
  1818. A_VFMADDSUB132PD,
  1819. A_VFMADDSUB132PS,
  1820. A_VFMADDSUB213PD,
  1821. A_VFMADDSUB213PS,
  1822. A_VFMADDSUB231PD,
  1823. A_VFMADDSUB231PS,
  1824. A_VFMSUB132PD,
  1825. A_VFMSUB132PS,
  1826. A_VFMSUB132SD,
  1827. A_VFMSUB132SS,
  1828. A_VFMSUB213PD,
  1829. A_VFMSUB213PS,
  1830. A_VFMSUB213SD,
  1831. A_VFMSUB213SS,
  1832. A_VFMSUB231PD,
  1833. A_VFMSUB231PS,
  1834. A_VFMSUB231SD,
  1835. A_VFMSUB231SS,
  1836. A_VFMSUBADD132PD,
  1837. A_VFMSUBADD132PS,
  1838. A_VFMSUBADD213PD,
  1839. A_VFMSUBADD213PS,
  1840. A_VFMSUBADD231PD,
  1841. A_VFMSUBADD231PS,
  1842. A_VFNMADD132PD,
  1843. A_VFNMADD132PS,
  1844. A_VFNMADD132SD,
  1845. A_VFNMADD132SS,
  1846. A_VFNMADD213PD,
  1847. A_VFNMADD213PS,
  1848. A_VFNMADD213SD,
  1849. A_VFNMADD213SS,
  1850. A_VFNMADD231PD,
  1851. A_VFNMADD231PS,
  1852. A_VFNMADD231SD,
  1853. A_VFNMADD231SS,
  1854. A_VFNMSUB132PD,
  1855. A_VFNMSUB132PS,
  1856. A_VFNMSUB132SD,
  1857. A_VFNMSUB132SS,
  1858. A_VFNMSUB213PD,
  1859. A_VFNMSUB213PS,
  1860. A_VFNMSUB213SD,
  1861. A_VFNMSUB213SS,
  1862. A_VFNMSUB231PD,
  1863. A_VFNMSUB231PS,
  1864. A_VFNMSUB231SD,
  1865. A_VFNMSUB231SS],[S_NO]) and
  1866. { we mix single and double opperations here because we assume that the compiler
  1867. generates vmovapd only after double operations and vmovaps only after single operations }
  1868. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  1869. GetNextInstruction(hp1,hp2) and
  1870. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  1871. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  1872. begin
  1873. TransferUsedRegs(TmpUsedRegs);
  1874. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1875. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1876. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1877. begin
  1878. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  1879. RemoveCurrentP(p, hp1); // <-- Is this actually safe? hp1 is not necessarily the next instruction. [Kit]
  1880. RemoveInstruction(hp2);
  1881. end;
  1882. end
  1883. else if (hp1.typ = ait_instruction) and
  1884. GetNextInstruction(hp1, hp2) and
  1885. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  1886. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  1887. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  1888. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  1889. (((taicpu(p).opcode=A_MOVAPS) and
  1890. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  1891. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  1892. ((taicpu(p).opcode=A_MOVAPD) and
  1893. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  1894. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  1895. ) then
  1896. { change
  1897. movapX reg,reg2
  1898. addsX/subsX/... reg3, reg2
  1899. movapX reg2,reg
  1900. to
  1901. addsX/subsX/... reg3,reg
  1902. }
  1903. begin
  1904. TransferUsedRegs(TmpUsedRegs);
  1905. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1906. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1907. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1908. begin
  1909. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  1910. debug_op2str(taicpu(p).opcode)+' '+
  1911. debug_op2str(taicpu(hp1).opcode)+' '+
  1912. debug_op2str(taicpu(hp2).opcode)+') done',p);
  1913. { we cannot eliminate the first move if
  1914. the operations uses the same register for source and dest }
  1915. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  1916. RemoveCurrentP(p, nil);
  1917. p:=hp1;
  1918. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  1919. RemoveInstruction(hp2);
  1920. result:=true;
  1921. end;
  1922. end
  1923. else if (hp1.typ = ait_instruction) and
  1924. (((taicpu(p).opcode=A_VMOVAPD) and
  1925. (taicpu(hp1).opcode=A_VCOMISD)) or
  1926. ((taicpu(p).opcode=A_VMOVAPS) and
  1927. ((taicpu(hp1).opcode=A_VCOMISS))
  1928. )
  1929. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  1930. { change
  1931. movapX reg,reg2
  1932. addsX/subsX/... reg3, reg2
  1933. movapX reg2,reg
  1934. to
  1935. addsX/subsX/... reg3,reg
  1936. }
  1937. begin
  1938. TransferUsedRegs(TmpUsedRegs);
  1939. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1940. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1941. begin
  1942. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  1943. debug_op2str(taicpu(p).opcode)+' '+
  1944. debug_op2str(taicpu(hp1).opcode)+') done',p);
  1945. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1946. taicpu(hp1).loadoper(0, taicpu(p).oper[1]^);
  1947. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  1948. taicpu(hp1).loadoper(1, taicpu(p).oper[1]^);
  1949. RemoveCurrentP(p, nil);
  1950. result:=true;
  1951. exit;
  1952. end;
  1953. end
  1954. end;
  1955. end;
  1956. end;
  1957. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  1958. var
  1959. hp1 : tai;
  1960. begin
  1961. result:=false;
  1962. { replace
  1963. V<Op>X %mreg1,%mreg2,%mreg3
  1964. VMovX %mreg3,%mreg4
  1965. dealloc %mreg3
  1966. by
  1967. V<Op>X %mreg1,%mreg2,%mreg4
  1968. ?
  1969. }
  1970. if GetNextInstruction(p,hp1) and
  1971. { we mix single and double operations here because we assume that the compiler
  1972. generates vmovapd only after double operations and vmovaps only after single operations }
  1973. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  1974. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  1975. (taicpu(hp1).oper[1]^.typ=top_reg) then
  1976. begin
  1977. TransferUsedRegs(TmpUsedRegs);
  1978. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1979. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  1980. begin
  1981. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  1982. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  1983. RemoveInstruction(hp1);
  1984. result:=true;
  1985. end;
  1986. end;
  1987. end;
  1988. { Replaces all references to AOldReg in a memory reference to ANewReg }
  1989. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  1990. begin
  1991. Result := False;
  1992. { For safety reasons, only check for exact register matches }
  1993. { Check base register }
  1994. if (ref.base = AOldReg) then
  1995. begin
  1996. ref.base := ANewReg;
  1997. Result := True;
  1998. end;
  1999. { Check index register }
  2000. if (ref.index = AOldReg) then
  2001. begin
  2002. ref.index := ANewReg;
  2003. Result := True;
  2004. end;
  2005. end;
  2006. { Replaces all references to AOldReg in an operand to ANewReg }
  2007. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2008. var
  2009. OldSupReg, NewSupReg: TSuperRegister;
  2010. OldSubReg, NewSubReg: TSubRegister;
  2011. OldRegType: TRegisterType;
  2012. ThisOper: POper;
  2013. begin
  2014. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2015. Result := False;
  2016. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2017. InternalError(2020011801);
  2018. OldSupReg := getsupreg(AOldReg);
  2019. OldSubReg := getsubreg(AOldReg);
  2020. OldRegType := getregtype(AOldReg);
  2021. NewSupReg := getsupreg(ANewReg);
  2022. NewSubReg := getsubreg(ANewReg);
  2023. if OldRegType <> getregtype(ANewReg) then
  2024. InternalError(2020011802);
  2025. if OldSubReg <> NewSubReg then
  2026. InternalError(2020011803);
  2027. case ThisOper^.typ of
  2028. top_reg:
  2029. if (
  2030. (ThisOper^.reg = AOldReg) or
  2031. (
  2032. (OldRegType = R_INTREGISTER) and
  2033. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2034. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2035. (
  2036. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2037. {$ifndef x86_64}
  2038. and (
  2039. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2040. don't have an 8-bit representation }
  2041. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2042. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2043. )
  2044. {$endif x86_64}
  2045. )
  2046. )
  2047. ) then
  2048. begin
  2049. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2050. Result := True;
  2051. end;
  2052. top_ref:
  2053. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2054. Result := True;
  2055. else
  2056. ;
  2057. end;
  2058. end;
  2059. { Replaces all references to AOldReg in an instruction to ANewReg }
  2060. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2061. const
  2062. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2063. var
  2064. OperIdx: Integer;
  2065. begin
  2066. Result := False;
  2067. for OperIdx := 0 to p.ops - 1 do
  2068. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2069. begin
  2070. { The shift and rotate instructions can only use CL }
  2071. if not (
  2072. (OperIdx = 0) and
  2073. { This second condition just helps to avoid unnecessarily
  2074. calling MatchInstruction for 10 different opcodes }
  2075. (p.oper[0]^.reg = NR_CL) and
  2076. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2077. ) then
  2078. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2079. end
  2080. else if p.oper[OperIdx]^.typ = top_ref then
  2081. { It's okay to replace registers in references that get written to }
  2082. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2083. end;
  2084. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2085. begin
  2086. with ref^ do
  2087. Result :=
  2088. (index = NR_NO) and
  2089. (
  2090. {$ifdef x86_64}
  2091. (
  2092. (base = NR_RIP) and
  2093. (refaddr in [addr_pic, addr_pic_no_got])
  2094. ) or
  2095. {$endif x86_64}
  2096. (base = NR_STACK_POINTER_REG) or
  2097. (base = current_procinfo.framepointer)
  2098. );
  2099. end;
  2100. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2101. var
  2102. l: asizeint;
  2103. begin
  2104. Result := False;
  2105. { Should have been checked previously }
  2106. if p.opcode <> A_LEA then
  2107. InternalError(2020072501);
  2108. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2109. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2110. not(cs_opt_size in current_settings.optimizerswitches) then
  2111. exit;
  2112. with p.oper[0]^.ref^ do
  2113. begin
  2114. if (base <> p.oper[1]^.reg) or
  2115. (index <> NR_NO) or
  2116. assigned(symbol) then
  2117. exit;
  2118. l:=offset;
  2119. if (l=1) and UseIncDec then
  2120. begin
  2121. p.opcode:=A_INC;
  2122. p.loadreg(0,p.oper[1]^.reg);
  2123. p.ops:=1;
  2124. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2125. end
  2126. else if (l=-1) and UseIncDec then
  2127. begin
  2128. p.opcode:=A_DEC;
  2129. p.loadreg(0,p.oper[1]^.reg);
  2130. p.ops:=1;
  2131. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2132. end
  2133. else
  2134. begin
  2135. if (l<0) and (l<>-2147483648) then
  2136. begin
  2137. p.opcode:=A_SUB;
  2138. p.loadConst(0,-l);
  2139. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2140. end
  2141. else
  2142. begin
  2143. p.opcode:=A_ADD;
  2144. p.loadConst(0,l);
  2145. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2146. end;
  2147. end;
  2148. end;
  2149. Result := True;
  2150. end;
  2151. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2152. var
  2153. CurrentReg, ReplaceReg: TRegister;
  2154. begin
  2155. Result := False;
  2156. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2157. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2158. case hp.opcode of
  2159. A_FSTSW, A_FNSTSW,
  2160. A_IN, A_INS, A_OUT, A_OUTS,
  2161. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2162. { These routines have explicit operands, but they are restricted in
  2163. what they can be (e.g. IN and OUT can only read from AL, AX or
  2164. EAX. }
  2165. Exit;
  2166. A_IMUL:
  2167. begin
  2168. { The 1-operand version writes to implicit registers
  2169. The 2-operand version reads from the first operator, and reads
  2170. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2171. the 3-operand version reads from a register that it doesn't write to
  2172. }
  2173. case hp.ops of
  2174. 1:
  2175. if (
  2176. (
  2177. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2178. ) or
  2179. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2180. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2181. begin
  2182. Result := True;
  2183. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2184. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2185. end;
  2186. 2:
  2187. { Only modify the first parameter }
  2188. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2189. begin
  2190. Result := True;
  2191. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2192. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2193. end;
  2194. 3:
  2195. { Only modify the second parameter }
  2196. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2197. begin
  2198. Result := True;
  2199. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2200. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2201. end;
  2202. else
  2203. InternalError(2020012901);
  2204. end;
  2205. end;
  2206. else
  2207. if (hp.ops > 0) and
  2208. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2209. begin
  2210. Result := True;
  2211. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2212. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2213. end;
  2214. end;
  2215. end;
  2216. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2217. var
  2218. hp1, hp2, hp3: tai;
  2219. DoOptimisation, TempBool: Boolean;
  2220. {$ifdef x86_64}
  2221. NewConst: TCGInt;
  2222. {$endif x86_64}
  2223. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2224. begin
  2225. if taicpu(hp1).opcode = signed_movop then
  2226. begin
  2227. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2228. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2229. end
  2230. else
  2231. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2232. end;
  2233. function TryConstMerge(var p1, p2: tai): Boolean;
  2234. var
  2235. ThisRef: TReference;
  2236. begin
  2237. Result := False;
  2238. ThisRef := taicpu(p2).oper[1]^.ref^;
  2239. { Only permit writes to the stack, since we can guarantee alignment with that }
  2240. if (ThisRef.index = NR_NO) and
  2241. (
  2242. (ThisRef.base = NR_STACK_POINTER_REG) or
  2243. (ThisRef.base = current_procinfo.framepointer)
  2244. ) then
  2245. begin
  2246. case taicpu(p).opsize of
  2247. S_B:
  2248. begin
  2249. { Word writes must be on a 2-byte boundary }
  2250. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2251. begin
  2252. { Reduce offset of second reference to see if it is sequential with the first }
  2253. Dec(ThisRef.offset, 1);
  2254. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2255. begin
  2256. { Make sure the constants aren't represented as a
  2257. negative number, as these won't merge properly }
  2258. taicpu(p1).opsize := S_W;
  2259. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2260. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2261. RemoveInstruction(p2);
  2262. Result := True;
  2263. end;
  2264. end;
  2265. end;
  2266. S_W:
  2267. begin
  2268. { Longword writes must be on a 4-byte boundary }
  2269. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2270. begin
  2271. { Reduce offset of second reference to see if it is sequential with the first }
  2272. Dec(ThisRef.offset, 2);
  2273. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2274. begin
  2275. { Make sure the constants aren't represented as a
  2276. negative number, as these won't merge properly }
  2277. taicpu(p1).opsize := S_L;
  2278. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2279. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2280. RemoveInstruction(p2);
  2281. Result := True;
  2282. end;
  2283. end;
  2284. end;
  2285. {$ifdef x86_64}
  2286. S_L:
  2287. begin
  2288. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2289. see if the constants can be encoded this way. }
  2290. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2291. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2292. { Quadword writes must be on an 8-byte boundary }
  2293. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2294. begin
  2295. { Reduce offset of second reference to see if it is sequential with the first }
  2296. Dec(ThisRef.offset, 4);
  2297. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2298. begin
  2299. { Make sure the constants aren't represented as a
  2300. negative number, as these won't merge properly }
  2301. taicpu(p1).opsize := S_Q;
  2302. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2303. taicpu(p1).oper[0]^.val := NewConst;
  2304. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2305. RemoveInstruction(p2);
  2306. Result := True;
  2307. end;
  2308. end;
  2309. end;
  2310. {$endif x86_64}
  2311. else
  2312. ;
  2313. end;
  2314. end;
  2315. end;
  2316. var
  2317. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2318. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2319. NewSize: topsize;
  2320. CurrentReg, ActiveReg: TRegister;
  2321. SourceRef, TargetRef: TReference;
  2322. MovAligned, MovUnaligned: TAsmOp;
  2323. begin
  2324. Result:=false;
  2325. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2326. { remove mov reg1,reg1? }
  2327. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2328. then
  2329. begin
  2330. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2331. { take care of the register (de)allocs following p }
  2332. RemoveCurrentP(p, hp1);
  2333. Result:=true;
  2334. exit;
  2335. end;
  2336. { All the next optimisations require a next instruction }
  2337. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2338. Exit;
  2339. { Look for:
  2340. mov %reg1,%reg2
  2341. ??? %reg2,r/m
  2342. Change to:
  2343. mov %reg1,%reg2
  2344. ??? %reg1,r/m
  2345. }
  2346. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2347. begin
  2348. CurrentReg := taicpu(p).oper[1]^.reg;
  2349. if RegReadByInstruction(CurrentReg, hp1) and
  2350. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2351. begin
  2352. { A change has occurred, just not in p }
  2353. Result := True;
  2354. TransferUsedRegs(TmpUsedRegs);
  2355. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2356. if not RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs) and
  2357. { Just in case something didn't get modified (e.g. an
  2358. implicit register) }
  2359. not RegReadByInstruction(CurrentReg, hp1) then
  2360. begin
  2361. { We can remove the original MOV }
  2362. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2363. RemoveCurrentp(p, hp1);
  2364. { UsedRegs got updated by RemoveCurrentp }
  2365. Result := True;
  2366. Exit;
  2367. end;
  2368. { If we know a MOV instruction has become a null operation, we might as well
  2369. get rid of it now to save time. }
  2370. if (taicpu(hp1).opcode = A_MOV) and
  2371. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2372. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2373. { Just being a register is enough to confirm it's a null operation }
  2374. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2375. begin
  2376. Result := True;
  2377. { Speed-up to reduce a pipeline stall... if we had something like...
  2378. movl %eax,%edx
  2379. movw %dx,%ax
  2380. ... the second instruction would change to movw %ax,%ax, but
  2381. given that it is now %ax that's active rather than %eax,
  2382. penalties might occur due to a partial register write, so instead,
  2383. change it to a MOVZX instruction when optimising for speed.
  2384. }
  2385. if not (cs_opt_size in current_settings.optimizerswitches) and
  2386. IsMOVZXAcceptable and
  2387. (taicpu(hp1).opsize < taicpu(p).opsize)
  2388. {$ifdef x86_64}
  2389. { operations already implicitly set the upper 64 bits to zero }
  2390. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2391. {$endif x86_64}
  2392. then
  2393. begin
  2394. CurrentReg := taicpu(hp1).oper[1]^.reg;
  2395. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2396. case taicpu(p).opsize of
  2397. S_W:
  2398. if taicpu(hp1).opsize = S_B then
  2399. taicpu(hp1).opsize := S_BL
  2400. else
  2401. InternalError(2020012911);
  2402. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2403. case taicpu(hp1).opsize of
  2404. S_B:
  2405. taicpu(hp1).opsize := S_BL;
  2406. S_W:
  2407. taicpu(hp1).opsize := S_WL;
  2408. else
  2409. InternalError(2020012912);
  2410. end;
  2411. else
  2412. InternalError(2020012910);
  2413. end;
  2414. taicpu(hp1).opcode := A_MOVZX;
  2415. taicpu(hp1).oper[1]^.reg := newreg(getregtype(CurrentReg), getsupreg(CurrentReg), R_SUBD)
  2416. end
  2417. else
  2418. begin
  2419. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2420. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2421. RemoveInstruction(hp1);
  2422. { The instruction after what was hp1 is now the immediate next instruction,
  2423. so we can continue to make optimisations if it's present }
  2424. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2425. Exit;
  2426. hp1 := hp2;
  2427. end;
  2428. end;
  2429. end;
  2430. end;
  2431. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2432. overwrites the original destination register. e.g.
  2433. movl ###,%reg2d
  2434. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2435. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2436. }
  2437. if (taicpu(p).oper[1]^.typ = top_reg) and
  2438. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2439. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2440. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2441. begin
  2442. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2443. begin
  2444. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2445. case taicpu(p).oper[0]^.typ of
  2446. top_const:
  2447. { We have something like:
  2448. movb $x, %regb
  2449. movzbl %regb,%regd
  2450. Change to:
  2451. movl $x, %regd
  2452. }
  2453. begin
  2454. case taicpu(hp1).opsize of
  2455. S_BW:
  2456. begin
  2457. convert_mov_value(A_MOVSX, $FF);
  2458. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2459. taicpu(p).opsize := S_W;
  2460. end;
  2461. S_BL:
  2462. begin
  2463. convert_mov_value(A_MOVSX, $FF);
  2464. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2465. taicpu(p).opsize := S_L;
  2466. end;
  2467. S_WL:
  2468. begin
  2469. convert_mov_value(A_MOVSX, $FFFF);
  2470. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2471. taicpu(p).opsize := S_L;
  2472. end;
  2473. {$ifdef x86_64}
  2474. S_BQ:
  2475. begin
  2476. convert_mov_value(A_MOVSX, $FF);
  2477. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2478. taicpu(p).opsize := S_Q;
  2479. end;
  2480. S_WQ:
  2481. begin
  2482. convert_mov_value(A_MOVSX, $FFFF);
  2483. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2484. taicpu(p).opsize := S_Q;
  2485. end;
  2486. S_LQ:
  2487. begin
  2488. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2489. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2490. taicpu(p).opsize := S_Q;
  2491. end;
  2492. {$endif x86_64}
  2493. else
  2494. { If hp1 was a MOV instruction, it should have been
  2495. optimised already }
  2496. InternalError(2020021001);
  2497. end;
  2498. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2499. RemoveInstruction(hp1);
  2500. Result := True;
  2501. Exit;
  2502. end;
  2503. top_ref:
  2504. { We have something like:
  2505. movb mem, %regb
  2506. movzbl %regb,%regd
  2507. Change to:
  2508. movzbl mem, %regd
  2509. }
  2510. if (taicpu(p).oper[0]^.ref^.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2511. begin
  2512. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2513. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  2514. RemoveCurrentP(p, hp1);
  2515. Result:=True;
  2516. Exit;
  2517. end;
  2518. else
  2519. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2520. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2521. Exit;
  2522. end;
  2523. end
  2524. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2525. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2526. optimised }
  2527. else
  2528. begin
  2529. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2530. RemoveCurrentP(p, hp1);
  2531. Result := True;
  2532. Exit;
  2533. end;
  2534. end;
  2535. if (taicpu(hp1).opcode = A_AND) and
  2536. (taicpu(p).oper[1]^.typ = top_reg) and
  2537. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2538. begin
  2539. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2540. begin
  2541. case taicpu(p).opsize of
  2542. S_L:
  2543. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2544. begin
  2545. { Optimize out:
  2546. mov x, %reg
  2547. and ffffffffh, %reg
  2548. }
  2549. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2550. RemoveInstruction(hp1);
  2551. Result:=true;
  2552. exit;
  2553. end;
  2554. S_Q: { TODO: Confirm if this is even possible }
  2555. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2556. begin
  2557. { Optimize out:
  2558. mov x, %reg
  2559. and ffffffffffffffffh, %reg
  2560. }
  2561. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2562. RemoveInstruction(hp1);
  2563. Result:=true;
  2564. exit;
  2565. end;
  2566. else
  2567. ;
  2568. end;
  2569. if ((taicpu(p).oper[0]^.typ=top_reg) or
  2570. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  2571. GetNextInstruction(hp1,hp2) and
  2572. MatchInstruction(hp2,A_TEST,[taicpu(p).opsize]) and
  2573. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) and
  2574. (MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2575. MatchOperand(taicpu(hp2).oper[0]^,-1)) and
  2576. GetNextInstruction(hp2,hp3) and
  2577. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2578. (taicpu(hp3).condition in [C_E,C_NE]) then
  2579. begin
  2580. TransferUsedRegs(TmpUsedRegs);
  2581. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2582. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2583. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2584. begin
  2585. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2586. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2587. taicpu(hp1).opcode:=A_TEST;
  2588. RemoveInstruction(hp2);
  2589. RemoveCurrentP(p, hp1);
  2590. Result:=true;
  2591. exit;
  2592. end;
  2593. end;
  2594. end
  2595. else if IsMOVZXAcceptable and
  2596. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  2597. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  2598. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  2599. then
  2600. begin
  2601. InputVal := debug_operstr(taicpu(p).oper[0]^);
  2602. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  2603. case taicpu(p).opsize of
  2604. S_B:
  2605. if (taicpu(hp1).oper[0]^.val = $ff) then
  2606. begin
  2607. { Convert:
  2608. movb x, %regl movb x, %regl
  2609. andw ffh, %regw andl ffh, %regd
  2610. To:
  2611. movzbw x, %regd movzbl x, %regd
  2612. (Identical registers, just different sizes)
  2613. }
  2614. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  2615. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  2616. case taicpu(hp1).opsize of
  2617. S_W: NewSize := S_BW;
  2618. S_L: NewSize := S_BL;
  2619. {$ifdef x86_64}
  2620. S_Q: NewSize := S_BQ;
  2621. {$endif x86_64}
  2622. else
  2623. InternalError(2018011510);
  2624. end;
  2625. end
  2626. else
  2627. NewSize := S_NO;
  2628. S_W:
  2629. if (taicpu(hp1).oper[0]^.val = $ffff) then
  2630. begin
  2631. { Convert:
  2632. movw x, %regw
  2633. andl ffffh, %regd
  2634. To:
  2635. movzwl x, %regd
  2636. (Identical registers, just different sizes)
  2637. }
  2638. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  2639. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  2640. case taicpu(hp1).opsize of
  2641. S_L: NewSize := S_WL;
  2642. {$ifdef x86_64}
  2643. S_Q: NewSize := S_WQ;
  2644. {$endif x86_64}
  2645. else
  2646. InternalError(2018011511);
  2647. end;
  2648. end
  2649. else
  2650. NewSize := S_NO;
  2651. else
  2652. NewSize := S_NO;
  2653. end;
  2654. if NewSize <> S_NO then
  2655. begin
  2656. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  2657. { The actual optimization }
  2658. taicpu(p).opcode := A_MOVZX;
  2659. taicpu(p).changeopsize(NewSize);
  2660. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  2661. { Safeguard if "and" is followed by a conditional command }
  2662. TransferUsedRegs(TmpUsedRegs);
  2663. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  2664. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  2665. begin
  2666. { At this point, the "and" command is effectively equivalent to
  2667. "test %reg,%reg". This will be handled separately by the
  2668. Peephole Optimizer. [Kit] }
  2669. DebugMsg(SPeepholeOptimization + PreMessage +
  2670. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2671. end
  2672. else
  2673. begin
  2674. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  2675. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2676. RemoveInstruction(hp1);
  2677. end;
  2678. Result := True;
  2679. Exit;
  2680. end;
  2681. end;
  2682. end;
  2683. if (taicpu(hp1).opcode = A_OR) and
  2684. (taicpu(p).oper[1]^.typ = top_reg) and
  2685. MatchOperand(taicpu(p).oper[0]^, 0) and
  2686. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  2687. begin
  2688. { mov 0, %reg
  2689. or ###,%reg
  2690. Change to (only if the flags are not used):
  2691. mov ###,%reg
  2692. }
  2693. TransferUsedRegs(TmpUsedRegs);
  2694. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2695. DoOptimisation := True;
  2696. { Even if the flags are used, we might be able to do the optimisation
  2697. if the conditions are predictable }
  2698. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2699. begin
  2700. { Only perform if ### = %reg (the same register) or equal to 0,
  2701. so %reg is guaranteed to still have a value of zero }
  2702. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  2703. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  2704. begin
  2705. hp2 := hp1;
  2706. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2707. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  2708. GetNextInstruction(hp2, hp3) do
  2709. begin
  2710. { Don't continue modifying if the flags state is getting changed }
  2711. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  2712. Break;
  2713. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  2714. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  2715. begin
  2716. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  2717. begin
  2718. { Condition is always true }
  2719. case taicpu(hp3).opcode of
  2720. A_Jcc:
  2721. begin
  2722. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  2723. { Check for jump shortcuts before we destroy the condition }
  2724. DoJumpOptimizations(hp3, TempBool);
  2725. MakeUnconditional(taicpu(hp3));
  2726. Result := True;
  2727. end;
  2728. A_CMOVcc:
  2729. begin
  2730. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  2731. taicpu(hp3).opcode := A_MOV;
  2732. taicpu(hp3).condition := C_None;
  2733. Result := True;
  2734. end;
  2735. A_SETcc:
  2736. begin
  2737. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  2738. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  2739. taicpu(hp3).opcode := A_MOV;
  2740. taicpu(hp3).ops := 2;
  2741. taicpu(hp3).condition := C_None;
  2742. taicpu(hp3).opsize := S_B;
  2743. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2744. taicpu(hp3).loadconst(0, 1);
  2745. Result := True;
  2746. end;
  2747. else
  2748. InternalError(2021090701);
  2749. end;
  2750. end
  2751. 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
  2752. begin
  2753. { Condition is always false }
  2754. case taicpu(hp3).opcode of
  2755. A_Jcc:
  2756. begin
  2757. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  2758. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  2759. RemoveInstruction(hp3);
  2760. Result := True;
  2761. { Since hp3 was deleted, hp2 must not be updated }
  2762. Continue;
  2763. end;
  2764. A_CMOVcc:
  2765. begin
  2766. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  2767. RemoveInstruction(hp3);
  2768. Result := True;
  2769. { Since hp3 was deleted, hp2 must not be updated }
  2770. Continue;
  2771. end;
  2772. A_SETcc:
  2773. begin
  2774. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  2775. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  2776. taicpu(hp3).opcode := A_MOV;
  2777. taicpu(hp3).ops := 2;
  2778. taicpu(hp3).condition := C_None;
  2779. taicpu(hp3).opsize := S_B;
  2780. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2781. taicpu(hp3).loadconst(0, 0);
  2782. Result := True;
  2783. end;
  2784. else
  2785. InternalError(2021090702);
  2786. end;
  2787. end
  2788. else
  2789. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  2790. DoOptimisation := False;
  2791. end;
  2792. hp2 := hp3;
  2793. end;
  2794. { Flags are still in use - don't optimise }
  2795. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2796. DoOptimisation := False;
  2797. end
  2798. else
  2799. DoOptimisation := False;
  2800. end;
  2801. if DoOptimisation then
  2802. begin
  2803. {$ifdef x86_64}
  2804. { OR only supports 32-bit sign-extended constants for 64-bit
  2805. instructions, so compensate for this if the constant is
  2806. encoded as a value greater than or equal to 2^31 }
  2807. if (taicpu(hp1).opsize = S_Q) and
  2808. (taicpu(hp1).oper[0]^.typ = top_const) and
  2809. (taicpu(hp1).oper[0]^.val >= $80000000) then
  2810. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  2811. {$endif x86_64}
  2812. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  2813. taicpu(hp1).opcode := A_MOV;
  2814. RemoveCurrentP(p, hp1);
  2815. Result := True;
  2816. Exit;
  2817. end;
  2818. end;
  2819. { Next instruction is also a MOV ? }
  2820. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  2821. begin
  2822. if MatchOpType(taicpu(p), top_const, top_ref) and
  2823. MatchOpType(taicpu(hp1), top_const, top_ref) and
  2824. TryConstMerge(p, hp1) then
  2825. begin
  2826. Result := True;
  2827. { In case we have four byte writes in a row, check for 2 more
  2828. right now so we don't have to wait for another iteration of
  2829. pass 1
  2830. }
  2831. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  2832. case taicpu(p).opsize of
  2833. S_W:
  2834. begin
  2835. if GetNextInstruction(p, hp1) and
  2836. MatchInstruction(hp1, A_MOV, [S_B]) and
  2837. MatchOpType(taicpu(hp1), top_const, top_ref) and
  2838. GetNextInstruction(hp1, hp2) and
  2839. MatchInstruction(hp2, A_MOV, [S_B]) and
  2840. MatchOpType(taicpu(hp2), top_const, top_ref) and
  2841. { Try to merge the two bytes }
  2842. TryConstMerge(hp1, hp2) then
  2843. { Now try to merge the two words (hp2 will get deleted) }
  2844. TryConstMerge(p, hp1);
  2845. end;
  2846. S_L:
  2847. begin
  2848. { Though this only really benefits x86_64 and not i386, it
  2849. gets a potential optimisation done faster and hence
  2850. reduces the number of times OptPass1MOV is entered }
  2851. if GetNextInstruction(p, hp1) and
  2852. MatchInstruction(hp1, A_MOV, [S_W]) and
  2853. MatchOpType(taicpu(hp1), top_const, top_ref) and
  2854. GetNextInstruction(hp1, hp2) and
  2855. MatchInstruction(hp2, A_MOV, [S_W]) and
  2856. MatchOpType(taicpu(hp2), top_const, top_ref) and
  2857. { Try to merge the two words }
  2858. TryConstMerge(hp1, hp2) then
  2859. { This will always fail on i386, so don't bother
  2860. calling it unless we're doing x86_64 }
  2861. {$ifdef x86_64}
  2862. { Now try to merge the two longwords (hp2 will get deleted) }
  2863. TryConstMerge(p, hp1)
  2864. {$endif x86_64}
  2865. ;
  2866. end;
  2867. else
  2868. ;
  2869. end;
  2870. Exit;
  2871. end;
  2872. if (taicpu(p).oper[1]^.typ = top_reg) and
  2873. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2874. begin
  2875. CurrentReg := taicpu(p).oper[1]^.reg;
  2876. TransferUsedRegs(TmpUsedRegs);
  2877. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2878. { we have
  2879. mov x, %treg
  2880. mov %treg, y
  2881. }
  2882. if not(RegInOp(CurrentReg, taicpu(hp1).oper[1]^)) then
  2883. if not(RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs)) then
  2884. { we've got
  2885. mov x, %treg
  2886. mov %treg, y
  2887. with %treg is not used after }
  2888. case taicpu(p).oper[0]^.typ Of
  2889. { top_reg is covered by DeepMOVOpt }
  2890. top_const:
  2891. begin
  2892. { change
  2893. mov const, %treg
  2894. mov %treg, y
  2895. to
  2896. mov const, y
  2897. }
  2898. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  2899. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  2900. begin
  2901. if taicpu(hp1).oper[1]^.typ=top_reg then
  2902. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2903. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  2904. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  2905. RemoveInstruction(hp1);
  2906. Result:=true;
  2907. Exit;
  2908. end;
  2909. end;
  2910. top_ref:
  2911. case taicpu(hp1).oper[1]^.typ of
  2912. top_reg:
  2913. begin
  2914. { change
  2915. mov mem, %treg
  2916. mov %treg, %reg
  2917. to
  2918. mov mem, %reg"
  2919. }
  2920. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2921. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  2922. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  2923. RemoveInstruction(hp1);
  2924. Result:=true;
  2925. Exit;
  2926. end;
  2927. top_ref:
  2928. begin
  2929. {$ifdef x86_64}
  2930. { Look for the following to simplify:
  2931. mov x(mem1), %reg
  2932. mov %reg, y(mem2)
  2933. mov x+8(mem1), %reg
  2934. mov %reg, y+8(mem2)
  2935. Change to:
  2936. movdqu x(mem1), %xmmreg
  2937. movdqu %xmmreg, y(mem2)
  2938. }
  2939. SourceRef := taicpu(p).oper[0]^.ref^;
  2940. TargetRef := taicpu(hp1).oper[1]^.ref^;
  2941. if (taicpu(p).opsize = S_Q) and
  2942. GetNextInstruction(hp1, hp2) and
  2943. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  2944. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  2945. begin
  2946. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  2947. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2948. Inc(SourceRef.offset, 8);
  2949. if UseAVX then
  2950. begin
  2951. MovAligned := A_VMOVDQA;
  2952. MovUnaligned := A_VMOVDQU;
  2953. end
  2954. else
  2955. begin
  2956. MovAligned := A_MOVDQA;
  2957. MovUnaligned := A_MOVDQU;
  2958. end;
  2959. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  2960. begin
  2961. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  2962. Inc(TargetRef.offset, 8);
  2963. if GetNextInstruction(hp2, hp3) and
  2964. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  2965. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  2966. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  2967. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  2968. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  2969. begin
  2970. CurrentReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  2971. if CurrentReg <> NR_NO then
  2972. begin
  2973. { Remember that the offsets are 8 ahead }
  2974. if ((SourceRef.offset mod 16) = 8) and
  2975. (
  2976. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2977. (SourceRef.base = current_procinfo.framepointer) or
  2978. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  2979. ) then
  2980. taicpu(p).opcode := MovAligned
  2981. else
  2982. taicpu(p).opcode := MovUnaligned;
  2983. taicpu(p).opsize := S_XMM;
  2984. taicpu(p).oper[1]^.reg := CurrentReg;
  2985. if ((TargetRef.offset mod 16) = 8) and
  2986. (
  2987. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2988. (TargetRef.base = current_procinfo.framepointer) or
  2989. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  2990. ) then
  2991. taicpu(hp1).opcode := MovAligned
  2992. else
  2993. taicpu(hp1).opcode := MovUnaligned;
  2994. taicpu(hp1).opsize := S_XMM;
  2995. taicpu(hp1).oper[0]^.reg := CurrentReg;
  2996. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  2997. RemoveInstruction(hp2);
  2998. RemoveInstruction(hp3);
  2999. Result := True;
  3000. Exit;
  3001. end;
  3002. end;
  3003. end
  3004. else
  3005. begin
  3006. { See if the next references are 8 less rather than 8 greater }
  3007. Dec(SourceRef.offset, 16); { -8 the other way }
  3008. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3009. begin
  3010. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3011. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3012. if GetNextInstruction(hp2, hp3) and
  3013. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3014. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3015. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3016. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3017. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3018. begin
  3019. CurrentReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3020. if CurrentReg <> NR_NO then
  3021. begin
  3022. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3023. if ((SourceRef.offset mod 16) = 0) and
  3024. (
  3025. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3026. (SourceRef.base = current_procinfo.framepointer) or
  3027. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3028. ) then
  3029. taicpu(hp2).opcode := MovAligned
  3030. else
  3031. taicpu(hp2).opcode := MovUnaligned;
  3032. taicpu(hp2).opsize := S_XMM;
  3033. taicpu(hp2).oper[1]^.reg := CurrentReg;
  3034. if ((TargetRef.offset mod 16) = 0) and
  3035. (
  3036. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3037. (TargetRef.base = current_procinfo.framepointer) or
  3038. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3039. ) then
  3040. taicpu(hp3).opcode := MovAligned
  3041. else
  3042. taicpu(hp3).opcode := MovUnaligned;
  3043. taicpu(hp3).opsize := S_XMM;
  3044. taicpu(hp3).oper[0]^.reg := CurrentReg;
  3045. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3046. RemoveInstruction(hp1);
  3047. RemoveCurrentP(p, hp2);
  3048. Result := True;
  3049. Exit;
  3050. end;
  3051. end;
  3052. end;
  3053. end;
  3054. end;
  3055. {$endif x86_64}
  3056. end;
  3057. else
  3058. { The write target should be a reg or a ref }
  3059. InternalError(2021091601);
  3060. end;
  3061. else
  3062. ;
  3063. end
  3064. else
  3065. { %treg is used afterwards, but all eventualities
  3066. other than the first MOV instruction being a constant
  3067. are covered by DeepMOVOpt, so only check for that }
  3068. if (taicpu(p).oper[0]^.typ = top_const) and
  3069. (
  3070. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3071. not (cs_opt_size in current_settings.optimizerswitches) or
  3072. (taicpu(hp1).opsize = S_B)
  3073. ) and
  3074. (
  3075. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3076. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3077. ) then
  3078. begin
  3079. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3080. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3081. end;
  3082. end;
  3083. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3084. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3085. { mov reg1, mem1 or mov mem1, reg1
  3086. mov mem2, reg2 mov reg2, mem2}
  3087. begin
  3088. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3089. { mov reg1, mem1 or mov mem1, reg1
  3090. mov mem2, reg1 mov reg2, mem1}
  3091. begin
  3092. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3093. { Removes the second statement from
  3094. mov reg1, mem1/reg2
  3095. mov mem1/reg2, reg1 }
  3096. begin
  3097. if taicpu(p).oper[0]^.typ=top_reg then
  3098. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3099. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3100. RemoveInstruction(hp1);
  3101. Result:=true;
  3102. exit;
  3103. end
  3104. else
  3105. begin
  3106. TransferUsedRegs(TmpUsedRegs);
  3107. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3108. if (taicpu(p).oper[1]^.typ = top_ref) and
  3109. { mov reg1, mem1
  3110. mov mem2, reg1 }
  3111. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3112. GetNextInstruction(hp1, hp2) and
  3113. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3114. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3115. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3116. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3117. { change to
  3118. mov reg1, mem1 mov reg1, mem1
  3119. mov mem2, reg1 cmp reg1, mem2
  3120. cmp mem1, reg1
  3121. }
  3122. begin
  3123. RemoveInstruction(hp2);
  3124. taicpu(hp1).opcode := A_CMP;
  3125. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3126. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3127. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3128. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3129. end;
  3130. end;
  3131. end
  3132. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3133. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3134. begin
  3135. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3136. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3137. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3138. end
  3139. else
  3140. begin
  3141. TransferUsedRegs(TmpUsedRegs);
  3142. if GetNextInstruction(hp1, hp2) and
  3143. MatchOpType(taicpu(p),top_ref,top_reg) and
  3144. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3145. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3146. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3147. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3148. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3149. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3150. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3151. { mov mem1, %reg1
  3152. mov %reg1, mem2
  3153. mov mem2, reg2
  3154. to:
  3155. mov mem1, reg2
  3156. mov reg2, mem2}
  3157. begin
  3158. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3159. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3160. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3161. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3162. RemoveInstruction(hp2);
  3163. Result := True;
  3164. end
  3165. {$ifdef i386}
  3166. { this is enabled for i386 only, as the rules to create the reg sets below
  3167. are too complicated for x86-64, so this makes this code too error prone
  3168. on x86-64
  3169. }
  3170. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3171. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3172. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3173. { mov mem1, reg1 mov mem1, reg1
  3174. mov reg1, mem2 mov reg1, mem2
  3175. mov mem2, reg2 mov mem2, reg1
  3176. to: to:
  3177. mov mem1, reg1 mov mem1, reg1
  3178. mov mem1, reg2 mov reg1, mem2
  3179. mov reg1, mem2
  3180. or (if mem1 depends on reg1
  3181. and/or if mem2 depends on reg2)
  3182. to:
  3183. mov mem1, reg1
  3184. mov reg1, mem2
  3185. mov reg1, reg2
  3186. }
  3187. begin
  3188. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3189. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3190. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3191. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3192. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3193. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3194. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3195. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3196. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3197. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3198. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3199. end
  3200. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3201. begin
  3202. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3203. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3204. end
  3205. else
  3206. begin
  3207. RemoveInstruction(hp2);
  3208. end
  3209. {$endif i386}
  3210. ;
  3211. end;
  3212. end
  3213. { movl [mem1],reg1
  3214. movl [mem1],reg2
  3215. to
  3216. movl [mem1],reg1
  3217. movl reg1,reg2
  3218. }
  3219. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3220. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3221. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3222. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3223. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3224. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3225. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3226. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3227. begin
  3228. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3229. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3230. end;
  3231. { movl const1,[mem1]
  3232. movl [mem1],reg1
  3233. to
  3234. movl const1,reg1
  3235. movl reg1,[mem1]
  3236. }
  3237. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3238. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3239. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3240. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3241. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3242. begin
  3243. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3244. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3245. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3246. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3247. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3248. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3249. Result:=true;
  3250. exit;
  3251. end;
  3252. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3253. { Change:
  3254. movl %reg1,%reg2
  3255. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3256. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3257. To:
  3258. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3259. movl x(%reg1),%reg1
  3260. movl %reg1,%regX
  3261. }
  3262. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3263. begin
  3264. CurrentReg := taicpu(p).oper[0]^.reg;
  3265. ActiveReg := taicpu(p).oper[1]^.reg;
  3266. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3267. (taicpu(hp1).oper[1]^.reg = CurrentReg) and
  3268. RegInRef(CurrentReg, taicpu(hp1).oper[0]^.ref^) and
  3269. GetNextInstruction(hp1, hp2) and
  3270. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3271. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3272. begin
  3273. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3274. if RegInRef(ActiveReg, SourceRef) and
  3275. { If %reg1 also appears in the second reference, then it will
  3276. not refer to the same memory block as the first reference }
  3277. not RegInRef(CurrentReg, SourceRef) then
  3278. begin
  3279. { Check to see if the references match if %reg2 is changed to %reg1 }
  3280. if SourceRef.base = ActiveReg then
  3281. SourceRef.base := CurrentReg;
  3282. if SourceRef.index = ActiveReg then
  3283. SourceRef.index := CurrentReg;
  3284. { RefsEqual also checks to ensure both references are non-volatile }
  3285. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3286. begin
  3287. taicpu(hp2).loadreg(0, CurrentReg);
  3288. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3289. Result := True;
  3290. if taicpu(hp2).oper[1]^.reg = ActiveReg then
  3291. begin
  3292. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3293. RemoveCurrentP(p, hp1);
  3294. Exit;
  3295. end
  3296. else
  3297. begin
  3298. { Check to see if %reg2 is no longer in use }
  3299. TransferUsedRegs(TmpUsedRegs);
  3300. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3301. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3302. if not RegUsedAfterInstruction(ActiveReg, hp2, TmpUsedRegs) then
  3303. begin
  3304. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3305. RemoveCurrentP(p, hp1);
  3306. Exit;
  3307. end;
  3308. end;
  3309. { If we reach this point, p and hp1 weren't actually modified,
  3310. so we can do a bit more work on this pass }
  3311. end;
  3312. end;
  3313. end;
  3314. end;
  3315. end;
  3316. { search further than the next instruction for a mov (as long as it's not a jump) }
  3317. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3318. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3319. (taicpu(p).oper[1]^.typ = top_reg) and
  3320. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3321. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3322. begin
  3323. { we work with hp2 here, so hp1 can be still used later on when
  3324. checking for GetNextInstruction_p }
  3325. hp3 := hp1;
  3326. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3327. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3328. { Saves on a large number of dereferences }
  3329. ActiveReg := taicpu(p).oper[1]^.reg;
  3330. TransferUsedRegs(TmpUsedRegs);
  3331. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3332. while GetNextInstructionUsingRegCond(hp3,hp2,ActiveReg,CrossJump) and
  3333. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3334. (hp2.typ=ait_instruction) do
  3335. begin
  3336. case taicpu(hp2).opcode of
  3337. A_POP:
  3338. if MatchOperand(taicpu(hp2).oper[0]^,ActiveReg) then
  3339. begin
  3340. if not CrossJump and
  3341. not RegUsedBetween(ActiveReg, p, hp2) then
  3342. begin
  3343. { We can remove the original MOV since the register
  3344. wasn't used between it and its popping from the stack }
  3345. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3346. RemoveCurrentp(p, hp1);
  3347. Result := True;
  3348. Exit;
  3349. end;
  3350. { Can't go any further }
  3351. Break;
  3352. end;
  3353. A_MOV:
  3354. if MatchOperand(taicpu(hp2).oper[0]^,ActiveReg) and
  3355. ((taicpu(p).oper[0]^.typ=top_const) or
  3356. ((taicpu(p).oper[0]^.typ=top_reg) and
  3357. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3358. )
  3359. ) then
  3360. begin
  3361. { we have
  3362. mov x, %treg
  3363. mov %treg, y
  3364. }
  3365. { We don't need to call UpdateUsedRegs for every instruction between
  3366. p and hp2 because the register we're concerned about will not
  3367. become deallocated (otherwise GetNextInstructionUsingReg would
  3368. have stopped at an earlier instruction). [Kit] }
  3369. TempRegUsed :=
  3370. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3371. RegReadByInstruction(ActiveReg, hp3) or
  3372. RegUsedAfterInstruction(ActiveReg, hp2, TmpUsedRegs);
  3373. case taicpu(p).oper[0]^.typ Of
  3374. top_reg:
  3375. begin
  3376. { change
  3377. mov %reg, %treg
  3378. mov %treg, y
  3379. to
  3380. mov %reg, y
  3381. }
  3382. CurrentReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3383. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3384. if MatchOperand(taicpu(hp2).oper[1]^, CurrentReg) then
  3385. begin
  3386. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3387. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3388. if TempRegUsed then
  3389. begin
  3390. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3391. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  3392. { Set the start of the next GetNextInstructionUsingRegCond search
  3393. to start at the entry right before hp2 (which is about to be removed) }
  3394. hp3 := tai(hp2.Previous);
  3395. RemoveInstruction(hp2);
  3396. { See if there's more we can optimise }
  3397. Continue;
  3398. end
  3399. else
  3400. begin
  3401. RemoveInstruction(hp2);
  3402. { We can remove the original MOV too }
  3403. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3404. RemoveCurrentP(p, hp1);
  3405. Result:=true;
  3406. Exit;
  3407. end;
  3408. end
  3409. else
  3410. begin
  3411. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  3412. taicpu(hp2).loadReg(0, CurrentReg);
  3413. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(CurrentReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3414. { Check to see if the register also appears in the reference }
  3415. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3416. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, ActiveReg, CurrentReg);
  3417. { Don't remove the first instruction if the temporary register is in use }
  3418. if not TempRegUsed and
  3419. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3420. not RegInOp(ActiveReg, taicpu(hp2).oper[1]^) then
  3421. begin
  3422. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3423. RemoveCurrentP(p, hp1);
  3424. Result:=true;
  3425. Exit;
  3426. end;
  3427. { No need to set Result to True here. If there's another instruction later
  3428. on that can be optimised, it will be detected when the main Pass 1 loop
  3429. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3430. end;
  3431. end;
  3432. top_const:
  3433. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3434. begin
  3435. { change
  3436. mov const, %treg
  3437. mov %treg, y
  3438. to
  3439. mov const, y
  3440. }
  3441. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3442. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3443. begin
  3444. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3445. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3446. if TempRegUsed then
  3447. begin
  3448. { Don't remove the first instruction if the temporary register is in use }
  3449. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3450. { No need to set Result to True. If there's another instruction later on
  3451. that can be optimised, it will be detected when the main Pass 1 loop
  3452. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3453. end
  3454. else
  3455. begin
  3456. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3457. RemoveCurrentP(p, hp1);
  3458. Result:=true;
  3459. Exit;
  3460. end;
  3461. end;
  3462. end;
  3463. else
  3464. Internalerror(2019103001);
  3465. end;
  3466. end
  3467. else
  3468. if MatchOperand(taicpu(hp2).oper[1]^, ActiveReg) then
  3469. begin
  3470. if not CrossJump and
  3471. not RegUsedBetween(ActiveReg, p, hp2) and
  3472. not RegReadByInstruction(ActiveReg, hp2) then
  3473. begin
  3474. { Register is not used before it is overwritten }
  3475. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3476. RemoveCurrentp(p, hp1);
  3477. Result := True;
  3478. Exit;
  3479. end;
  3480. if (taicpu(p).oper[0]^.typ = top_const) and
  3481. (taicpu(hp2).oper[0]^.typ = top_const) then
  3482. begin
  3483. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3484. begin
  3485. { Same value - register hasn't changed }
  3486. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3487. RemoveInstruction(hp2);
  3488. Result := True;
  3489. { See if there's more we can optimise }
  3490. Continue;
  3491. end;
  3492. end;
  3493. end;
  3494. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  3495. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  3496. MatchOperand(taicpu(hp2).oper[0]^, ActiveReg) and
  3497. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, ActiveReg) then
  3498. begin
  3499. {
  3500. Change from:
  3501. mov ###, %reg
  3502. ...
  3503. movs/z %reg,%reg (Same register, just different sizes)
  3504. To:
  3505. movs/z ###, %reg (Longer version)
  3506. ...
  3507. (remove)
  3508. }
  3509. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  3510. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  3511. { Keep the first instruction as mov if ### is a constant }
  3512. if taicpu(p).oper[0]^.typ = top_const then
  3513. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  3514. else
  3515. begin
  3516. taicpu(p).opcode := taicpu(hp2).opcode;
  3517. taicpu(p).opsize := taicpu(hp2).opsize;
  3518. end;
  3519. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  3520. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  3521. RemoveInstruction(hp2);
  3522. Result := True;
  3523. Exit;
  3524. end;
  3525. else
  3526. { Move down to the MatchOpType if-block below };
  3527. end;
  3528. { Also catches MOV/S/Z instructions that aren't modified }
  3529. if taicpu(p).oper[0]^.typ = top_reg then
  3530. begin
  3531. CurrentReg := taicpu(p).oper[0]^.reg;
  3532. if
  3533. not RegModifiedByInstruction(CurrentReg, hp3) and
  3534. not RegModifiedBetween(CurrentReg, hp3, hp2) and
  3535. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  3536. begin
  3537. Result := True;
  3538. { Just in case something didn't get modified (e.g. an
  3539. implicit register). Also, if it does read from this
  3540. register, then there's no longer an advantage to
  3541. changing the register on subsequent instructions.}
  3542. if not RegReadByInstruction(ActiveReg, hp2) then
  3543. begin
  3544. { If a conditional jump was crossed, do not delete
  3545. the original MOV no matter what }
  3546. if not CrossJump and
  3547. { RegEndOfLife returns True if the register is
  3548. deallocated before the next instruction or has
  3549. been loaded with a new value }
  3550. RegEndOfLife(ActiveReg, taicpu(hp2)) then
  3551. begin
  3552. { We can remove the original MOV }
  3553. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  3554. RemoveCurrentp(p, hp1);
  3555. Exit;
  3556. end;
  3557. if not RegModifiedByInstruction(ActiveReg, hp2) then
  3558. begin
  3559. { See if there's more we can optimise }
  3560. hp3 := hp2;
  3561. Continue;
  3562. end;
  3563. end;
  3564. end;
  3565. end;
  3566. { Break out of the while loop under normal circumstances }
  3567. Break;
  3568. end;
  3569. end;
  3570. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  3571. (taicpu(p).oper[1]^.typ = top_reg) and
  3572. (taicpu(p).opsize = S_L) and
  3573. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  3574. (taicpu(hp2).opcode = A_AND) and
  3575. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  3576. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3577. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  3578. ) then
  3579. begin
  3580. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  3581. begin
  3582. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  3583. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  3584. begin
  3585. { Optimize out:
  3586. mov x, %reg
  3587. and ffffffffh, %reg
  3588. }
  3589. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  3590. RemoveInstruction(hp2);
  3591. Result:=true;
  3592. exit;
  3593. end;
  3594. end;
  3595. end;
  3596. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  3597. x >= RetOffset) as it doesn't do anything (it writes either to a
  3598. parameter or to the temporary storage room for the function
  3599. result)
  3600. }
  3601. if IsExitCode(hp1) and
  3602. (taicpu(p).oper[1]^.typ = top_ref) and
  3603. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  3604. (
  3605. (
  3606. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  3607. not (
  3608. assigned(current_procinfo.procdef.funcretsym) and
  3609. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  3610. )
  3611. ) or
  3612. { Also discard writes to the stack that are below the base pointer,
  3613. as this is temporary storage rather than a function result on the
  3614. stack, say. }
  3615. (
  3616. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  3617. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  3618. )
  3619. ) then
  3620. begin
  3621. RemoveCurrentp(p, hp1);
  3622. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  3623. RemoveLastDeallocForFuncRes(p);
  3624. Result:=true;
  3625. exit;
  3626. end;
  3627. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  3628. begin
  3629. if MatchOpType(taicpu(p),top_reg,top_ref) and
  3630. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3631. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3632. begin
  3633. { change
  3634. mov reg1, mem1
  3635. test/cmp x, mem1
  3636. to
  3637. mov reg1, mem1
  3638. test/cmp x, reg1
  3639. }
  3640. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  3641. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  3642. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3643. Result := True;
  3644. Exit;
  3645. end;
  3646. if DoMovCmpMemOpt(p, hp1, True) then
  3647. begin
  3648. Result := True;
  3649. Exit;
  3650. end;
  3651. end;
  3652. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  3653. { If the flags register is in use, don't change the instruction to an
  3654. ADD otherwise this will scramble the flags. [Kit] }
  3655. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  3656. begin
  3657. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  3658. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3659. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3660. ) or
  3661. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3662. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3663. )
  3664. ) then
  3665. { mov reg1,ref
  3666. lea reg2,[reg1,reg2]
  3667. to
  3668. add reg2,ref}
  3669. begin
  3670. TransferUsedRegs(TmpUsedRegs);
  3671. { reg1 may not be used afterwards }
  3672. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3673. begin
  3674. Taicpu(hp1).opcode:=A_ADD;
  3675. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3676. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3677. RemoveCurrentp(p, hp1);
  3678. result:=true;
  3679. exit;
  3680. end;
  3681. end;
  3682. { If the LEA instruction can be converted into an arithmetic instruction,
  3683. it may be possible to then fold it in the next optimisation, otherwise
  3684. there's nothing more that can be optimised here. }
  3685. if not ConvertLEA(taicpu(hp1)) then
  3686. Exit;
  3687. end;
  3688. if (taicpu(p).oper[1]^.typ = top_reg) and
  3689. (hp1.typ = ait_instruction) and
  3690. GetNextInstruction(hp1, hp2) and
  3691. MatchInstruction(hp2,A_MOV,[]) and
  3692. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  3693. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  3694. (
  3695. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  3696. {$ifdef x86_64}
  3697. or
  3698. (
  3699. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  3700. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  3701. )
  3702. {$endif x86_64}
  3703. ) then
  3704. begin
  3705. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  3706. (taicpu(hp2).oper[0]^.typ=top_reg) then
  3707. { change movsX/movzX reg/ref, reg2
  3708. add/sub/or/... reg3/$const, reg2
  3709. mov reg2 reg/ref
  3710. dealloc reg2
  3711. to
  3712. add/sub/or/... reg3/$const, reg/ref }
  3713. begin
  3714. TransferUsedRegs(TmpUsedRegs);
  3715. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3716. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3717. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3718. begin
  3719. { by example:
  3720. movswl %si,%eax movswl %si,%eax p
  3721. decl %eax addl %edx,%eax hp1
  3722. movw %ax,%si movw %ax,%si hp2
  3723. ->
  3724. movswl %si,%eax movswl %si,%eax p
  3725. decw %eax addw %edx,%eax hp1
  3726. movw %ax,%si movw %ax,%si hp2
  3727. }
  3728. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  3729. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3730. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3731. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3732. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3733. {
  3734. ->
  3735. movswl %si,%eax movswl %si,%eax p
  3736. decw %si addw %dx,%si hp1
  3737. movw %ax,%si movw %ax,%si hp2
  3738. }
  3739. case taicpu(hp1).ops of
  3740. 1:
  3741. begin
  3742. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3743. if taicpu(hp1).oper[0]^.typ=top_reg then
  3744. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3745. end;
  3746. 2:
  3747. begin
  3748. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3749. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3750. (taicpu(hp1).opcode<>A_SHL) and
  3751. (taicpu(hp1).opcode<>A_SHR) and
  3752. (taicpu(hp1).opcode<>A_SAR) then
  3753. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3754. end;
  3755. else
  3756. internalerror(2008042701);
  3757. end;
  3758. {
  3759. ->
  3760. decw %si addw %dx,%si p
  3761. }
  3762. RemoveInstruction(hp2);
  3763. RemoveCurrentP(p, hp1);
  3764. Result:=True;
  3765. Exit;
  3766. end;
  3767. end;
  3768. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3769. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  3770. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  3771. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  3772. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  3773. )
  3774. {$ifdef i386}
  3775. { byte registers of esi, edi, ebp, esp are not available on i386 }
  3776. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3777. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3778. {$endif i386}
  3779. then
  3780. { change movsX/movzX reg/ref, reg2
  3781. add/sub/or/... regX/$const, reg2
  3782. mov reg2, reg3
  3783. dealloc reg2
  3784. to
  3785. movsX/movzX reg/ref, reg3
  3786. add/sub/or/... reg3/$const, reg3
  3787. }
  3788. begin
  3789. TransferUsedRegs(TmpUsedRegs);
  3790. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3791. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3792. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3793. begin
  3794. { by example:
  3795. movswl %si,%eax movswl %si,%eax p
  3796. decl %eax addl %edx,%eax hp1
  3797. movw %ax,%si movw %ax,%si hp2
  3798. ->
  3799. movswl %si,%eax movswl %si,%eax p
  3800. decw %eax addw %edx,%eax hp1
  3801. movw %ax,%si movw %ax,%si hp2
  3802. }
  3803. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  3804. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3805. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3806. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3807. { limit size of constants as well to avoid assembler errors, but
  3808. check opsize to avoid overflow when left shifting the 1 }
  3809. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  3810. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  3811. {$ifdef x86_64}
  3812. { Be careful of, for example:
  3813. movl %reg1,%reg2
  3814. addl %reg3,%reg2
  3815. movq %reg2,%reg4
  3816. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  3817. }
  3818. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  3819. begin
  3820. taicpu(hp2).changeopsize(S_L);
  3821. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  3822. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  3823. end;
  3824. {$endif x86_64}
  3825. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3826. taicpu(p).changeopsize(taicpu(hp2).opsize);
  3827. if taicpu(p).oper[0]^.typ=top_reg then
  3828. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3829. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  3830. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  3831. {
  3832. ->
  3833. movswl %si,%eax movswl %si,%eax p
  3834. decw %si addw %dx,%si hp1
  3835. movw %ax,%si movw %ax,%si hp2
  3836. }
  3837. case taicpu(hp1).ops of
  3838. 1:
  3839. begin
  3840. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3841. if taicpu(hp1).oper[0]^.typ=top_reg then
  3842. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3843. end;
  3844. 2:
  3845. begin
  3846. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3847. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3848. (taicpu(hp1).opcode<>A_SHL) and
  3849. (taicpu(hp1).opcode<>A_SHR) and
  3850. (taicpu(hp1).opcode<>A_SAR) then
  3851. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3852. end;
  3853. else
  3854. internalerror(2018111801);
  3855. end;
  3856. {
  3857. ->
  3858. decw %si addw %dx,%si p
  3859. }
  3860. RemoveInstruction(hp2);
  3861. end;
  3862. end;
  3863. end;
  3864. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  3865. GetNextInstruction(hp1, hp2) and
  3866. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  3867. MatchOperand(Taicpu(p).oper[0]^,0) and
  3868. (Taicpu(p).oper[1]^.typ = top_reg) and
  3869. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  3870. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  3871. { mov reg1,0
  3872. bts reg1,operand1 --> mov reg1,operand2
  3873. or reg1,operand2 bts reg1,operand1}
  3874. begin
  3875. Taicpu(hp2).opcode:=A_MOV;
  3876. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  3877. asml.remove(hp1);
  3878. insertllitem(hp2,hp2.next,hp1);
  3879. RemoveCurrentp(p, hp1);
  3880. Result:=true;
  3881. exit;
  3882. end;
  3883. {
  3884. mov ref,reg0
  3885. <op> reg0,reg1
  3886. dealloc reg0
  3887. to
  3888. <op> ref,reg1
  3889. }
  3890. if MatchOpType(taicpu(p),top_ref,top_reg) and
  3891. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  3892. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3893. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  3894. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  3895. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  3896. begin
  3897. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  3898. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  3899. RemoveCurrentp(p, hp1);
  3900. Result:=true;
  3901. exit;
  3902. end;
  3903. {$ifdef x86_64}
  3904. { Convert:
  3905. movq x(ref),%reg64
  3906. shrq y,%reg64
  3907. To:
  3908. movl x+4(ref),%reg32
  3909. shrl y-32,%reg32 (Remove if y = 32)
  3910. }
  3911. if (taicpu(p).opsize = S_Q) and
  3912. (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  3913. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFB) and
  3914. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  3915. MatchOpType(taicpu(hp1), top_const, top_reg) and
  3916. (taicpu(hp1).oper[0]^.val >= 32) and
  3917. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  3918. begin
  3919. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  3920. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  3921. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  3922. { Convert to 32-bit }
  3923. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3924. taicpu(p).opsize := S_L;
  3925. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  3926. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  3927. if (taicpu(hp1).oper[0]^.val = 32) then
  3928. begin
  3929. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  3930. RemoveInstruction(hp1);
  3931. end
  3932. else
  3933. begin
  3934. { This will potentially open up more arithmetic operations since
  3935. the peephole optimizer now has a big hint that only the lower
  3936. 32 bits are currently in use (and opcodes are smaller in size) }
  3937. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3938. taicpu(hp1).opsize := S_L;
  3939. Dec(taicpu(hp1).oper[0]^.val, 32);
  3940. DebugMsg(SPeepholeOptimization + PreMessage +
  3941. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  3942. end;
  3943. Result := True;
  3944. Exit;
  3945. end;
  3946. {$endif x86_64}
  3947. { Backward optimisation. If we have:
  3948. func. %reg1,%reg2
  3949. mov %reg2,%reg3
  3950. (dealloc %reg2)
  3951. Change to:
  3952. func. %reg1,%reg3 (see comment below for what a valid func. is)
  3953. }
  3954. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3955. begin
  3956. CurrentReg := taicpu(p).oper[0]^.reg;
  3957. ActiveReg := taicpu(p).oper[1]^.reg;
  3958. TransferUsedRegs(TmpUsedRegs);
  3959. if not RegUsedAfterInstruction(CurrentReg, p, TmpUsedRegs) and
  3960. GetLastInstruction(p, hp2) and
  3961. (hp2.typ = ait_instruction) and
  3962. { Have to make sure it's an instruction that only reads from
  3963. operand 1 and only writes (not reads or modifies) from operand 2;
  3964. in essence, a one-operand pure function such as BSR or POPCNT }
  3965. (taicpu(hp2).ops = 2) and
  3966. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2]) and
  3967. (taicpu(hp2).oper[1]^.typ = top_reg) and
  3968. (taicpu(hp2).oper[1]^.reg = CurrentReg) then
  3969. begin
  3970. case taicpu(hp2).opcode of
  3971. A_FSTSW, A_FNSTSW,
  3972. A_IN, A_INS, A_OUT, A_OUTS,
  3973. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS,
  3974. { These routines have explicit operands, but they are restricted in
  3975. what they can be (e.g. IN and OUT can only read from AL, AX or
  3976. EAX. }
  3977. A_CMOVcc:
  3978. { CMOV is not valid either because then CurrentReg will depend
  3979. on an unknown value if the condition is False and hence is
  3980. not a pure write }
  3981. ;
  3982. else
  3983. begin
  3984. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  3985. taicpu(hp2).oper[1]^.reg := ActiveReg;
  3986. AllocRegBetween(ActiveReg, hp2, p, TmpUsedRegs);
  3987. RemoveCurrentp(p, hp1);
  3988. Result := True;
  3989. Exit;
  3990. end;
  3991. end;
  3992. end;
  3993. end;
  3994. end;
  3995. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  3996. var
  3997. hp1 : tai;
  3998. begin
  3999. Result:=false;
  4000. if taicpu(p).ops <> 2 then
  4001. exit;
  4002. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4003. GetNextInstruction(p,hp1) then
  4004. begin
  4005. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4006. (taicpu(hp1).ops = 2) then
  4007. begin
  4008. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4009. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4010. { movXX reg1, mem1 or movXX mem1, reg1
  4011. movXX mem2, reg2 movXX reg2, mem2}
  4012. begin
  4013. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4014. { movXX reg1, mem1 or movXX mem1, reg1
  4015. movXX mem2, reg1 movXX reg2, mem1}
  4016. begin
  4017. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4018. begin
  4019. { Removes the second statement from
  4020. movXX reg1, mem1/reg2
  4021. movXX mem1/reg2, reg1
  4022. }
  4023. if taicpu(p).oper[0]^.typ=top_reg then
  4024. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4025. { Removes the second statement from
  4026. movXX mem1/reg1, reg2
  4027. movXX reg2, mem1/reg1
  4028. }
  4029. if (taicpu(p).oper[1]^.typ=top_reg) and
  4030. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4031. begin
  4032. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4033. RemoveInstruction(hp1);
  4034. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4035. Result:=true;
  4036. exit;
  4037. end
  4038. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4039. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4040. begin
  4041. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4042. RemoveInstruction(hp1);
  4043. Result:=true;
  4044. exit;
  4045. end;
  4046. end
  4047. end;
  4048. end;
  4049. end;
  4050. end;
  4051. end;
  4052. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4053. var
  4054. hp1 : tai;
  4055. begin
  4056. result:=false;
  4057. { replace
  4058. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4059. MovX %mreg2,%mreg1
  4060. dealloc %mreg2
  4061. by
  4062. <Op>X %mreg2,%mreg1
  4063. ?
  4064. }
  4065. if GetNextInstruction(p,hp1) and
  4066. { we mix single and double opperations here because we assume that the compiler
  4067. generates vmovapd only after double operations and vmovaps only after single operations }
  4068. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4069. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4070. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4071. (taicpu(p).oper[0]^.typ=top_reg) then
  4072. begin
  4073. TransferUsedRegs(TmpUsedRegs);
  4074. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4075. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4076. begin
  4077. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4078. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4079. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4080. RemoveInstruction(hp1);
  4081. result:=true;
  4082. end;
  4083. end;
  4084. end;
  4085. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4086. var
  4087. hp1, p_label, p_dist, hp1_dist: tai;
  4088. JumpLabel, JumpLabel_dist: TAsmLabel;
  4089. FirstValue, SecondValue: TCGInt;
  4090. begin
  4091. Result := False;
  4092. if (taicpu(p).oper[0]^.typ = top_const) and
  4093. (taicpu(p).oper[0]^.val <> -1) then
  4094. begin
  4095. { Convert unsigned maximum constants to -1 to aid optimisation }
  4096. case taicpu(p).opsize of
  4097. S_B:
  4098. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4099. begin
  4100. taicpu(p).oper[0]^.val := -1;
  4101. Result := True;
  4102. Exit;
  4103. end;
  4104. S_W:
  4105. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4106. begin
  4107. taicpu(p).oper[0]^.val := -1;
  4108. Result := True;
  4109. Exit;
  4110. end;
  4111. S_L:
  4112. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4113. begin
  4114. taicpu(p).oper[0]^.val := -1;
  4115. Result := True;
  4116. Exit;
  4117. end;
  4118. {$ifdef x86_64}
  4119. S_Q:
  4120. { Storing anything greater than $7FFFFFFF is not possible so do
  4121. nothing };
  4122. {$endif x86_64}
  4123. else
  4124. InternalError(2021121001);
  4125. end;
  4126. end;
  4127. if GetNextInstruction(p, hp1) and
  4128. TrySwapMovCmp(p, hp1) then
  4129. begin
  4130. Result := True;
  4131. Exit;
  4132. end;
  4133. { Search for:
  4134. test $x,(reg/ref)
  4135. jne @lbl1
  4136. test $y,(reg/ref) (same register or reference)
  4137. jne @lbl1
  4138. Change to:
  4139. test $(x or y),(reg/ref)
  4140. jne @lbl1
  4141. (Note, this doesn't work with je instead of jne)
  4142. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4143. Also search for:
  4144. test $x,(reg/ref)
  4145. je @lbl1
  4146. test $y,(reg/ref)
  4147. je/jne @lbl2
  4148. If (x or y) = x, then the second jump is deterministic
  4149. }
  4150. if (
  4151. (
  4152. (taicpu(p).oper[0]^.typ = top_const) or
  4153. (
  4154. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4155. (taicpu(p).oper[0]^.typ = top_reg) and
  4156. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4157. )
  4158. ) and
  4159. MatchInstruction(hp1, A_JCC, [])
  4160. ) then
  4161. begin
  4162. if (taicpu(p).oper[0]^.typ = top_reg) and
  4163. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4164. FirstValue := -1
  4165. else
  4166. FirstValue := taicpu(p).oper[0]^.val;
  4167. { If we have several test/jne's in a row, it might be the case that
  4168. the second label doesn't go to the same location, but the one
  4169. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4170. so accommodate for this with a while loop.
  4171. }
  4172. hp1_dist := hp1;
  4173. if GetNextInstruction(hp1, p_dist) and
  4174. (p_dist.typ = ait_instruction) and
  4175. (
  4176. (
  4177. (taicpu(p_dist).opcode = A_TEST) and
  4178. (
  4179. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4180. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4181. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4182. )
  4183. ) or
  4184. (
  4185. { cmp 0,%reg = test %reg,%reg }
  4186. (taicpu(p_dist).opcode = A_CMP) and
  4187. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4188. )
  4189. ) and
  4190. { Make sure the destination operands are actually the same }
  4191. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4192. GetNextInstruction(p_dist, hp1_dist) and
  4193. MatchInstruction(hp1_dist, A_JCC, []) then
  4194. begin
  4195. if
  4196. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4197. (
  4198. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4199. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4200. ) then
  4201. SecondValue := -1
  4202. else
  4203. SecondValue := taicpu(p_dist).oper[0]^.val;
  4204. { If both of the TEST constants are identical, delete the second
  4205. TEST that is unnecessary. }
  4206. if (FirstValue = SecondValue) then
  4207. begin
  4208. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4209. RemoveInstruction(p_dist);
  4210. { Don't let the flags register become deallocated and reallocated between the jumps }
  4211. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4212. Result := True;
  4213. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4214. begin
  4215. { Since the second jump's condition is a subset of the first, we
  4216. know it will never branch because the first jump dominates it.
  4217. Get it out of the way now rather than wait for the jump
  4218. optimisations for a speed boost. }
  4219. if IsJumpToLabel(taicpu(hp1_dist)) then
  4220. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4221. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4222. RemoveInstruction(hp1_dist);
  4223. end
  4224. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4225. begin
  4226. { If the inverse of the first condition is a subset of the second,
  4227. the second one will definitely branch if the first one doesn't }
  4228. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4229. MakeUnconditional(taicpu(hp1_dist));
  4230. RemoveDeadCodeAfterJump(hp1_dist);
  4231. end;
  4232. Exit;
  4233. end;
  4234. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4235. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4236. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4237. then the second jump will never branch, so it can also be
  4238. removed regardless of where it goes }
  4239. (
  4240. (FirstValue = -1) or
  4241. (SecondValue = -1) or
  4242. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4243. ) then
  4244. begin
  4245. { Same jump location... can be a register since nothing's changed }
  4246. { If any of the entries are equivalent to test %reg,%reg, then the
  4247. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  4248. taicpu(p).loadconst(0, FirstValue or SecondValue);
  4249. if IsJumpToLabel(taicpu(hp1_dist)) then
  4250. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4251. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  4252. RemoveInstruction(hp1_dist);
  4253. { Only remove the second test if no jumps or other conditional instructions follow }
  4254. TransferUsedRegs(TmpUsedRegs);
  4255. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4256. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4257. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  4258. RemoveInstruction(p_dist);
  4259. Result := True;
  4260. Exit;
  4261. end;
  4262. end;
  4263. end;
  4264. { Search for:
  4265. test %reg,%reg
  4266. j(c1) @lbl1
  4267. ...
  4268. @lbl:
  4269. test %reg,%reg (same register)
  4270. j(c2) @lbl2
  4271. If c2 is a subset of c1, change to:
  4272. test %reg,%reg
  4273. j(c1) @lbl2
  4274. (@lbl1 may become a dead label as a result)
  4275. }
  4276. if (taicpu(p).oper[1]^.typ = top_reg) and
  4277. (taicpu(p).oper[0]^.typ = top_reg) and
  4278. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  4279. MatchInstruction(hp1, A_JCC, []) and
  4280. IsJumpToLabel(taicpu(hp1)) then
  4281. begin
  4282. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4283. p_label := nil;
  4284. if Assigned(JumpLabel) then
  4285. p_label := getlabelwithsym(JumpLabel);
  4286. if Assigned(p_label) and
  4287. GetNextInstruction(p_label, p_dist) and
  4288. MatchInstruction(p_dist, A_TEST, []) and
  4289. { It's fine if the second test uses smaller sub-registers }
  4290. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  4291. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  4292. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  4293. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  4294. GetNextInstruction(p_dist, hp1_dist) and
  4295. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4296. begin
  4297. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4298. if JumpLabel = JumpLabel_dist then
  4299. { This is an infinite loop }
  4300. Exit;
  4301. { Best optimisation when the first condition is a subset (or equal) of the second }
  4302. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  4303. begin
  4304. { Any registers used here will already be allocated }
  4305. if Assigned(JumpLabel_dist) then
  4306. JumpLabel_dist.IncRefs;
  4307. if Assigned(JumpLabel) then
  4308. JumpLabel.DecRefs;
  4309. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  4310. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  4311. Result := True;
  4312. Exit;
  4313. end;
  4314. end;
  4315. end;
  4316. end;
  4317. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  4318. var
  4319. hp1, hp2: tai;
  4320. ActiveReg: TRegister;
  4321. OldOffset: asizeint;
  4322. ThisConst: TCGInt;
  4323. function RegDeallocated: Boolean;
  4324. begin
  4325. TransferUsedRegs(TmpUsedRegs);
  4326. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4327. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4328. end;
  4329. begin
  4330. result:=false;
  4331. hp1 := nil;
  4332. { replace
  4333. addX const,%reg1
  4334. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4335. dealloc %reg1
  4336. by
  4337. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  4338. }
  4339. if MatchOpType(taicpu(p),top_const,top_reg) then
  4340. begin
  4341. ActiveReg := taicpu(p).oper[1]^.reg;
  4342. { Ensures the entire register was updated }
  4343. if (taicpu(p).opsize >= S_L) and
  4344. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  4345. MatchInstruction(hp1,A_LEA,[]) and
  4346. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  4347. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  4348. (
  4349. { Cover the case where the register in the reference is also the destination register }
  4350. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  4351. (
  4352. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  4353. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  4354. RegDeallocated
  4355. )
  4356. ) then
  4357. begin
  4358. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  4359. {$push}
  4360. {$R-}{$Q-}
  4361. { Explicitly disable overflow checking for these offset calculation
  4362. as those do not matter for the final result }
  4363. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  4364. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  4365. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  4366. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4367. {$pop}
  4368. {$ifdef x86_64}
  4369. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  4370. begin
  4371. { Overflow; abort }
  4372. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  4373. end
  4374. else
  4375. {$endif x86_64}
  4376. begin
  4377. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  4378. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  4379. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  4380. RemoveCurrentP(p, hp1)
  4381. else
  4382. RemoveCurrentP(p);
  4383. result:=true;
  4384. Exit;
  4385. end;
  4386. end;
  4387. if (
  4388. { Save calling GetNextInstructionUsingReg again }
  4389. Assigned(hp1) or
  4390. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  4391. ) and
  4392. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  4393. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  4394. begin
  4395. if taicpu(hp1).oper[0]^.typ = top_const then
  4396. begin
  4397. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  4398. if taicpu(hp1).opcode = A_ADD then
  4399. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  4400. else
  4401. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  4402. Result := True;
  4403. { Handle any overflows }
  4404. case taicpu(p).opsize of
  4405. S_B:
  4406. taicpu(p).oper[0]^.val := ThisConst and $FF;
  4407. S_W:
  4408. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  4409. S_L:
  4410. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  4411. {$ifdef x86_64}
  4412. S_Q:
  4413. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  4414. { Overflow; abort }
  4415. Result := False
  4416. else
  4417. taicpu(p).oper[0]^.val := ThisConst;
  4418. {$endif x86_64}
  4419. else
  4420. InternalError(2021102610);
  4421. end;
  4422. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  4423. if Result then
  4424. begin
  4425. if (taicpu(p).oper[0]^.val < 0) and
  4426. (
  4427. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  4428. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  4429. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  4430. ) then
  4431. begin
  4432. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  4433. taicpu(p).opcode := A_SUB;
  4434. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  4435. end
  4436. else
  4437. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  4438. RemoveInstruction(hp1);
  4439. end;
  4440. end
  4441. else
  4442. begin
  4443. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  4444. TransferUsedRegs(TmpUsedRegs);
  4445. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4446. hp2 := p;
  4447. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  4448. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  4449. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  4450. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  4451. begin
  4452. { Move the constant addition to after the reg/ref addition to improve optimisation }
  4453. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  4454. Asml.Remove(p);
  4455. Asml.InsertAfter(p, hp1);
  4456. p := hp1;
  4457. Result := True;
  4458. end;
  4459. end;
  4460. end;
  4461. end;
  4462. end;
  4463. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  4464. var
  4465. hp1: tai;
  4466. ref: Integer;
  4467. saveref: treference;
  4468. TempReg: TRegister;
  4469. Multiple: TCGInt;
  4470. begin
  4471. Result:=false;
  4472. { removes seg register prefixes from LEA operations, as they
  4473. don't do anything}
  4474. taicpu(p).oper[0]^.ref^.Segment:=NR_NO;
  4475. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  4476. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4477. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  4478. (
  4479. { do not mess with leas accessing the stack pointer
  4480. unless it's a null operation }
  4481. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  4482. (
  4483. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  4484. (taicpu(p).oper[0]^.ref^.offset = 0)
  4485. )
  4486. ) and
  4487. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  4488. begin
  4489. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  4490. begin
  4491. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  4492. begin
  4493. hp1:=taicpu.op_reg_reg(A_MOV,taicpu(p).opsize,taicpu(p).oper[0]^.ref^.base,
  4494. taicpu(p).oper[1]^.reg);
  4495. InsertLLItem(p.previous,p.next, hp1);
  4496. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',hp1);
  4497. p.free;
  4498. p:=hp1;
  4499. end
  4500. else
  4501. begin
  4502. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  4503. RemoveCurrentP(p);
  4504. end;
  4505. Result:=true;
  4506. exit;
  4507. end
  4508. else if (
  4509. { continue to use lea to adjust the stack pointer,
  4510. it is the recommended way, but only if not optimizing for size }
  4511. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  4512. (cs_opt_size in current_settings.optimizerswitches)
  4513. ) and
  4514. { If the flags register is in use, don't change the instruction
  4515. to an ADD otherwise this will scramble the flags. [Kit] }
  4516. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  4517. ConvertLEA(taicpu(p)) then
  4518. begin
  4519. Result:=true;
  4520. exit;
  4521. end;
  4522. end;
  4523. if GetNextInstruction(p,hp1) and
  4524. (hp1.typ=ait_instruction) then
  4525. begin
  4526. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  4527. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4528. MatchOpType(Taicpu(hp1),top_reg,top_reg) and
  4529. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) then
  4530. begin
  4531. TransferUsedRegs(TmpUsedRegs);
  4532. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4533. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4534. begin
  4535. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4536. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  4537. RemoveInstruction(hp1);
  4538. result:=true;
  4539. exit;
  4540. end;
  4541. end;
  4542. { changes
  4543. lea <ref1>, reg1
  4544. <op> ...,<ref. with reg1>,...
  4545. to
  4546. <op> ...,<ref1>,... }
  4547. if (taicpu(p).oper[1]^.reg<>current_procinfo.framepointer) and
  4548. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) and
  4549. not(MatchInstruction(hp1,A_LEA,[])) then
  4550. begin
  4551. { find a reference which uses reg1 }
  4552. 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
  4553. ref:=0
  4554. 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
  4555. ref:=1
  4556. else
  4557. ref:=-1;
  4558. if (ref<>-1) and
  4559. { reg1 must be either the base or the index }
  4560. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  4561. begin
  4562. { reg1 can be removed from the reference }
  4563. saveref:=taicpu(hp1).oper[ref]^.ref^;
  4564. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  4565. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  4566. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  4567. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  4568. else
  4569. Internalerror(2019111201);
  4570. { check if the can insert all data of the lea into the second instruction }
  4571. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4572. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  4573. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  4574. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  4575. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  4576. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4577. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  4578. {$ifdef x86_64}
  4579. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  4580. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  4581. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  4582. )
  4583. {$endif x86_64}
  4584. then
  4585. begin
  4586. { reg1 might not used by the second instruction after it is remove from the reference }
  4587. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  4588. begin
  4589. TransferUsedRegs(TmpUsedRegs);
  4590. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4591. { reg1 is not updated so it might not be used afterwards }
  4592. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4593. begin
  4594. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  4595. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  4596. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4597. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4598. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4599. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  4600. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  4601. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  4602. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  4603. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  4604. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4605. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4606. RemoveCurrentP(p, hp1);
  4607. result:=true;
  4608. exit;
  4609. end
  4610. end;
  4611. end;
  4612. { recover }
  4613. taicpu(hp1).oper[ref]^.ref^:=saveref;
  4614. end;
  4615. end;
  4616. end;
  4617. { for now, we do not mess with the stack pointer, thought it might be usefull to remove
  4618. unneeded lea sequences on the stack pointer, it needs to be tested in detail }
  4619. if (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) and
  4620. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  4621. begin
  4622. { Check common LEA/LEA conditions }
  4623. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  4624. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  4625. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  4626. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  4627. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  4628. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  4629. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  4630. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  4631. (
  4632. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  4633. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  4634. ) and (
  4635. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  4636. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4637. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  4638. ) then
  4639. begin
  4640. { changes
  4641. lea (regX,scale), reg1
  4642. lea offset(reg1,reg1), reg1
  4643. to
  4644. lea offset(regX,scale*2), reg1
  4645. and
  4646. lea (regX,scale1), reg1
  4647. lea offset(reg1,scale2), reg1
  4648. to
  4649. lea offset(regX,scale1*scale2), reg1
  4650. ... so long as the final scale does not exceed 8
  4651. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  4652. }
  4653. if (taicpu(p).oper[0]^.ref^.offset = 0) and
  4654. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4655. (
  4656. (
  4657. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4658. ) or (
  4659. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4660. (
  4661. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  4662. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  4663. )
  4664. )
  4665. ) and (
  4666. (
  4667. { lea (reg1,scale2), reg1 variant }
  4668. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  4669. (
  4670. (
  4671. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  4672. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  4673. ) or (
  4674. { lea (regX,regX), reg1 variant }
  4675. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4676. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  4677. )
  4678. )
  4679. ) or (
  4680. { lea (reg1,reg1), reg1 variant }
  4681. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4682. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  4683. )
  4684. ) then
  4685. begin
  4686. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  4687. { Make everything homogeneous to make calculations easier }
  4688. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  4689. begin
  4690. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  4691. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  4692. taicpu(p).oper[0]^.ref^.scalefactor := 2
  4693. else
  4694. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  4695. taicpu(p).oper[0]^.ref^.base := NR_NO;
  4696. end;
  4697. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  4698. begin
  4699. { Just to prevent miscalculations }
  4700. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  4701. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  4702. else
  4703. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  4704. end
  4705. else
  4706. begin
  4707. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  4708. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  4709. end;
  4710. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  4711. RemoveCurrentP(p);
  4712. result:=true;
  4713. exit;
  4714. end
  4715. { changes
  4716. lea offset1(regX), reg1
  4717. lea offset2(reg1), reg1
  4718. to
  4719. lea offset1+offset2(regX), reg1 }
  4720. else if
  4721. (
  4722. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4723. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  4724. ) or (
  4725. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4726. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  4727. (
  4728. (
  4729. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4730. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4731. ) or (
  4732. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4733. (
  4734. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4735. (
  4736. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4737. (
  4738. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  4739. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  4740. )
  4741. )
  4742. )
  4743. )
  4744. )
  4745. ) then
  4746. begin
  4747. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  4748. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  4749. begin
  4750. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  4751. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4752. { if the register is used as index and base, we have to increase for base as well
  4753. and adapt base }
  4754. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  4755. begin
  4756. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4757. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4758. end;
  4759. end
  4760. else
  4761. begin
  4762. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4763. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4764. end;
  4765. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4766. begin
  4767. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  4768. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4769. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4770. end;
  4771. RemoveCurrentP(p);
  4772. result:=true;
  4773. exit;
  4774. end;
  4775. end;
  4776. { Change:
  4777. leal/q $x(%reg1),%reg2
  4778. ...
  4779. shll/q $y,%reg2
  4780. To:
  4781. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  4782. }
  4783. if MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  4784. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4785. (taicpu(hp1).oper[0]^.val <= 3) then
  4786. begin
  4787. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  4788. TransferUsedRegs(TmpUsedRegs);
  4789. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4790. TempReg := taicpu(hp1).oper[1]^.reg; { Store locally to reduce the number of dereferences }
  4791. if
  4792. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  4793. (this works even if scalefactor is zero) }
  4794. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  4795. { Ensure offset doesn't go out of bounds }
  4796. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  4797. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  4798. MatchOperand(taicpu(p).oper[1]^, TempReg) and
  4799. (
  4800. (
  4801. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, TempReg) and
  4802. (
  4803. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4804. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  4805. (
  4806. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  4807. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4808. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  4809. )
  4810. )
  4811. ) or (
  4812. (
  4813. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  4814. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  4815. ) and
  4816. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, TempReg)
  4817. )
  4818. ) then
  4819. begin
  4820. repeat
  4821. with taicpu(p).oper[0]^.ref^ do
  4822. begin
  4823. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  4824. if index = base then
  4825. begin
  4826. if Multiple > 4 then
  4827. { Optimisation will no longer work because resultant
  4828. scale factor will exceed 8 }
  4829. Break;
  4830. base := NR_NO;
  4831. scalefactor := 2;
  4832. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  4833. end
  4834. else if (base <> NR_NO) and (base <> NR_INVALID) then
  4835. begin
  4836. { Scale factor only works on the index register }
  4837. index := base;
  4838. base := NR_NO;
  4839. end;
  4840. { For safety }
  4841. if scalefactor <= 1 then
  4842. begin
  4843. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  4844. scalefactor := Multiple;
  4845. end
  4846. else
  4847. begin
  4848. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  4849. scalefactor := scalefactor * Multiple;
  4850. end;
  4851. offset := offset * Multiple;
  4852. end;
  4853. RemoveInstruction(hp1);
  4854. Result := True;
  4855. Exit;
  4856. { This repeat..until loop exists for the benefit of Break }
  4857. until True;
  4858. end;
  4859. end;
  4860. end;
  4861. end;
  4862. function TX86AsmOptimizer.DoSubAddOpt(var p: tai): Boolean;
  4863. var
  4864. hp1 : tai;
  4865. begin
  4866. DoSubAddOpt := False;
  4867. if taicpu(p).oper[0]^.typ <> top_const then
  4868. { Should have been confirmed before calling }
  4869. InternalError(2021102601);
  4870. if GetLastInstruction(p, hp1) and
  4871. (hp1.typ = ait_instruction) and
  4872. (taicpu(hp1).opsize = taicpu(p).opsize) then
  4873. case taicpu(hp1).opcode Of
  4874. A_DEC:
  4875. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4876. begin
  4877. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+1);
  4878. RemoveInstruction(hp1);
  4879. end;
  4880. A_SUB:
  4881. if (taicpu(hp1).oper[0]^.typ = top_const) and
  4882. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  4883. begin
  4884. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val);
  4885. RemoveInstruction(hp1);
  4886. end;
  4887. A_ADD:
  4888. begin
  4889. if (taicpu(hp1).oper[0]^.typ = top_const) and
  4890. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  4891. begin
  4892. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  4893. RemoveInstruction(hp1);
  4894. if (taicpu(p).oper[0]^.val = 0) then
  4895. begin
  4896. hp1 := tai(p.next);
  4897. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  4898. if not GetLastInstruction(hp1, p) then
  4899. p := hp1;
  4900. DoSubAddOpt := True;
  4901. end
  4902. end;
  4903. end;
  4904. else
  4905. ;
  4906. end;
  4907. end;
  4908. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  4909. begin
  4910. Result := False;
  4911. if UpdateTmpUsedRegs then
  4912. TransferUsedRegs(TmpUsedRegs);
  4913. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4914. { The x86 assemblers have difficulty comparing values against absolute addresses }
  4915. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  4916. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  4917. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  4918. (
  4919. (
  4920. (taicpu(hp1).opcode = A_TEST)
  4921. ) or (
  4922. (taicpu(hp1).opcode = A_CMP) and
  4923. { A sanity check more than anything }
  4924. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  4925. )
  4926. ) then
  4927. begin
  4928. { change
  4929. mov mem, %reg
  4930. cmp/test x, %reg / test %reg,%reg
  4931. (reg deallocated)
  4932. to
  4933. cmp/test x, mem / cmp 0, mem
  4934. }
  4935. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4936. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  4937. begin
  4938. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  4939. if (taicpu(hp1).opcode = A_TEST) and
  4940. (
  4941. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  4942. MatchOperand(taicpu(hp1).oper[0]^, -1)
  4943. ) then
  4944. begin
  4945. taicpu(hp1).opcode := A_CMP;
  4946. taicpu(hp1).loadconst(0, 0);
  4947. end;
  4948. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  4949. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  4950. RemoveCurrentP(p, hp1);
  4951. Result := True;
  4952. Exit;
  4953. end;
  4954. end;
  4955. end;
  4956. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  4957. var
  4958. hp1, hp2: tai;
  4959. ActiveReg: TRegister;
  4960. OldOffset: asizeint;
  4961. ThisConst: TCGInt;
  4962. function RegDeallocated: Boolean;
  4963. begin
  4964. TransferUsedRegs(TmpUsedRegs);
  4965. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4966. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4967. end;
  4968. begin
  4969. Result:=false;
  4970. hp1 := nil;
  4971. { replace
  4972. subX const,%reg1
  4973. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4974. dealloc %reg1
  4975. by
  4976. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  4977. }
  4978. if MatchOpType(taicpu(p),top_const,top_reg) then
  4979. begin
  4980. ActiveReg := taicpu(p).oper[1]^.reg;
  4981. { Ensures the entire register was updated }
  4982. if (taicpu(p).opsize >= S_L) and
  4983. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  4984. MatchInstruction(hp1,A_LEA,[]) and
  4985. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  4986. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  4987. (
  4988. { Cover the case where the register in the reference is also the destination register }
  4989. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  4990. (
  4991. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  4992. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  4993. RegDeallocated
  4994. )
  4995. ) then
  4996. begin
  4997. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  4998. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  4999. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5000. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5001. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5002. {$ifdef x86_64}
  5003. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5004. begin
  5005. { Overflow; abort }
  5006. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5007. end
  5008. else
  5009. {$endif x86_64}
  5010. begin
  5011. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  5012. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5013. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5014. RemoveCurrentP(p, hp1)
  5015. else
  5016. RemoveCurrentP(p);
  5017. result:=true;
  5018. Exit;
  5019. end;
  5020. end;
  5021. if (
  5022. { Save calling GetNextInstructionUsingReg again }
  5023. Assigned(hp1) or
  5024. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5025. ) and
  5026. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  5027. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5028. begin
  5029. if taicpu(hp1).oper[0]^.typ = top_const then
  5030. begin
  5031. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  5032. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5033. Result := True;
  5034. { Handle any overflows }
  5035. case taicpu(p).opsize of
  5036. S_B:
  5037. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5038. S_W:
  5039. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5040. S_L:
  5041. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5042. {$ifdef x86_64}
  5043. S_Q:
  5044. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5045. { Overflow; abort }
  5046. Result := False
  5047. else
  5048. taicpu(p).oper[0]^.val := ThisConst;
  5049. {$endif x86_64}
  5050. else
  5051. InternalError(2021102610);
  5052. end;
  5053. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5054. if Result then
  5055. begin
  5056. if (taicpu(p).oper[0]^.val < 0) and
  5057. (
  5058. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5059. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5060. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5061. ) then
  5062. begin
  5063. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  5064. taicpu(p).opcode := A_SUB;
  5065. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5066. end
  5067. else
  5068. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  5069. RemoveInstruction(hp1);
  5070. end;
  5071. end
  5072. else
  5073. begin
  5074. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  5075. TransferUsedRegs(TmpUsedRegs);
  5076. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5077. hp2 := p;
  5078. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5079. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5080. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5081. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5082. begin
  5083. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  5084. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  5085. Asml.Remove(p);
  5086. Asml.InsertAfter(p, hp1);
  5087. p := hp1;
  5088. Result := True;
  5089. Exit;
  5090. end;
  5091. end;
  5092. end;
  5093. { * change "subl $2, %esp; pushw x" to "pushl x"}
  5094. { * change "sub/add const1, reg" or "dec reg" followed by
  5095. "sub const2, reg" to one "sub ..., reg" }
  5096. {$ifdef i386}
  5097. if (taicpu(p).oper[0]^.val = 2) and
  5098. (ActiveReg = NR_ESP) and
  5099. { Don't do the sub/push optimization if the sub }
  5100. { comes from setting up the stack frame (JM) }
  5101. (not(GetLastInstruction(p,hp1)) or
  5102. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  5103. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  5104. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  5105. begin
  5106. hp1 := tai(p.next);
  5107. while Assigned(hp1) and
  5108. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  5109. not RegReadByInstruction(NR_ESP,hp1) and
  5110. not RegModifiedByInstruction(NR_ESP,hp1) do
  5111. hp1 := tai(hp1.next);
  5112. if Assigned(hp1) and
  5113. MatchInstruction(hp1,A_PUSH,[S_W]) then
  5114. begin
  5115. taicpu(hp1).changeopsize(S_L);
  5116. if taicpu(hp1).oper[0]^.typ=top_reg then
  5117. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  5118. hp1 := tai(p.next);
  5119. RemoveCurrentp(p, hp1);
  5120. Result:=true;
  5121. exit;
  5122. end;
  5123. end;
  5124. {$endif i386}
  5125. if DoSubAddOpt(p) then
  5126. Result:=true;
  5127. end;
  5128. end;
  5129. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  5130. var
  5131. TmpBool1,TmpBool2 : Boolean;
  5132. tmpref : treference;
  5133. hp1,hp2: tai;
  5134. mask: tcgint;
  5135. begin
  5136. Result:=false;
  5137. { All these optimisations work on "shl/sal const,%reg" }
  5138. if not MatchOpType(taicpu(p),top_const,top_reg) then
  5139. Exit;
  5140. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  5141. (taicpu(p).oper[0]^.val <= 3) then
  5142. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  5143. begin
  5144. { should we check the next instruction? }
  5145. TmpBool1 := True;
  5146. { have we found an add/sub which could be
  5147. integrated in the lea? }
  5148. TmpBool2 := False;
  5149. reference_reset(tmpref,2,[]);
  5150. TmpRef.index := taicpu(p).oper[1]^.reg;
  5151. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5152. while TmpBool1 and
  5153. GetNextInstruction(p, hp1) and
  5154. (tai(hp1).typ = ait_instruction) and
  5155. ((((taicpu(hp1).opcode = A_ADD) or
  5156. (taicpu(hp1).opcode = A_SUB)) and
  5157. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  5158. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  5159. (((taicpu(hp1).opcode = A_INC) or
  5160. (taicpu(hp1).opcode = A_DEC)) and
  5161. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5162. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  5163. ((taicpu(hp1).opcode = A_LEA) and
  5164. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5165. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  5166. (not GetNextInstruction(hp1,hp2) or
  5167. not instrReadsFlags(hp2)) Do
  5168. begin
  5169. TmpBool1 := False;
  5170. if taicpu(hp1).opcode=A_LEA then
  5171. begin
  5172. if (TmpRef.base = NR_NO) and
  5173. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  5174. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  5175. (taicpu(hp1).oper[0]^.ref^.segment=NR_NO) and
  5176. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  5177. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  5178. begin
  5179. TmpBool1 := True;
  5180. TmpBool2 := True;
  5181. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  5182. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  5183. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  5184. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  5185. RemoveInstruction(hp1);
  5186. end
  5187. end
  5188. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  5189. begin
  5190. TmpBool1 := True;
  5191. TmpBool2 := True;
  5192. case taicpu(hp1).opcode of
  5193. A_ADD:
  5194. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5195. A_SUB:
  5196. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5197. else
  5198. internalerror(2019050536);
  5199. end;
  5200. RemoveInstruction(hp1);
  5201. end
  5202. else
  5203. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5204. (((taicpu(hp1).opcode = A_ADD) and
  5205. (TmpRef.base = NR_NO)) or
  5206. (taicpu(hp1).opcode = A_INC) or
  5207. (taicpu(hp1).opcode = A_DEC)) then
  5208. begin
  5209. TmpBool1 := True;
  5210. TmpBool2 := True;
  5211. case taicpu(hp1).opcode of
  5212. A_ADD:
  5213. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  5214. A_INC:
  5215. inc(TmpRef.offset);
  5216. A_DEC:
  5217. dec(TmpRef.offset);
  5218. else
  5219. internalerror(2019050535);
  5220. end;
  5221. RemoveInstruction(hp1);
  5222. end;
  5223. end;
  5224. if TmpBool2
  5225. {$ifndef x86_64}
  5226. or
  5227. ((current_settings.optimizecputype < cpu_Pentium2) and
  5228. (taicpu(p).oper[0]^.val <= 3) and
  5229. not(cs_opt_size in current_settings.optimizerswitches))
  5230. {$endif x86_64}
  5231. then
  5232. begin
  5233. if not(TmpBool2) and
  5234. (taicpu(p).oper[0]^.val=1) then
  5235. begin
  5236. hp1:=taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5237. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  5238. end
  5239. else
  5240. hp1:=taicpu.op_ref_reg(A_LEA, taicpu(p).opsize, TmpRef,
  5241. taicpu(p).oper[1]^.reg);
  5242. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  5243. InsertLLItem(p.previous, p.next, hp1);
  5244. p.free;
  5245. p := hp1;
  5246. end;
  5247. end
  5248. {$ifndef x86_64}
  5249. else if (current_settings.optimizecputype < cpu_Pentium2) then
  5250. begin
  5251. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  5252. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  5253. (unlike shl, which is only Tairable in the U pipe) }
  5254. if taicpu(p).oper[0]^.val=1 then
  5255. begin
  5256. hp1 := taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5257. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg);
  5258. InsertLLItem(p.previous, p.next, hp1);
  5259. p.free;
  5260. p := hp1;
  5261. end
  5262. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  5263. "shl $3, %reg" to "lea (,%reg,8), %reg }
  5264. else if (taicpu(p).opsize = S_L) and
  5265. (taicpu(p).oper[0]^.val<= 3) then
  5266. begin
  5267. reference_reset(tmpref,2,[]);
  5268. TmpRef.index := taicpu(p).oper[1]^.reg;
  5269. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5270. hp1 := taicpu.Op_ref_reg(A_LEA,S_L,TmpRef, taicpu(p).oper[1]^.reg);
  5271. InsertLLItem(p.previous, p.next, hp1);
  5272. p.free;
  5273. p := hp1;
  5274. end;
  5275. end
  5276. {$endif x86_64}
  5277. else if
  5278. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  5279. (
  5280. (
  5281. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  5282. SetAndTest(hp1, hp2)
  5283. {$ifdef x86_64}
  5284. ) or
  5285. (
  5286. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  5287. GetNextInstruction(hp1, hp2) and
  5288. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  5289. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  5290. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  5291. {$endif x86_64}
  5292. )
  5293. ) and
  5294. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  5295. begin
  5296. { Change:
  5297. shl x, %reg1
  5298. mov -(1<<x), %reg2
  5299. and %reg2, %reg1
  5300. Or:
  5301. shl x, %reg1
  5302. and -(1<<x), %reg1
  5303. To just:
  5304. shl x, %reg1
  5305. Since the and operation only zeroes bits that are already zero from the shl operation
  5306. }
  5307. case taicpu(p).oper[0]^.val of
  5308. 8:
  5309. mask:=$FFFFFFFFFFFFFF00;
  5310. 16:
  5311. mask:=$FFFFFFFFFFFF0000;
  5312. 32:
  5313. mask:=$FFFFFFFF00000000;
  5314. 63:
  5315. { Constant pre-calculated to prevent overflow errors with Int64 }
  5316. mask:=$8000000000000000;
  5317. else
  5318. begin
  5319. if taicpu(p).oper[0]^.val >= 64 then
  5320. { Shouldn't happen realistically, since the register
  5321. is guaranteed to be set to zero at this point }
  5322. mask := 0
  5323. else
  5324. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  5325. end;
  5326. end;
  5327. if taicpu(hp1).oper[0]^.val = mask then
  5328. begin
  5329. { Everything checks out, perform the optimisation, as long as
  5330. the FLAGS register isn't being used}
  5331. TransferUsedRegs(TmpUsedRegs);
  5332. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5333. {$ifdef x86_64}
  5334. if (hp1 <> hp2) then
  5335. begin
  5336. { "shl/mov/and" version }
  5337. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  5338. { Don't do the optimisation if the FLAGS register is in use }
  5339. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  5340. begin
  5341. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  5342. { Don't remove the 'mov' instruction if its register is used elsewhere }
  5343. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  5344. begin
  5345. RemoveInstruction(hp1);
  5346. Result := True;
  5347. end;
  5348. { Only set Result to True if the 'mov' instruction was removed }
  5349. RemoveInstruction(hp2);
  5350. end;
  5351. end
  5352. else
  5353. {$endif x86_64}
  5354. begin
  5355. { "shl/and" version }
  5356. { Don't do the optimisation if the FLAGS register is in use }
  5357. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  5358. begin
  5359. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  5360. RemoveInstruction(hp1);
  5361. Result := True;
  5362. end;
  5363. end;
  5364. Exit;
  5365. end
  5366. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  5367. begin
  5368. { Even if the mask doesn't allow for its removal, we might be
  5369. able to optimise the mask for the "shl/and" version, which
  5370. may permit other peephole optimisations }
  5371. {$ifdef DEBUG_AOPTCPU}
  5372. mask := taicpu(hp1).oper[0]^.val and mask;
  5373. if taicpu(hp1).oper[0]^.val <> mask then
  5374. begin
  5375. DebugMsg(
  5376. SPeepholeOptimization +
  5377. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  5378. ' to $' + debug_tostr(mask) +
  5379. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  5380. taicpu(hp1).oper[0]^.val := mask;
  5381. end;
  5382. {$else DEBUG_AOPTCPU}
  5383. { If debugging is off, just set the operand even if it's the same }
  5384. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  5385. {$endif DEBUG_AOPTCPU}
  5386. end;
  5387. end;
  5388. {
  5389. change
  5390. shl/sal const,reg
  5391. <op> ...(...,reg,1),...
  5392. into
  5393. <op> ...(...,reg,1 shl const),...
  5394. if const in 1..3
  5395. }
  5396. if MatchOpType(taicpu(p), top_const, top_reg) and
  5397. (taicpu(p).oper[0]^.val in [1..3]) and
  5398. GetNextInstruction(p, hp1) and
  5399. MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  5400. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  5401. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  5402. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  5403. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  5404. begin
  5405. TransferUsedRegs(TmpUsedRegs);
  5406. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5407. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  5408. begin
  5409. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  5410. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  5411. RemoveCurrentP(p);
  5412. Result:=true;
  5413. end;
  5414. end;
  5415. end;
  5416. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  5417. var
  5418. CurrentRef: TReference;
  5419. FullReg: TRegister;
  5420. hp1, hp2: tai;
  5421. begin
  5422. Result := False;
  5423. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  5424. Exit;
  5425. { We assume you've checked if the operand is actually a reference by
  5426. this point. If it isn't, you'll most likely get an access violation }
  5427. CurrentRef := first_mov.oper[1]^.ref^;
  5428. { Memory must be aligned }
  5429. if (CurrentRef.offset mod 4) <> 0 then
  5430. Exit;
  5431. Inc(CurrentRef.offset);
  5432. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5433. if MatchOperand(second_mov.oper[0]^, 0) and
  5434. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  5435. GetNextInstruction(second_mov, hp1) and
  5436. (hp1.typ = ait_instruction) and
  5437. (taicpu(hp1).opcode = A_MOV) and
  5438. MatchOpType(taicpu(hp1), top_const, top_ref) and
  5439. (taicpu(hp1).oper[0]^.val = 0) then
  5440. begin
  5441. Inc(CurrentRef.offset);
  5442. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  5443. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  5444. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  5445. begin
  5446. case taicpu(hp1).opsize of
  5447. S_B:
  5448. if GetNextInstruction(hp1, hp2) and
  5449. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  5450. MatchOpType(taicpu(hp2), top_const, top_ref) and
  5451. (taicpu(hp2).oper[0]^.val = 0) then
  5452. begin
  5453. Inc(CurrentRef.offset);
  5454. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5455. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  5456. (taicpu(hp2).opsize = S_B) then
  5457. begin
  5458. RemoveInstruction(hp1);
  5459. RemoveInstruction(hp2);
  5460. first_mov.opsize := S_L;
  5461. if first_mov.oper[0]^.typ = top_reg then
  5462. begin
  5463. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  5464. { Reuse second_mov as a MOVZX instruction }
  5465. second_mov.opcode := A_MOVZX;
  5466. second_mov.opsize := S_BL;
  5467. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5468. second_mov.loadreg(1, FullReg);
  5469. first_mov.oper[0]^.reg := FullReg;
  5470. asml.Remove(second_mov);
  5471. asml.InsertBefore(second_mov, first_mov);
  5472. end
  5473. else
  5474. { It's a value }
  5475. begin
  5476. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  5477. RemoveInstruction(second_mov);
  5478. end;
  5479. Result := True;
  5480. Exit;
  5481. end;
  5482. end;
  5483. S_W:
  5484. begin
  5485. RemoveInstruction(hp1);
  5486. first_mov.opsize := S_L;
  5487. if first_mov.oper[0]^.typ = top_reg then
  5488. begin
  5489. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  5490. { Reuse second_mov as a MOVZX instruction }
  5491. second_mov.opcode := A_MOVZX;
  5492. second_mov.opsize := S_BL;
  5493. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5494. second_mov.loadreg(1, FullReg);
  5495. first_mov.oper[0]^.reg := FullReg;
  5496. asml.Remove(second_mov);
  5497. asml.InsertBefore(second_mov, first_mov);
  5498. end
  5499. else
  5500. { It's a value }
  5501. begin
  5502. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  5503. RemoveInstruction(second_mov);
  5504. end;
  5505. Result := True;
  5506. Exit;
  5507. end;
  5508. else
  5509. ;
  5510. end;
  5511. end;
  5512. end;
  5513. end;
  5514. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  5515. { returns true if a "continue" should be done after this optimization }
  5516. var
  5517. hp1, hp2: tai;
  5518. begin
  5519. Result := false;
  5520. if MatchOpType(taicpu(p),top_ref) and
  5521. GetNextInstruction(p, hp1) and
  5522. (hp1.typ = ait_instruction) and
  5523. (((taicpu(hp1).opcode = A_FLD) and
  5524. (taicpu(p).opcode = A_FSTP)) or
  5525. ((taicpu(p).opcode = A_FISTP) and
  5526. (taicpu(hp1).opcode = A_FILD))) and
  5527. MatchOpType(taicpu(hp1),top_ref) and
  5528. (taicpu(hp1).opsize = taicpu(p).opsize) and
  5529. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  5530. begin
  5531. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  5532. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  5533. GetNextInstruction(hp1, hp2) and
  5534. (hp2.typ = ait_instruction) and
  5535. IsExitCode(hp2) and
  5536. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  5537. not(assigned(current_procinfo.procdef.funcretsym) and
  5538. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  5539. (taicpu(p).oper[0]^.ref^.index = NR_NO) then
  5540. begin
  5541. RemoveInstruction(hp1);
  5542. RemoveCurrentP(p, hp2);
  5543. RemoveLastDeallocForFuncRes(p);
  5544. Result := true;
  5545. end
  5546. else
  5547. { we can do this only in fast math mode as fstp is rounding ...
  5548. ... still disabled as it breaks the compiler and/or rtl }
  5549. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  5550. { ... or if another fstp equal to the first one follows }
  5551. (GetNextInstruction(hp1,hp2) and
  5552. (hp2.typ = ait_instruction) and
  5553. (taicpu(p).opcode=taicpu(hp2).opcode) and
  5554. (taicpu(p).opsize=taicpu(hp2).opsize))
  5555. ) and
  5556. { fst can't store an extended/comp value }
  5557. (taicpu(p).opsize <> S_FX) and
  5558. (taicpu(p).opsize <> S_IQ) then
  5559. begin
  5560. if (taicpu(p).opcode = A_FSTP) then
  5561. taicpu(p).opcode := A_FST
  5562. else
  5563. taicpu(p).opcode := A_FIST;
  5564. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  5565. RemoveInstruction(hp1);
  5566. end;
  5567. end;
  5568. end;
  5569. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  5570. var
  5571. hp1, hp2: tai;
  5572. begin
  5573. result:=false;
  5574. if MatchOpType(taicpu(p),top_reg) and
  5575. GetNextInstruction(p, hp1) and
  5576. (hp1.typ = Ait_Instruction) and
  5577. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5578. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  5579. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  5580. { change to
  5581. fld reg fxxx reg,st
  5582. fxxxp st, st1 (hp1)
  5583. Remark: non commutative operations must be reversed!
  5584. }
  5585. begin
  5586. case taicpu(hp1).opcode Of
  5587. A_FMULP,A_FADDP,
  5588. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  5589. begin
  5590. case taicpu(hp1).opcode Of
  5591. A_FADDP: taicpu(hp1).opcode := A_FADD;
  5592. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  5593. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  5594. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  5595. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  5596. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  5597. else
  5598. internalerror(2019050534);
  5599. end;
  5600. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  5601. taicpu(hp1).oper[1]^.reg := NR_ST;
  5602. RemoveCurrentP(p, hp1);
  5603. Result:=true;
  5604. exit;
  5605. end;
  5606. else
  5607. ;
  5608. end;
  5609. end
  5610. else
  5611. if MatchOpType(taicpu(p),top_ref) and
  5612. GetNextInstruction(p, hp2) and
  5613. (hp2.typ = Ait_Instruction) and
  5614. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  5615. (taicpu(p).opsize in [S_FS, S_FL]) and
  5616. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  5617. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  5618. if GetLastInstruction(p, hp1) and
  5619. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  5620. MatchOpType(taicpu(hp1),top_ref) and
  5621. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  5622. if ((taicpu(hp2).opcode = A_FMULP) or
  5623. (taicpu(hp2).opcode = A_FADDP)) then
  5624. { change to
  5625. fld/fst mem1 (hp1) fld/fst mem1
  5626. fld mem1 (p) fadd/
  5627. faddp/ fmul st, st
  5628. fmulp st, st1 (hp2) }
  5629. begin
  5630. RemoveCurrentP(p, hp1);
  5631. if (taicpu(hp2).opcode = A_FADDP) then
  5632. taicpu(hp2).opcode := A_FADD
  5633. else
  5634. taicpu(hp2).opcode := A_FMUL;
  5635. taicpu(hp2).oper[1]^.reg := NR_ST;
  5636. end
  5637. else
  5638. { change to
  5639. fld/fst mem1 (hp1) fld/fst mem1
  5640. fld mem1 (p) fld st}
  5641. begin
  5642. taicpu(p).changeopsize(S_FL);
  5643. taicpu(p).loadreg(0,NR_ST);
  5644. end
  5645. else
  5646. begin
  5647. case taicpu(hp2).opcode Of
  5648. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  5649. { change to
  5650. fld/fst mem1 (hp1) fld/fst mem1
  5651. fld mem2 (p) fxxx mem2
  5652. fxxxp st, st1 (hp2) }
  5653. begin
  5654. case taicpu(hp2).opcode Of
  5655. A_FADDP: taicpu(p).opcode := A_FADD;
  5656. A_FMULP: taicpu(p).opcode := A_FMUL;
  5657. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  5658. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  5659. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  5660. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  5661. else
  5662. internalerror(2019050533);
  5663. end;
  5664. RemoveInstruction(hp2);
  5665. end
  5666. else
  5667. ;
  5668. end
  5669. end
  5670. end;
  5671. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  5672. begin
  5673. Result := condition_in(cond1, cond2) or
  5674. { Not strictly subsets due to the actual flags checked, but because we're
  5675. comparing integers, E is a subset of AE and GE and their aliases }
  5676. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  5677. end;
  5678. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  5679. var
  5680. v: TCGInt;
  5681. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  5682. FirstMatch: Boolean;
  5683. NewReg: TRegister;
  5684. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  5685. begin
  5686. Result:=false;
  5687. { All these optimisations need a next instruction }
  5688. if not GetNextInstruction(p, hp1) then
  5689. Exit;
  5690. { Search for:
  5691. cmp ###,###
  5692. j(c1) @lbl1
  5693. ...
  5694. @lbl:
  5695. cmp ###.### (same comparison as above)
  5696. j(c2) @lbl2
  5697. If c1 is a subset of c2, change to:
  5698. cmp ###,###
  5699. j(c2) @lbl2
  5700. (@lbl1 may become a dead label as a result)
  5701. }
  5702. { Also handle cases where there are multiple jumps in a row }
  5703. p_jump := hp1;
  5704. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  5705. begin
  5706. if IsJumpToLabel(taicpu(p_jump)) then
  5707. begin
  5708. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  5709. p_label := nil;
  5710. if Assigned(JumpLabel) then
  5711. p_label := getlabelwithsym(JumpLabel);
  5712. if Assigned(p_label) and
  5713. GetNextInstruction(p_label, p_dist) and
  5714. MatchInstruction(p_dist, A_CMP, []) and
  5715. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  5716. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5717. GetNextInstruction(p_dist, hp1_dist) and
  5718. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5719. begin
  5720. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5721. if JumpLabel = JumpLabel_dist then
  5722. { This is an infinite loop }
  5723. Exit;
  5724. { Best optimisation when the first condition is a subset (or equal) of the second }
  5725. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  5726. begin
  5727. { Any registers used here will already be allocated }
  5728. if Assigned(JumpLabel_dist) then
  5729. JumpLabel_dist.IncRefs;
  5730. if Assigned(JumpLabel) then
  5731. JumpLabel.DecRefs;
  5732. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  5733. taicpu(p_jump).condition := taicpu(hp1_dist).condition;
  5734. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  5735. Result := True;
  5736. { Don't exit yet. Since p and p_jump haven't actually been
  5737. removed, we can check for more on this iteration }
  5738. end
  5739. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  5740. GetNextInstruction(hp1_dist, hp1_label) and
  5741. SkipAligns(hp1_label, hp1_label) and
  5742. (hp1_label.typ = ait_label) then
  5743. begin
  5744. JumpLabel_far := tai_label(hp1_label).labsym;
  5745. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  5746. { This is an infinite loop }
  5747. Exit;
  5748. if Assigned(JumpLabel_far) then
  5749. begin
  5750. { In this situation, if the first jump branches, the second one will never,
  5751. branch so change the destination label to after the second jump }
  5752. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  5753. if Assigned(JumpLabel) then
  5754. JumpLabel.DecRefs;
  5755. JumpLabel_far.IncRefs;
  5756. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  5757. Result := True;
  5758. { Don't exit yet. Since p and p_jump haven't actually been
  5759. removed, we can check for more on this iteration }
  5760. Continue;
  5761. end;
  5762. end;
  5763. end;
  5764. end;
  5765. { Search for:
  5766. cmp ###,###
  5767. j(c1) @lbl1
  5768. cmp ###,### (same as first)
  5769. Remove second cmp
  5770. }
  5771. if GetNextInstruction(p_jump, hp2) and
  5772. (
  5773. (
  5774. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  5775. (
  5776. (
  5777. MatchOpType(taicpu(p), top_const, top_reg) and
  5778. MatchOpType(taicpu(hp2), top_const, top_reg) and
  5779. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  5780. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  5781. ) or (
  5782. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  5783. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  5784. )
  5785. )
  5786. ) or (
  5787. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  5788. MatchOperand(taicpu(p).oper[0]^, 0) and
  5789. (taicpu(p).oper[1]^.typ = top_reg) and
  5790. MatchInstruction(hp2, A_TEST, []) and
  5791. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  5792. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  5793. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  5794. )
  5795. ) then
  5796. begin
  5797. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  5798. RemoveInstruction(hp2);
  5799. Result := True;
  5800. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  5801. end;
  5802. GetNextInstruction(p_jump, p_jump);
  5803. end;
  5804. {
  5805. Try to optimise the following:
  5806. cmp $x,### ($x and $y can be registers or constants)
  5807. je @lbl1 (only reference)
  5808. cmp $y,### (### are identical)
  5809. @Lbl:
  5810. sete %reg1
  5811. Change to:
  5812. cmp $x,###
  5813. sete %reg2 (allocate new %reg2)
  5814. cmp $y,###
  5815. sete %reg1
  5816. orb %reg2,%reg1
  5817. (dealloc %reg2)
  5818. This adds an instruction (so don't perform under -Os), but it removes
  5819. a conditional branch.
  5820. }
  5821. if not (cs_opt_size in current_settings.optimizerswitches) and
  5822. (
  5823. (hp1 = p_jump) or
  5824. GetNextInstruction(p, hp1)
  5825. ) and
  5826. MatchInstruction(hp1, A_Jcc, []) and
  5827. IsJumpToLabel(taicpu(hp1)) and
  5828. (taicpu(hp1).condition in [C_E, C_Z]) and
  5829. GetNextInstruction(hp1, hp2) and
  5830. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  5831. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  5832. { The first operand of CMP instructions can only be a register or
  5833. immediate anyway, so no need to check }
  5834. GetNextInstruction(hp2, p_label) and
  5835. (p_label.typ = ait_label) and
  5836. (tai_label(p_label).labsym.getrefs = 1) and
  5837. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  5838. GetNextInstruction(p_label, p_dist) and
  5839. MatchInstruction(p_dist, A_SETcc, []) and
  5840. (taicpu(p_dist).condition in [C_E, C_Z]) and
  5841. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  5842. begin
  5843. TransferUsedRegs(TmpUsedRegs);
  5844. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5845. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5846. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  5847. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5848. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  5849. { Get the instruction after the SETcc instruction so we can
  5850. allocate a new register over the entire range }
  5851. GetNextInstruction(p_dist, hp1_dist) then
  5852. begin
  5853. { Register can appear in p if it's not used afterwards, so only
  5854. allocate between hp1 and hp1_dist }
  5855. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  5856. if NewReg <> NR_NO then
  5857. begin
  5858. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  5859. { Change the jump instruction into a SETcc instruction }
  5860. taicpu(hp1).opcode := A_SETcc;
  5861. taicpu(hp1).opsize := S_B;
  5862. taicpu(hp1).loadreg(0, NewReg);
  5863. { This is now a dead label }
  5864. tai_label(p_label).labsym.decrefs;
  5865. { Prefer adding before the next instruction so the FLAGS
  5866. register is deallicated first }
  5867. AsmL.InsertBefore(
  5868. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  5869. hp1_dist
  5870. );
  5871. Result := True;
  5872. { Don't exit yet, as p wasn't changed and hp1, while
  5873. modified, is still intact and might be optimised by the
  5874. SETcc optimisation below }
  5875. end;
  5876. end;
  5877. end;
  5878. if taicpu(p).oper[0]^.typ = top_const then
  5879. begin
  5880. if (taicpu(p).oper[0]^.val = 0) and
  5881. (taicpu(p).oper[1]^.typ = top_reg) and
  5882. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  5883. begin
  5884. hp2 := p;
  5885. FirstMatch := True;
  5886. { When dealing with "cmp $0,%reg", only ZF and SF contain
  5887. anything meaningful once it's converted to "test %reg,%reg";
  5888. additionally, some jumps will always (or never) branch, so
  5889. evaluate every jump immediately following the
  5890. comparison, optimising the conditions if possible.
  5891. Similarly with SETcc... those that are always set to 0 or 1
  5892. are changed to MOV instructions }
  5893. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  5894. (
  5895. GetNextInstruction(hp2, hp1) and
  5896. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  5897. ) do
  5898. begin
  5899. FirstMatch := False;
  5900. case taicpu(hp1).condition of
  5901. C_B, C_C, C_NAE, C_O:
  5902. { For B/NAE:
  5903. Will never branch since an unsigned integer can never be below zero
  5904. For C/O:
  5905. Result cannot overflow because 0 is being subtracted
  5906. }
  5907. begin
  5908. if taicpu(hp1).opcode = A_Jcc then
  5909. begin
  5910. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  5911. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  5912. RemoveInstruction(hp1);
  5913. { Since hp1 was deleted, hp2 must not be updated }
  5914. Continue;
  5915. end
  5916. else
  5917. begin
  5918. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  5919. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  5920. taicpu(hp1).opcode := A_MOV;
  5921. taicpu(hp1).ops := 2;
  5922. taicpu(hp1).condition := C_None;
  5923. taicpu(hp1).opsize := S_B;
  5924. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  5925. taicpu(hp1).loadconst(0, 0);
  5926. end;
  5927. end;
  5928. C_BE, C_NA:
  5929. begin
  5930. { Will only branch if equal to zero }
  5931. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  5932. taicpu(hp1).condition := C_E;
  5933. end;
  5934. C_A, C_NBE:
  5935. begin
  5936. { Will only branch if not equal to zero }
  5937. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  5938. taicpu(hp1).condition := C_NE;
  5939. end;
  5940. C_AE, C_NB, C_NC, C_NO:
  5941. begin
  5942. { Will always branch }
  5943. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  5944. if taicpu(hp1).opcode = A_Jcc then
  5945. begin
  5946. MakeUnconditional(taicpu(hp1));
  5947. { Any jumps/set that follow will now be dead code }
  5948. RemoveDeadCodeAfterJump(taicpu(hp1));
  5949. Break;
  5950. end
  5951. else
  5952. begin
  5953. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  5954. taicpu(hp1).opcode := A_MOV;
  5955. taicpu(hp1).ops := 2;
  5956. taicpu(hp1).condition := C_None;
  5957. taicpu(hp1).opsize := S_B;
  5958. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  5959. taicpu(hp1).loadconst(0, 1);
  5960. end;
  5961. end;
  5962. C_None:
  5963. InternalError(2020012201);
  5964. C_P, C_PE, C_NP, C_PO:
  5965. { We can't handle parity checks and they should never be generated
  5966. after a general-purpose CMP (it's used in some floating-point
  5967. comparisons that don't use CMP) }
  5968. InternalError(2020012202);
  5969. else
  5970. { Zero/Equality, Sign, their complements and all of the
  5971. signed comparisons do not need to be converted };
  5972. end;
  5973. hp2 := hp1;
  5974. end;
  5975. { Convert the instruction to a TEST }
  5976. taicpu(p).opcode := A_TEST;
  5977. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  5978. Result := True;
  5979. Exit;
  5980. end
  5981. else if (taicpu(p).oper[0]^.val = 1) and
  5982. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  5983. (taicpu(hp1).condition in [C_L, C_NGE]) then
  5984. begin
  5985. { Convert; To:
  5986. cmp $1,r/m cmp $0,r/m
  5987. jl @lbl jle @lbl
  5988. }
  5989. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  5990. taicpu(p).oper[0]^.val := 0;
  5991. taicpu(hp1).condition := C_LE;
  5992. { If the instruction is now "cmp $0,%reg", convert it to a
  5993. TEST (and effectively do the work of the "cmp $0,%reg" in
  5994. the block above)
  5995. If it's a reference, we can get away with not setting
  5996. Result to True because he haven't evaluated the jump
  5997. in this pass yet.
  5998. }
  5999. if (taicpu(p).oper[1]^.typ = top_reg) then
  6000. begin
  6001. taicpu(p).opcode := A_TEST;
  6002. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6003. Result := True;
  6004. end;
  6005. Exit;
  6006. end
  6007. else if (taicpu(p).oper[1]^.typ = top_reg)
  6008. {$ifdef x86_64}
  6009. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  6010. {$endif x86_64}
  6011. then
  6012. begin
  6013. { cmp register,$8000 neg register
  6014. je target --> jo target
  6015. .... only if register is deallocated before jump.}
  6016. case Taicpu(p).opsize of
  6017. S_B: v:=$80;
  6018. S_W: v:=$8000;
  6019. S_L: v:=qword($80000000);
  6020. else
  6021. internalerror(2013112905);
  6022. end;
  6023. if (taicpu(p).oper[0]^.val=v) and
  6024. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6025. (Taicpu(hp1).condition in [C_E,C_NE]) then
  6026. begin
  6027. TransferUsedRegs(TmpUsedRegs);
  6028. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  6029. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  6030. begin
  6031. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  6032. Taicpu(p).opcode:=A_NEG;
  6033. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  6034. Taicpu(p).clearop(1);
  6035. Taicpu(p).ops:=1;
  6036. if Taicpu(hp1).condition=C_E then
  6037. Taicpu(hp1).condition:=C_O
  6038. else
  6039. Taicpu(hp1).condition:=C_NO;
  6040. Result:=true;
  6041. exit;
  6042. end;
  6043. end;
  6044. end;
  6045. end;
  6046. if TrySwapMovCmp(p, hp1) then
  6047. begin
  6048. Result := True;
  6049. Exit;
  6050. end;
  6051. end;
  6052. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  6053. var
  6054. hp1: tai;
  6055. begin
  6056. {
  6057. remove the second (v)pxor from
  6058. pxor reg,reg
  6059. ...
  6060. pxor reg,reg
  6061. }
  6062. Result:=false;
  6063. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6064. MatchOpType(taicpu(p),top_reg,top_reg) and
  6065. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6066. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6067. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6068. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  6069. begin
  6070. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  6071. RemoveInstruction(hp1);
  6072. Result:=true;
  6073. Exit;
  6074. end
  6075. {
  6076. replace
  6077. pxor reg1,reg1
  6078. movapd/s reg1,reg2
  6079. dealloc reg1
  6080. by
  6081. pxor reg2,reg2
  6082. }
  6083. else if GetNextInstruction(p,hp1) and
  6084. { we mix single and double opperations here because we assume that the compiler
  6085. generates vmovapd only after double operations and vmovaps only after single operations }
  6086. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  6087. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6088. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  6089. (taicpu(p).oper[0]^.typ=top_reg) then
  6090. begin
  6091. TransferUsedRegs(TmpUsedRegs);
  6092. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6093. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  6094. begin
  6095. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  6096. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  6097. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  6098. RemoveInstruction(hp1);
  6099. result:=true;
  6100. end;
  6101. end;
  6102. end;
  6103. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  6104. var
  6105. hp1: tai;
  6106. begin
  6107. {
  6108. remove the second (v)pxor from
  6109. (v)pxor reg,reg
  6110. ...
  6111. (v)pxor reg,reg
  6112. }
  6113. Result:=false;
  6114. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  6115. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  6116. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6117. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6118. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6119. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  6120. begin
  6121. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2PXor done',hp1);
  6122. RemoveInstruction(hp1);
  6123. Result:=true;
  6124. Exit;
  6125. end
  6126. else
  6127. Result:=OptPass1VOP(p);
  6128. end;
  6129. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  6130. var
  6131. hp1 : tai;
  6132. begin
  6133. result:=false;
  6134. { replace
  6135. IMul const,%mreg1,%mreg2
  6136. Mov %reg2,%mreg3
  6137. dealloc %mreg3
  6138. by
  6139. Imul const,%mreg1,%mreg23
  6140. }
  6141. if (taicpu(p).ops=3) and
  6142. GetNextInstruction(p,hp1) and
  6143. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6144. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6145. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6146. begin
  6147. TransferUsedRegs(TmpUsedRegs);
  6148. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6149. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6150. begin
  6151. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6152. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  6153. RemoveInstruction(hp1);
  6154. result:=true;
  6155. end;
  6156. end;
  6157. end;
  6158. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  6159. var
  6160. hp1 : tai;
  6161. begin
  6162. result:=false;
  6163. { replace
  6164. IMul %reg0,%reg1,%reg2
  6165. Mov %reg2,%reg3
  6166. dealloc %reg2
  6167. by
  6168. Imul %reg0,%reg1,%reg3
  6169. }
  6170. if GetNextInstruction(p,hp1) and
  6171. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6172. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6173. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6174. begin
  6175. TransferUsedRegs(TmpUsedRegs);
  6176. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6177. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6178. begin
  6179. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6180. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  6181. RemoveInstruction(hp1);
  6182. result:=true;
  6183. end;
  6184. end;
  6185. end;
  6186. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  6187. var
  6188. hp1: tai;
  6189. begin
  6190. Result:=false;
  6191. { get rid of
  6192. (v)cvtss2sd reg0,<reg1,>reg2
  6193. (v)cvtss2sd reg2,<reg2,>reg0
  6194. }
  6195. if GetNextInstruction(p,hp1) and
  6196. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  6197. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  6198. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  6199. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  6200. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  6201. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  6202. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  6203. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  6204. )
  6205. ) then
  6206. begin
  6207. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  6208. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  6209. begin
  6210. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  6211. RemoveCurrentP(p);
  6212. RemoveInstruction(hp1);
  6213. end
  6214. else
  6215. begin
  6216. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  6217. if taicpu(hp1).opcode=A_CVTSD2SS then
  6218. begin
  6219. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  6220. taicpu(p).opcode:=A_MOVAPS;
  6221. end
  6222. else
  6223. begin
  6224. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  6225. taicpu(p).opcode:=A_VMOVAPS;
  6226. end;
  6227. taicpu(p).ops:=2;
  6228. RemoveInstruction(hp1);
  6229. end;
  6230. Result:=true;
  6231. Exit;
  6232. end;
  6233. end;
  6234. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  6235. var
  6236. hp1, hp2, hp3, hp4, hp5: tai;
  6237. ThisReg: TRegister;
  6238. begin
  6239. Result := False;
  6240. if not GetNextInstruction(p,hp1) or (hp1.typ <> ait_instruction) then
  6241. Exit;
  6242. {
  6243. convert
  6244. j<c> .L1
  6245. mov 1,reg
  6246. jmp .L2
  6247. .L1
  6248. mov 0,reg
  6249. .L2
  6250. into
  6251. mov 0,reg
  6252. set<not(c)> reg
  6253. take care of alignment and that the mov 0,reg is not converted into a xor as this
  6254. would destroy the flag contents
  6255. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  6256. executed at the same time as a previous comparison.
  6257. set<not(c)> reg
  6258. movzx reg, reg
  6259. }
  6260. if MatchInstruction(hp1,A_MOV,[]) and
  6261. (taicpu(hp1).oper[0]^.typ = top_const) and
  6262. (
  6263. (
  6264. (taicpu(hp1).oper[1]^.typ = top_reg)
  6265. {$ifdef i386}
  6266. { Under i386, ESI, EDI, EBP and ESP
  6267. don't have an 8-bit representation }
  6268. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6269. {$endif i386}
  6270. ) or (
  6271. {$ifdef i386}
  6272. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  6273. {$endif i386}
  6274. (taicpu(hp1).opsize = S_B)
  6275. )
  6276. ) and
  6277. GetNextInstruction(hp1,hp2) and
  6278. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  6279. GetNextInstruction(hp2,hp3) and
  6280. SkipAligns(hp3, hp3) and
  6281. (hp3.typ=ait_label) and
  6282. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  6283. GetNextInstruction(hp3,hp4) and
  6284. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  6285. (taicpu(hp4).oper[0]^.typ = top_const) and
  6286. (
  6287. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  6288. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  6289. ) and
  6290. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  6291. GetNextInstruction(hp4,hp5) and
  6292. SkipAligns(hp5, hp5) and
  6293. (hp5.typ=ait_label) and
  6294. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  6295. begin
  6296. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6297. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6298. tai_label(hp3).labsym.DecRefs;
  6299. { If this isn't the only reference to the middle label, we can
  6300. still make a saving - only that the first jump and everything
  6301. that follows will remain. }
  6302. if (tai_label(hp3).labsym.getrefs = 0) then
  6303. begin
  6304. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6305. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  6306. else
  6307. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  6308. { remove jump, first label and second MOV (also catching any aligns) }
  6309. repeat
  6310. if not GetNextInstruction(hp2, hp3) then
  6311. InternalError(2021040810);
  6312. RemoveInstruction(hp2);
  6313. hp2 := hp3;
  6314. until hp2 = hp5;
  6315. { Don't decrement reference count before the removal loop
  6316. above, otherwise GetNextInstruction won't stop on the
  6317. the label }
  6318. tai_label(hp5).labsym.DecRefs;
  6319. end
  6320. else
  6321. begin
  6322. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6323. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  6324. else
  6325. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  6326. end;
  6327. taicpu(p).opcode:=A_SETcc;
  6328. taicpu(p).opsize:=S_B;
  6329. taicpu(p).is_jmp:=False;
  6330. if taicpu(hp1).opsize=S_B then
  6331. begin
  6332. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  6333. if taicpu(hp1).oper[1]^.typ = top_reg then
  6334. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  6335. RemoveInstruction(hp1);
  6336. end
  6337. else
  6338. begin
  6339. { Will be a register because the size can't be S_B otherwise }
  6340. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  6341. taicpu(p).loadreg(0, ThisReg);
  6342. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  6343. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  6344. begin
  6345. case taicpu(hp1).opsize of
  6346. S_W:
  6347. taicpu(hp1).opsize := S_BW;
  6348. S_L:
  6349. taicpu(hp1).opsize := S_BL;
  6350. {$ifdef x86_64}
  6351. S_Q:
  6352. begin
  6353. taicpu(hp1).opsize := S_BL;
  6354. { Change the destination register to 32-bit }
  6355. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  6356. end;
  6357. {$endif x86_64}
  6358. else
  6359. InternalError(2021040820);
  6360. end;
  6361. taicpu(hp1).opcode := A_MOVZX;
  6362. taicpu(hp1).loadreg(0, ThisReg);
  6363. end
  6364. else
  6365. begin
  6366. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  6367. { hp1 is already a MOV instruction with the correct register }
  6368. taicpu(hp1).loadconst(0, 0);
  6369. { Inserting it right before p will guarantee that the flags are also tracked }
  6370. asml.Remove(hp1);
  6371. asml.InsertBefore(hp1, p);
  6372. end;
  6373. end;
  6374. Result:=true;
  6375. exit;
  6376. end
  6377. end;
  6378. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  6379. var
  6380. hp1, hp2, hp3: tai;
  6381. SourceRef, TargetRef: TReference;
  6382. CurrentReg: TRegister;
  6383. begin
  6384. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  6385. if not UseAVX then
  6386. InternalError(2021100501);
  6387. Result := False;
  6388. { Look for the following to simplify:
  6389. vmovdqa/u x(mem1), %xmmreg
  6390. vmovdqa/u %xmmreg, y(mem2)
  6391. vmovdqa/u x+16(mem1), %xmmreg
  6392. vmovdqa/u %xmmreg, y+16(mem2)
  6393. Change to:
  6394. vmovdqa/u x(mem1), %ymmreg
  6395. vmovdqa/u %ymmreg, y(mem2)
  6396. vpxor %ymmreg, %ymmreg, %ymmreg
  6397. ( The VPXOR instruction is to zero the upper half, thus removing the
  6398. need to call the potentially expensive VZEROUPPER instruction. Other
  6399. peephole optimisations can remove VPXOR if it's unnecessary )
  6400. }
  6401. TransferUsedRegs(TmpUsedRegs);
  6402. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6403. { NOTE: In the optimisations below, if the references dictate that an
  6404. aligned move is possible (i.e. VMOVDQA), the existing instructions
  6405. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  6406. if (taicpu(p).opsize = S_XMM) and
  6407. MatchOpType(taicpu(p), top_ref, top_reg) and
  6408. GetNextInstruction(p, hp1) and
  6409. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6410. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  6411. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6412. begin
  6413. SourceRef := taicpu(p).oper[0]^.ref^;
  6414. TargetRef := taicpu(hp1).oper[1]^.ref^;
  6415. if GetNextInstruction(hp1, hp2) and
  6416. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6417. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  6418. begin
  6419. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  6420. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6421. Inc(SourceRef.offset, 16);
  6422. { Reuse the register in the first block move }
  6423. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  6424. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  6425. begin
  6426. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6427. Inc(TargetRef.offset, 16);
  6428. if GetNextInstruction(hp2, hp3) and
  6429. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6430. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6431. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6432. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6433. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6434. begin
  6435. { Update the register tracking to the new size }
  6436. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  6437. { Remember that the offsets are 16 ahead }
  6438. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6439. if not (
  6440. ((SourceRef.offset mod 32) = 16) and
  6441. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6442. ) then
  6443. taicpu(p).opcode := A_VMOVDQU;
  6444. taicpu(p).opsize := S_YMM;
  6445. taicpu(p).oper[1]^.reg := CurrentReg;
  6446. if not (
  6447. ((TargetRef.offset mod 32) = 16) and
  6448. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6449. ) then
  6450. taicpu(hp1).opcode := A_VMOVDQU;
  6451. taicpu(hp1).opsize := S_YMM;
  6452. taicpu(hp1).oper[0]^.reg := CurrentReg;
  6453. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  6454. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6455. if (pi_uses_ymm in current_procinfo.flags) then
  6456. RemoveInstruction(hp2)
  6457. else
  6458. begin
  6459. taicpu(hp2).opcode := A_VPXOR;
  6460. taicpu(hp2).opsize := S_YMM;
  6461. taicpu(hp2).loadreg(0, CurrentReg);
  6462. taicpu(hp2).loadreg(1, CurrentReg);
  6463. taicpu(hp2).loadreg(2, CurrentReg);
  6464. taicpu(hp2).ops := 3;
  6465. end;
  6466. RemoveInstruction(hp3);
  6467. Result := True;
  6468. Exit;
  6469. end;
  6470. end
  6471. else
  6472. begin
  6473. { See if the next references are 16 less rather than 16 greater }
  6474. Dec(SourceRef.offset, 32); { -16 the other way }
  6475. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  6476. begin
  6477. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6478. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  6479. if GetNextInstruction(hp2, hp3) and
  6480. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  6481. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6482. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6483. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6484. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6485. begin
  6486. { Update the register tracking to the new size }
  6487. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  6488. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  6489. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6490. if not(
  6491. ((SourceRef.offset mod 32) = 0) and
  6492. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6493. ) then
  6494. taicpu(hp2).opcode := A_VMOVDQU;
  6495. taicpu(hp2).opsize := S_YMM;
  6496. taicpu(hp2).oper[1]^.reg := CurrentReg;
  6497. if not (
  6498. ((TargetRef.offset mod 32) = 0) and
  6499. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6500. ) then
  6501. taicpu(hp3).opcode := A_VMOVDQU;
  6502. taicpu(hp3).opsize := S_YMM;
  6503. taicpu(hp3).oper[0]^.reg := CurrentReg;
  6504. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  6505. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6506. if (pi_uses_ymm in current_procinfo.flags) then
  6507. RemoveInstruction(hp1)
  6508. else
  6509. begin
  6510. taicpu(hp1).opcode := A_VPXOR;
  6511. taicpu(hp1).opsize := S_YMM;
  6512. taicpu(hp1).loadreg(0, CurrentReg);
  6513. taicpu(hp1).loadreg(1, CurrentReg);
  6514. taicpu(hp1).loadreg(2, CurrentReg);
  6515. taicpu(hp1).ops := 3;
  6516. Asml.Remove(hp1);
  6517. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  6518. end;
  6519. RemoveCurrentP(p, hp2);
  6520. Result := True;
  6521. Exit;
  6522. end;
  6523. end;
  6524. end;
  6525. end;
  6526. end;
  6527. end;
  6528. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  6529. var
  6530. hp2, hp3, first_assignment: tai;
  6531. IncCount, OperIdx: Integer;
  6532. OrigLabel: TAsmLabel;
  6533. begin
  6534. Count := 0;
  6535. Result := False;
  6536. first_assignment := nil;
  6537. if (LoopCount >= 20) then
  6538. begin
  6539. { Guard against infinite loops }
  6540. Exit;
  6541. end;
  6542. if (taicpu(p).oper[0]^.typ <> top_ref) or
  6543. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  6544. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  6545. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  6546. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  6547. Exit;
  6548. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  6549. {
  6550. change
  6551. jmp .L1
  6552. ...
  6553. .L1:
  6554. mov ##, ## ( multiple movs possible )
  6555. jmp/ret
  6556. into
  6557. mov ##, ##
  6558. jmp/ret
  6559. }
  6560. if not Assigned(hp1) then
  6561. begin
  6562. hp1 := GetLabelWithSym(OrigLabel);
  6563. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  6564. Exit;
  6565. end;
  6566. hp2 := hp1;
  6567. while Assigned(hp2) do
  6568. begin
  6569. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  6570. SkipLabels(hp2,hp2);
  6571. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  6572. Break;
  6573. case taicpu(hp2).opcode of
  6574. A_MOVSS:
  6575. begin
  6576. if taicpu(hp2).ops = 0 then
  6577. { Wrong MOVSS }
  6578. Break;
  6579. Inc(Count);
  6580. if Count >= 5 then
  6581. { Too many to be worthwhile }
  6582. Break;
  6583. GetNextInstruction(hp2, hp2);
  6584. Continue;
  6585. end;
  6586. A_MOV,
  6587. A_MOVD,
  6588. A_MOVQ,
  6589. A_MOVSX,
  6590. {$ifdef x86_64}
  6591. A_MOVSXD,
  6592. {$endif x86_64}
  6593. A_MOVZX,
  6594. A_MOVAPS,
  6595. A_MOVUPS,
  6596. A_MOVSD,
  6597. A_MOVAPD,
  6598. A_MOVUPD,
  6599. A_MOVDQA,
  6600. A_MOVDQU,
  6601. A_VMOVSS,
  6602. A_VMOVAPS,
  6603. A_VMOVUPS,
  6604. A_VMOVSD,
  6605. A_VMOVAPD,
  6606. A_VMOVUPD,
  6607. A_VMOVDQA,
  6608. A_VMOVDQU:
  6609. begin
  6610. Inc(Count);
  6611. if Count >= 5 then
  6612. { Too many to be worthwhile }
  6613. Break;
  6614. GetNextInstruction(hp2, hp2);
  6615. Continue;
  6616. end;
  6617. A_JMP:
  6618. begin
  6619. { Guard against infinite loops }
  6620. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  6621. Exit;
  6622. { Analyse this jump first in case it also duplicates assignments }
  6623. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  6624. begin
  6625. { Something did change! }
  6626. Result := True;
  6627. Inc(Count, IncCount);
  6628. if Count >= 5 then
  6629. begin
  6630. { Too many to be worthwhile }
  6631. Exit;
  6632. end;
  6633. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  6634. Break;
  6635. end;
  6636. Result := True;
  6637. Break;
  6638. end;
  6639. A_RET:
  6640. begin
  6641. Result := True;
  6642. Break;
  6643. end;
  6644. else
  6645. Break;
  6646. end;
  6647. end;
  6648. if Result then
  6649. begin
  6650. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  6651. if Count = 0 then
  6652. begin
  6653. Result := False;
  6654. Exit;
  6655. end;
  6656. hp3 := p;
  6657. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  6658. while True do
  6659. begin
  6660. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  6661. SkipLabels(hp1,hp1);
  6662. if (hp1.typ <> ait_instruction) then
  6663. InternalError(2021040720);
  6664. case taicpu(hp1).opcode of
  6665. A_JMP:
  6666. begin
  6667. { Change the original jump to the new destination }
  6668. OrigLabel.decrefs;
  6669. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  6670. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  6671. { Set p to the first duplicated assignment so it can get optimised if needs be }
  6672. if not Assigned(first_assignment) then
  6673. InternalError(2021040810)
  6674. else
  6675. p := first_assignment;
  6676. Exit;
  6677. end;
  6678. A_RET:
  6679. begin
  6680. { Now change the jump into a RET instruction }
  6681. ConvertJumpToRET(p, hp1);
  6682. { Set p to the first duplicated assignment so it can get optimised if needs be }
  6683. if not Assigned(first_assignment) then
  6684. InternalError(2021040811)
  6685. else
  6686. p := first_assignment;
  6687. Exit;
  6688. end;
  6689. else
  6690. begin
  6691. { Duplicate the MOV instruction }
  6692. hp3:=tai(hp1.getcopy);
  6693. if first_assignment = nil then
  6694. first_assignment := hp3;
  6695. asml.InsertBefore(hp3, p);
  6696. { Make sure the compiler knows about any final registers written here }
  6697. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  6698. with taicpu(hp3).oper[OperIdx]^ do
  6699. begin
  6700. case typ of
  6701. top_ref:
  6702. begin
  6703. if (ref^.base <> NR_NO) and
  6704. (getsupreg(ref^.base) <> RS_ESP) and
  6705. (getsupreg(ref^.base) <> RS_EBP)
  6706. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  6707. then
  6708. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  6709. if (ref^.index <> NR_NO) and
  6710. (getsupreg(ref^.index) <> RS_ESP) and
  6711. (getsupreg(ref^.index) <> RS_EBP)
  6712. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  6713. (ref^.index <> ref^.base) then
  6714. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  6715. end;
  6716. top_reg:
  6717. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  6718. else
  6719. ;
  6720. end;
  6721. end;
  6722. end;
  6723. end;
  6724. if not GetNextInstruction(hp1, hp1) then
  6725. { Should have dropped out earlier }
  6726. InternalError(2021040710);
  6727. end;
  6728. end;
  6729. end;
  6730. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  6731. var
  6732. hp2: tai;
  6733. X: Integer;
  6734. const
  6735. WriteOp: array[0..3] of set of TInsChange = (
  6736. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  6737. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  6738. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  6739. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  6740. RegWriteFlags: array[0..7] of set of TInsChange = (
  6741. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  6742. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  6743. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  6744. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  6745. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  6746. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  6747. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  6748. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  6749. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  6750. begin
  6751. { If we have something like:
  6752. cmp ###,%reg1
  6753. mov 0,%reg2
  6754. And no modified registers are shared, move the instruction to before
  6755. the comparison as this means it can be optimised without worrying
  6756. about the FLAGS register. (CMP/MOV is generated by
  6757. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  6758. As long as the second instruction doesn't use the flags or one of the
  6759. registers used by CMP or TEST (also check any references that use the
  6760. registers), then it can be moved prior to the comparison.
  6761. }
  6762. Result := False;
  6763. if (hp1.typ <> ait_instruction) or
  6764. taicpu(hp1).is_jmp or
  6765. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  6766. Exit;
  6767. { NOP is a pipeline fence, likely marking the beginning of the function
  6768. epilogue, so drop out. Similarly, drop out if POP or RET are
  6769. encountered }
  6770. if MatchInstruction(hp1, A_NOP, A_POP, []) then
  6771. Exit;
  6772. if (taicpu(hp1).opcode = A_MOVSS) and
  6773. (taicpu(hp1).ops = 0) then
  6774. { Wrong MOVSS }
  6775. Exit;
  6776. { Check for writes to specific registers first }
  6777. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  6778. for X := 0 to 7 do
  6779. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  6780. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  6781. Exit;
  6782. for X := 0 to taicpu(hp1).ops - 1 do
  6783. begin
  6784. { Check to see if this operand writes to something }
  6785. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  6786. { And matches something in the CMP/TEST instruction }
  6787. (
  6788. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  6789. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  6790. (
  6791. { If it's a register, make sure the register written to doesn't
  6792. appear in the cmp instruction as part of a reference }
  6793. (taicpu(hp1).oper[X]^.typ = top_reg) and
  6794. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  6795. )
  6796. ) then
  6797. Exit;
  6798. end;
  6799. { The instruction can be safely moved }
  6800. asml.Remove(hp1);
  6801. { Try to insert after the last instructions where the FLAGS register is not yet in use }
  6802. if not GetLastInstruction(p, hp2) then
  6803. asml.InsertBefore(hp1, p)
  6804. else
  6805. asml.InsertAfter(hp1, hp2);
  6806. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  6807. for X := 0 to taicpu(hp1).ops - 1 do
  6808. case taicpu(hp1).oper[X]^.typ of
  6809. top_reg:
  6810. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  6811. top_ref:
  6812. begin
  6813. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  6814. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  6815. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  6816. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  6817. end;
  6818. else
  6819. ;
  6820. end;
  6821. if taicpu(hp1).opcode = A_LEA then
  6822. { The flags will be overwritten by the CMP/TEST instruction }
  6823. ConvertLEA(taicpu(hp1));
  6824. Result := True;
  6825. end;
  6826. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  6827. function IsXCHGAcceptable: Boolean; inline;
  6828. begin
  6829. { Always accept if optimising for size }
  6830. Result := (cs_opt_size in current_settings.optimizerswitches) or
  6831. (
  6832. {$ifdef x86_64}
  6833. { XCHG takes 3 cycles on AMD Athlon64 }
  6834. (current_settings.optimizecputype >= cpu_core_i)
  6835. {$else x86_64}
  6836. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  6837. than 3, so it becomes a saving compared to three MOVs with two of
  6838. them able to execute simultaneously. [Kit] }
  6839. (current_settings.optimizecputype >= cpu_PentiumM)
  6840. {$endif x86_64}
  6841. );
  6842. end;
  6843. var
  6844. NewRef: TReference;
  6845. hp1, hp2, hp3, hp4: Tai;
  6846. {$ifndef x86_64}
  6847. OperIdx: Integer;
  6848. {$endif x86_64}
  6849. NewInstr : Taicpu;
  6850. NewAligh : Tai_align;
  6851. DestLabel: TAsmLabel;
  6852. function TryMovArith2Lea(InputInstr: tai): Boolean;
  6853. var
  6854. NextInstr: tai;
  6855. begin
  6856. Result := False;
  6857. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  6858. if not GetNextInstruction(InputInstr, NextInstr) or
  6859. (
  6860. { The FLAGS register isn't always tracked properly, so do not
  6861. perform this optimisation if a conditional statement follows }
  6862. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  6863. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  6864. ) then
  6865. begin
  6866. reference_reset(NewRef, 1, []);
  6867. NewRef.base := taicpu(p).oper[0]^.reg;
  6868. NewRef.scalefactor := 1;
  6869. if taicpu(InputInstr).opcode = A_ADD then
  6870. begin
  6871. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  6872. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  6873. end
  6874. else
  6875. begin
  6876. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  6877. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  6878. end;
  6879. taicpu(p).opcode := A_LEA;
  6880. taicpu(p).loadref(0, NewRef);
  6881. RemoveInstruction(InputInstr);
  6882. Result := True;
  6883. end;
  6884. end;
  6885. begin
  6886. Result:=false;
  6887. { This optimisation adds an instruction, so only do it for speed }
  6888. if not (cs_opt_size in current_settings.optimizerswitches) and
  6889. MatchOpType(taicpu(p), top_const, top_reg) and
  6890. (taicpu(p).oper[0]^.val = 0) then
  6891. begin
  6892. { To avoid compiler warning }
  6893. DestLabel := nil;
  6894. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  6895. InternalError(2021040750);
  6896. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  6897. Exit;
  6898. case hp1.typ of
  6899. ait_label:
  6900. begin
  6901. { Change:
  6902. mov $0,%reg mov $0,%reg
  6903. @Lbl1: @Lbl1:
  6904. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  6905. je @Lbl2 jne @Lbl2
  6906. To: To:
  6907. mov $0,%reg mov $0,%reg
  6908. jmp @Lbl2 jmp @Lbl3
  6909. (align) (align)
  6910. @Lbl1: @Lbl1:
  6911. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  6912. je @Lbl2 je @Lbl2
  6913. @Lbl3: <-- Only if label exists
  6914. (Not if it's optimised for size)
  6915. }
  6916. if not GetNextInstruction(hp1, hp2) then
  6917. Exit;
  6918. if not (cs_opt_size in current_settings.optimizerswitches) and
  6919. (hp2.typ = ait_instruction) and
  6920. (
  6921. { Register sizes must exactly match }
  6922. (
  6923. (taicpu(hp2).opcode = A_CMP) and
  6924. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  6925. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  6926. ) or (
  6927. (taicpu(hp2).opcode = A_TEST) and
  6928. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  6929. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  6930. )
  6931. ) and GetNextInstruction(hp2, hp3) and
  6932. (hp3.typ = ait_instruction) and
  6933. (taicpu(hp3).opcode = A_JCC) and
  6934. (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
  6935. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  6936. begin
  6937. { Check condition of jump }
  6938. { Always true? }
  6939. if condition_in(C_E, taicpu(hp3).condition) then
  6940. begin
  6941. { Copy label symbol and obtain matching label entry for the
  6942. conditional jump, as this will be our destination}
  6943. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  6944. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  6945. Result := True;
  6946. end
  6947. { Always false? }
  6948. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  6949. begin
  6950. { This is only worth it if there's a jump to take }
  6951. case hp2.typ of
  6952. ait_instruction:
  6953. begin
  6954. if taicpu(hp2).opcode = A_JMP then
  6955. begin
  6956. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  6957. { An unconditional jump follows the conditional jump which will always be false,
  6958. so use this jump's destination for the new jump }
  6959. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  6960. Result := True;
  6961. end
  6962. else if taicpu(hp2).opcode = A_JCC then
  6963. begin
  6964. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  6965. if condition_in(C_E, taicpu(hp2).condition) then
  6966. begin
  6967. { A second conditional jump follows the conditional jump which will always be false,
  6968. while the second jump is always True, so use this jump's destination for the new jump }
  6969. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  6970. Result := True;
  6971. end;
  6972. { Don't risk it if the jump isn't always true (Result remains False) }
  6973. end;
  6974. end;
  6975. else
  6976. { If anything else don't optimise };
  6977. end;
  6978. end;
  6979. if Result then
  6980. begin
  6981. { Just so we have something to insert as a paremeter}
  6982. reference_reset(NewRef, 1, []);
  6983. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  6984. { Now actually load the correct parameter }
  6985. NewInstr.loadsymbol(0, DestLabel, 0);
  6986. { Get instruction before original label (may not be p under -O3) }
  6987. if not GetLastInstruction(hp1, hp2) then
  6988. { Shouldn't fail here }
  6989. InternalError(2021040701);
  6990. DestLabel.increfs;
  6991. AsmL.InsertAfter(NewInstr, hp2);
  6992. { Add new alignment field }
  6993. (* AsmL.InsertAfter(
  6994. cai_align.create_max(
  6995. current_settings.alignment.jumpalign,
  6996. current_settings.alignment.jumpalignskipmax
  6997. ),
  6998. NewInstr
  6999. ); *)
  7000. end;
  7001. Exit;
  7002. end;
  7003. end;
  7004. else
  7005. ;
  7006. end;
  7007. end;
  7008. if not GetNextInstruction(p, hp1) then
  7009. Exit;
  7010. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  7011. and DoMovCmpMemOpt(p, hp1, True) then
  7012. begin
  7013. Result := True;
  7014. Exit;
  7015. end
  7016. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  7017. begin
  7018. { Sometimes the MOVs that OptPass2JMP produces can be improved
  7019. further, but we can't just put this jump optimisation in pass 1
  7020. because it tends to perform worse when conditional jumps are
  7021. nearby (e.g. when converting CMOV instructions). [Kit] }
  7022. if OptPass2JMP(hp1) then
  7023. { call OptPass1MOV once to potentially merge any MOVs that were created }
  7024. Result := OptPass1MOV(p)
  7025. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  7026. returned True and the instruction is still a MOV, thus checking
  7027. the optimisations below }
  7028. { If OptPass2JMP returned False, no optimisations were done to
  7029. the jump and there are no further optimisations that can be done
  7030. to the MOV instruction on this pass }
  7031. end
  7032. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7033. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  7034. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  7035. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7036. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7037. begin
  7038. { Change:
  7039. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  7040. addl/q $x,%reg2 subl/q $x,%reg2
  7041. To:
  7042. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  7043. }
  7044. if (taicpu(hp1).oper[0]^.typ = top_const) and
  7045. { be lazy, checking separately for sub would be slightly better }
  7046. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  7047. begin
  7048. TransferUsedRegs(TmpUsedRegs);
  7049. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7050. if TryMovArith2Lea(hp1) then
  7051. begin
  7052. Result := True;
  7053. Exit;
  7054. end
  7055. end
  7056. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  7057. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  7058. { Same as above, but also adds or subtracts to %reg2 in between.
  7059. It's still valid as long as the flags aren't in use }
  7060. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  7061. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7062. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  7063. { be lazy, checking separately for sub would be slightly better }
  7064. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  7065. begin
  7066. TransferUsedRegs(TmpUsedRegs);
  7067. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7068. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7069. if TryMovArith2Lea(hp2) then
  7070. begin
  7071. Result := True;
  7072. Exit;
  7073. end;
  7074. end;
  7075. end
  7076. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7077. {$ifdef x86_64}
  7078. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  7079. {$else x86_64}
  7080. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  7081. {$endif x86_64}
  7082. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7083. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  7084. { mov reg1, reg2 mov reg1, reg2
  7085. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  7086. begin
  7087. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7088. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  7089. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  7090. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  7091. TransferUsedRegs(TmpUsedRegs);
  7092. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7093. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  7094. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  7095. then
  7096. begin
  7097. RemoveCurrentP(p, hp1);
  7098. Result:=true;
  7099. end;
  7100. exit;
  7101. end
  7102. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7103. IsXCHGAcceptable and
  7104. { XCHG doesn't support 8-byte registers }
  7105. (taicpu(p).opsize <> S_B) and
  7106. MatchInstruction(hp1, A_MOV, []) and
  7107. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7108. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  7109. GetNextInstruction(hp1, hp2) and
  7110. MatchInstruction(hp2, A_MOV, []) and
  7111. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  7112. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7113. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  7114. begin
  7115. { mov %reg1,%reg2
  7116. mov %reg3,%reg1 -> xchg %reg3,%reg1
  7117. mov %reg2,%reg3
  7118. (%reg2 not used afterwards)
  7119. Note that xchg takes 3 cycles to execute, and generally mov's take
  7120. only one cycle apiece, but the first two mov's can be executed in
  7121. parallel, only taking 2 cycles overall. Older processors should
  7122. therefore only optimise for size. [Kit]
  7123. }
  7124. TransferUsedRegs(TmpUsedRegs);
  7125. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7126. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7127. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  7128. begin
  7129. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  7130. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  7131. taicpu(hp1).opcode := A_XCHG;
  7132. RemoveCurrentP(p, hp1);
  7133. RemoveInstruction(hp2);
  7134. Result := True;
  7135. Exit;
  7136. end;
  7137. end
  7138. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7139. MatchInstruction(hp1, A_SAR, []) then
  7140. begin
  7141. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  7142. begin
  7143. { the use of %edx also covers the opsize being S_L }
  7144. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  7145. begin
  7146. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  7147. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  7148. (taicpu(p).oper[1]^.reg = NR_EDX) then
  7149. begin
  7150. { Change:
  7151. movl %eax,%edx
  7152. sarl $31,%edx
  7153. To:
  7154. cltd
  7155. }
  7156. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  7157. RemoveInstruction(hp1);
  7158. taicpu(p).opcode := A_CDQ;
  7159. taicpu(p).opsize := S_NO;
  7160. taicpu(p).clearop(1);
  7161. taicpu(p).clearop(0);
  7162. taicpu(p).ops:=0;
  7163. Result := True;
  7164. end
  7165. else if (cs_opt_size in current_settings.optimizerswitches) and
  7166. (taicpu(p).oper[0]^.reg = NR_EDX) and
  7167. (taicpu(p).oper[1]^.reg = NR_EAX) then
  7168. begin
  7169. { Change:
  7170. movl %edx,%eax
  7171. sarl $31,%edx
  7172. To:
  7173. movl %edx,%eax
  7174. cltd
  7175. Note that this creates a dependency between the two instructions,
  7176. so only perform if optimising for size.
  7177. }
  7178. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  7179. taicpu(hp1).opcode := A_CDQ;
  7180. taicpu(hp1).opsize := S_NO;
  7181. taicpu(hp1).clearop(1);
  7182. taicpu(hp1).clearop(0);
  7183. taicpu(hp1).ops:=0;
  7184. end;
  7185. {$ifndef x86_64}
  7186. end
  7187. { Don't bother if CMOV is supported, because a more optimal
  7188. sequence would have been generated for the Abs() intrinsic }
  7189. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  7190. { the use of %eax also covers the opsize being S_L }
  7191. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  7192. (taicpu(p).oper[0]^.reg = NR_EAX) and
  7193. (taicpu(p).oper[1]^.reg = NR_EDX) and
  7194. GetNextInstruction(hp1, hp2) and
  7195. MatchInstruction(hp2, A_XOR, [S_L]) and
  7196. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  7197. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  7198. GetNextInstruction(hp2, hp3) and
  7199. MatchInstruction(hp3, A_SUB, [S_L]) and
  7200. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  7201. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  7202. begin
  7203. { Change:
  7204. movl %eax,%edx
  7205. sarl $31,%eax
  7206. xorl %eax,%edx
  7207. subl %eax,%edx
  7208. (Instruction that uses %edx)
  7209. (%eax deallocated)
  7210. (%edx deallocated)
  7211. To:
  7212. cltd
  7213. xorl %edx,%eax <-- Note the registers have swapped
  7214. subl %edx,%eax
  7215. (Instruction that uses %eax) <-- %eax rather than %edx
  7216. }
  7217. TransferUsedRegs(TmpUsedRegs);
  7218. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7219. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7220. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7221. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  7222. begin
  7223. if GetNextInstruction(hp3, hp4) and
  7224. not RegModifiedByInstruction(NR_EDX, hp4) and
  7225. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  7226. begin
  7227. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  7228. taicpu(p).opcode := A_CDQ;
  7229. taicpu(p).clearop(1);
  7230. taicpu(p).clearop(0);
  7231. taicpu(p).ops:=0;
  7232. RemoveInstruction(hp1);
  7233. taicpu(hp2).loadreg(0, NR_EDX);
  7234. taicpu(hp2).loadreg(1, NR_EAX);
  7235. taicpu(hp3).loadreg(0, NR_EDX);
  7236. taicpu(hp3).loadreg(1, NR_EAX);
  7237. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  7238. { Convert references in the following instruction (hp4) from %edx to %eax }
  7239. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  7240. with taicpu(hp4).oper[OperIdx]^ do
  7241. case typ of
  7242. top_reg:
  7243. if getsupreg(reg) = RS_EDX then
  7244. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7245. top_ref:
  7246. begin
  7247. if getsupreg(reg) = RS_EDX then
  7248. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7249. if getsupreg(reg) = RS_EDX then
  7250. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7251. end;
  7252. else
  7253. ;
  7254. end;
  7255. end;
  7256. end;
  7257. {$else x86_64}
  7258. end;
  7259. end
  7260. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  7261. { the use of %rdx also covers the opsize being S_Q }
  7262. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  7263. begin
  7264. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  7265. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  7266. (taicpu(p).oper[1]^.reg = NR_RDX) then
  7267. begin
  7268. { Change:
  7269. movq %rax,%rdx
  7270. sarq $63,%rdx
  7271. To:
  7272. cqto
  7273. }
  7274. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  7275. RemoveInstruction(hp1);
  7276. taicpu(p).opcode := A_CQO;
  7277. taicpu(p).opsize := S_NO;
  7278. taicpu(p).clearop(1);
  7279. taicpu(p).clearop(0);
  7280. taicpu(p).ops:=0;
  7281. Result := True;
  7282. end
  7283. else if (cs_opt_size in current_settings.optimizerswitches) and
  7284. (taicpu(p).oper[0]^.reg = NR_RDX) and
  7285. (taicpu(p).oper[1]^.reg = NR_RAX) then
  7286. begin
  7287. { Change:
  7288. movq %rdx,%rax
  7289. sarq $63,%rdx
  7290. To:
  7291. movq %rdx,%rax
  7292. cqto
  7293. Note that this creates a dependency between the two instructions,
  7294. so only perform if optimising for size.
  7295. }
  7296. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  7297. taicpu(hp1).opcode := A_CQO;
  7298. taicpu(hp1).opsize := S_NO;
  7299. taicpu(hp1).clearop(1);
  7300. taicpu(hp1).clearop(0);
  7301. taicpu(hp1).ops:=0;
  7302. {$endif x86_64}
  7303. end;
  7304. end;
  7305. end
  7306. else if MatchInstruction(hp1, A_MOV, []) and
  7307. (taicpu(hp1).oper[1]^.typ = top_reg) then
  7308. { Though "GetNextInstruction" could be factored out, along with
  7309. the instructions that depend on hp2, it is an expensive call that
  7310. should be delayed for as long as possible, hence we do cheaper
  7311. checks first that are likely to be False. [Kit] }
  7312. begin
  7313. if (
  7314. (
  7315. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  7316. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  7317. (
  7318. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7319. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  7320. )
  7321. ) or
  7322. (
  7323. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  7324. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  7325. (
  7326. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7327. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  7328. )
  7329. )
  7330. ) and
  7331. GetNextInstruction(hp1, hp2) and
  7332. MatchInstruction(hp2, A_SAR, []) and
  7333. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  7334. begin
  7335. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  7336. begin
  7337. { Change:
  7338. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  7339. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  7340. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  7341. To:
  7342. movl r/m,%eax <- Note the change in register
  7343. cltd
  7344. }
  7345. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  7346. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  7347. taicpu(p).loadreg(1, NR_EAX);
  7348. taicpu(hp1).opcode := A_CDQ;
  7349. taicpu(hp1).clearop(1);
  7350. taicpu(hp1).clearop(0);
  7351. taicpu(hp1).ops:=0;
  7352. RemoveInstruction(hp2);
  7353. (*
  7354. {$ifdef x86_64}
  7355. end
  7356. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  7357. { This code sequence does not get generated - however it might become useful
  7358. if and when 128-bit signed integer types make an appearance, so the code
  7359. is kept here for when it is eventually needed. [Kit] }
  7360. (
  7361. (
  7362. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  7363. (
  7364. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7365. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  7366. )
  7367. ) or
  7368. (
  7369. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  7370. (
  7371. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7372. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  7373. )
  7374. )
  7375. ) and
  7376. GetNextInstruction(hp1, hp2) and
  7377. MatchInstruction(hp2, A_SAR, [S_Q]) and
  7378. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  7379. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  7380. begin
  7381. { Change:
  7382. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  7383. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  7384. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  7385. To:
  7386. movq r/m,%rax <- Note the change in register
  7387. cqto
  7388. }
  7389. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  7390. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  7391. taicpu(p).loadreg(1, NR_RAX);
  7392. taicpu(hp1).opcode := A_CQO;
  7393. taicpu(hp1).clearop(1);
  7394. taicpu(hp1).clearop(0);
  7395. taicpu(hp1).ops:=0;
  7396. RemoveInstruction(hp2);
  7397. {$endif x86_64}
  7398. *)
  7399. end;
  7400. end;
  7401. {$ifdef x86_64}
  7402. end
  7403. else if (taicpu(p).opsize = S_L) and
  7404. (taicpu(p).oper[1]^.typ = top_reg) and
  7405. (
  7406. MatchInstruction(hp1, A_MOV,[]) and
  7407. (taicpu(hp1).opsize = S_L) and
  7408. (taicpu(hp1).oper[1]^.typ = top_reg)
  7409. ) and (
  7410. GetNextInstruction(hp1, hp2) and
  7411. (tai(hp2).typ=ait_instruction) and
  7412. (taicpu(hp2).opsize = S_Q) and
  7413. (
  7414. (
  7415. MatchInstruction(hp2, A_ADD,[]) and
  7416. (taicpu(hp2).opsize = S_Q) and
  7417. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7418. (
  7419. (
  7420. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7421. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7422. ) or (
  7423. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7424. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7425. )
  7426. )
  7427. ) or (
  7428. MatchInstruction(hp2, A_LEA,[]) and
  7429. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  7430. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  7431. (
  7432. (
  7433. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7434. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7435. ) or (
  7436. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7437. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  7438. )
  7439. ) and (
  7440. (
  7441. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7442. ) or (
  7443. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7444. )
  7445. )
  7446. )
  7447. )
  7448. ) and (
  7449. GetNextInstruction(hp2, hp3) and
  7450. MatchInstruction(hp3, A_SHR,[]) and
  7451. (taicpu(hp3).opsize = S_Q) and
  7452. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7453. (taicpu(hp3).oper[0]^.val = 1) and
  7454. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  7455. ) then
  7456. begin
  7457. { Change movl x, reg1d movl x, reg1d
  7458. movl y, reg2d movl y, reg2d
  7459. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  7460. shrq $1, reg1q shrq $1, reg1q
  7461. ( reg1d and reg2d can be switched around in the first two instructions )
  7462. To movl x, reg1d
  7463. addl y, reg1d
  7464. rcrl $1, reg1d
  7465. This corresponds to the common expression (x + y) shr 1, where
  7466. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  7467. smaller code, but won't account for x + y causing an overflow). [Kit]
  7468. }
  7469. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  7470. { Change first MOV command to have the same register as the final output }
  7471. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  7472. else
  7473. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  7474. { Change second MOV command to an ADD command. This is easier than
  7475. converting the existing command because it means we don't have to
  7476. touch 'y', which might be a complicated reference, and also the
  7477. fact that the third command might either be ADD or LEA. [Kit] }
  7478. taicpu(hp1).opcode := A_ADD;
  7479. { Delete old ADD/LEA instruction }
  7480. RemoveInstruction(hp2);
  7481. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  7482. taicpu(hp3).opcode := A_RCR;
  7483. taicpu(hp3).changeopsize(S_L);
  7484. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  7485. {$endif x86_64}
  7486. end;
  7487. end;
  7488. {$push}
  7489. {$q-}{$r-}
  7490. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  7491. var
  7492. ThisReg: TRegister;
  7493. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  7494. TargetSubReg: TSubRegister;
  7495. hp1, hp2: tai;
  7496. RegInUse, RegChanged, p_removed: Boolean;
  7497. { Store list of found instructions so we don't have to call
  7498. GetNextInstructionUsingReg multiple times }
  7499. InstrList: array of taicpu;
  7500. InstrMax, Index: Integer;
  7501. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  7502. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  7503. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  7504. WorkingValue: TCgInt;
  7505. PreMessage: string;
  7506. { Data flow analysis }
  7507. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  7508. BitwiseOnly, OrXorUsed,
  7509. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  7510. function CheckOverflowConditions: Boolean;
  7511. begin
  7512. Result := True;
  7513. if (TestValSignedMax > SignedUpperLimit) then
  7514. UpperSignedOverflow := True;
  7515. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  7516. LowerSignedOverflow := True;
  7517. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  7518. LowerUnsignedOverflow := True;
  7519. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  7520. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  7521. begin
  7522. { Absolute overflow }
  7523. Result := False;
  7524. Exit;
  7525. end;
  7526. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  7527. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  7528. ShiftDownOverflow := True;
  7529. if (TestValMin < 0) or (TestValMax < 0) then
  7530. begin
  7531. LowerUnsignedOverflow := True;
  7532. UpperUnsignedOverflow := True;
  7533. end;
  7534. end;
  7535. function AdjustInitialLoad: Boolean;
  7536. begin
  7537. Result := False;
  7538. if not p_removed then
  7539. begin
  7540. if TargetSize = MinSize then
  7541. begin
  7542. { Convert the input MOVZX to a MOV }
  7543. if (taicpu(p).oper[0]^.typ = top_reg) and
  7544. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  7545. begin
  7546. { Or remove it completely! }
  7547. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  7548. RemoveCurrentP(p);
  7549. p_removed := True;
  7550. end
  7551. else
  7552. begin
  7553. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  7554. taicpu(p).opcode := A_MOV;
  7555. taicpu(p).oper[1]^.reg := ThisReg;
  7556. taicpu(p).opsize := TargetSize;
  7557. end;
  7558. Result := True;
  7559. end
  7560. else if TargetSize <> MaxSize then
  7561. begin
  7562. case MaxSize of
  7563. S_L:
  7564. if TargetSize = S_W then
  7565. begin
  7566. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  7567. taicpu(p).opsize := S_BW;
  7568. taicpu(p).oper[1]^.reg := ThisReg;
  7569. Result := True;
  7570. end
  7571. else
  7572. InternalError(2020112341);
  7573. S_W:
  7574. if TargetSize = S_L then
  7575. begin
  7576. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  7577. taicpu(p).opsize := S_BL;
  7578. taicpu(p).oper[1]^.reg := ThisReg;
  7579. Result := True;
  7580. end
  7581. else
  7582. InternalError(2020112342);
  7583. else
  7584. ;
  7585. end;
  7586. end;
  7587. end;
  7588. end;
  7589. procedure AdjustFinalLoad;
  7590. begin
  7591. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  7592. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  7593. begin
  7594. { Convert the output MOVZX to a MOV }
  7595. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7596. begin
  7597. { Or remove it completely! }
  7598. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  7599. { Be careful; if p = hp1 and p was also removed, p
  7600. will become a dangling pointer }
  7601. if p = hp1 then
  7602. begin
  7603. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  7604. p_removed := True;
  7605. end
  7606. else
  7607. RemoveInstruction(hp1);
  7608. end
  7609. else
  7610. begin
  7611. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  7612. taicpu(hp1).opcode := A_MOV;
  7613. taicpu(hp1).oper[0]^.reg := ThisReg;
  7614. taicpu(hp1).opsize := TargetSize;
  7615. end;
  7616. end
  7617. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  7618. begin
  7619. { Need to change the size of the output }
  7620. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  7621. taicpu(hp1).oper[0]^.reg := ThisReg;
  7622. taicpu(hp1).opsize := S_BL;
  7623. end;
  7624. end;
  7625. function CompressInstructions: Boolean;
  7626. var
  7627. LocalIndex: Integer;
  7628. begin
  7629. Result := False;
  7630. { The objective here is to try to find a combination that
  7631. removes one of the MOV/Z instructions. }
  7632. if (
  7633. (taicpu(p).oper[0]^.typ <> top_reg) or
  7634. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  7635. ) and
  7636. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7637. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7638. begin
  7639. { Make a preference to remove the second MOVZX instruction }
  7640. case taicpu(hp1).opsize of
  7641. S_BL, S_WL:
  7642. begin
  7643. TargetSize := S_L;
  7644. TargetSubReg := R_SUBD;
  7645. end;
  7646. S_BW:
  7647. begin
  7648. TargetSize := S_W;
  7649. TargetSubReg := R_SUBW;
  7650. end;
  7651. else
  7652. InternalError(2020112302);
  7653. end;
  7654. end
  7655. else
  7656. begin
  7657. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  7658. begin
  7659. { Exceeded lower bound but not upper bound }
  7660. TargetSize := MaxSize;
  7661. end
  7662. else if not LowerUnsignedOverflow then
  7663. begin
  7664. { Size didn't exceed lower bound }
  7665. TargetSize := MinSize;
  7666. end
  7667. else
  7668. Exit;
  7669. end;
  7670. case TargetSize of
  7671. S_B:
  7672. TargetSubReg := R_SUBL;
  7673. S_W:
  7674. TargetSubReg := R_SUBW;
  7675. S_L:
  7676. TargetSubReg := R_SUBD;
  7677. else
  7678. InternalError(2020112350);
  7679. end;
  7680. { Update the register to its new size }
  7681. setsubreg(ThisReg, TargetSubReg);
  7682. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7683. begin
  7684. { Check to see if the active register is used afterwards;
  7685. if not, we can change it and make a saving. }
  7686. RegInUse := False;
  7687. TransferUsedRegs(TmpUsedRegs);
  7688. { The target register may be marked as in use to cross
  7689. a jump to a distant label, so exclude it }
  7690. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  7691. hp2 := p;
  7692. repeat
  7693. { Explicitly check for the excluded register (don't include the first
  7694. instruction as it may be reading from here }
  7695. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  7696. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  7697. begin
  7698. RegInUse := True;
  7699. Break;
  7700. end;
  7701. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  7702. if not GetNextInstruction(hp2, hp2) then
  7703. InternalError(2020112340);
  7704. until (hp2 = hp1);
  7705. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  7706. { We might still be able to get away with this }
  7707. RegInUse := not
  7708. (
  7709. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  7710. (hp2.typ = ait_instruction) and
  7711. (
  7712. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  7713. instruction that doesn't actually contain ThisReg }
  7714. (cs_opt_level3 in current_settings.optimizerswitches) or
  7715. RegInInstruction(ThisReg, hp2)
  7716. ) and
  7717. RegLoadedWithNewValue(ThisReg, hp2)
  7718. );
  7719. if not RegInUse then
  7720. begin
  7721. { Force the register size to the same as this instruction so it can be removed}
  7722. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  7723. begin
  7724. TargetSize := S_L;
  7725. TargetSubReg := R_SUBD;
  7726. end
  7727. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  7728. begin
  7729. TargetSize := S_W;
  7730. TargetSubReg := R_SUBW;
  7731. end;
  7732. ThisReg := taicpu(hp1).oper[1]^.reg;
  7733. setsubreg(ThisReg, TargetSubReg);
  7734. RegChanged := True;
  7735. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  7736. TransferUsedRegs(TmpUsedRegs);
  7737. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  7738. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  7739. if p = hp1 then
  7740. begin
  7741. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  7742. p_removed := True;
  7743. end
  7744. else
  7745. RemoveInstruction(hp1);
  7746. { Instruction will become "mov %reg,%reg" }
  7747. if not p_removed and (taicpu(p).opcode = A_MOV) and
  7748. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  7749. begin
  7750. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  7751. RemoveCurrentP(p);
  7752. p_removed := True;
  7753. end
  7754. else
  7755. taicpu(p).oper[1]^.reg := ThisReg;
  7756. Result := True;
  7757. end
  7758. else
  7759. begin
  7760. if TargetSize <> MaxSize then
  7761. begin
  7762. { Since the register is in use, we have to force it to
  7763. MaxSize otherwise part of it may become undefined later on }
  7764. TargetSize := MaxSize;
  7765. case TargetSize of
  7766. S_B:
  7767. TargetSubReg := R_SUBL;
  7768. S_W:
  7769. TargetSubReg := R_SUBW;
  7770. S_L:
  7771. TargetSubReg := R_SUBD;
  7772. else
  7773. InternalError(2020112351);
  7774. end;
  7775. setsubreg(ThisReg, TargetSubReg);
  7776. end;
  7777. AdjustFinalLoad;
  7778. end;
  7779. end
  7780. else
  7781. AdjustFinalLoad;
  7782. Result := AdjustInitialLoad or Result;
  7783. { Now go through every instruction we found and change the
  7784. size. If TargetSize = MaxSize, then almost no changes are
  7785. needed and Result can remain False if it hasn't been set
  7786. yet.
  7787. If RegChanged is True, then the register requires changing
  7788. and so the point about TargetSize = MaxSize doesn't apply. }
  7789. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  7790. begin
  7791. for LocalIndex := 0 to InstrMax do
  7792. begin
  7793. { If p_removed is true, then the original MOV/Z was removed
  7794. and removing the AND instruction may not be safe if it
  7795. appears first }
  7796. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  7797. InternalError(2020112310);
  7798. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  7799. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  7800. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  7801. InstrList[LocalIndex].opsize := TargetSize;
  7802. end;
  7803. Result := True;
  7804. end;
  7805. end;
  7806. begin
  7807. Result := False;
  7808. p_removed := False;
  7809. ThisReg := taicpu(p).oper[1]^.reg;
  7810. { Check for:
  7811. movs/z ###,%ecx (or %cx or %rcx)
  7812. ...
  7813. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  7814. (dealloc %ecx)
  7815. Change to:
  7816. mov ###,%cl (if ### = %cl, then remove completely)
  7817. ...
  7818. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  7819. }
  7820. if (getsupreg(ThisReg) = RS_ECX) and
  7821. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  7822. (hp1.typ = ait_instruction) and
  7823. (
  7824. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  7825. instruction that doesn't actually contain ECX }
  7826. (cs_opt_level3 in current_settings.optimizerswitches) or
  7827. RegInInstruction(NR_ECX, hp1) or
  7828. (
  7829. { It's common for the shift/rotate's read/write register to be
  7830. initialised in between, so under -O2 and under, search ahead
  7831. one more instruction
  7832. }
  7833. GetNextInstruction(hp1, hp1) and
  7834. (hp1.typ = ait_instruction) and
  7835. RegInInstruction(NR_ECX, hp1)
  7836. )
  7837. ) and
  7838. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  7839. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  7840. begin
  7841. TransferUsedRegs(TmpUsedRegs);
  7842. hp2 := p;
  7843. repeat
  7844. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7845. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  7846. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  7847. begin
  7848. case taicpu(p).opsize of
  7849. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  7850. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  7851. begin
  7852. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  7853. RemoveCurrentP(p);
  7854. end
  7855. else
  7856. begin
  7857. taicpu(p).opcode := A_MOV;
  7858. taicpu(p).opsize := S_B;
  7859. taicpu(p).oper[1]^.reg := NR_CL;
  7860. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  7861. end;
  7862. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  7863. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  7864. begin
  7865. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  7866. RemoveCurrentP(p);
  7867. end
  7868. else
  7869. begin
  7870. taicpu(p).opcode := A_MOV;
  7871. taicpu(p).opsize := S_W;
  7872. taicpu(p).oper[1]^.reg := NR_CX;
  7873. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  7874. end;
  7875. {$ifdef x86_64}
  7876. S_LQ:
  7877. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  7878. begin
  7879. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  7880. RemoveCurrentP(p);
  7881. end
  7882. else
  7883. begin
  7884. taicpu(p).opcode := A_MOV;
  7885. taicpu(p).opsize := S_L;
  7886. taicpu(p).oper[1]^.reg := NR_ECX;
  7887. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  7888. end;
  7889. {$endif x86_64}
  7890. else
  7891. InternalError(2021120401);
  7892. end;
  7893. Result := True;
  7894. Exit;
  7895. end;
  7896. end;
  7897. { This is anything but quick! }
  7898. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  7899. Exit;
  7900. SetLength(InstrList, 0);
  7901. InstrMax := -1;
  7902. case taicpu(p).opsize of
  7903. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  7904. begin
  7905. {$if defined(i386) or defined(i8086)}
  7906. { If the target size is 8-bit, make sure we can actually encode it }
  7907. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  7908. Exit;
  7909. {$endif i386 or i8086}
  7910. LowerLimit := $FF;
  7911. SignedLowerLimit := $7F;
  7912. SignedLowerLimitBottom := -128;
  7913. MinSize := S_B;
  7914. if taicpu(p).opsize = S_BW then
  7915. begin
  7916. MaxSize := S_W;
  7917. UpperLimit := $FFFF;
  7918. SignedUpperLimit := $7FFF;
  7919. SignedUpperLimitBottom := -32768;
  7920. end
  7921. else
  7922. begin
  7923. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  7924. MaxSize := S_L;
  7925. UpperLimit := $FFFFFFFF;
  7926. SignedUpperLimit := $7FFFFFFF;
  7927. SignedUpperLimitBottom := -2147483648;
  7928. end;
  7929. end;
  7930. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  7931. begin
  7932. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  7933. LowerLimit := $FFFF;
  7934. SignedLowerLimit := $7FFF;
  7935. SignedLowerLimitBottom := -32768;
  7936. UpperLimit := $FFFFFFFF;
  7937. SignedUpperLimit := $7FFFFFFF;
  7938. SignedUpperLimitBottom := -2147483648;
  7939. MinSize := S_W;
  7940. MaxSize := S_L;
  7941. end;
  7942. {$ifdef x86_64}
  7943. S_LQ:
  7944. begin
  7945. { Both the lower and upper limits are set to 32-bit. If a limit
  7946. is breached, then optimisation is impossible }
  7947. LowerLimit := $FFFFFFFF;
  7948. SignedLowerLimit := $7FFFFFFF;
  7949. SignedLowerLimitBottom := -2147483648;
  7950. UpperLimit := $FFFFFFFF;
  7951. SignedUpperLimit := $7FFFFFFF;
  7952. SignedUpperLimitBottom := -2147483648;
  7953. MinSize := S_L;
  7954. MaxSize := S_L;
  7955. end;
  7956. {$endif x86_64}
  7957. else
  7958. InternalError(2020112301);
  7959. end;
  7960. TestValMin := 0;
  7961. TestValMax := LowerLimit;
  7962. TestValSignedMax := SignedLowerLimit;
  7963. TryShiftDownLimit := LowerLimit;
  7964. TryShiftDown := S_NO;
  7965. ShiftDownOverflow := False;
  7966. RegChanged := False;
  7967. BitwiseOnly := True;
  7968. OrXorUsed := False;
  7969. UpperSignedOverflow := False;
  7970. LowerSignedOverflow := False;
  7971. UpperUnsignedOverflow := False;
  7972. LowerUnsignedOverflow := False;
  7973. hp1 := p;
  7974. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  7975. (hp1.typ = ait_instruction) and
  7976. (
  7977. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  7978. instruction that doesn't actually contain ThisReg }
  7979. (cs_opt_level3 in current_settings.optimizerswitches) or
  7980. { This allows this Movx optimisation to work through the SETcc instructions
  7981. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  7982. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  7983. skip over these SETcc instructions). }
  7984. (taicpu(hp1).opcode = A_SETcc) or
  7985. RegInInstruction(ThisReg, hp1)
  7986. ) do
  7987. begin
  7988. case taicpu(hp1).opcode of
  7989. A_INC,A_DEC:
  7990. begin
  7991. { Has to be an exact match on the register }
  7992. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  7993. Break;
  7994. if taicpu(hp1).opcode = A_INC then
  7995. begin
  7996. Inc(TestValMin);
  7997. Inc(TestValMax);
  7998. Inc(TestValSignedMax);
  7999. end
  8000. else
  8001. begin
  8002. Dec(TestValMin);
  8003. Dec(TestValMax);
  8004. Dec(TestValSignedMax);
  8005. end;
  8006. end;
  8007. A_TEST, A_CMP:
  8008. begin
  8009. if (
  8010. { Too high a risk of non-linear behaviour that breaks DFA
  8011. here, unless it's cmp $0,%reg, which is equivalent to
  8012. test %reg,%reg }
  8013. OrXorUsed and
  8014. (taicpu(hp1).opcode = A_CMP) and
  8015. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  8016. ) or
  8017. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  8018. { Has to be an exact match on the register }
  8019. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8020. (
  8021. { Permit "test %reg,%reg" }
  8022. (taicpu(hp1).opcode = A_TEST) and
  8023. (taicpu(hp1).oper[0]^.typ = top_reg) and
  8024. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  8025. ) or
  8026. (taicpu(hp1).oper[0]^.typ <> top_const) or
  8027. { Make sure the comparison value is not smaller than the
  8028. smallest allowed signed value for the minimum size (e.g.
  8029. -128 for 8-bit) }
  8030. not (
  8031. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  8032. { Is it in the negative range? }
  8033. (
  8034. (taicpu(hp1).oper[0]^.val < 0) and
  8035. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  8036. )
  8037. ) then
  8038. Break;
  8039. { Check to see if the active register is used afterwards }
  8040. TransferUsedRegs(TmpUsedRegs);
  8041. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  8042. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  8043. begin
  8044. { Make sure the comparison or any previous instructions
  8045. hasn't pushed the test values outside of the range of
  8046. MinSize }
  8047. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  8048. begin
  8049. { Exceeded lower bound but not upper bound }
  8050. TargetSize := MaxSize;
  8051. end
  8052. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  8053. begin
  8054. { Size didn't exceed lower bound }
  8055. TargetSize := MinSize;
  8056. end
  8057. else
  8058. Break;
  8059. case TargetSize of
  8060. S_B:
  8061. TargetSubReg := R_SUBL;
  8062. S_W:
  8063. TargetSubReg := R_SUBW;
  8064. S_L:
  8065. TargetSubReg := R_SUBD;
  8066. else
  8067. InternalError(2021051002);
  8068. end;
  8069. if TargetSize <> MaxSize then
  8070. begin
  8071. { Update the register to its new size }
  8072. setsubreg(ThisReg, TargetSubReg);
  8073. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  8074. taicpu(hp1).oper[1]^.reg := ThisReg;
  8075. taicpu(hp1).opsize := TargetSize;
  8076. { Convert the input MOVZX to a MOV if necessary }
  8077. AdjustInitialLoad;
  8078. if (InstrMax >= 0) then
  8079. begin
  8080. for Index := 0 to InstrMax do
  8081. begin
  8082. { If p_removed is true, then the original MOV/Z was removed
  8083. and removing the AND instruction may not be safe if it
  8084. appears first }
  8085. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  8086. InternalError(2020112311);
  8087. if InstrList[Index].oper[0]^.typ = top_reg then
  8088. InstrList[Index].oper[0]^.reg := ThisReg;
  8089. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  8090. InstrList[Index].opsize := MinSize;
  8091. end;
  8092. end;
  8093. Result := True;
  8094. end;
  8095. Exit;
  8096. end;
  8097. end;
  8098. A_SETcc:
  8099. begin
  8100. { This allows this Movx optimisation to work through the SETcc instructions
  8101. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  8102. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  8103. skip over these SETcc instructions). }
  8104. if (cs_opt_level3 in current_settings.optimizerswitches) or
  8105. { Of course, break out if the current register is used }
  8106. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  8107. Break
  8108. else
  8109. { We must use Continue so the instruction doesn't get added
  8110. to InstrList }
  8111. Continue;
  8112. end;
  8113. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  8114. begin
  8115. if
  8116. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  8117. { Has to be an exact match on the register }
  8118. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  8119. (
  8120. (
  8121. (taicpu(hp1).oper[0]^.typ = top_const) and
  8122. (
  8123. (
  8124. (taicpu(hp1).opcode = A_SHL) and
  8125. (
  8126. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  8127. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  8128. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  8129. )
  8130. ) or (
  8131. (taicpu(hp1).opcode <> A_SHL) and
  8132. (
  8133. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8134. { Is it in the negative range? }
  8135. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  8136. )
  8137. )
  8138. )
  8139. ) or (
  8140. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  8141. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  8142. )
  8143. ) then
  8144. Break;
  8145. { Only process OR and XOR if there are only bitwise operations,
  8146. since otherwise they can too easily fool the data flow
  8147. analysis (they can cause non-linear behaviour) }
  8148. case taicpu(hp1).opcode of
  8149. A_ADD:
  8150. begin
  8151. if OrXorUsed then
  8152. { Too high a risk of non-linear behaviour that breaks DFA here }
  8153. Break
  8154. else
  8155. BitwiseOnly := False;
  8156. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8157. begin
  8158. TestValMin := TestValMin * 2;
  8159. TestValMax := TestValMax * 2;
  8160. TestValSignedMax := TestValSignedMax * 2;
  8161. end
  8162. else
  8163. begin
  8164. WorkingValue := taicpu(hp1).oper[0]^.val;
  8165. TestValMin := TestValMin + WorkingValue;
  8166. TestValMax := TestValMax + WorkingValue;
  8167. TestValSignedMax := TestValSignedMax + WorkingValue;
  8168. end;
  8169. end;
  8170. A_SUB:
  8171. begin
  8172. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8173. begin
  8174. TestValMin := 0;
  8175. TestValMax := 0;
  8176. TestValSignedMax := 0;
  8177. end
  8178. else
  8179. begin
  8180. if OrXorUsed then
  8181. { Too high a risk of non-linear behaviour that breaks DFA here }
  8182. Break
  8183. else
  8184. BitwiseOnly := False;
  8185. WorkingValue := taicpu(hp1).oper[0]^.val;
  8186. TestValMin := TestValMin - WorkingValue;
  8187. TestValMax := TestValMax - WorkingValue;
  8188. TestValSignedMax := TestValSignedMax - WorkingValue;
  8189. end;
  8190. end;
  8191. A_AND:
  8192. if (taicpu(hp1).oper[0]^.typ = top_const) then
  8193. begin
  8194. { we might be able to go smaller if AND appears first }
  8195. if InstrMax = -1 then
  8196. case MinSize of
  8197. S_B:
  8198. ;
  8199. S_W:
  8200. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8201. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8202. begin
  8203. TryShiftDown := S_B;
  8204. TryShiftDownLimit := $FF;
  8205. end;
  8206. S_L:
  8207. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8208. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8209. begin
  8210. TryShiftDown := S_B;
  8211. TryShiftDownLimit := $FF;
  8212. end
  8213. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  8214. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  8215. begin
  8216. TryShiftDown := S_W;
  8217. TryShiftDownLimit := $FFFF;
  8218. end;
  8219. else
  8220. InternalError(2020112320);
  8221. end;
  8222. WorkingValue := taicpu(hp1).oper[0]^.val;
  8223. TestValMin := TestValMin and WorkingValue;
  8224. TestValMax := TestValMax and WorkingValue;
  8225. TestValSignedMax := TestValSignedMax and WorkingValue;
  8226. end;
  8227. A_OR:
  8228. begin
  8229. if not BitwiseOnly then
  8230. Break;
  8231. OrXorUsed := True;
  8232. WorkingValue := taicpu(hp1).oper[0]^.val;
  8233. TestValMin := TestValMin or WorkingValue;
  8234. TestValMax := TestValMax or WorkingValue;
  8235. TestValSignedMax := TestValSignedMax or WorkingValue;
  8236. end;
  8237. A_XOR:
  8238. begin
  8239. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8240. begin
  8241. TestValMin := 0;
  8242. TestValMax := 0;
  8243. TestValSignedMax := 0;
  8244. end
  8245. else
  8246. begin
  8247. if not BitwiseOnly then
  8248. Break;
  8249. OrXorUsed := True;
  8250. WorkingValue := taicpu(hp1).oper[0]^.val;
  8251. TestValMin := TestValMin xor WorkingValue;
  8252. TestValMax := TestValMax xor WorkingValue;
  8253. TestValSignedMax := TestValSignedMax xor WorkingValue;
  8254. end;
  8255. end;
  8256. A_SHL:
  8257. begin
  8258. BitwiseOnly := False;
  8259. WorkingValue := taicpu(hp1).oper[0]^.val;
  8260. TestValMin := TestValMin shl WorkingValue;
  8261. TestValMax := TestValMax shl WorkingValue;
  8262. TestValSignedMax := TestValSignedMax shl WorkingValue;
  8263. end;
  8264. A_SHR,
  8265. { The first instruction was MOVZX, so the value won't be negative }
  8266. A_SAR:
  8267. begin
  8268. if InstrMax <> -1 then
  8269. BitwiseOnly := False
  8270. else
  8271. { we might be able to go smaller if SHR appears first }
  8272. case MinSize of
  8273. S_B:
  8274. ;
  8275. S_W:
  8276. if (taicpu(hp1).oper[0]^.val >= 8) then
  8277. begin
  8278. TryShiftDown := S_B;
  8279. TryShiftDownLimit := $FF;
  8280. TryShiftDownSignedLimit := $7F;
  8281. TryShiftDownSignedLimitLower := -128;
  8282. end;
  8283. S_L:
  8284. if (taicpu(hp1).oper[0]^.val >= 24) then
  8285. begin
  8286. TryShiftDown := S_B;
  8287. TryShiftDownLimit := $FF;
  8288. TryShiftDownSignedLimit := $7F;
  8289. TryShiftDownSignedLimitLower := -128;
  8290. end
  8291. else if (taicpu(hp1).oper[0]^.val >= 16) then
  8292. begin
  8293. TryShiftDown := S_W;
  8294. TryShiftDownLimit := $FFFF;
  8295. TryShiftDownSignedLimit := $7FFF;
  8296. TryShiftDownSignedLimitLower := -32768;
  8297. end;
  8298. else
  8299. InternalError(2020112321);
  8300. end;
  8301. WorkingValue := taicpu(hp1).oper[0]^.val;
  8302. if taicpu(hp1).opcode = A_SAR then
  8303. begin
  8304. TestValMin := SarInt64(TestValMin, WorkingValue);
  8305. TestValMax := SarInt64(TestValMax, WorkingValue);
  8306. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  8307. end
  8308. else
  8309. begin
  8310. TestValMin := TestValMin shr WorkingValue;
  8311. TestValMax := TestValMax shr WorkingValue;
  8312. TestValSignedMax := TestValSignedMax shr WorkingValue;
  8313. end;
  8314. end;
  8315. else
  8316. InternalError(2020112303);
  8317. end;
  8318. end;
  8319. (*
  8320. A_IMUL:
  8321. case taicpu(hp1).ops of
  8322. 2:
  8323. begin
  8324. if not MatchOpType(hp1, top_reg, top_reg) or
  8325. { Has to be an exact match on the register }
  8326. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  8327. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  8328. Break;
  8329. TestValMin := TestValMin * TestValMin;
  8330. TestValMax := TestValMax * TestValMax;
  8331. TestValSignedMax := TestValSignedMax * TestValMax;
  8332. end;
  8333. 3:
  8334. begin
  8335. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8336. { Has to be an exact match on the register }
  8337. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8338. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8339. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8340. { Is it in the negative range? }
  8341. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8342. Break;
  8343. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  8344. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  8345. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  8346. end;
  8347. else
  8348. Break;
  8349. end;
  8350. A_IDIV:
  8351. case taicpu(hp1).ops of
  8352. 3:
  8353. begin
  8354. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8355. { Has to be an exact match on the register }
  8356. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8357. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8358. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8359. { Is it in the negative range? }
  8360. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8361. Break;
  8362. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  8363. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  8364. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  8365. end;
  8366. else
  8367. Break;
  8368. end;
  8369. *)
  8370. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  8371. begin
  8372. { If there are no instructions in between, then we might be able to make a saving }
  8373. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  8374. Break;
  8375. { We have something like:
  8376. movzbw %dl,%dx
  8377. ...
  8378. movswl %dx,%edx
  8379. Change the latter to a zero-extension then enter the
  8380. A_MOVZX case branch.
  8381. }
  8382. {$ifdef x86_64}
  8383. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8384. begin
  8385. { this becomes a zero extension from 32-bit to 64-bit, but
  8386. the upper 32 bits are already zero, so just delete the
  8387. instruction }
  8388. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  8389. RemoveInstruction(hp1);
  8390. Result := True;
  8391. Exit;
  8392. end
  8393. else
  8394. {$endif x86_64}
  8395. begin
  8396. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  8397. taicpu(hp1).opcode := A_MOVZX;
  8398. {$ifdef x86_64}
  8399. case taicpu(hp1).opsize of
  8400. S_BQ:
  8401. begin
  8402. taicpu(hp1).opsize := S_BL;
  8403. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8404. end;
  8405. S_WQ:
  8406. begin
  8407. taicpu(hp1).opsize := S_WL;
  8408. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8409. end;
  8410. S_LQ:
  8411. begin
  8412. taicpu(hp1).opcode := A_MOV;
  8413. taicpu(hp1).opsize := S_L;
  8414. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8415. { In this instance, we need to break out because the
  8416. instruction is no longer MOVZX or MOVSXD }
  8417. Result := True;
  8418. Exit;
  8419. end;
  8420. else
  8421. ;
  8422. end;
  8423. {$endif x86_64}
  8424. Result := CompressInstructions;
  8425. Exit;
  8426. end;
  8427. end;
  8428. A_MOVZX:
  8429. begin
  8430. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  8431. Break;
  8432. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  8433. begin
  8434. if (InstrMax = -1) and
  8435. { Will return false if the second parameter isn't ThisReg
  8436. (can happen on -O2 and under) }
  8437. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8438. begin
  8439. { The two MOVZX instructions are adjacent, so remove the first one }
  8440. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  8441. RemoveCurrentP(p);
  8442. Result := True;
  8443. Exit;
  8444. end;
  8445. Break;
  8446. end;
  8447. Result := CompressInstructions;
  8448. Exit;
  8449. end;
  8450. else
  8451. { This includes ADC, SBB and IDIV }
  8452. Break;
  8453. end;
  8454. if not CheckOverflowConditions then
  8455. Break;
  8456. { Contains highest index (so instruction count - 1) }
  8457. Inc(InstrMax);
  8458. if InstrMax > High(InstrList) then
  8459. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  8460. InstrList[InstrMax] := taicpu(hp1);
  8461. end;
  8462. end;
  8463. {$pop}
  8464. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  8465. var
  8466. hp1 : tai;
  8467. begin
  8468. Result:=false;
  8469. if (taicpu(p).ops >= 2) and
  8470. ((taicpu(p).oper[0]^.typ = top_const) or
  8471. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  8472. (taicpu(p).oper[1]^.typ = top_reg) and
  8473. ((taicpu(p).ops = 2) or
  8474. ((taicpu(p).oper[2]^.typ = top_reg) and
  8475. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  8476. GetLastInstruction(p,hp1) and
  8477. MatchInstruction(hp1,A_MOV,[]) and
  8478. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8479. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8480. begin
  8481. TransferUsedRegs(TmpUsedRegs);
  8482. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  8483. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  8484. { change
  8485. mov reg1,reg2
  8486. imul y,reg2 to imul y,reg1,reg2 }
  8487. begin
  8488. taicpu(p).ops := 3;
  8489. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  8490. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  8491. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  8492. RemoveInstruction(hp1);
  8493. result:=true;
  8494. end;
  8495. end;
  8496. end;
  8497. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  8498. var
  8499. ThisLabel: TAsmLabel;
  8500. begin
  8501. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  8502. ThisLabel.decrefs;
  8503. taicpu(p).opcode := A_RET;
  8504. taicpu(p).is_jmp := false;
  8505. taicpu(p).ops := taicpu(ret_p).ops;
  8506. case taicpu(ret_p).ops of
  8507. 0:
  8508. taicpu(p).clearop(0);
  8509. 1:
  8510. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  8511. else
  8512. internalerror(2016041301);
  8513. end;
  8514. { If the original label is now dead, it might turn out that the label
  8515. immediately follows p. As a result, everything beyond it, which will
  8516. be just some final register configuration and a RET instruction, is
  8517. now dead code. [Kit] }
  8518. { NOTE: This is much faster than introducing a OptPass2RET routine and
  8519. running RemoveDeadCodeAfterJump for each RET instruction, because
  8520. this optimisation rarely happens and most RETs appear at the end of
  8521. routines where there is nothing that can be stripped. [Kit] }
  8522. if not ThisLabel.is_used then
  8523. RemoveDeadCodeAfterJump(p);
  8524. end;
  8525. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  8526. var
  8527. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  8528. Unconditional, PotentialModified: Boolean;
  8529. OperPtr: POper;
  8530. NewRef: TReference;
  8531. InstrList: array of taicpu;
  8532. InstrMax, Index: Integer;
  8533. const
  8534. {$ifdef DEBUG_AOPTCPU}
  8535. SNoFlags: shortstring = ' so the flags aren''t modified';
  8536. {$else DEBUG_AOPTCPU}
  8537. SNoFlags = '';
  8538. {$endif DEBUG_AOPTCPU}
  8539. begin
  8540. Result:=false;
  8541. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  8542. begin
  8543. if MatchInstruction(hp1, A_TEST, [S_B]) and
  8544. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8545. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  8546. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  8547. GetNextInstruction(hp1, hp2) and
  8548. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  8549. { Change from: To:
  8550. set(C) %reg j(~C) label
  8551. test %reg,%reg/cmp $0,%reg
  8552. je label
  8553. set(C) %reg j(C) label
  8554. test %reg,%reg/cmp $0,%reg
  8555. jne label
  8556. (Also do something similar with sete/setne instead of je/jne)
  8557. }
  8558. begin
  8559. { Before we do anything else, we need to check the instructions
  8560. in between SETcc and TEST to make sure they don't modify the
  8561. FLAGS register - if -O2 or under, there won't be any
  8562. instructions between SET and TEST }
  8563. TransferUsedRegs(TmpUsedRegs);
  8564. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8565. if (cs_opt_level3 in current_settings.optimizerswitches) then
  8566. begin
  8567. next := p;
  8568. SetLength(InstrList, 0);
  8569. InstrMax := -1;
  8570. PotentialModified := False;
  8571. { Make a note of every instruction that modifies the FLAGS
  8572. register }
  8573. while GetNextInstruction(next, next) and (next <> hp1) do
  8574. begin
  8575. if next.typ <> ait_instruction then
  8576. { GetNextInstructionUsingReg should have returned False }
  8577. InternalError(2021051701);
  8578. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  8579. begin
  8580. case taicpu(next).opcode of
  8581. A_SETcc,
  8582. A_CMOVcc,
  8583. A_Jcc:
  8584. begin
  8585. if PotentialModified then
  8586. { Not safe because the flags were modified earlier }
  8587. Exit
  8588. else
  8589. { Condition is the same as the initial SETcc, so this is safe
  8590. (don't add to instruction list though) }
  8591. Continue;
  8592. end;
  8593. A_ADD:
  8594. begin
  8595. if (taicpu(next).opsize = S_B) or
  8596. { LEA doesn't support 8-bit operands }
  8597. (taicpu(next).oper[1]^.typ <> top_reg) or
  8598. { Must write to a register }
  8599. (taicpu(next).oper[0]^.typ = top_ref) then
  8600. { Require a constant or a register }
  8601. Exit;
  8602. PotentialModified := True;
  8603. end;
  8604. A_SUB:
  8605. begin
  8606. if (taicpu(next).opsize = S_B) or
  8607. { LEA doesn't support 8-bit operands }
  8608. (taicpu(next).oper[1]^.typ <> top_reg) or
  8609. { Must write to a register }
  8610. (taicpu(next).oper[0]^.typ <> top_const) or
  8611. (taicpu(next).oper[0]^.val = $80000000) then
  8612. { Can't subtract a register with LEA - also
  8613. check that the value isn't -2^31, as this
  8614. can't be negated }
  8615. Exit;
  8616. PotentialModified := True;
  8617. end;
  8618. A_SAL,
  8619. A_SHL:
  8620. begin
  8621. if (taicpu(next).opsize = S_B) or
  8622. { LEA doesn't support 8-bit operands }
  8623. (taicpu(next).oper[1]^.typ <> top_reg) or
  8624. { Must write to a register }
  8625. (taicpu(next).oper[0]^.typ <> top_const) or
  8626. (taicpu(next).oper[0]^.val < 0) or
  8627. (taicpu(next).oper[0]^.val > 3) then
  8628. Exit;
  8629. PotentialModified := True;
  8630. end;
  8631. A_IMUL:
  8632. begin
  8633. if (taicpu(next).ops <> 3) or
  8634. (taicpu(next).oper[1]^.typ <> top_reg) or
  8635. { Must write to a register }
  8636. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  8637. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  8638. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  8639. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  8640. Exit
  8641. else
  8642. PotentialModified := True;
  8643. end;
  8644. else
  8645. { Don't know how to change this, so abort }
  8646. Exit;
  8647. end;
  8648. { Contains highest index (so instruction count - 1) }
  8649. Inc(InstrMax);
  8650. if InstrMax > High(InstrList) then
  8651. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  8652. InstrList[InstrMax] := taicpu(next);
  8653. end;
  8654. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  8655. end;
  8656. if not Assigned(next) or (next <> hp1) then
  8657. { It should be equal to hp1 }
  8658. InternalError(2021051702);
  8659. { Cycle through each instruction and check to see if we can
  8660. change them to versions that don't modify the flags }
  8661. if (InstrMax >= 0) then
  8662. begin
  8663. for Index := 0 to InstrMax do
  8664. case InstrList[Index].opcode of
  8665. A_ADD:
  8666. begin
  8667. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  8668. InstrList[Index].opcode := A_LEA;
  8669. reference_reset(NewRef, 1, []);
  8670. NewRef.base := InstrList[Index].oper[1]^.reg;
  8671. if InstrList[Index].oper[0]^.typ = top_reg then
  8672. begin
  8673. NewRef.index := InstrList[Index].oper[0]^.reg;
  8674. NewRef.scalefactor := 1;
  8675. end
  8676. else
  8677. NewRef.offset := InstrList[Index].oper[0]^.val;
  8678. InstrList[Index].loadref(0, NewRef);
  8679. end;
  8680. A_SUB:
  8681. begin
  8682. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  8683. InstrList[Index].opcode := A_LEA;
  8684. reference_reset(NewRef, 1, []);
  8685. NewRef.base := InstrList[Index].oper[1]^.reg;
  8686. NewRef.offset := -InstrList[Index].oper[0]^.val;
  8687. InstrList[Index].loadref(0, NewRef);
  8688. end;
  8689. A_SHL,
  8690. A_SAL:
  8691. begin
  8692. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  8693. InstrList[Index].opcode := A_LEA;
  8694. reference_reset(NewRef, 1, []);
  8695. NewRef.index := InstrList[Index].oper[1]^.reg;
  8696. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  8697. InstrList[Index].loadref(0, NewRef);
  8698. end;
  8699. A_IMUL:
  8700. begin
  8701. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  8702. InstrList[Index].opcode := A_LEA;
  8703. reference_reset(NewRef, 1, []);
  8704. NewRef.index := InstrList[Index].oper[1]^.reg;
  8705. case InstrList[Index].oper[0]^.val of
  8706. 2, 4, 8:
  8707. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  8708. else {3, 5 and 9}
  8709. begin
  8710. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  8711. NewRef.base := InstrList[Index].oper[1]^.reg;
  8712. end;
  8713. end;
  8714. InstrList[Index].loadref(0, NewRef);
  8715. end;
  8716. else
  8717. InternalError(2021051710);
  8718. end;
  8719. end;
  8720. { Mark the FLAGS register as used across this whole block }
  8721. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  8722. end;
  8723. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  8724. JumpC := taicpu(hp2).condition;
  8725. Unconditional := False;
  8726. if conditions_equal(JumpC, C_E) then
  8727. SetC := inverse_cond(taicpu(p).condition)
  8728. else if conditions_equal(JumpC, C_NE) then
  8729. SetC := taicpu(p).condition
  8730. else
  8731. { We've got something weird here (and inefficent) }
  8732. begin
  8733. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  8734. SetC := C_NONE;
  8735. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  8736. if condition_in(C_AE, JumpC) then
  8737. Unconditional := True
  8738. else
  8739. { Not sure what to do with this jump - drop out }
  8740. Exit;
  8741. end;
  8742. RemoveInstruction(hp1);
  8743. if Unconditional then
  8744. MakeUnconditional(taicpu(hp2))
  8745. else
  8746. begin
  8747. if SetC = C_NONE then
  8748. InternalError(2018061402);
  8749. taicpu(hp2).SetCondition(SetC);
  8750. end;
  8751. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  8752. TmpUsedRegs }
  8753. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  8754. begin
  8755. RemoveCurrentp(p, hp2);
  8756. if taicpu(hp2).opcode = A_SETcc then
  8757. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  8758. else
  8759. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  8760. end
  8761. else
  8762. if taicpu(hp2).opcode = A_SETcc then
  8763. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  8764. else
  8765. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  8766. Result := True;
  8767. end
  8768. else if
  8769. { Make sure the instructions are adjacent }
  8770. (
  8771. not (cs_opt_level3 in current_settings.optimizerswitches) or
  8772. GetNextInstruction(p, hp1)
  8773. ) and
  8774. MatchInstruction(hp1, A_MOV, [S_B]) and
  8775. { Writing to memory is allowed }
  8776. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  8777. begin
  8778. {
  8779. Watch out for sequences such as:
  8780. set(c)b %regb
  8781. movb %regb,(ref)
  8782. movb $0,1(ref)
  8783. movb $0,2(ref)
  8784. movb $0,3(ref)
  8785. Much more efficient to turn it into:
  8786. movl $0,%regl
  8787. set(c)b %regb
  8788. movl %regl,(ref)
  8789. Or:
  8790. set(c)b %regb
  8791. movzbl %regb,%regl
  8792. movl %regl,(ref)
  8793. }
  8794. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  8795. GetNextInstruction(hp1, hp2) and
  8796. MatchInstruction(hp2, A_MOV, [S_B]) and
  8797. (taicpu(hp2).oper[1]^.typ = top_ref) and
  8798. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  8799. begin
  8800. { Don't do anything else except set Result to True }
  8801. end
  8802. else
  8803. begin
  8804. if taicpu(p).oper[0]^.typ = top_reg then
  8805. begin
  8806. TransferUsedRegs(TmpUsedRegs);
  8807. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8808. end;
  8809. { If it's not a register, it's a memory address }
  8810. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  8811. begin
  8812. { Even if the register is still in use, we can minimise the
  8813. pipeline stall by changing the MOV into another SETcc. }
  8814. taicpu(hp1).opcode := A_SETcc;
  8815. taicpu(hp1).condition := taicpu(p).condition;
  8816. if taicpu(hp1).oper[1]^.typ = top_ref then
  8817. begin
  8818. { Swapping the operand pointers like this is probably a
  8819. bit naughty, but it is far faster than using loadoper
  8820. to transfer the reference from oper[1] to oper[0] if
  8821. you take into account the extra procedure calls and
  8822. the memory allocation and deallocation required }
  8823. OperPtr := taicpu(hp1).oper[1];
  8824. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  8825. taicpu(hp1).oper[0] := OperPtr;
  8826. end
  8827. else
  8828. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  8829. taicpu(hp1).clearop(1);
  8830. taicpu(hp1).ops := 1;
  8831. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  8832. end
  8833. else
  8834. begin
  8835. if taicpu(hp1).oper[1]^.typ = top_reg then
  8836. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  8837. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  8838. RemoveInstruction(hp1);
  8839. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  8840. end
  8841. end;
  8842. Result := True;
  8843. end;
  8844. end;
  8845. end;
  8846. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  8847. var
  8848. hp1: tai;
  8849. Count: Integer;
  8850. OrigLabel: TAsmLabel;
  8851. begin
  8852. result := False;
  8853. { Sometimes, the optimisations below can permit this }
  8854. RemoveDeadCodeAfterJump(p);
  8855. 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
  8856. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  8857. begin
  8858. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8859. { Also a side-effect of optimisations }
  8860. if CollapseZeroDistJump(p, OrigLabel) then
  8861. begin
  8862. Result := True;
  8863. Exit;
  8864. end;
  8865. hp1 := GetLabelWithSym(OrigLabel);
  8866. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  8867. begin
  8868. case taicpu(hp1).opcode of
  8869. A_RET:
  8870. {
  8871. change
  8872. jmp .L1
  8873. ...
  8874. .L1:
  8875. ret
  8876. into
  8877. ret
  8878. }
  8879. begin
  8880. ConvertJumpToRET(p, hp1);
  8881. result:=true;
  8882. end;
  8883. { Check any kind of direct assignment instruction }
  8884. A_MOV,
  8885. A_MOVD,
  8886. A_MOVQ,
  8887. A_MOVSX,
  8888. {$ifdef x86_64}
  8889. A_MOVSXD,
  8890. {$endif x86_64}
  8891. A_MOVZX,
  8892. A_MOVAPS,
  8893. A_MOVUPS,
  8894. A_MOVSD,
  8895. A_MOVAPD,
  8896. A_MOVUPD,
  8897. A_MOVDQA,
  8898. A_MOVDQU,
  8899. A_VMOVSS,
  8900. A_VMOVAPS,
  8901. A_VMOVUPS,
  8902. A_VMOVSD,
  8903. A_VMOVAPD,
  8904. A_VMOVUPD,
  8905. A_VMOVDQA,
  8906. A_VMOVDQU:
  8907. if ((current_settings.optimizerswitches * [cs_opt_level3, cs_opt_size]) <> [cs_opt_size]) and
  8908. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  8909. begin
  8910. Result := True;
  8911. Exit;
  8912. end;
  8913. else
  8914. ;
  8915. end;
  8916. end;
  8917. end;
  8918. end;
  8919. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  8920. begin
  8921. CanBeCMOV:=assigned(p) and
  8922. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  8923. { we can't use cmov ref,reg because
  8924. ref could be nil and cmov still throws an exception
  8925. if ref=nil but the mov isn't done (FK)
  8926. or ((taicpu(p).oper[0]^.typ = top_ref) and
  8927. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  8928. }
  8929. (taicpu(p).oper[1]^.typ = top_reg) and
  8930. (
  8931. (taicpu(p).oper[0]^.typ = top_reg) or
  8932. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  8933. it is not expected that this can cause a seg. violation }
  8934. (
  8935. (taicpu(p).oper[0]^.typ = top_ref) and
  8936. IsRefSafe(taicpu(p).oper[0]^.ref)
  8937. )
  8938. );
  8939. end;
  8940. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  8941. var
  8942. hp1,hp2: tai;
  8943. {$ifndef i8086}
  8944. hp3,hp4,hpmov2, hp5: tai;
  8945. l : Longint;
  8946. condition : TAsmCond;
  8947. {$endif i8086}
  8948. carryadd_opcode : TAsmOp;
  8949. symbol: TAsmSymbol;
  8950. increg, tmpreg: TRegister;
  8951. begin
  8952. result:=false;
  8953. if GetNextInstruction(p,hp1) and (hp1.typ=ait_instruction) then
  8954. begin
  8955. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8956. if (
  8957. (
  8958. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  8959. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  8960. (Taicpu(hp1).oper[0]^.val=1)
  8961. ) or
  8962. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  8963. ) and
  8964. GetNextInstruction(hp1,hp2) and
  8965. SkipAligns(hp2, hp2) and
  8966. (hp2.typ = ait_label) and
  8967. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  8968. { jb @@1 cmc
  8969. inc/dec operand --> adc/sbb operand,0
  8970. @@1:
  8971. ... and ...
  8972. jnb @@1
  8973. inc/dec operand --> adc/sbb operand,0
  8974. @@1: }
  8975. begin
  8976. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  8977. begin
  8978. case taicpu(hp1).opcode of
  8979. A_INC,
  8980. A_ADD:
  8981. carryadd_opcode:=A_ADC;
  8982. A_DEC,
  8983. A_SUB:
  8984. carryadd_opcode:=A_SBB;
  8985. else
  8986. InternalError(2021011001);
  8987. end;
  8988. Taicpu(p).clearop(0);
  8989. Taicpu(p).ops:=0;
  8990. Taicpu(p).is_jmp:=false;
  8991. Taicpu(p).opcode:=A_CMC;
  8992. Taicpu(p).condition:=C_NONE;
  8993. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  8994. Taicpu(hp1).ops:=2;
  8995. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  8996. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  8997. else
  8998. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  8999. Taicpu(hp1).loadconst(0,0);
  9000. Taicpu(hp1).opcode:=carryadd_opcode;
  9001. result:=true;
  9002. exit;
  9003. end
  9004. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  9005. begin
  9006. case taicpu(hp1).opcode of
  9007. A_INC,
  9008. A_ADD:
  9009. carryadd_opcode:=A_ADC;
  9010. A_DEC,
  9011. A_SUB:
  9012. carryadd_opcode:=A_SBB;
  9013. else
  9014. InternalError(2021011002);
  9015. end;
  9016. Taicpu(hp1).ops:=2;
  9017. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  9018. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  9019. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  9020. else
  9021. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  9022. Taicpu(hp1).loadconst(0,0);
  9023. Taicpu(hp1).opcode:=carryadd_opcode;
  9024. RemoveCurrentP(p, hp1);
  9025. result:=true;
  9026. exit;
  9027. end
  9028. {
  9029. jcc @@1 setcc tmpreg
  9030. inc/dec/add/sub operand -> (movzx tmpreg)
  9031. @@1: add/sub tmpreg,operand
  9032. While this increases code size slightly, it makes the code much faster if the
  9033. jump is unpredictable
  9034. }
  9035. else if not(cs_opt_size in current_settings.optimizerswitches) then
  9036. begin
  9037. { search for an available register which is volatile }
  9038. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  9039. if increg <> NR_NO then
  9040. begin
  9041. { We don't need to check if tmpreg is in hp1 or not, because
  9042. it will be marked as in use at p (if not, this is
  9043. indictive of a compiler bug). }
  9044. TAsmLabel(symbol).decrefs;
  9045. Taicpu(p).clearop(0);
  9046. Taicpu(p).ops:=1;
  9047. Taicpu(p).is_jmp:=false;
  9048. Taicpu(p).opcode:=A_SETcc;
  9049. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  9050. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  9051. Taicpu(p).loadreg(0,increg);
  9052. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  9053. begin
  9054. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  9055. R_SUBW:
  9056. begin
  9057. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  9058. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  9059. end;
  9060. R_SUBD:
  9061. begin
  9062. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  9063. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  9064. end;
  9065. {$ifdef x86_64}
  9066. R_SUBQ:
  9067. begin
  9068. { MOVZX doesn't have a 64-bit variant, because
  9069. the 32-bit version implicitly zeroes the
  9070. upper 32-bits of the destination register }
  9071. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  9072. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  9073. setsubreg(tmpreg, R_SUBQ);
  9074. end;
  9075. {$endif x86_64}
  9076. else
  9077. Internalerror(2020030601);
  9078. end;
  9079. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  9080. asml.InsertAfter(hp2,p);
  9081. end
  9082. else
  9083. tmpreg := increg;
  9084. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  9085. begin
  9086. Taicpu(hp1).ops:=2;
  9087. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  9088. end;
  9089. Taicpu(hp1).loadreg(0,tmpreg);
  9090. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  9091. Result := True;
  9092. { p is no longer a Jcc instruction, so exit }
  9093. Exit;
  9094. end;
  9095. end;
  9096. end;
  9097. { Detect the following:
  9098. jmp<cond> @Lbl1
  9099. jmp @Lbl2
  9100. ...
  9101. @Lbl1:
  9102. ret
  9103. Change to:
  9104. jmp<inv_cond> @Lbl2
  9105. ret
  9106. }
  9107. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  9108. begin
  9109. hp2:=getlabelwithsym(TAsmLabel(symbol));
  9110. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  9111. MatchInstruction(hp2,A_RET,[S_NO]) then
  9112. begin
  9113. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  9114. { Change label address to that of the unconditional jump }
  9115. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  9116. TAsmLabel(symbol).DecRefs;
  9117. taicpu(hp1).opcode := A_RET;
  9118. taicpu(hp1).is_jmp := false;
  9119. taicpu(hp1).ops := taicpu(hp2).ops;
  9120. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  9121. case taicpu(hp2).ops of
  9122. 0:
  9123. taicpu(hp1).clearop(0);
  9124. 1:
  9125. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  9126. else
  9127. internalerror(2016041302);
  9128. end;
  9129. end;
  9130. {$ifndef i8086}
  9131. end
  9132. {
  9133. convert
  9134. j<c> .L1
  9135. mov 1,reg
  9136. jmp .L2
  9137. .L1
  9138. mov 0,reg
  9139. .L2
  9140. into
  9141. mov 0,reg
  9142. set<not(c)> reg
  9143. take care of alignment and that the mov 0,reg is not converted into a xor as this
  9144. would destroy the flag contents
  9145. }
  9146. else if MatchInstruction(hp1,A_MOV,[]) and
  9147. MatchOpType(taicpu(hp1),top_const,top_reg) and
  9148. {$ifdef i386}
  9149. (
  9150. { Under i386, ESI, EDI, EBP and ESP
  9151. don't have an 8-bit representation }
  9152. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  9153. ) and
  9154. {$endif i386}
  9155. (taicpu(hp1).oper[0]^.val=1) and
  9156. GetNextInstruction(hp1,hp2) and
  9157. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  9158. GetNextInstruction(hp2,hp3) and
  9159. { skip align }
  9160. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  9161. (hp3.typ=ait_label) and
  9162. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  9163. (tai_label(hp3).labsym.getrefs=1) and
  9164. GetNextInstruction(hp3,hp4) and
  9165. MatchInstruction(hp4,A_MOV,[]) and
  9166. MatchOpType(taicpu(hp4),top_const,top_reg) and
  9167. (taicpu(hp4).oper[0]^.val=0) and
  9168. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  9169. GetNextInstruction(hp4,hp5) and
  9170. (hp5.typ=ait_label) and
  9171. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  9172. (tai_label(hp5).labsym.getrefs=1) then
  9173. begin
  9174. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  9175. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  9176. { remove last label }
  9177. RemoveInstruction(hp5);
  9178. { remove second label }
  9179. RemoveInstruction(hp3);
  9180. { if align is present remove it }
  9181. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  9182. RemoveInstruction(hp3);
  9183. { remove jmp }
  9184. RemoveInstruction(hp2);
  9185. if taicpu(hp1).opsize=S_B then
  9186. RemoveInstruction(hp1)
  9187. else
  9188. taicpu(hp1).loadconst(0,0);
  9189. taicpu(hp4).opcode:=A_SETcc;
  9190. taicpu(hp4).opsize:=S_B;
  9191. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  9192. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  9193. taicpu(hp4).opercnt:=1;
  9194. taicpu(hp4).ops:=1;
  9195. taicpu(hp4).freeop(1);
  9196. RemoveCurrentP(p);
  9197. Result:=true;
  9198. exit;
  9199. end
  9200. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  9201. begin
  9202. { check for
  9203. jCC xxx
  9204. <several movs>
  9205. xxx:
  9206. }
  9207. l:=0;
  9208. while assigned(hp1) and
  9209. CanBeCMOV(hp1) and
  9210. { stop on labels }
  9211. not(hp1.typ=ait_label) do
  9212. begin
  9213. inc(l);
  9214. GetNextInstruction(hp1,hp1);
  9215. end;
  9216. if assigned(hp1) then
  9217. begin
  9218. if FindLabel(tasmlabel(symbol),hp1) then
  9219. begin
  9220. if (l<=4) and (l>0) then
  9221. begin
  9222. condition:=inverse_cond(taicpu(p).condition);
  9223. UpdateUsedRegs(tai(p.next));
  9224. GetNextInstruction(p,hp1);
  9225. repeat
  9226. if not Assigned(hp1) then
  9227. InternalError(2018062900);
  9228. taicpu(hp1).opcode:=A_CMOVcc;
  9229. taicpu(hp1).condition:=condition;
  9230. UpdateUsedRegs(tai(hp1.next));
  9231. GetNextInstruction(hp1,hp1);
  9232. until not(CanBeCMOV(hp1));
  9233. { Remember what hp1 is in case there's multiple aligns to get rid of }
  9234. hp2 := hp1;
  9235. repeat
  9236. if not Assigned(hp2) then
  9237. InternalError(2018062910);
  9238. case hp2.typ of
  9239. ait_label:
  9240. { What we expected - break out of the loop (it won't be a dead label at the top of
  9241. a cluster because that was optimised at an earlier stage) }
  9242. Break;
  9243. ait_align:
  9244. { Go to the next entry until a label is found (may be multiple aligns before it) }
  9245. begin
  9246. hp2 := tai(hp2.Next);
  9247. Continue;
  9248. end;
  9249. else
  9250. begin
  9251. { Might be a comment or temporary allocation entry }
  9252. if not (hp2.typ in SkipInstr) then
  9253. InternalError(2018062911);
  9254. hp2 := tai(hp2.Next);
  9255. Continue;
  9256. end;
  9257. end;
  9258. until False;
  9259. { Now we can safely decrement the reference count }
  9260. tasmlabel(symbol).decrefs;
  9261. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  9262. { Remove the original jump }
  9263. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  9264. UpdateUsedRegs(tai(hp2.next));
  9265. GetNextInstruction(hp2, p); { Instruction after the label }
  9266. { Remove the label if this is its final reference }
  9267. if (tasmlabel(symbol).getrefs=0) then
  9268. StripLabelFast(hp1);
  9269. if Assigned(p) then
  9270. result:=true;
  9271. exit;
  9272. end;
  9273. end
  9274. else
  9275. begin
  9276. { check further for
  9277. jCC xxx
  9278. <several movs 1>
  9279. jmp yyy
  9280. xxx:
  9281. <several movs 2>
  9282. yyy:
  9283. }
  9284. { hp2 points to jmp yyy }
  9285. hp2:=hp1;
  9286. { skip hp1 to xxx (or an align right before it) }
  9287. GetNextInstruction(hp1, hp1);
  9288. if assigned(hp2) and
  9289. assigned(hp1) and
  9290. (l<=3) and
  9291. (hp2.typ=ait_instruction) and
  9292. (taicpu(hp2).is_jmp) and
  9293. (taicpu(hp2).condition=C_None) and
  9294. { real label and jump, no further references to the
  9295. label are allowed }
  9296. (tasmlabel(symbol).getrefs=1) and
  9297. FindLabel(tasmlabel(symbol),hp1) then
  9298. begin
  9299. l:=0;
  9300. { skip hp1 to <several moves 2> }
  9301. if (hp1.typ = ait_align) then
  9302. GetNextInstruction(hp1, hp1);
  9303. GetNextInstruction(hp1, hpmov2);
  9304. hp1 := hpmov2;
  9305. while assigned(hp1) and
  9306. CanBeCMOV(hp1) do
  9307. begin
  9308. inc(l);
  9309. GetNextInstruction(hp1, hp1);
  9310. end;
  9311. { hp1 points to yyy (or an align right before it) }
  9312. hp3 := hp1;
  9313. if assigned(hp1) and
  9314. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  9315. begin
  9316. condition:=inverse_cond(taicpu(p).condition);
  9317. UpdateUsedRegs(tai(p.next));
  9318. GetNextInstruction(p,hp1);
  9319. repeat
  9320. taicpu(hp1).opcode:=A_CMOVcc;
  9321. taicpu(hp1).condition:=condition;
  9322. UpdateUsedRegs(tai(hp1.next));
  9323. GetNextInstruction(hp1,hp1);
  9324. until not(assigned(hp1)) or
  9325. not(CanBeCMOV(hp1));
  9326. condition:=inverse_cond(condition);
  9327. if GetLastInstruction(hpmov2,hp1) then
  9328. UpdateUsedRegs(tai(hp1.next));
  9329. hp1 := hpmov2;
  9330. { hp1 is now at <several movs 2> }
  9331. while Assigned(hp1) and CanBeCMOV(hp1) do
  9332. begin
  9333. taicpu(hp1).opcode:=A_CMOVcc;
  9334. taicpu(hp1).condition:=condition;
  9335. UpdateUsedRegs(tai(hp1.next));
  9336. GetNextInstruction(hp1,hp1);
  9337. end;
  9338. hp1 := p;
  9339. { Get first instruction after label }
  9340. UpdateUsedRegs(tai(hp3.next));
  9341. GetNextInstruction(hp3, p);
  9342. if assigned(p) and (hp3.typ = ait_align) then
  9343. GetNextInstruction(p, p);
  9344. { Don't dereference yet, as doing so will cause
  9345. GetNextInstruction to skip the label and
  9346. optional align marker. [Kit] }
  9347. GetNextInstruction(hp2, hp4);
  9348. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  9349. { remove jCC }
  9350. RemoveInstruction(hp1);
  9351. { Now we can safely decrement it }
  9352. tasmlabel(symbol).decrefs;
  9353. { Remove label xxx (it will have a ref of zero due to the initial check }
  9354. StripLabelFast(hp4);
  9355. { remove jmp }
  9356. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  9357. RemoveInstruction(hp2);
  9358. { As before, now we can safely decrement it }
  9359. tasmlabel(symbol).decrefs;
  9360. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  9361. if tasmlabel(symbol).getrefs = 0 then
  9362. StripLabelFast(hp3);
  9363. if Assigned(p) then
  9364. result:=true;
  9365. exit;
  9366. end;
  9367. end;
  9368. end;
  9369. end;
  9370. {$endif i8086}
  9371. end;
  9372. end;
  9373. end;
  9374. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  9375. var
  9376. hp1,hp2,hp3: tai;
  9377. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  9378. NewSize: TOpSize;
  9379. NewRegSize: TSubRegister;
  9380. Limit: TCgInt;
  9381. SwapOper: POper;
  9382. begin
  9383. result:=false;
  9384. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  9385. GetNextInstruction(p,hp1) and
  9386. (hp1.typ = ait_instruction);
  9387. if reg_and_hp1_is_instr and
  9388. (
  9389. (taicpu(hp1).opcode <> A_LEA) or
  9390. { If the LEA instruction can be converted into an arithmetic instruction,
  9391. it may be possible to then fold it. }
  9392. (
  9393. { If the flags register is in use, don't change the instruction
  9394. to an ADD otherwise this will scramble the flags. [Kit] }
  9395. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  9396. ConvertLEA(taicpu(hp1))
  9397. )
  9398. ) and
  9399. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  9400. GetNextInstruction(hp1,hp2) and
  9401. MatchInstruction(hp2,A_MOV,[]) and
  9402. (taicpu(hp2).oper[0]^.typ = top_reg) and
  9403. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  9404. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  9405. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  9406. {$ifdef i386}
  9407. { not all registers have byte size sub registers on i386 }
  9408. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  9409. {$endif i386}
  9410. (((taicpu(hp1).ops=2) and
  9411. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  9412. ((taicpu(hp1).ops=1) and
  9413. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  9414. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  9415. begin
  9416. { change movsX/movzX reg/ref, reg2
  9417. add/sub/or/... reg3/$const, reg2
  9418. mov reg2 reg/ref
  9419. to add/sub/or/... reg3/$const, reg/ref }
  9420. { by example:
  9421. movswl %si,%eax movswl %si,%eax p
  9422. decl %eax addl %edx,%eax hp1
  9423. movw %ax,%si movw %ax,%si hp2
  9424. ->
  9425. movswl %si,%eax movswl %si,%eax p
  9426. decw %eax addw %edx,%eax hp1
  9427. movw %ax,%si movw %ax,%si hp2
  9428. }
  9429. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  9430. {
  9431. ->
  9432. movswl %si,%eax movswl %si,%eax p
  9433. decw %si addw %dx,%si hp1
  9434. movw %ax,%si movw %ax,%si hp2
  9435. }
  9436. case taicpu(hp1).ops of
  9437. 1:
  9438. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  9439. 2:
  9440. begin
  9441. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  9442. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9443. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  9444. end;
  9445. else
  9446. internalerror(2008042702);
  9447. end;
  9448. {
  9449. ->
  9450. decw %si addw %dx,%si p
  9451. }
  9452. DebugMsg(SPeepholeOptimization + 'var3',p);
  9453. RemoveCurrentP(p, hp1);
  9454. RemoveInstruction(hp2);
  9455. Result := True;
  9456. Exit;
  9457. end;
  9458. if reg_and_hp1_is_instr and
  9459. (taicpu(hp1).opcode = A_MOV) and
  9460. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9461. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  9462. {$ifdef x86_64}
  9463. { check for implicit extension to 64 bit }
  9464. or
  9465. ((taicpu(p).opsize in [S_BL,S_WL]) and
  9466. (taicpu(hp1).opsize=S_Q) and
  9467. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  9468. )
  9469. {$endif x86_64}
  9470. )
  9471. then
  9472. begin
  9473. { change
  9474. movx %reg1,%reg2
  9475. mov %reg2,%reg3
  9476. dealloc %reg2
  9477. into
  9478. movx %reg,%reg3
  9479. }
  9480. TransferUsedRegs(TmpUsedRegs);
  9481. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9482. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  9483. begin
  9484. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  9485. {$ifdef x86_64}
  9486. if (taicpu(p).opsize in [S_BL,S_WL]) and
  9487. (taicpu(hp1).opsize=S_Q) then
  9488. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  9489. else
  9490. {$endif x86_64}
  9491. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  9492. RemoveInstruction(hp1);
  9493. Result := True;
  9494. Exit;
  9495. end;
  9496. end;
  9497. if reg_and_hp1_is_instr and
  9498. ((taicpu(hp1).opcode=A_MOV) or
  9499. (taicpu(hp1).opcode=A_ADD) or
  9500. (taicpu(hp1).opcode=A_SUB) or
  9501. (taicpu(hp1).opcode=A_CMP) or
  9502. (taicpu(hp1).opcode=A_OR) or
  9503. (taicpu(hp1).opcode=A_XOR) or
  9504. (taicpu(hp1).opcode=A_AND)
  9505. ) and
  9506. (taicpu(hp1).oper[1]^.typ = top_reg) then
  9507. begin
  9508. AndTest := (taicpu(hp1).opcode=A_AND) and
  9509. GetNextInstruction(hp1, hp2) and
  9510. (hp2.typ = ait_instruction) and
  9511. (
  9512. (
  9513. (taicpu(hp2).opcode=A_TEST) and
  9514. (
  9515. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  9516. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  9517. (
  9518. { If the AND and TEST instructions share a constant, this is also valid }
  9519. (taicpu(hp1).oper[0]^.typ = top_const) and
  9520. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  9521. )
  9522. ) and
  9523. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  9524. ) or
  9525. (
  9526. (taicpu(hp2).opcode=A_CMP) and
  9527. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  9528. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  9529. )
  9530. );
  9531. { change
  9532. movx (oper),%reg2
  9533. and $x,%reg2
  9534. test %reg2,%reg2
  9535. dealloc %reg2
  9536. into
  9537. op %reg1,%reg3
  9538. if the second op accesses only the bits stored in reg1
  9539. }
  9540. if ((taicpu(p).oper[0]^.typ=top_reg) or
  9541. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  9542. (taicpu(hp1).oper[0]^.typ = top_const) and
  9543. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  9544. AndTest then
  9545. begin
  9546. { Check if the AND constant is in range }
  9547. case taicpu(p).opsize of
  9548. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9549. begin
  9550. NewSize := S_B;
  9551. Limit := $FF;
  9552. end;
  9553. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9554. begin
  9555. NewSize := S_W;
  9556. Limit := $FFFF;
  9557. end;
  9558. {$ifdef x86_64}
  9559. S_LQ:
  9560. begin
  9561. NewSize := S_L;
  9562. Limit := $FFFFFFFF;
  9563. end;
  9564. {$endif x86_64}
  9565. else
  9566. InternalError(2021120303);
  9567. end;
  9568. if (
  9569. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  9570. { Check for negative operands }
  9571. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  9572. ) and
  9573. GetNextInstruction(hp2,hp3) and
  9574. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  9575. (taicpu(hp3).condition in [C_E,C_NE]) then
  9576. begin
  9577. TransferUsedRegs(TmpUsedRegs);
  9578. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9579. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9580. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  9581. begin
  9582. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  9583. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  9584. taicpu(hp1).opcode := A_TEST;
  9585. taicpu(hp1).opsize := NewSize;
  9586. RemoveInstruction(hp2);
  9587. RemoveCurrentP(p, hp1);
  9588. Result:=true;
  9589. exit;
  9590. end;
  9591. end;
  9592. end;
  9593. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  9594. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  9595. (taicpu(hp1).opsize=S_B)) or
  9596. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  9597. (taicpu(hp1).opsize=S_W))
  9598. {$ifdef x86_64}
  9599. or ((taicpu(p).opsize=S_LQ) and
  9600. (taicpu(hp1).opsize=S_L))
  9601. {$endif x86_64}
  9602. ) and
  9603. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  9604. begin
  9605. { change
  9606. movx %reg1,%reg2
  9607. op %reg2,%reg3
  9608. dealloc %reg2
  9609. into
  9610. op %reg1,%reg3
  9611. if the second op accesses only the bits stored in reg1
  9612. }
  9613. TransferUsedRegs(TmpUsedRegs);
  9614. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9615. if AndTest then
  9616. begin
  9617. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  9618. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  9619. end
  9620. else
  9621. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  9622. if not RegUsed then
  9623. begin
  9624. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  9625. if taicpu(p).oper[0]^.typ=top_reg then
  9626. begin
  9627. case taicpu(hp1).opsize of
  9628. S_B:
  9629. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  9630. S_W:
  9631. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  9632. S_L:
  9633. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  9634. else
  9635. Internalerror(2020102301);
  9636. end;
  9637. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  9638. end
  9639. else
  9640. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  9641. RemoveCurrentP(p);
  9642. if AndTest then
  9643. RemoveInstruction(hp2);
  9644. result:=true;
  9645. exit;
  9646. end;
  9647. end
  9648. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  9649. (
  9650. { Bitwise operations only }
  9651. (taicpu(hp1).opcode=A_AND) or
  9652. (taicpu(hp1).opcode=A_TEST) or
  9653. (
  9654. (taicpu(hp1).oper[0]^.typ = top_const) and
  9655. (
  9656. (taicpu(hp1).opcode=A_OR) or
  9657. (taicpu(hp1).opcode=A_XOR)
  9658. )
  9659. )
  9660. ) and
  9661. (
  9662. (taicpu(hp1).oper[0]^.typ = top_const) or
  9663. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  9664. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  9665. ) then
  9666. begin
  9667. { change
  9668. movx %reg2,%reg2
  9669. op const,%reg2
  9670. into
  9671. op const,%reg2 (smaller version)
  9672. movx %reg2,%reg2
  9673. also change
  9674. movx %reg1,%reg2
  9675. and/test (oper),%reg2
  9676. dealloc %reg2
  9677. into
  9678. and/test (oper),%reg1
  9679. }
  9680. case taicpu(p).opsize of
  9681. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9682. begin
  9683. NewSize := S_B;
  9684. NewRegSize := R_SUBL;
  9685. Limit := $FF;
  9686. end;
  9687. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9688. begin
  9689. NewSize := S_W;
  9690. NewRegSize := R_SUBW;
  9691. Limit := $FFFF;
  9692. end;
  9693. {$ifdef x86_64}
  9694. S_LQ:
  9695. begin
  9696. NewSize := S_L;
  9697. NewRegSize := R_SUBD;
  9698. Limit := $FFFFFFFF;
  9699. end;
  9700. {$endif x86_64}
  9701. else
  9702. Internalerror(2021120302);
  9703. end;
  9704. TransferUsedRegs(TmpUsedRegs);
  9705. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9706. if AndTest then
  9707. begin
  9708. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  9709. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  9710. end
  9711. else
  9712. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  9713. if
  9714. (
  9715. (taicpu(p).opcode = A_MOVZX) and
  9716. (
  9717. (taicpu(hp1).opcode=A_AND) or
  9718. (taicpu(hp1).opcode=A_TEST)
  9719. ) and
  9720. not (
  9721. { If both are references, then the final instruction will have
  9722. both operands as references, which is not allowed }
  9723. (taicpu(p).oper[0]^.typ = top_ref) and
  9724. (taicpu(hp1).oper[0]^.typ = top_ref)
  9725. ) and
  9726. not RegUsed
  9727. ) or
  9728. (
  9729. (
  9730. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  9731. not RegUsed
  9732. ) and
  9733. (taicpu(p).oper[0]^.typ = top_reg) and
  9734. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  9735. (taicpu(hp1).oper[0]^.typ = top_const) and
  9736. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  9737. ) then
  9738. begin
  9739. {$if defined(i386) or defined(i8086)}
  9740. { If the target size is 8-bit, make sure we can actually encode it }
  9741. 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
  9742. Exit;
  9743. {$endif i386 or i8086}
  9744. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  9745. taicpu(hp1).opsize := NewSize;
  9746. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  9747. if AndTest then
  9748. begin
  9749. RemoveInstruction(hp2);
  9750. if not RegUsed then
  9751. begin
  9752. taicpu(hp1).opcode := A_TEST;
  9753. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  9754. begin
  9755. { Make sure the reference is the second operand }
  9756. SwapOper := taicpu(hp1).oper[0];
  9757. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  9758. taicpu(hp1).oper[1] := SwapOper;
  9759. end;
  9760. end;
  9761. end;
  9762. case taicpu(hp1).oper[0]^.typ of
  9763. top_reg:
  9764. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  9765. top_const:
  9766. { For the AND/TEST case }
  9767. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  9768. else
  9769. ;
  9770. end;
  9771. if RegUsed then
  9772. begin
  9773. AsmL.Remove(p);
  9774. AsmL.InsertAfter(p, hp1);
  9775. p := hp1;
  9776. end
  9777. else
  9778. RemoveCurrentP(p, hp1);
  9779. result:=true;
  9780. exit;
  9781. end;
  9782. end;
  9783. end;
  9784. if reg_and_hp1_is_instr and
  9785. (taicpu(p).oper[0]^.typ = top_reg) and
  9786. (
  9787. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  9788. ) and
  9789. (taicpu(hp1).oper[0]^.typ = top_const) and
  9790. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  9791. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  9792. { Minimum shift value allowed is the bit difference between the sizes }
  9793. (taicpu(hp1).oper[0]^.val >=
  9794. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  9795. 8 * (
  9796. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  9797. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  9798. )
  9799. ) then
  9800. begin
  9801. { For:
  9802. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  9803. shl/sal ##, %reg1
  9804. Remove the movsx/movzx instruction if the shift overwrites the
  9805. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  9806. }
  9807. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  9808. RemoveCurrentP(p, hp1);
  9809. Result := True;
  9810. Exit;
  9811. end
  9812. else if reg_and_hp1_is_instr and
  9813. (taicpu(p).oper[0]^.typ = top_reg) and
  9814. (
  9815. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  9816. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  9817. ) and
  9818. (taicpu(hp1).oper[0]^.typ = top_const) and
  9819. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  9820. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  9821. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  9822. (taicpu(hp1).oper[0]^.val <
  9823. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  9824. 8 * (
  9825. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  9826. )
  9827. ) then
  9828. begin
  9829. { For:
  9830. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  9831. sar ##, %reg1 shr ##, %reg1
  9832. Move the shift to before the movx instruction if the shift value
  9833. is not too large.
  9834. }
  9835. asml.Remove(hp1);
  9836. asml.InsertBefore(hp1, p);
  9837. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  9838. case taicpu(p).opsize of
  9839. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  9840. taicpu(hp1).opsize := S_B;
  9841. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  9842. taicpu(hp1).opsize := S_W;
  9843. {$ifdef x86_64}
  9844. S_LQ:
  9845. taicpu(hp1).opsize := S_L;
  9846. {$endif}
  9847. else
  9848. InternalError(2020112401);
  9849. end;
  9850. if (taicpu(hp1).opcode = A_SHR) then
  9851. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  9852. else
  9853. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  9854. Result := True;
  9855. end;
  9856. if reg_and_hp1_is_instr and
  9857. (taicpu(p).oper[0]^.typ = top_reg) and
  9858. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  9859. (
  9860. (taicpu(hp1).opcode = taicpu(p).opcode)
  9861. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  9862. {$ifdef x86_64}
  9863. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  9864. {$endif x86_64}
  9865. ) then
  9866. begin
  9867. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  9868. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  9869. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  9870. begin
  9871. {
  9872. For example:
  9873. movzbw %al,%ax
  9874. movzwl %ax,%eax
  9875. Compress into:
  9876. movzbl %al,%eax
  9877. }
  9878. RegUsed := False;
  9879. case taicpu(p).opsize of
  9880. S_BW:
  9881. case taicpu(hp1).opsize of
  9882. S_WL:
  9883. begin
  9884. taicpu(p).opsize := S_BL;
  9885. RegUsed := True;
  9886. end;
  9887. {$ifdef x86_64}
  9888. S_WQ:
  9889. begin
  9890. if taicpu(p).opcode = A_MOVZX then
  9891. begin
  9892. taicpu(p).opsize := S_BL;
  9893. { 64-bit zero extension is implicit, so change to the 32-bit register }
  9894. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9895. end
  9896. else
  9897. taicpu(p).opsize := S_BQ;
  9898. RegUsed := True;
  9899. end;
  9900. {$endif x86_64}
  9901. else
  9902. ;
  9903. end;
  9904. {$ifdef x86_64}
  9905. S_BL:
  9906. case taicpu(hp1).opsize of
  9907. S_LQ:
  9908. begin
  9909. if taicpu(p).opcode = A_MOVZX then
  9910. begin
  9911. taicpu(p).opsize := S_BL;
  9912. { 64-bit zero extension is implicit, so change to the 32-bit register }
  9913. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9914. end
  9915. else
  9916. taicpu(p).opsize := S_BQ;
  9917. RegUsed := True;
  9918. end;
  9919. else
  9920. ;
  9921. end;
  9922. S_WL:
  9923. case taicpu(hp1).opsize of
  9924. S_LQ:
  9925. begin
  9926. if taicpu(p).opcode = A_MOVZX then
  9927. begin
  9928. taicpu(p).opsize := S_WL;
  9929. { 64-bit zero extension is implicit, so change to the 32-bit register }
  9930. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9931. end
  9932. else
  9933. taicpu(p).opsize := S_WQ;
  9934. RegUsed := True;
  9935. end;
  9936. else
  9937. ;
  9938. end;
  9939. {$endif x86_64}
  9940. else
  9941. ;
  9942. end;
  9943. if RegUsed then
  9944. begin
  9945. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  9946. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  9947. RemoveInstruction(hp1);
  9948. Result := True;
  9949. Exit;
  9950. end;
  9951. end;
  9952. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  9953. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  9954. GetNextInstruction(hp1, hp2) and
  9955. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  9956. (
  9957. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  9958. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  9959. {$ifdef x86_64}
  9960. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  9961. {$endif x86_64}
  9962. ) and
  9963. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  9964. (
  9965. (
  9966. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9967. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  9968. ) or
  9969. (
  9970. { Only allow the operands in reverse order for TEST instructions }
  9971. (taicpu(hp2).opcode = A_TEST) and
  9972. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  9973. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  9974. )
  9975. ) then
  9976. begin
  9977. {
  9978. For example:
  9979. movzbl %al,%eax
  9980. movzbl (ref),%edx
  9981. andl %edx,%eax
  9982. (%edx deallocated)
  9983. Change to:
  9984. andb (ref),%al
  9985. movzbl %al,%eax
  9986. Rules are:
  9987. - First two instructions have the same opcode and opsize
  9988. - First instruction's operands are the same super-register
  9989. - Second instruction operates on a different register
  9990. - Third instruction is AND, OR, XOR or TEST
  9991. - Third instruction's operands are the destination registers of the first two instructions
  9992. - Third instruction writes to the destination register of the first instruction (except with TEST)
  9993. - Second instruction's destination register is deallocated afterwards
  9994. }
  9995. TransferUsedRegs(TmpUsedRegs);
  9996. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9997. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9998. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  9999. begin
  10000. case taicpu(p).opsize of
  10001. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10002. NewSize := S_B;
  10003. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10004. NewSize := S_W;
  10005. {$ifdef x86_64}
  10006. S_LQ:
  10007. NewSize := S_L;
  10008. {$endif x86_64}
  10009. else
  10010. InternalError(2021120301);
  10011. end;
  10012. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  10013. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  10014. taicpu(hp2).opsize := NewSize;
  10015. RemoveInstruction(hp1);
  10016. { With TEST, it's best to keep the MOVX instruction at the top }
  10017. if (taicpu(hp2).opcode <> A_TEST) then
  10018. begin
  10019. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  10020. asml.Remove(p);
  10021. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  10022. asml.InsertAfter(p, hp2);
  10023. p := hp2;
  10024. end
  10025. else
  10026. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  10027. Result := True;
  10028. Exit;
  10029. end;
  10030. end;
  10031. end;
  10032. if taicpu(p).opcode=A_MOVZX then
  10033. begin
  10034. { removes superfluous And's after movzx's }
  10035. if reg_and_hp1_is_instr and
  10036. (taicpu(hp1).opcode = A_AND) and
  10037. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10038. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  10039. {$ifdef x86_64}
  10040. { check for implicit extension to 64 bit }
  10041. or
  10042. ((taicpu(p).opsize in [S_BL,S_WL]) and
  10043. (taicpu(hp1).opsize=S_Q) and
  10044. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  10045. )
  10046. {$endif x86_64}
  10047. )
  10048. then
  10049. begin
  10050. case taicpu(p).opsize Of
  10051. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10052. if (taicpu(hp1).oper[0]^.val = $ff) then
  10053. begin
  10054. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  10055. RemoveInstruction(hp1);
  10056. Result:=true;
  10057. exit;
  10058. end;
  10059. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10060. if (taicpu(hp1).oper[0]^.val = $ffff) then
  10061. begin
  10062. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  10063. RemoveInstruction(hp1);
  10064. Result:=true;
  10065. exit;
  10066. end;
  10067. {$ifdef x86_64}
  10068. S_LQ:
  10069. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  10070. begin
  10071. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  10072. RemoveInstruction(hp1);
  10073. Result:=true;
  10074. exit;
  10075. end;
  10076. {$endif x86_64}
  10077. else
  10078. ;
  10079. end;
  10080. { we cannot get rid of the and, but can we get rid of the movz ?}
  10081. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  10082. begin
  10083. case taicpu(p).opsize Of
  10084. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10085. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  10086. begin
  10087. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  10088. RemoveCurrentP(p,hp1);
  10089. Result:=true;
  10090. exit;
  10091. end;
  10092. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10093. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  10094. begin
  10095. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  10096. RemoveCurrentP(p,hp1);
  10097. Result:=true;
  10098. exit;
  10099. end;
  10100. {$ifdef x86_64}
  10101. S_LQ:
  10102. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  10103. begin
  10104. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  10105. RemoveCurrentP(p,hp1);
  10106. Result:=true;
  10107. exit;
  10108. end;
  10109. {$endif x86_64}
  10110. else
  10111. ;
  10112. end;
  10113. end;
  10114. end;
  10115. { changes some movzx constructs to faster synonyms (all examples
  10116. are given with eax/ax, but are also valid for other registers)}
  10117. if MatchOpType(taicpu(p),top_reg,top_reg) then
  10118. begin
  10119. case taicpu(p).opsize of
  10120. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  10121. (the machine code is equivalent to movzbl %al,%eax), but the
  10122. code generator still generates that assembler instruction and
  10123. it is silently converted. This should probably be checked.
  10124. [Kit] }
  10125. S_BW:
  10126. begin
  10127. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10128. (
  10129. not IsMOVZXAcceptable
  10130. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  10131. or (
  10132. (cs_opt_size in current_settings.optimizerswitches) and
  10133. (taicpu(p).oper[1]^.reg = NR_AX)
  10134. )
  10135. ) then
  10136. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  10137. begin
  10138. DebugMsg(SPeepholeOptimization + 'var7',p);
  10139. taicpu(p).opcode := A_AND;
  10140. taicpu(p).changeopsize(S_W);
  10141. taicpu(p).loadConst(0,$ff);
  10142. Result := True;
  10143. end
  10144. else if not IsMOVZXAcceptable and
  10145. GetNextInstruction(p, hp1) and
  10146. (tai(hp1).typ = ait_instruction) and
  10147. (taicpu(hp1).opcode = A_AND) and
  10148. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10149. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10150. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  10151. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  10152. begin
  10153. DebugMsg(SPeepholeOptimization + 'var8',p);
  10154. taicpu(p).opcode := A_MOV;
  10155. taicpu(p).changeopsize(S_W);
  10156. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  10157. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10158. Result := True;
  10159. end;
  10160. end;
  10161. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  10162. S_BL:
  10163. begin
  10164. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10165. (
  10166. not IsMOVZXAcceptable
  10167. { and $0xff,%eax has a smaller encoding but risks a partial write penalty }
  10168. or (
  10169. (cs_opt_size in current_settings.optimizerswitches) and
  10170. (taicpu(p).oper[1]^.reg = NR_EAX)
  10171. )
  10172. ) then
  10173. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  10174. begin
  10175. DebugMsg(SPeepholeOptimization + 'var9',p);
  10176. taicpu(p).opcode := A_AND;
  10177. taicpu(p).changeopsize(S_L);
  10178. taicpu(p).loadConst(0,$ff);
  10179. Result := True;
  10180. end
  10181. else if not IsMOVZXAcceptable and
  10182. GetNextInstruction(p, hp1) and
  10183. (tai(hp1).typ = ait_instruction) and
  10184. (taicpu(hp1).opcode = A_AND) and
  10185. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10186. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10187. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  10188. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  10189. begin
  10190. DebugMsg(SPeepholeOptimization + 'var10',p);
  10191. taicpu(p).opcode := A_MOV;
  10192. taicpu(p).changeopsize(S_L);
  10193. { do not use R_SUBWHOLE
  10194. as movl %rdx,%eax
  10195. is invalid in assembler PM }
  10196. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10197. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10198. Result := True;
  10199. end;
  10200. end;
  10201. {$endif i8086}
  10202. S_WL:
  10203. if not IsMOVZXAcceptable then
  10204. begin
  10205. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  10206. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  10207. begin
  10208. DebugMsg(SPeepholeOptimization + 'var11',p);
  10209. taicpu(p).opcode := A_AND;
  10210. taicpu(p).changeopsize(S_L);
  10211. taicpu(p).loadConst(0,$ffff);
  10212. Result := True;
  10213. end
  10214. else if GetNextInstruction(p, hp1) and
  10215. (tai(hp1).typ = ait_instruction) and
  10216. (taicpu(hp1).opcode = A_AND) and
  10217. (taicpu(hp1).oper[0]^.typ = top_const) and
  10218. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10219. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10220. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  10221. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  10222. begin
  10223. DebugMsg(SPeepholeOptimization + 'var12',p);
  10224. taicpu(p).opcode := A_MOV;
  10225. taicpu(p).changeopsize(S_L);
  10226. { do not use R_SUBWHOLE
  10227. as movl %rdx,%eax
  10228. is invalid in assembler PM }
  10229. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10230. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10231. Result := True;
  10232. end;
  10233. end;
  10234. else
  10235. InternalError(2017050705);
  10236. end;
  10237. end
  10238. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  10239. begin
  10240. if GetNextInstruction(p, hp1) and
  10241. (tai(hp1).typ = ait_instruction) and
  10242. (taicpu(hp1).opcode = A_AND) and
  10243. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10244. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10245. begin
  10246. //taicpu(p).opcode := A_MOV;
  10247. case taicpu(p).opsize Of
  10248. S_BL:
  10249. begin
  10250. DebugMsg(SPeepholeOptimization + 'var13',p);
  10251. taicpu(hp1).changeopsize(S_L);
  10252. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10253. end;
  10254. S_WL:
  10255. begin
  10256. DebugMsg(SPeepholeOptimization + 'var14',p);
  10257. taicpu(hp1).changeopsize(S_L);
  10258. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10259. end;
  10260. S_BW:
  10261. begin
  10262. DebugMsg(SPeepholeOptimization + 'var15',p);
  10263. taicpu(hp1).changeopsize(S_W);
  10264. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10265. end;
  10266. else
  10267. Internalerror(2017050704)
  10268. end;
  10269. Result := True;
  10270. end;
  10271. end;
  10272. end;
  10273. end;
  10274. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  10275. var
  10276. hp1, hp2 : tai;
  10277. MaskLength : Cardinal;
  10278. MaskedBits : TCgInt;
  10279. ActiveReg : TRegister;
  10280. begin
  10281. Result:=false;
  10282. { There are no optimisations for reference targets }
  10283. if (taicpu(p).oper[1]^.typ <> top_reg) then
  10284. Exit;
  10285. while GetNextInstruction(p, hp1) and
  10286. (hp1.typ = ait_instruction) do
  10287. begin
  10288. if (taicpu(p).oper[0]^.typ = top_const) then
  10289. begin
  10290. case taicpu(hp1).opcode of
  10291. A_AND:
  10292. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10293. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10294. { the second register must contain the first one, so compare their subreg types }
  10295. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  10296. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  10297. { change
  10298. and const1, reg
  10299. and const2, reg
  10300. to
  10301. and (const1 and const2), reg
  10302. }
  10303. begin
  10304. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  10305. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  10306. RemoveCurrentP(p, hp1);
  10307. Result:=true;
  10308. exit;
  10309. end;
  10310. A_CMP:
  10311. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  10312. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  10313. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10314. { Just check that the condition on the next instruction is compatible }
  10315. GetNextInstruction(hp1, hp2) and
  10316. (hp2.typ = ait_instruction) and
  10317. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  10318. then
  10319. { change
  10320. and 2^n, reg
  10321. cmp 2^n, reg
  10322. j(c) / set(c) / cmov(c) (c is equal or not equal)
  10323. to
  10324. and 2^n, reg
  10325. test reg, reg
  10326. j(~c) / set(~c) / cmov(~c)
  10327. }
  10328. begin
  10329. { Keep TEST instruction in, rather than remove it, because
  10330. it may trigger other optimisations such as MovAndTest2Test }
  10331. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  10332. taicpu(hp1).opcode := A_TEST;
  10333. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  10334. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  10335. Result := True;
  10336. Exit;
  10337. end;
  10338. A_MOVZX:
  10339. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10340. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  10341. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10342. (
  10343. (
  10344. (taicpu(p).opsize=S_W) and
  10345. (taicpu(hp1).opsize=S_BW)
  10346. ) or
  10347. (
  10348. (taicpu(p).opsize=S_L) and
  10349. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  10350. )
  10351. {$ifdef x86_64}
  10352. or
  10353. (
  10354. (taicpu(p).opsize=S_Q) and
  10355. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  10356. )
  10357. {$endif x86_64}
  10358. ) then
  10359. begin
  10360. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10361. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  10362. ) or
  10363. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10364. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  10365. then
  10366. begin
  10367. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  10368. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  10369. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  10370. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  10371. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  10372. }
  10373. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  10374. RemoveInstruction(hp1);
  10375. { See if there are other optimisations possible }
  10376. Continue;
  10377. end;
  10378. end;
  10379. A_SHL:
  10380. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10381. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  10382. begin
  10383. {$ifopt R+}
  10384. {$define RANGE_WAS_ON}
  10385. {$R-}
  10386. {$endif}
  10387. { get length of potential and mask }
  10388. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  10389. { really a mask? }
  10390. {$ifdef RANGE_WAS_ON}
  10391. {$R+}
  10392. {$endif}
  10393. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  10394. { unmasked part shifted out? }
  10395. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  10396. begin
  10397. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  10398. RemoveCurrentP(p, hp1);
  10399. Result:=true;
  10400. exit;
  10401. end;
  10402. end;
  10403. A_SHR:
  10404. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10405. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  10406. (taicpu(hp1).oper[0]^.val <= 63) then
  10407. begin
  10408. { Does SHR combined with the AND cover all the bits?
  10409. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  10410. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  10411. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  10412. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  10413. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  10414. begin
  10415. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  10416. RemoveCurrentP(p, hp1);
  10417. Result := True;
  10418. Exit;
  10419. end;
  10420. end;
  10421. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10422. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  10423. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10424. begin
  10425. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  10426. (
  10427. (
  10428. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10429. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  10430. ) or (
  10431. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10432. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  10433. {$ifdef x86_64}
  10434. ) or (
  10435. (taicpu(hp1).opsize = S_LQ) and
  10436. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  10437. {$endif x86_64}
  10438. )
  10439. ) then
  10440. begin
  10441. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  10442. begin
  10443. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  10444. RemoveInstruction(hp1);
  10445. { See if there are other optimisations possible }
  10446. Continue;
  10447. end;
  10448. { The super-registers are the same though.
  10449. Note that this change by itself doesn't improve
  10450. code speed, but it opens up other optimisations. }
  10451. {$ifdef x86_64}
  10452. { Convert 64-bit register to 32-bit }
  10453. case taicpu(hp1).opsize of
  10454. S_BQ:
  10455. begin
  10456. taicpu(hp1).opsize := S_BL;
  10457. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  10458. end;
  10459. S_WQ:
  10460. begin
  10461. taicpu(hp1).opsize := S_WL;
  10462. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  10463. end
  10464. else
  10465. ;
  10466. end;
  10467. {$endif x86_64}
  10468. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  10469. taicpu(hp1).opcode := A_MOVZX;
  10470. { See if there are other optimisations possible }
  10471. Continue;
  10472. end;
  10473. end;
  10474. else
  10475. ;
  10476. end;
  10477. end
  10478. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  10479. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  10480. begin
  10481. {$ifdef x86_64}
  10482. if (taicpu(p).opsize = S_Q) then
  10483. begin
  10484. { Never necessary }
  10485. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  10486. RemoveCurrentP(p, hp1);
  10487. Result := True;
  10488. Exit;
  10489. end;
  10490. {$endif x86_64}
  10491. { Forward check to determine necessity of and %reg,%reg }
  10492. TransferUsedRegs(TmpUsedRegs);
  10493. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10494. { Saves on a bunch of dereferences }
  10495. ActiveReg := taicpu(p).oper[1]^.reg;
  10496. case taicpu(hp1).opcode of
  10497. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10498. if (
  10499. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10500. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10501. ) and
  10502. (
  10503. (taicpu(hp1).opcode <> A_MOV) or
  10504. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  10505. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  10506. ) and
  10507. not (
  10508. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  10509. (taicpu(hp1).opcode = A_MOV) and
  10510. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  10511. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  10512. ) and
  10513. (
  10514. (
  10515. (taicpu(hp1).oper[0]^.typ = top_reg) and
  10516. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  10517. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  10518. ) or
  10519. (
  10520. {$ifdef x86_64}
  10521. (
  10522. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  10523. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  10524. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  10525. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  10526. ) and
  10527. {$endif x86_64}
  10528. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  10529. )
  10530. ) then
  10531. begin
  10532. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  10533. RemoveCurrentP(p, hp1);
  10534. Result := True;
  10535. Exit;
  10536. end;
  10537. A_ADD,
  10538. A_AND,
  10539. A_BSF,
  10540. A_BSR,
  10541. A_BTC,
  10542. A_BTR,
  10543. A_BTS,
  10544. A_OR,
  10545. A_SUB,
  10546. A_XOR:
  10547. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  10548. if (
  10549. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10550. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10551. ) and
  10552. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  10553. begin
  10554. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  10555. RemoveCurrentP(p, hp1);
  10556. Result := True;
  10557. Exit;
  10558. end;
  10559. A_CMP,
  10560. A_TEST:
  10561. if (
  10562. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10563. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10564. ) and
  10565. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  10566. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  10567. begin
  10568. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  10569. RemoveCurrentP(p, hp1);
  10570. Result := True;
  10571. Exit;
  10572. end;
  10573. A_BSWAP,
  10574. A_NEG,
  10575. A_NOT:
  10576. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  10577. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  10578. begin
  10579. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  10580. RemoveCurrentP(p, hp1);
  10581. Result := True;
  10582. Exit;
  10583. end;
  10584. else
  10585. ;
  10586. end;
  10587. end;
  10588. if (taicpu(hp1).is_jmp) and
  10589. (taicpu(hp1).opcode<>A_JMP) and
  10590. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  10591. begin
  10592. { change
  10593. and x, reg
  10594. jxx
  10595. to
  10596. test x, reg
  10597. jxx
  10598. if reg is deallocated before the
  10599. jump, but only if it's a conditional jump (PFV)
  10600. }
  10601. taicpu(p).opcode := A_TEST;
  10602. Exit;
  10603. end;
  10604. Break;
  10605. end;
  10606. { Lone AND tests }
  10607. if (taicpu(p).oper[0]^.typ = top_const) then
  10608. begin
  10609. {
  10610. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  10611. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  10612. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  10613. }
  10614. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  10615. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  10616. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  10617. begin
  10618. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  10619. if taicpu(p).opsize = S_L then
  10620. begin
  10621. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  10622. Result := True;
  10623. end;
  10624. end;
  10625. end;
  10626. { Backward check to determine necessity of and %reg,%reg }
  10627. if (taicpu(p).oper[0]^.typ = top_reg) and
  10628. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  10629. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  10630. GetLastInstruction(p, hp2) and
  10631. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  10632. { Check size of adjacent instruction to determine if the AND is
  10633. effectively a null operation }
  10634. (
  10635. (taicpu(p).opsize = taicpu(hp2).opsize) or
  10636. { Note: Don't include S_Q }
  10637. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  10638. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  10639. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  10640. ) then
  10641. begin
  10642. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  10643. { If GetNextInstruction returned False, hp1 will be nil }
  10644. RemoveCurrentP(p, hp1);
  10645. Result := True;
  10646. Exit;
  10647. end;
  10648. end;
  10649. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  10650. var
  10651. hp1: tai; NewRef: TReference;
  10652. { This entire nested function is used in an if-statement below, but we
  10653. want to avoid all the used reg transfers and GetNextInstruction calls
  10654. until we really have to check }
  10655. function MemRegisterNotUsedLater: Boolean; inline;
  10656. var
  10657. hp2: tai;
  10658. begin
  10659. TransferUsedRegs(TmpUsedRegs);
  10660. hp2 := p;
  10661. repeat
  10662. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  10663. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  10664. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  10665. end;
  10666. begin
  10667. Result := False;
  10668. if not GetNextInstruction(p, hp1) or (hp1.typ <> ait_instruction) then
  10669. Exit;
  10670. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) then
  10671. begin
  10672. { Change:
  10673. add %reg2,%reg1
  10674. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  10675. To:
  10676. mov/s/z #(%reg1,%reg2),%reg1
  10677. }
  10678. if MatchOpType(taicpu(p), top_reg, top_reg) and
  10679. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  10680. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  10681. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  10682. (
  10683. (
  10684. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  10685. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  10686. { r/esp cannot be an index }
  10687. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  10688. ) or (
  10689. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  10690. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  10691. )
  10692. ) and (
  10693. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  10694. (
  10695. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  10696. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  10697. MemRegisterNotUsedLater
  10698. )
  10699. ) then
  10700. begin
  10701. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  10702. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  10703. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  10704. RemoveCurrentp(p, hp1);
  10705. Result := True;
  10706. Exit;
  10707. end;
  10708. { Change:
  10709. addl/q $x,%reg1
  10710. movl/q %reg1,%reg2
  10711. To:
  10712. leal/q $x(%reg1),%reg2
  10713. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  10714. Breaks the dependency chain.
  10715. }
  10716. if MatchOpType(taicpu(p),top_const,top_reg) and
  10717. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  10718. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10719. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  10720. (
  10721. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  10722. not (cs_opt_size in current_settings.optimizerswitches) or
  10723. (
  10724. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  10725. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  10726. )
  10727. ) then
  10728. begin
  10729. { Change the MOV instruction to a LEA instruction, and update the
  10730. first operand }
  10731. reference_reset(NewRef, 1, []);
  10732. NewRef.base := taicpu(p).oper[1]^.reg;
  10733. NewRef.scalefactor := 1;
  10734. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  10735. taicpu(hp1).opcode := A_LEA;
  10736. taicpu(hp1).loadref(0, NewRef);
  10737. TransferUsedRegs(TmpUsedRegs);
  10738. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10739. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  10740. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  10741. begin
  10742. { Move what is now the LEA instruction to before the SUB instruction }
  10743. Asml.Remove(hp1);
  10744. Asml.InsertBefore(hp1, p);
  10745. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  10746. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  10747. p := hp1;
  10748. end
  10749. else
  10750. begin
  10751. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  10752. RemoveCurrentP(p, hp1);
  10753. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', p);
  10754. end;
  10755. Result := True;
  10756. end;
  10757. end;
  10758. end;
  10759. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  10760. var
  10761. SubReg: TSubRegister;
  10762. begin
  10763. Result:=false;
  10764. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  10765. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  10766. with taicpu(p).oper[0]^.ref^ do
  10767. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  10768. begin
  10769. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  10770. begin
  10771. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  10772. taicpu(p).opcode := A_ADD;
  10773. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  10774. Result := True;
  10775. end
  10776. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  10777. begin
  10778. if (base <> NR_NO) then
  10779. begin
  10780. if (scalefactor <= 1) then
  10781. begin
  10782. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  10783. taicpu(p).opcode := A_ADD;
  10784. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  10785. Result := True;
  10786. end;
  10787. end
  10788. else
  10789. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  10790. if (scalefactor in [2, 4, 8]) then
  10791. begin
  10792. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  10793. taicpu(p).loadconst(0, BsrByte(scalefactor));
  10794. taicpu(p).opcode := A_SHL;
  10795. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  10796. Result := True;
  10797. end;
  10798. end;
  10799. end;
  10800. end;
  10801. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  10802. var
  10803. hp1: tai; NewRef: TReference;
  10804. begin
  10805. { Change:
  10806. subl/q $x,%reg1
  10807. movl/q %reg1,%reg2
  10808. To:
  10809. leal/q $-x(%reg1),%reg2
  10810. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  10811. Breaks the dependency chain and potentially permits the removal of
  10812. a CMP instruction if one follows.
  10813. }
  10814. Result := False;
  10815. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  10816. MatchOpType(taicpu(p),top_const,top_reg) and
  10817. GetNextInstruction(p, hp1) and
  10818. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  10819. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10820. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  10821. (
  10822. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  10823. not (cs_opt_size in current_settings.optimizerswitches) or
  10824. (
  10825. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  10826. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  10827. )
  10828. ) then
  10829. begin
  10830. { Change the MOV instruction to a LEA instruction, and update the
  10831. first operand }
  10832. reference_reset(NewRef, 1, []);
  10833. NewRef.base := taicpu(p).oper[1]^.reg;
  10834. NewRef.scalefactor := 1;
  10835. NewRef.offset := -taicpu(p).oper[0]^.val;
  10836. taicpu(hp1).opcode := A_LEA;
  10837. taicpu(hp1).loadref(0, NewRef);
  10838. TransferUsedRegs(TmpUsedRegs);
  10839. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10840. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  10841. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  10842. begin
  10843. { Move what is now the LEA instruction to before the SUB instruction }
  10844. Asml.Remove(hp1);
  10845. Asml.InsertBefore(hp1, p);
  10846. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  10847. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  10848. p := hp1;
  10849. end
  10850. else
  10851. begin
  10852. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  10853. RemoveCurrentP(p, hp1);
  10854. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', p);
  10855. end;
  10856. Result := True;
  10857. end;
  10858. end;
  10859. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  10860. begin
  10861. { we can skip all instructions not messing with the stack pointer }
  10862. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  10863. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  10864. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  10865. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  10866. ({(taicpu(hp1).ops=0) or }
  10867. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  10868. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  10869. ) and }
  10870. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  10871. )
  10872. ) do
  10873. GetNextInstruction(hp1,hp1);
  10874. Result:=assigned(hp1);
  10875. end;
  10876. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  10877. var
  10878. hp1, hp2, hp3, hp4, hp5: tai;
  10879. begin
  10880. Result:=false;
  10881. hp5:=nil;
  10882. { replace
  10883. leal(q) x(<stackpointer>),<stackpointer>
  10884. call procname
  10885. leal(q) -x(<stackpointer>),<stackpointer>
  10886. ret
  10887. by
  10888. jmp procname
  10889. but do it only on level 4 because it destroys stack back traces
  10890. }
  10891. if (cs_opt_level4 in current_settings.optimizerswitches) and
  10892. MatchOpType(taicpu(p),top_ref,top_reg) and
  10893. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  10894. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  10895. { the -8 or -24 are not required, but bail out early if possible,
  10896. higher values are unlikely }
  10897. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  10898. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  10899. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  10900. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  10901. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and
  10902. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  10903. GetNextInstruction(p, hp1) and
  10904. { Take a copy of hp1 }
  10905. SetAndTest(hp1, hp4) and
  10906. { trick to skip label }
  10907. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  10908. SkipSimpleInstructions(hp1) and
  10909. MatchInstruction(hp1,A_CALL,[S_NO]) and
  10910. GetNextInstruction(hp1, hp2) and
  10911. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  10912. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  10913. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  10914. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  10915. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  10916. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  10917. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  10918. (taicpu(hp2).oper[0]^.ref^.segment=NR_NO) and
  10919. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  10920. GetNextInstruction(hp2, hp3) and
  10921. { trick to skip label }
  10922. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  10923. (MatchInstruction(hp3,A_RET,[S_NO]) or
  10924. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  10925. SetAndTest(hp3,hp5) and
  10926. GetNextInstruction(hp3,hp3) and
  10927. MatchInstruction(hp3,A_RET,[S_NO])
  10928. )
  10929. ) and
  10930. (taicpu(hp3).ops=0) then
  10931. begin
  10932. taicpu(hp1).opcode := A_JMP;
  10933. taicpu(hp1).is_jmp := true;
  10934. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  10935. RemoveCurrentP(p, hp4);
  10936. RemoveInstruction(hp2);
  10937. RemoveInstruction(hp3);
  10938. if Assigned(hp5) then
  10939. begin
  10940. AsmL.Remove(hp5);
  10941. ASmL.InsertBefore(hp5,hp1)
  10942. end;
  10943. Result:=true;
  10944. end;
  10945. end;
  10946. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  10947. {$ifdef x86_64}
  10948. var
  10949. hp1, hp2, hp3, hp4, hp5: tai;
  10950. {$endif x86_64}
  10951. begin
  10952. Result:=false;
  10953. {$ifdef x86_64}
  10954. hp5:=nil;
  10955. { replace
  10956. push %rax
  10957. call procname
  10958. pop %rcx
  10959. ret
  10960. by
  10961. jmp procname
  10962. but do it only on level 4 because it destroys stack back traces
  10963. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  10964. for all supported calling conventions
  10965. }
  10966. if (cs_opt_level4 in current_settings.optimizerswitches) and
  10967. MatchOpType(taicpu(p),top_reg) and
  10968. (taicpu(p).oper[0]^.reg=NR_RAX) and
  10969. GetNextInstruction(p, hp1) and
  10970. { Take a copy of hp1 }
  10971. SetAndTest(hp1, hp4) and
  10972. { trick to skip label }
  10973. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  10974. SkipSimpleInstructions(hp1) and
  10975. MatchInstruction(hp1,A_CALL,[S_NO]) and
  10976. GetNextInstruction(hp1, hp2) and
  10977. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  10978. MatchOpType(taicpu(hp2),top_reg) and
  10979. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  10980. GetNextInstruction(hp2, hp3) and
  10981. { trick to skip label }
  10982. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  10983. (MatchInstruction(hp3,A_RET,[S_NO]) or
  10984. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  10985. SetAndTest(hp3,hp5) and
  10986. GetNextInstruction(hp3,hp3) and
  10987. MatchInstruction(hp3,A_RET,[S_NO])
  10988. )
  10989. ) and
  10990. (taicpu(hp3).ops=0) then
  10991. begin
  10992. taicpu(hp1).opcode := A_JMP;
  10993. taicpu(hp1).is_jmp := true;
  10994. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  10995. RemoveCurrentP(p, hp4);
  10996. RemoveInstruction(hp2);
  10997. RemoveInstruction(hp3);
  10998. if Assigned(hp5) then
  10999. begin
  11000. AsmL.Remove(hp5);
  11001. ASmL.InsertBefore(hp5,hp1)
  11002. end;
  11003. Result:=true;
  11004. end;
  11005. {$endif x86_64}
  11006. end;
  11007. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  11008. var
  11009. Value, RegName: string;
  11010. begin
  11011. Result:=false;
  11012. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  11013. begin
  11014. case taicpu(p).oper[0]^.val of
  11015. 0:
  11016. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  11017. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11018. begin
  11019. { change "mov $0,%reg" into "xor %reg,%reg" }
  11020. taicpu(p).opcode := A_XOR;
  11021. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  11022. Result := True;
  11023. {$ifdef x86_64}
  11024. end
  11025. else if (taicpu(p).opsize = S_Q) then
  11026. begin
  11027. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  11028. { The actual optimization }
  11029. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11030. taicpu(p).changeopsize(S_L);
  11031. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  11032. Result := True;
  11033. end;
  11034. $1..$FFFFFFFF:
  11035. begin
  11036. { Code size reduction by J. Gareth "Kit" Moreton }
  11037. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  11038. case taicpu(p).opsize of
  11039. S_Q:
  11040. begin
  11041. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  11042. Value := debug_tostr(taicpu(p).oper[0]^.val);
  11043. { The actual optimization }
  11044. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11045. taicpu(p).changeopsize(S_L);
  11046. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  11047. Result := True;
  11048. end;
  11049. else
  11050. { Do nothing };
  11051. end;
  11052. {$endif x86_64}
  11053. end;
  11054. -1:
  11055. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  11056. if (cs_opt_size in current_settings.optimizerswitches) and
  11057. (taicpu(p).opsize <> S_B) and
  11058. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11059. begin
  11060. { change "mov $-1,%reg" into "or $-1,%reg" }
  11061. { NOTES:
  11062. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  11063. - This operation creates a false dependency on the register, so only do it when optimising for size
  11064. - 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
  11065. }
  11066. taicpu(p).opcode := A_OR;
  11067. Result := True;
  11068. end;
  11069. else
  11070. { Do nothing };
  11071. end;
  11072. end;
  11073. end;
  11074. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  11075. var
  11076. hp1: tai;
  11077. begin
  11078. { Detect:
  11079. andw x, %ax (0 <= x < $8000)
  11080. ...
  11081. movzwl %ax,%eax
  11082. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  11083. }
  11084. Result := False; if MatchOpType(taicpu(p), top_const, top_reg) and
  11085. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  11086. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  11087. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11088. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11089. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11090. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11091. begin
  11092. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  11093. taicpu(hp1).opcode := A_CWDE;
  11094. taicpu(hp1).clearop(0);
  11095. taicpu(hp1).clearop(1);
  11096. taicpu(hp1).ops := 0;
  11097. { A change was made, but not with p, so move forward 1 }
  11098. p := tai(p.Next);
  11099. Result := True;
  11100. end;
  11101. end;
  11102. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  11103. begin
  11104. Result := False;
  11105. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  11106. Exit;
  11107. { Convert:
  11108. movswl %ax,%eax -> cwtl
  11109. movslq %eax,%rax -> cdqe
  11110. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  11111. refer to the same opcode and depends only on the assembler's
  11112. current operand-size attribute. [Kit]
  11113. }
  11114. with taicpu(p) do
  11115. case opsize of
  11116. S_WL:
  11117. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  11118. begin
  11119. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  11120. opcode := A_CWDE;
  11121. clearop(0);
  11122. clearop(1);
  11123. ops := 0;
  11124. Result := True;
  11125. end;
  11126. {$ifdef x86_64}
  11127. S_LQ:
  11128. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  11129. begin
  11130. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  11131. opcode := A_CDQE;
  11132. clearop(0);
  11133. clearop(1);
  11134. ops := 0;
  11135. Result := True;
  11136. end;
  11137. {$endif x86_64}
  11138. else
  11139. ;
  11140. end;
  11141. end;
  11142. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  11143. var
  11144. hp1: tai;
  11145. begin
  11146. { Detect:
  11147. shr x, %ax (x > 0)
  11148. ...
  11149. movzwl %ax,%eax
  11150. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  11151. }
  11152. Result := False;
  11153. if MatchOpType(taicpu(p), top_const, top_reg) and
  11154. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  11155. (taicpu(p).oper[0]^.val > 0) and
  11156. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11157. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11158. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11159. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11160. begin
  11161. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  11162. taicpu(hp1).opcode := A_CWDE;
  11163. taicpu(hp1).clearop(0);
  11164. taicpu(hp1).clearop(1);
  11165. taicpu(hp1).ops := 0;
  11166. { A change was made, but not with p, so move forward 1 }
  11167. p := tai(p.Next);
  11168. Result := True;
  11169. end;
  11170. end;
  11171. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  11172. var
  11173. hp1, hp2: tai;
  11174. Opposite, SecondOpposite: TAsmOp;
  11175. NewCond: TAsmCond;
  11176. begin
  11177. Result := False;
  11178. { Change:
  11179. add/sub 128,(dest)
  11180. To:
  11181. sub/add -128,(dest)
  11182. This generaally takes fewer bytes to encode because -128 can be stored
  11183. in a signed byte, whereas +128 cannot.
  11184. }
  11185. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  11186. begin
  11187. if taicpu(p).opcode = A_ADD then
  11188. Opposite := A_SUB
  11189. else
  11190. Opposite := A_ADD;
  11191. { Be careful if the flags are in use, because the CF flag inverts
  11192. when changing from ADD to SUB and vice versa }
  11193. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11194. GetNextInstruction(p, hp1) then
  11195. begin
  11196. TransferUsedRegs(TmpUsedRegs);
  11197. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  11198. hp2 := hp1;
  11199. { Scan ahead to check if everything's safe }
  11200. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  11201. begin
  11202. if (hp1.typ <> ait_instruction) then
  11203. { Probably unsafe since the flags are still in use }
  11204. Exit;
  11205. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  11206. { Stop searching at an unconditional jump }
  11207. Break;
  11208. if not
  11209. (
  11210. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  11211. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  11212. ) and
  11213. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  11214. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  11215. Exit;
  11216. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11217. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  11218. { Move to the next instruction }
  11219. GetNextInstruction(hp1, hp1);
  11220. end;
  11221. while Assigned(hp2) and (hp2 <> hp1) do
  11222. begin
  11223. NewCond := C_None;
  11224. case taicpu(hp2).condition of
  11225. C_A, C_NBE:
  11226. NewCond := C_BE;
  11227. C_B, C_C, C_NAE:
  11228. NewCond := C_AE;
  11229. C_AE, C_NB, C_NC:
  11230. NewCond := C_B;
  11231. C_BE, C_NA:
  11232. NewCond := C_A;
  11233. else
  11234. { No change needed };
  11235. end;
  11236. if NewCond <> C_None then
  11237. begin
  11238. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  11239. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  11240. taicpu(hp2).condition := NewCond;
  11241. end
  11242. else
  11243. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  11244. begin
  11245. { Because of the flipping of the carry bit, to ensure
  11246. the operation remains equivalent, ADC becomes SBB
  11247. and vice versa, and the constant is not-inverted.
  11248. If multiple ADCs or SBBs appear in a row, each one
  11249. changed causes the carry bit to invert, so they all
  11250. need to be flipped }
  11251. if taicpu(hp2).opcode = A_ADC then
  11252. SecondOpposite := A_SBB
  11253. else
  11254. SecondOpposite := A_ADC;
  11255. if taicpu(hp2).oper[0]^.typ <> top_const then
  11256. { Should have broken out of this optimisation already }
  11257. InternalError(2021112901);
  11258. 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]^) + ' -> ' +
  11259. 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);
  11260. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  11261. taicpu(hp2).opcode := SecondOpposite;
  11262. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  11263. end;
  11264. { Move to the next instruction }
  11265. GetNextInstruction(hp2, hp2);
  11266. end;
  11267. if (hp2 <> hp1) then
  11268. InternalError(2021111501);
  11269. end;
  11270. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  11271. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  11272. taicpu(p).opcode := Opposite;
  11273. taicpu(p).oper[0]^.val := -128;
  11274. { No further optimisations can be made on this instruction, so move
  11275. onto the next one to save time }
  11276. p := tai(p.Next);
  11277. UpdateUsedRegs(p);
  11278. Result := True;
  11279. Exit;
  11280. end;
  11281. { Detect:
  11282. add/sub %reg2,(dest)
  11283. add/sub x, (dest)
  11284. (dest can be a register or a reference)
  11285. Swap the instructions to minimise a pipeline stall. This reverses the
  11286. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  11287. optimisations could be made.
  11288. }
  11289. if (taicpu(p).oper[0]^.typ = top_reg) and
  11290. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  11291. (
  11292. (
  11293. (taicpu(p).oper[1]^.typ = top_reg) and
  11294. { We can try searching further ahead if we're writing to a register }
  11295. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  11296. ) or
  11297. (
  11298. (taicpu(p).oper[1]^.typ = top_ref) and
  11299. GetNextInstruction(p, hp1)
  11300. )
  11301. ) and
  11302. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  11303. (taicpu(hp1).oper[0]^.typ = top_const) and
  11304. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  11305. begin
  11306. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  11307. TransferUsedRegs(TmpUsedRegs);
  11308. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11309. hp2 := p;
  11310. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  11311. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  11312. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  11313. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  11314. begin
  11315. asml.remove(hp1);
  11316. asml.InsertBefore(hp1, p);
  11317. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  11318. Result := True;
  11319. end;
  11320. end;
  11321. end;
  11322. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  11323. begin
  11324. Result:=false;
  11325. { change "cmp $0, %reg" to "test %reg, %reg" }
  11326. if MatchOpType(taicpu(p),top_const,top_reg) and
  11327. (taicpu(p).oper[0]^.val = 0) then
  11328. begin
  11329. taicpu(p).opcode := A_TEST;
  11330. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  11331. Result:=true;
  11332. end;
  11333. end;
  11334. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  11335. var
  11336. IsTestConstX : Boolean;
  11337. hp1,hp2 : tai;
  11338. begin
  11339. Result:=false;
  11340. { removes the line marked with (x) from the sequence
  11341. and/or/xor/add/sub/... $x, %y
  11342. test/or %y, %y | test $-1, %y (x)
  11343. j(n)z _Label
  11344. as the first instruction already adjusts the ZF
  11345. %y operand may also be a reference }
  11346. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  11347. MatchOperand(taicpu(p).oper[0]^,-1);
  11348. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  11349. GetLastInstruction(p, hp1) and
  11350. (tai(hp1).typ = ait_instruction) and
  11351. GetNextInstruction(p,hp2) and
  11352. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  11353. case taicpu(hp1).opcode Of
  11354. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  11355. { These two instructions set the zero flag if the result is zero }
  11356. A_POPCNT, A_LZCNT:
  11357. begin
  11358. if (
  11359. { With POPCNT, an input of zero will set the zero flag
  11360. because the population count of zero is zero }
  11361. (taicpu(hp1).opcode = A_POPCNT) and
  11362. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  11363. (
  11364. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  11365. { Faster than going through the second half of the 'or'
  11366. condition below }
  11367. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  11368. )
  11369. ) or (
  11370. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  11371. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11372. { and in case of carry for A(E)/B(E)/C/NC }
  11373. (
  11374. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  11375. (
  11376. (taicpu(hp1).opcode <> A_ADD) and
  11377. (taicpu(hp1).opcode <> A_SUB) and
  11378. (taicpu(hp1).opcode <> A_LZCNT)
  11379. )
  11380. )
  11381. ) then
  11382. begin
  11383. RemoveCurrentP(p, hp2);
  11384. Result:=true;
  11385. Exit;
  11386. end;
  11387. end;
  11388. A_SHL, A_SAL, A_SHR, A_SAR:
  11389. begin
  11390. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  11391. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  11392. { therefore, it's only safe to do this optimization for }
  11393. { shifts by a (nonzero) constant }
  11394. (taicpu(hp1).oper[0]^.typ = top_const) and
  11395. (taicpu(hp1).oper[0]^.val <> 0) and
  11396. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11397. { and in case of carry for A(E)/B(E)/C/NC }
  11398. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11399. begin
  11400. RemoveCurrentP(p, hp2);
  11401. Result:=true;
  11402. Exit;
  11403. end;
  11404. end;
  11405. A_DEC, A_INC, A_NEG:
  11406. begin
  11407. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  11408. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11409. { and in case of carry for A(E)/B(E)/C/NC }
  11410. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11411. begin
  11412. RemoveCurrentP(p, hp2);
  11413. Result:=true;
  11414. Exit;
  11415. end;
  11416. end
  11417. else
  11418. ;
  11419. end; { case }
  11420. { change "test $-1,%reg" into "test %reg,%reg" }
  11421. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  11422. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  11423. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  11424. if MatchInstruction(p, A_OR, []) and
  11425. { Can only match if they're both registers }
  11426. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  11427. begin
  11428. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  11429. taicpu(p).opcode := A_TEST;
  11430. { No need to set Result to True, as we've done all the optimisations we can }
  11431. end;
  11432. end;
  11433. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  11434. var
  11435. hp1,hp3 : tai;
  11436. {$ifndef x86_64}
  11437. hp2 : taicpu;
  11438. {$endif x86_64}
  11439. begin
  11440. Result:=false;
  11441. hp3:=nil;
  11442. {$ifndef x86_64}
  11443. { don't do this on modern CPUs, this really hurts them due to
  11444. broken call/ret pairing }
  11445. if (current_settings.optimizecputype < cpu_Pentium2) and
  11446. not(cs_create_pic in current_settings.moduleswitches) and
  11447. GetNextInstruction(p, hp1) and
  11448. MatchInstruction(hp1,A_JMP,[S_NO]) and
  11449. MatchOpType(taicpu(hp1),top_ref) and
  11450. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  11451. begin
  11452. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  11453. InsertLLItem(p.previous, p, hp2);
  11454. taicpu(p).opcode := A_JMP;
  11455. taicpu(p).is_jmp := true;
  11456. RemoveInstruction(hp1);
  11457. Result:=true;
  11458. end
  11459. else
  11460. {$endif x86_64}
  11461. { replace
  11462. call procname
  11463. ret
  11464. by
  11465. jmp procname
  11466. but do it only on level 4 because it destroys stack back traces
  11467. else if the subroutine is marked as no return, remove the ret
  11468. }
  11469. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  11470. (po_noreturn in current_procinfo.procdef.procoptions)) and
  11471. GetNextInstruction(p, hp1) and
  11472. (MatchInstruction(hp1,A_RET,[S_NO]) or
  11473. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  11474. SetAndTest(hp1,hp3) and
  11475. GetNextInstruction(hp1,hp1) and
  11476. MatchInstruction(hp1,A_RET,[S_NO])
  11477. )
  11478. ) and
  11479. (taicpu(hp1).ops=0) then
  11480. begin
  11481. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11482. { we might destroy stack alignment here if we do not do a call }
  11483. (target_info.stackalign<=sizeof(SizeUInt)) then
  11484. begin
  11485. taicpu(p).opcode := A_JMP;
  11486. taicpu(p).is_jmp := true;
  11487. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  11488. end
  11489. else
  11490. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  11491. RemoveInstruction(hp1);
  11492. if Assigned(hp3) then
  11493. begin
  11494. AsmL.Remove(hp3);
  11495. AsmL.InsertBefore(hp3,p)
  11496. end;
  11497. Result:=true;
  11498. end;
  11499. end;
  11500. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  11501. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  11502. begin
  11503. case OpSize of
  11504. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11505. Result := (Val <= $FF) and (Val >= -128);
  11506. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11507. Result := (Val <= $FFFF) and (Val >= -32768);
  11508. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  11509. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  11510. else
  11511. Result := True;
  11512. end;
  11513. end;
  11514. var
  11515. hp1, hp2 : tai;
  11516. SizeChange: Boolean;
  11517. PreMessage: string;
  11518. begin
  11519. Result := False;
  11520. if (taicpu(p).oper[0]^.typ = top_reg) and
  11521. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11522. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  11523. begin
  11524. { Change (using movzbl %al,%eax as an example):
  11525. movzbl %al, %eax movzbl %al, %eax
  11526. cmpl x, %eax testl %eax,%eax
  11527. To:
  11528. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  11529. movzbl %al, %eax movzbl %al, %eax
  11530. Smaller instruction and minimises pipeline stall as the CPU
  11531. doesn't have to wait for the register to get zero-extended. [Kit]
  11532. Also allow if the smaller of the two registers is being checked,
  11533. as this still removes the false dependency.
  11534. }
  11535. if
  11536. (
  11537. (
  11538. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  11539. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  11540. ) or (
  11541. { If MatchOperand returns True, they must both be registers }
  11542. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  11543. )
  11544. ) and
  11545. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  11546. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  11547. begin
  11548. 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);
  11549. asml.Remove(hp1);
  11550. asml.InsertBefore(hp1, p);
  11551. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  11552. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  11553. begin
  11554. taicpu(hp1).opcode := A_TEST;
  11555. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  11556. end;
  11557. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  11558. case taicpu(p).opsize of
  11559. S_BW, S_BL:
  11560. begin
  11561. SizeChange := taicpu(hp1).opsize <> S_B;
  11562. taicpu(hp1).changeopsize(S_B);
  11563. end;
  11564. S_WL:
  11565. begin
  11566. SizeChange := taicpu(hp1).opsize <> S_W;
  11567. taicpu(hp1).changeopsize(S_W);
  11568. end
  11569. else
  11570. InternalError(2020112701);
  11571. end;
  11572. UpdateUsedRegs(tai(p.Next));
  11573. { Check if the register is used aferwards - if not, we can
  11574. remove the movzx instruction completely }
  11575. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  11576. begin
  11577. { Hp1 is a better position than p for debugging purposes }
  11578. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  11579. RemoveCurrentp(p, hp1);
  11580. Result := True;
  11581. end;
  11582. if SizeChange then
  11583. DebugMsg(SPeepholeOptimization + PreMessage +
  11584. 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)
  11585. else
  11586. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  11587. Exit;
  11588. end;
  11589. { Change (using movzwl %ax,%eax as an example):
  11590. movzwl %ax, %eax
  11591. movb %al, (dest) (Register is smaller than read register in movz)
  11592. To:
  11593. movb %al, (dest) (Move one back to avoid a false dependency)
  11594. movzwl %ax, %eax
  11595. }
  11596. if (taicpu(hp1).opcode = A_MOV) and
  11597. (taicpu(hp1).oper[0]^.typ = top_reg) and
  11598. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  11599. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  11600. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  11601. begin
  11602. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  11603. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  11604. asml.Remove(hp1);
  11605. asml.InsertBefore(hp1, p);
  11606. if taicpu(hp1).oper[1]^.typ = top_reg then
  11607. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  11608. { Check if the register is used aferwards - if not, we can
  11609. remove the movzx instruction completely }
  11610. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  11611. begin
  11612. { Hp1 is a better position than p for debugging purposes }
  11613. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  11614. RemoveCurrentp(p, hp1);
  11615. Result := True;
  11616. end;
  11617. Exit;
  11618. end;
  11619. end;
  11620. end;
  11621. {$ifdef x86_64}
  11622. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  11623. var
  11624. PreMessage, RegName: string;
  11625. begin
  11626. { Code size reduction by J. Gareth "Kit" Moreton }
  11627. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  11628. as this removes the REX prefix }
  11629. Result := False;
  11630. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  11631. Exit;
  11632. if taicpu(p).oper[0]^.typ <> top_reg then
  11633. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  11634. InternalError(2018011500);
  11635. case taicpu(p).opsize of
  11636. S_Q:
  11637. begin
  11638. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  11639. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  11640. { The actual optimization }
  11641. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  11642. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11643. taicpu(p).changeopsize(S_L);
  11644. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  11645. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  11646. end;
  11647. else
  11648. ;
  11649. end;
  11650. end;
  11651. {$endif}
  11652. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  11653. var
  11654. XReg: TRegister;
  11655. begin
  11656. Result := False;
  11657. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  11658. Smaller encoding and slightly faster on some platforms (also works for
  11659. ZMM-sized registers) }
  11660. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  11661. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  11662. begin
  11663. XReg := taicpu(p).oper[0]^.reg;
  11664. if (taicpu(p).oper[1]^.reg = XReg) then
  11665. begin
  11666. taicpu(p).changeopsize(S_XMM);
  11667. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  11668. if (cs_opt_size in current_settings.optimizerswitches) then
  11669. begin
  11670. { Change input registers to %xmm0 to reduce size. Note that
  11671. there's a risk of a false dependency doing this, so only
  11672. optimise for size here }
  11673. XReg := NR_XMM0;
  11674. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  11675. end
  11676. else
  11677. begin
  11678. setsubreg(XReg, R_SUBMMX);
  11679. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  11680. end;
  11681. taicpu(p).oper[0]^.reg := XReg;
  11682. taicpu(p).oper[1]^.reg := XReg;
  11683. Result := True;
  11684. end;
  11685. end;
  11686. end;
  11687. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  11688. var
  11689. OperIdx: Integer;
  11690. begin
  11691. for OperIdx := 0 to p.ops - 1 do
  11692. if p.oper[OperIdx]^.typ = top_ref then
  11693. optimize_ref(p.oper[OperIdx]^.ref^, False);
  11694. end;
  11695. end.