aoptx86.pas 542 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698
  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 := paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption);
  962. for CurrentSuperReg in RegSet do
  963. begin
  964. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  965. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  966. {$if defined(i386) or defined(i8086)}
  967. { If the target size is 8-bit, make sure we can actually encode it }
  968. and (
  969. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  970. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  971. )
  972. {$endif i386 or i8086}
  973. then
  974. begin
  975. Currentp := p;
  976. Breakout := False;
  977. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  978. begin
  979. case Currentp.typ of
  980. ait_instruction:
  981. begin
  982. if RegInInstruction(CurrentReg, Currentp) then
  983. begin
  984. Breakout := True;
  985. Break;
  986. end;
  987. { Cannot allocate across an unconditional jump }
  988. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  989. Exit;
  990. end;
  991. ait_marker:
  992. { Don't try anything more if a marker is hit }
  993. Exit;
  994. ait_regalloc:
  995. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  996. begin
  997. Breakout := True;
  998. Break;
  999. end;
  1000. else
  1001. ;
  1002. end;
  1003. end;
  1004. if Breakout then
  1005. { Try the next register }
  1006. Continue;
  1007. { We have a free register available }
  1008. Result := CurrentReg;
  1009. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1010. Exit;
  1011. end;
  1012. end;
  1013. end;
  1014. { Attempts to allocate a volatile MM register for use between p and hp,
  1015. using AUsedRegs for the current register usage information. Returns NR_NO
  1016. if no free register could be found }
  1017. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1018. var
  1019. RegSet: TCPURegisterSet;
  1020. CurrentSuperReg: Integer;
  1021. CurrentReg: TRegister;
  1022. Currentp: tai;
  1023. Breakout: Boolean;
  1024. begin
  1025. { TODO: Currently, only the volatile registers are checked - can this be extended to use any register the procedure has preserved? }
  1026. Result := NR_NO;
  1027. RegSet := paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption);
  1028. for CurrentSuperReg in RegSet do
  1029. begin
  1030. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1031. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1032. begin
  1033. Currentp := p;
  1034. Breakout := False;
  1035. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1036. begin
  1037. case Currentp.typ of
  1038. ait_instruction:
  1039. begin
  1040. if RegInInstruction(CurrentReg, Currentp) then
  1041. begin
  1042. Breakout := True;
  1043. Break;
  1044. end;
  1045. { Cannot allocate across an unconditional jump }
  1046. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1047. Exit;
  1048. end;
  1049. ait_marker:
  1050. { Don't try anything more if a marker is hit }
  1051. Exit;
  1052. ait_regalloc:
  1053. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1054. begin
  1055. Breakout := True;
  1056. Break;
  1057. end;
  1058. else
  1059. ;
  1060. end;
  1061. end;
  1062. if Breakout then
  1063. { Try the next register }
  1064. Continue;
  1065. { We have a free register available }
  1066. Result := CurrentReg;
  1067. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1068. Exit;
  1069. end;
  1070. end;
  1071. end;
  1072. function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1073. begin
  1074. if not SuperRegistersEqual(reg1,reg2) then
  1075. exit(false);
  1076. if getregtype(reg1)<>R_INTREGISTER then
  1077. exit(true); {because SuperRegisterEqual is true}
  1078. case getsubreg(reg1) of
  1079. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1080. higher, it preserves the high bits, so the new value depends on
  1081. reg2's previous value. In other words, it is equivalent to doing:
  1082. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1083. R_SUBL:
  1084. exit(getsubreg(reg2)=R_SUBL);
  1085. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1086. higher, it actually does a:
  1087. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1088. R_SUBH:
  1089. exit(getsubreg(reg2)=R_SUBH);
  1090. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1091. bits of reg2:
  1092. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1093. R_SUBW:
  1094. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1095. { a write to R_SUBD always overwrites every other subregister,
  1096. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1097. R_SUBD,
  1098. R_SUBQ:
  1099. exit(true);
  1100. else
  1101. internalerror(2017042801);
  1102. end;
  1103. end;
  1104. function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1105. begin
  1106. if not SuperRegistersEqual(reg1,reg2) then
  1107. exit(false);
  1108. if getregtype(reg1)<>R_INTREGISTER then
  1109. exit(true); {because SuperRegisterEqual is true}
  1110. case getsubreg(reg1) of
  1111. R_SUBL:
  1112. exit(getsubreg(reg2)<>R_SUBH);
  1113. R_SUBH:
  1114. exit(getsubreg(reg2)<>R_SUBL);
  1115. R_SUBW,
  1116. R_SUBD,
  1117. R_SUBQ:
  1118. exit(true);
  1119. else
  1120. internalerror(2017042802);
  1121. end;
  1122. end;
  1123. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1124. var
  1125. hp1 : tai;
  1126. l : TCGInt;
  1127. begin
  1128. result:=false;
  1129. { changes the code sequence
  1130. shr/sar const1, x
  1131. shl const2, x
  1132. to
  1133. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1134. if GetNextInstruction(p, hp1) and
  1135. MatchInstruction(hp1,A_SHL,[]) and
  1136. (taicpu(p).oper[0]^.typ = top_const) and
  1137. (taicpu(hp1).oper[0]^.typ = top_const) and
  1138. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1139. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1140. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1141. begin
  1142. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1143. not(cs_opt_size in current_settings.optimizerswitches) then
  1144. begin
  1145. { shr/sar const1, %reg
  1146. shl const2, %reg
  1147. with const1 > const2 }
  1148. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1149. taicpu(hp1).opcode := A_AND;
  1150. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1151. case taicpu(p).opsize Of
  1152. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1153. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1154. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1155. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1156. else
  1157. Internalerror(2017050703)
  1158. end;
  1159. end
  1160. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1161. not(cs_opt_size in current_settings.optimizerswitches) then
  1162. begin
  1163. { shr/sar const1, %reg
  1164. shl const2, %reg
  1165. with const1 < const2 }
  1166. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1167. taicpu(p).opcode := A_AND;
  1168. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1169. case taicpu(p).opsize Of
  1170. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1171. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1172. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1173. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1174. else
  1175. Internalerror(2017050702)
  1176. end;
  1177. end
  1178. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1179. begin
  1180. { shr/sar const1, %reg
  1181. shl const2, %reg
  1182. with const1 = const2 }
  1183. taicpu(p).opcode := A_AND;
  1184. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1185. case taicpu(p).opsize Of
  1186. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1187. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1188. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1189. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1190. else
  1191. Internalerror(2017050701)
  1192. end;
  1193. RemoveInstruction(hp1);
  1194. end;
  1195. end;
  1196. end;
  1197. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1198. var
  1199. opsize : topsize;
  1200. hp1 : tai;
  1201. tmpref : treference;
  1202. ShiftValue : Cardinal;
  1203. BaseValue : TCGInt;
  1204. begin
  1205. result:=false;
  1206. opsize:=taicpu(p).opsize;
  1207. { changes certain "imul const, %reg"'s to lea sequences }
  1208. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1209. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1210. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1211. if (taicpu(p).oper[0]^.val = 1) then
  1212. if (taicpu(p).ops = 2) then
  1213. { remove "imul $1, reg" }
  1214. begin
  1215. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1216. Result := RemoveCurrentP(p);
  1217. end
  1218. else
  1219. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1220. begin
  1221. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1222. InsertLLItem(p.previous, p.next, hp1);
  1223. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1224. p.free;
  1225. p := hp1;
  1226. end
  1227. else if ((taicpu(p).ops <= 2) or
  1228. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1229. not(cs_opt_size in current_settings.optimizerswitches) and
  1230. (not(GetNextInstruction(p, hp1)) or
  1231. not((tai(hp1).typ = ait_instruction) and
  1232. ((taicpu(hp1).opcode=A_Jcc) and
  1233. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1234. begin
  1235. {
  1236. imul X, reg1, reg2 to
  1237. lea (reg1,reg1,Y), reg2
  1238. shl ZZ,reg2
  1239. imul XX, reg1 to
  1240. lea (reg1,reg1,YY), reg1
  1241. shl ZZ,reg2
  1242. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1243. it does not exist as a separate optimization target in FPC though.
  1244. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1245. at most two zeros
  1246. }
  1247. reference_reset(tmpref,1,[]);
  1248. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1249. begin
  1250. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1251. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1252. TmpRef.base := taicpu(p).oper[1]^.reg;
  1253. TmpRef.index := taicpu(p).oper[1]^.reg;
  1254. if not(BaseValue in [3,5,9]) then
  1255. Internalerror(2018110101);
  1256. TmpRef.ScaleFactor := BaseValue-1;
  1257. if (taicpu(p).ops = 2) then
  1258. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1259. else
  1260. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1261. AsmL.InsertAfter(hp1,p);
  1262. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1263. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1264. RemoveCurrentP(p, hp1);
  1265. if ShiftValue>0 then
  1266. AsmL.InsertAfter(taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg),hp1);
  1267. end;
  1268. end;
  1269. end;
  1270. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1271. begin
  1272. Result := False;
  1273. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1274. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1275. begin
  1276. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1277. taicpu(p).opcode := A_MOV;
  1278. Result := True;
  1279. end;
  1280. end;
  1281. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1282. var
  1283. p: taicpu absolute hp;
  1284. i: Integer;
  1285. begin
  1286. Result := False;
  1287. if not assigned(hp) or
  1288. (hp.typ <> ait_instruction) then
  1289. Exit;
  1290. // p := taicpu(hp);
  1291. Prefetch(insprop[p.opcode]);
  1292. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1293. with insprop[p.opcode] do
  1294. begin
  1295. case getsubreg(reg) of
  1296. R_SUBW,R_SUBD,R_SUBQ:
  1297. Result:=
  1298. RegLoadedWithNewValue(NR_CARRYFLAG,hp) and
  1299. RegLoadedWithNewValue(NR_PARITYFLAG,hp) and
  1300. RegLoadedWithNewValue(NR_AUXILIARYFLAG,hp) and
  1301. RegLoadedWithNewValue(NR_ZEROFLAG,hp) and
  1302. RegLoadedWithNewValue(NR_SIGNFLAG,hp) and
  1303. RegLoadedWithNewValue(NR_OVERFLOWFLAG,hp);
  1304. R_SUBFLAGCARRY:
  1305. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1306. R_SUBFLAGPARITY:
  1307. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1308. R_SUBFLAGAUXILIARY:
  1309. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1310. R_SUBFLAGZERO:
  1311. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1312. R_SUBFLAGSIGN:
  1313. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1314. R_SUBFLAGOVERFLOW:
  1315. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1316. R_SUBFLAGINTERRUPT:
  1317. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1318. R_SUBFLAGDIRECTION:
  1319. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1320. else
  1321. begin
  1322. writeln(getsubreg(reg));
  1323. internalerror(2017050501);
  1324. end;
  1325. end;
  1326. exit;
  1327. end;
  1328. { Handle special cases first }
  1329. case p.opcode of
  1330. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1331. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1332. begin
  1333. Result :=
  1334. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1335. (p.oper[1]^.typ = top_reg) and
  1336. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1337. (
  1338. (p.oper[0]^.typ = top_const) or
  1339. (
  1340. (p.oper[0]^.typ = top_reg) and
  1341. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1342. ) or (
  1343. (p.oper[0]^.typ = top_ref) and
  1344. not RegInRef(reg,p.oper[0]^.ref^)
  1345. )
  1346. );
  1347. end;
  1348. A_MUL, A_IMUL:
  1349. Result :=
  1350. (
  1351. (p.ops=3) and { IMUL only }
  1352. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1353. (
  1354. (
  1355. (p.oper[1]^.typ=top_reg) and
  1356. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1357. ) or (
  1358. (p.oper[1]^.typ=top_ref) and
  1359. not RegInRef(reg,p.oper[1]^.ref^)
  1360. )
  1361. )
  1362. ) or (
  1363. (
  1364. (p.ops=1) and
  1365. (
  1366. (
  1367. (
  1368. (p.oper[0]^.typ=top_reg) and
  1369. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1370. )
  1371. ) or (
  1372. (p.oper[0]^.typ=top_ref) and
  1373. not RegInRef(reg,p.oper[0]^.ref^)
  1374. )
  1375. ) and (
  1376. (
  1377. (p.opsize=S_B) and
  1378. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1379. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1380. ) or (
  1381. (p.opsize=S_W) and
  1382. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1383. ) or (
  1384. (p.opsize=S_L) and
  1385. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1386. {$ifdef x86_64}
  1387. ) or (
  1388. (p.opsize=S_Q) and
  1389. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1390. {$endif x86_64}
  1391. )
  1392. )
  1393. )
  1394. );
  1395. A_CBW:
  1396. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1397. {$ifndef x86_64}
  1398. A_LDS:
  1399. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1400. A_LES:
  1401. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1402. {$endif not x86_64}
  1403. A_LFS:
  1404. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1405. A_LGS:
  1406. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1407. A_LSS:
  1408. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1409. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1410. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1411. A_LODSB:
  1412. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1413. A_LODSW:
  1414. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1415. {$ifdef x86_64}
  1416. A_LODSQ:
  1417. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1418. {$endif x86_64}
  1419. A_LODSD:
  1420. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1421. A_FSTSW, A_FNSTSW:
  1422. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1423. else
  1424. begin
  1425. with insprop[p.opcode] do
  1426. begin
  1427. if (
  1428. { xor %reg,%reg etc. is classed as a new value }
  1429. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1430. MatchOpType(p, top_reg, top_reg) and
  1431. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1432. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1433. ) then
  1434. begin
  1435. Result := True;
  1436. Exit;
  1437. end;
  1438. { Make sure the entire register is overwritten }
  1439. if (getregtype(reg) = R_INTREGISTER) then
  1440. begin
  1441. if (p.ops > 0) then
  1442. begin
  1443. if RegInOp(reg, p.oper[0]^) then
  1444. begin
  1445. if (p.oper[0]^.typ = top_ref) then
  1446. begin
  1447. if RegInRef(reg, p.oper[0]^.ref^) then
  1448. begin
  1449. Result := False;
  1450. Exit;
  1451. end;
  1452. end
  1453. else if (p.oper[0]^.typ = top_reg) then
  1454. begin
  1455. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1456. begin
  1457. Result := False;
  1458. Exit;
  1459. end
  1460. else if ([Ch_WOp1]*Ch<>[]) then
  1461. begin
  1462. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1463. Result := True
  1464. else
  1465. begin
  1466. Result := False;
  1467. Exit;
  1468. end;
  1469. end;
  1470. end;
  1471. end;
  1472. if (p.ops > 1) then
  1473. begin
  1474. if RegInOp(reg, p.oper[1]^) then
  1475. begin
  1476. if (p.oper[1]^.typ = top_ref) then
  1477. begin
  1478. if RegInRef(reg, p.oper[1]^.ref^) then
  1479. begin
  1480. Result := False;
  1481. Exit;
  1482. end;
  1483. end
  1484. else if (p.oper[1]^.typ = top_reg) then
  1485. begin
  1486. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1487. begin
  1488. Result := False;
  1489. Exit;
  1490. end
  1491. else if ([Ch_WOp2]*Ch<>[]) then
  1492. begin
  1493. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1494. Result := True
  1495. else
  1496. begin
  1497. Result := False;
  1498. Exit;
  1499. end;
  1500. end;
  1501. end;
  1502. end;
  1503. if (p.ops > 2) then
  1504. begin
  1505. if RegInOp(reg, p.oper[2]^) then
  1506. begin
  1507. if (p.oper[2]^.typ = top_ref) then
  1508. begin
  1509. if RegInRef(reg, p.oper[2]^.ref^) then
  1510. begin
  1511. Result := False;
  1512. Exit;
  1513. end;
  1514. end
  1515. else if (p.oper[2]^.typ = top_reg) then
  1516. begin
  1517. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1518. begin
  1519. Result := False;
  1520. Exit;
  1521. end
  1522. else if ([Ch_WOp3]*Ch<>[]) then
  1523. begin
  1524. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1525. Result := True
  1526. else
  1527. begin
  1528. Result := False;
  1529. Exit;
  1530. end;
  1531. end;
  1532. end;
  1533. end;
  1534. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1535. begin
  1536. if (p.oper[3]^.typ = top_ref) then
  1537. begin
  1538. if RegInRef(reg, p.oper[3]^.ref^) then
  1539. begin
  1540. Result := False;
  1541. Exit;
  1542. end;
  1543. end
  1544. else if (p.oper[3]^.typ = top_reg) then
  1545. begin
  1546. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1547. begin
  1548. Result := False;
  1549. Exit;
  1550. end
  1551. else if ([Ch_WOp4]*Ch<>[]) then
  1552. begin
  1553. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1554. Result := True
  1555. else
  1556. begin
  1557. Result := False;
  1558. Exit;
  1559. end;
  1560. end;
  1561. end;
  1562. end;
  1563. end;
  1564. end;
  1565. end;
  1566. { Don't do these ones first in case an input operand is equal to an explicit output registers }
  1567. case getsupreg(reg) of
  1568. RS_EAX:
  1569. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1570. begin
  1571. Result := True;
  1572. Exit;
  1573. end;
  1574. RS_ECX:
  1575. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1576. begin
  1577. Result := True;
  1578. Exit;
  1579. end;
  1580. RS_EDX:
  1581. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1582. begin
  1583. Result := True;
  1584. Exit;
  1585. end;
  1586. RS_EBX:
  1587. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1588. begin
  1589. Result := True;
  1590. Exit;
  1591. end;
  1592. RS_ESP:
  1593. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1594. begin
  1595. Result := True;
  1596. Exit;
  1597. end;
  1598. RS_EBP:
  1599. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1600. begin
  1601. Result := True;
  1602. Exit;
  1603. end;
  1604. RS_ESI:
  1605. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1606. begin
  1607. Result := True;
  1608. Exit;
  1609. end;
  1610. RS_EDI:
  1611. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1612. begin
  1613. Result := True;
  1614. Exit;
  1615. end;
  1616. else
  1617. ;
  1618. end;
  1619. end;
  1620. end;
  1621. end;
  1622. end;
  1623. end;
  1624. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1625. var
  1626. hp2,hp3 : tai;
  1627. begin
  1628. { some x86-64 issue a NOP before the real exit code }
  1629. if MatchInstruction(p,A_NOP,[]) then
  1630. GetNextInstruction(p,p);
  1631. result:=assigned(p) and (p.typ=ait_instruction) and
  1632. ((taicpu(p).opcode = A_RET) or
  1633. ((taicpu(p).opcode=A_LEAVE) and
  1634. GetNextInstruction(p,hp2) and
  1635. MatchInstruction(hp2,A_RET,[S_NO])
  1636. ) or
  1637. (((taicpu(p).opcode=A_LEA) and
  1638. MatchOpType(taicpu(p),top_ref,top_reg) and
  1639. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1640. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1641. ) and
  1642. GetNextInstruction(p,hp2) and
  1643. MatchInstruction(hp2,A_RET,[S_NO])
  1644. ) or
  1645. ((((taicpu(p).opcode=A_MOV) and
  1646. MatchOpType(taicpu(p),top_reg,top_reg) and
  1647. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1648. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1649. ((taicpu(p).opcode=A_LEA) and
  1650. MatchOpType(taicpu(p),top_ref,top_reg) and
  1651. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1652. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1653. )
  1654. ) and
  1655. GetNextInstruction(p,hp2) and
  1656. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1657. MatchOpType(taicpu(hp2),top_reg) and
  1658. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1659. GetNextInstruction(hp2,hp3) and
  1660. MatchInstruction(hp3,A_RET,[S_NO])
  1661. )
  1662. );
  1663. end;
  1664. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1665. begin
  1666. isFoldableArithOp := False;
  1667. case hp1.opcode of
  1668. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1669. isFoldableArithOp :=
  1670. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1671. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1672. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1673. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1674. (taicpu(hp1).oper[1]^.reg = reg);
  1675. A_INC,A_DEC,A_NEG,A_NOT:
  1676. isFoldableArithOp :=
  1677. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1678. (taicpu(hp1).oper[0]^.reg = reg);
  1679. else
  1680. ;
  1681. end;
  1682. end;
  1683. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1684. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1685. var
  1686. hp2: tai;
  1687. begin
  1688. hp2 := p;
  1689. repeat
  1690. hp2 := tai(hp2.previous);
  1691. if assigned(hp2) and
  1692. (hp2.typ = ait_regalloc) and
  1693. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1694. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1695. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1696. begin
  1697. RemoveInstruction(hp2);
  1698. break;
  1699. end;
  1700. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1701. end;
  1702. begin
  1703. case current_procinfo.procdef.returndef.typ of
  1704. arraydef,recorddef,pointerdef,
  1705. stringdef,enumdef,procdef,objectdef,errordef,
  1706. filedef,setdef,procvardef,
  1707. classrefdef,forwarddef:
  1708. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1709. orddef:
  1710. if current_procinfo.procdef.returndef.size <> 0 then
  1711. begin
  1712. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1713. { for int64/qword }
  1714. if current_procinfo.procdef.returndef.size = 8 then
  1715. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1716. end;
  1717. else
  1718. ;
  1719. end;
  1720. end;
  1721. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1722. var
  1723. hp1,hp2 : tai;
  1724. begin
  1725. result:=false;
  1726. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1727. begin
  1728. { vmova* reg1,reg1
  1729. =>
  1730. <nop> }
  1731. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1732. begin
  1733. RemoveCurrentP(p);
  1734. result:=true;
  1735. exit;
  1736. end
  1737. else if GetNextInstruction(p,hp1) then
  1738. begin
  1739. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1740. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1741. begin
  1742. { vmova* reg1,reg2
  1743. vmova* reg2,reg3
  1744. dealloc reg2
  1745. =>
  1746. vmova* reg1,reg3 }
  1747. TransferUsedRegs(TmpUsedRegs);
  1748. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1749. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1750. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1751. begin
  1752. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1753. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1754. RemoveInstruction(hp1);
  1755. result:=true;
  1756. exit;
  1757. end
  1758. { special case:
  1759. vmova* reg1,<op>
  1760. vmova* <op>,reg1
  1761. =>
  1762. vmova* reg1,<op> }
  1763. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1764. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1765. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1766. ) then
  1767. begin
  1768. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1769. RemoveInstruction(hp1);
  1770. result:=true;
  1771. exit;
  1772. end
  1773. end
  1774. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  1775. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  1776. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  1777. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  1778. ) and
  1779. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1780. begin
  1781. { vmova* reg1,reg2
  1782. vmovs* reg2,<op>
  1783. dealloc reg2
  1784. =>
  1785. vmovs* reg1,reg3 }
  1786. TransferUsedRegs(TmpUsedRegs);
  1787. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1788. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1789. begin
  1790. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  1791. taicpu(p).opcode:=taicpu(hp1).opcode;
  1792. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1793. RemoveInstruction(hp1);
  1794. result:=true;
  1795. exit;
  1796. end
  1797. end;
  1798. end;
  1799. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  1800. begin
  1801. if MatchInstruction(hp1,[A_VFMADDPD,
  1802. A_VFMADD132PD,
  1803. A_VFMADD132PS,
  1804. A_VFMADD132SD,
  1805. A_VFMADD132SS,
  1806. A_VFMADD213PD,
  1807. A_VFMADD213PS,
  1808. A_VFMADD213SD,
  1809. A_VFMADD213SS,
  1810. A_VFMADD231PD,
  1811. A_VFMADD231PS,
  1812. A_VFMADD231SD,
  1813. A_VFMADD231SS,
  1814. A_VFMADDSUB132PD,
  1815. A_VFMADDSUB132PS,
  1816. A_VFMADDSUB213PD,
  1817. A_VFMADDSUB213PS,
  1818. A_VFMADDSUB231PD,
  1819. A_VFMADDSUB231PS,
  1820. A_VFMSUB132PD,
  1821. A_VFMSUB132PS,
  1822. A_VFMSUB132SD,
  1823. A_VFMSUB132SS,
  1824. A_VFMSUB213PD,
  1825. A_VFMSUB213PS,
  1826. A_VFMSUB213SD,
  1827. A_VFMSUB213SS,
  1828. A_VFMSUB231PD,
  1829. A_VFMSUB231PS,
  1830. A_VFMSUB231SD,
  1831. A_VFMSUB231SS,
  1832. A_VFMSUBADD132PD,
  1833. A_VFMSUBADD132PS,
  1834. A_VFMSUBADD213PD,
  1835. A_VFMSUBADD213PS,
  1836. A_VFMSUBADD231PD,
  1837. A_VFMSUBADD231PS,
  1838. A_VFNMADD132PD,
  1839. A_VFNMADD132PS,
  1840. A_VFNMADD132SD,
  1841. A_VFNMADD132SS,
  1842. A_VFNMADD213PD,
  1843. A_VFNMADD213PS,
  1844. A_VFNMADD213SD,
  1845. A_VFNMADD213SS,
  1846. A_VFNMADD231PD,
  1847. A_VFNMADD231PS,
  1848. A_VFNMADD231SD,
  1849. A_VFNMADD231SS,
  1850. A_VFNMSUB132PD,
  1851. A_VFNMSUB132PS,
  1852. A_VFNMSUB132SD,
  1853. A_VFNMSUB132SS,
  1854. A_VFNMSUB213PD,
  1855. A_VFNMSUB213PS,
  1856. A_VFNMSUB213SD,
  1857. A_VFNMSUB213SS,
  1858. A_VFNMSUB231PD,
  1859. A_VFNMSUB231PS,
  1860. A_VFNMSUB231SD,
  1861. A_VFNMSUB231SS],[S_NO]) and
  1862. { we mix single and double opperations here because we assume that the compiler
  1863. generates vmovapd only after double operations and vmovaps only after single operations }
  1864. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  1865. GetNextInstruction(hp1,hp2) and
  1866. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  1867. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  1868. begin
  1869. TransferUsedRegs(TmpUsedRegs);
  1870. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1871. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1872. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1873. begin
  1874. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  1875. RemoveCurrentP(p, hp1); // <-- Is this actually safe? hp1 is not necessarily the next instruction. [Kit]
  1876. RemoveInstruction(hp2);
  1877. end;
  1878. end
  1879. else if (hp1.typ = ait_instruction) and
  1880. GetNextInstruction(hp1, hp2) and
  1881. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  1882. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  1883. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  1884. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  1885. (((taicpu(p).opcode=A_MOVAPS) and
  1886. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  1887. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  1888. ((taicpu(p).opcode=A_MOVAPD) and
  1889. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  1890. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  1891. ) then
  1892. { change
  1893. movapX reg,reg2
  1894. addsX/subsX/... reg3, reg2
  1895. movapX reg2,reg
  1896. to
  1897. addsX/subsX/... reg3,reg
  1898. }
  1899. begin
  1900. TransferUsedRegs(TmpUsedRegs);
  1901. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1902. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1903. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1904. begin
  1905. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  1906. debug_op2str(taicpu(p).opcode)+' '+
  1907. debug_op2str(taicpu(hp1).opcode)+' '+
  1908. debug_op2str(taicpu(hp2).opcode)+') done',p);
  1909. { we cannot eliminate the first move if
  1910. the operations uses the same register for source and dest }
  1911. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  1912. RemoveCurrentP(p, nil);
  1913. p:=hp1;
  1914. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  1915. RemoveInstruction(hp2);
  1916. result:=true;
  1917. end;
  1918. end;
  1919. end;
  1920. end;
  1921. end;
  1922. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  1923. var
  1924. hp1 : tai;
  1925. begin
  1926. result:=false;
  1927. { replace
  1928. V<Op>X %mreg1,%mreg2,%mreg3
  1929. VMovX %mreg3,%mreg4
  1930. dealloc %mreg3
  1931. by
  1932. V<Op>X %mreg1,%mreg2,%mreg4
  1933. ?
  1934. }
  1935. if GetNextInstruction(p,hp1) and
  1936. { we mix single and double operations here because we assume that the compiler
  1937. generates vmovapd only after double operations and vmovaps only after single operations }
  1938. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  1939. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  1940. (taicpu(hp1).oper[1]^.typ=top_reg) then
  1941. begin
  1942. TransferUsedRegs(TmpUsedRegs);
  1943. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1944. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  1945. begin
  1946. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  1947. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  1948. RemoveInstruction(hp1);
  1949. result:=true;
  1950. end;
  1951. end;
  1952. end;
  1953. { Replaces all references to AOldReg in a memory reference to ANewReg }
  1954. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  1955. begin
  1956. Result := False;
  1957. { For safety reasons, only check for exact register matches }
  1958. { Check base register }
  1959. if (ref.base = AOldReg) then
  1960. begin
  1961. ref.base := ANewReg;
  1962. Result := True;
  1963. end;
  1964. { Check index register }
  1965. if (ref.index = AOldReg) then
  1966. begin
  1967. ref.index := ANewReg;
  1968. Result := True;
  1969. end;
  1970. end;
  1971. { Replaces all references to AOldReg in an operand to ANewReg }
  1972. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  1973. var
  1974. OldSupReg, NewSupReg: TSuperRegister;
  1975. OldSubReg, NewSubReg: TSubRegister;
  1976. OldRegType: TRegisterType;
  1977. ThisOper: POper;
  1978. begin
  1979. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  1980. Result := False;
  1981. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  1982. InternalError(2020011801);
  1983. OldSupReg := getsupreg(AOldReg);
  1984. OldSubReg := getsubreg(AOldReg);
  1985. OldRegType := getregtype(AOldReg);
  1986. NewSupReg := getsupreg(ANewReg);
  1987. NewSubReg := getsubreg(ANewReg);
  1988. if OldRegType <> getregtype(ANewReg) then
  1989. InternalError(2020011802);
  1990. if OldSubReg <> NewSubReg then
  1991. InternalError(2020011803);
  1992. case ThisOper^.typ of
  1993. top_reg:
  1994. if (
  1995. (ThisOper^.reg = AOldReg) or
  1996. (
  1997. (OldRegType = R_INTREGISTER) and
  1998. (getsupreg(ThisOper^.reg) = OldSupReg) and
  1999. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2000. (
  2001. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2002. {$ifndef x86_64}
  2003. and (
  2004. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2005. don't have an 8-bit representation }
  2006. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2007. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2008. )
  2009. {$endif x86_64}
  2010. )
  2011. )
  2012. ) then
  2013. begin
  2014. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2015. Result := True;
  2016. end;
  2017. top_ref:
  2018. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2019. Result := True;
  2020. else
  2021. ;
  2022. end;
  2023. end;
  2024. { Replaces all references to AOldReg in an instruction to ANewReg }
  2025. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2026. const
  2027. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2028. var
  2029. OperIdx: Integer;
  2030. begin
  2031. Result := False;
  2032. for OperIdx := 0 to p.ops - 1 do
  2033. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2034. begin
  2035. { The shift and rotate instructions can only use CL }
  2036. if not (
  2037. (OperIdx = 0) and
  2038. { This second condition just helps to avoid unnecessarily
  2039. calling MatchInstruction for 10 different opcodes }
  2040. (p.oper[0]^.reg = NR_CL) and
  2041. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2042. ) then
  2043. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2044. end
  2045. else if p.oper[OperIdx]^.typ = top_ref then
  2046. { It's okay to replace registers in references that get written to }
  2047. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2048. end;
  2049. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2050. begin
  2051. with ref^ do
  2052. Result :=
  2053. (index = NR_NO) and
  2054. (
  2055. {$ifdef x86_64}
  2056. (
  2057. (base = NR_RIP) and
  2058. (refaddr in [addr_pic, addr_pic_no_got])
  2059. ) or
  2060. {$endif x86_64}
  2061. (base = NR_STACK_POINTER_REG) or
  2062. (base = current_procinfo.framepointer)
  2063. );
  2064. end;
  2065. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2066. var
  2067. l: asizeint;
  2068. begin
  2069. Result := False;
  2070. { Should have been checked previously }
  2071. if p.opcode <> A_LEA then
  2072. InternalError(2020072501);
  2073. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2074. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2075. not(cs_opt_size in current_settings.optimizerswitches) then
  2076. exit;
  2077. with p.oper[0]^.ref^ do
  2078. begin
  2079. if (base <> p.oper[1]^.reg) or
  2080. (index <> NR_NO) or
  2081. assigned(symbol) then
  2082. exit;
  2083. l:=offset;
  2084. if (l=1) and UseIncDec then
  2085. begin
  2086. p.opcode:=A_INC;
  2087. p.loadreg(0,p.oper[1]^.reg);
  2088. p.ops:=1;
  2089. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2090. end
  2091. else if (l=-1) and UseIncDec then
  2092. begin
  2093. p.opcode:=A_DEC;
  2094. p.loadreg(0,p.oper[1]^.reg);
  2095. p.ops:=1;
  2096. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2097. end
  2098. else
  2099. begin
  2100. if (l<0) and (l<>-2147483648) then
  2101. begin
  2102. p.opcode:=A_SUB;
  2103. p.loadConst(0,-l);
  2104. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2105. end
  2106. else
  2107. begin
  2108. p.opcode:=A_ADD;
  2109. p.loadConst(0,l);
  2110. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2111. end;
  2112. end;
  2113. end;
  2114. Result := True;
  2115. end;
  2116. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2117. var
  2118. CurrentReg, ReplaceReg: TRegister;
  2119. begin
  2120. Result := False;
  2121. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2122. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2123. case hp.opcode of
  2124. A_FSTSW, A_FNSTSW,
  2125. A_IN, A_INS, A_OUT, A_OUTS,
  2126. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2127. { These routines have explicit operands, but they are restricted in
  2128. what they can be (e.g. IN and OUT can only read from AL, AX or
  2129. EAX. }
  2130. Exit;
  2131. A_IMUL:
  2132. begin
  2133. { The 1-operand version writes to implicit registers
  2134. The 2-operand version reads from the first operator, and reads
  2135. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2136. the 3-operand version reads from a register that it doesn't write to
  2137. }
  2138. case hp.ops of
  2139. 1:
  2140. if (
  2141. (
  2142. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2143. ) or
  2144. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2145. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2146. begin
  2147. Result := True;
  2148. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2149. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2150. end;
  2151. 2:
  2152. { Only modify the first parameter }
  2153. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2154. begin
  2155. Result := True;
  2156. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2157. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2158. end;
  2159. 3:
  2160. { Only modify the second parameter }
  2161. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2162. begin
  2163. Result := True;
  2164. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2165. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2166. end;
  2167. else
  2168. InternalError(2020012901);
  2169. end;
  2170. end;
  2171. else
  2172. if (hp.ops > 0) and
  2173. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2174. begin
  2175. Result := True;
  2176. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2177. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2178. end;
  2179. end;
  2180. end;
  2181. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2182. var
  2183. hp1, hp2, hp3: tai;
  2184. DoOptimisation, TempBool: Boolean;
  2185. {$ifdef x86_64}
  2186. NewConst: TCGInt;
  2187. {$endif x86_64}
  2188. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2189. begin
  2190. if taicpu(hp1).opcode = signed_movop then
  2191. begin
  2192. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2193. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2194. end
  2195. else
  2196. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2197. end;
  2198. function TryConstMerge(var p1, p2: tai): Boolean;
  2199. var
  2200. ThisRef: TReference;
  2201. begin
  2202. Result := False;
  2203. ThisRef := taicpu(p2).oper[1]^.ref^;
  2204. { Only permit writes to the stack, since we can guarantee alignment with that }
  2205. if (ThisRef.index = NR_NO) and
  2206. (
  2207. (ThisRef.base = NR_STACK_POINTER_REG) or
  2208. (ThisRef.base = current_procinfo.framepointer)
  2209. ) then
  2210. begin
  2211. case taicpu(p).opsize of
  2212. S_B:
  2213. begin
  2214. { Word writes must be on a 2-byte boundary }
  2215. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2216. begin
  2217. { Reduce offset of second reference to see if it is sequential with the first }
  2218. Dec(ThisRef.offset, 1);
  2219. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2220. begin
  2221. { Make sure the constants aren't represented as a
  2222. negative number, as these won't merge properly }
  2223. taicpu(p1).opsize := S_W;
  2224. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2225. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2226. RemoveInstruction(p2);
  2227. Result := True;
  2228. end;
  2229. end;
  2230. end;
  2231. S_W:
  2232. begin
  2233. { Longword writes must be on a 4-byte boundary }
  2234. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2235. begin
  2236. { Reduce offset of second reference to see if it is sequential with the first }
  2237. Dec(ThisRef.offset, 2);
  2238. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2239. begin
  2240. { Make sure the constants aren't represented as a
  2241. negative number, as these won't merge properly }
  2242. taicpu(p1).opsize := S_L;
  2243. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2244. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2245. RemoveInstruction(p2);
  2246. Result := True;
  2247. end;
  2248. end;
  2249. end;
  2250. {$ifdef x86_64}
  2251. S_L:
  2252. begin
  2253. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2254. see if the constants can be encoded this way. }
  2255. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2256. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2257. { Quadword writes must be on an 8-byte boundary }
  2258. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2259. begin
  2260. { Reduce offset of second reference to see if it is sequential with the first }
  2261. Dec(ThisRef.offset, 4);
  2262. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2263. begin
  2264. { Make sure the constants aren't represented as a
  2265. negative number, as these won't merge properly }
  2266. taicpu(p1).opsize := S_Q;
  2267. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2268. taicpu(p1).oper[0]^.val := NewConst;
  2269. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2270. RemoveInstruction(p2);
  2271. Result := True;
  2272. end;
  2273. end;
  2274. end;
  2275. {$endif x86_64}
  2276. else
  2277. ;
  2278. end;
  2279. end;
  2280. end;
  2281. var
  2282. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2283. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2284. NewSize: topsize;
  2285. CurrentReg, ActiveReg: TRegister;
  2286. SourceRef, TargetRef: TReference;
  2287. MovAligned, MovUnaligned: TAsmOp;
  2288. begin
  2289. Result:=false;
  2290. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2291. { remove mov reg1,reg1? }
  2292. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2293. then
  2294. begin
  2295. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2296. { take care of the register (de)allocs following p }
  2297. RemoveCurrentP(p, hp1);
  2298. Result:=true;
  2299. exit;
  2300. end;
  2301. { All the next optimisations require a next instruction }
  2302. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2303. Exit;
  2304. { Look for:
  2305. mov %reg1,%reg2
  2306. ??? %reg2,r/m
  2307. Change to:
  2308. mov %reg1,%reg2
  2309. ??? %reg1,r/m
  2310. }
  2311. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2312. begin
  2313. CurrentReg := taicpu(p).oper[1]^.reg;
  2314. if RegReadByInstruction(CurrentReg, hp1) and
  2315. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2316. begin
  2317. { A change has occurred, just not in p }
  2318. Result := True;
  2319. TransferUsedRegs(TmpUsedRegs);
  2320. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2321. if not RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs) and
  2322. { Just in case something didn't get modified (e.g. an
  2323. implicit register) }
  2324. not RegReadByInstruction(CurrentReg, hp1) then
  2325. begin
  2326. { We can remove the original MOV }
  2327. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2328. RemoveCurrentp(p, hp1);
  2329. { UsedRegs got updated by RemoveCurrentp }
  2330. Result := True;
  2331. Exit;
  2332. end;
  2333. { If we know a MOV instruction has become a null operation, we might as well
  2334. get rid of it now to save time. }
  2335. if (taicpu(hp1).opcode = A_MOV) and
  2336. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2337. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2338. { Just being a register is enough to confirm it's a null operation }
  2339. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2340. begin
  2341. Result := True;
  2342. { Speed-up to reduce a pipeline stall... if we had something like...
  2343. movl %eax,%edx
  2344. movw %dx,%ax
  2345. ... the second instruction would change to movw %ax,%ax, but
  2346. given that it is now %ax that's active rather than %eax,
  2347. penalties might occur due to a partial register write, so instead,
  2348. change it to a MOVZX instruction when optimising for speed.
  2349. }
  2350. if not (cs_opt_size in current_settings.optimizerswitches) and
  2351. IsMOVZXAcceptable and
  2352. (taicpu(hp1).opsize < taicpu(p).opsize)
  2353. {$ifdef x86_64}
  2354. { operations already implicitly set the upper 64 bits to zero }
  2355. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2356. {$endif x86_64}
  2357. then
  2358. begin
  2359. CurrentReg := taicpu(hp1).oper[1]^.reg;
  2360. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2361. case taicpu(p).opsize of
  2362. S_W:
  2363. if taicpu(hp1).opsize = S_B then
  2364. taicpu(hp1).opsize := S_BL
  2365. else
  2366. InternalError(2020012911);
  2367. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2368. case taicpu(hp1).opsize of
  2369. S_B:
  2370. taicpu(hp1).opsize := S_BL;
  2371. S_W:
  2372. taicpu(hp1).opsize := S_WL;
  2373. else
  2374. InternalError(2020012912);
  2375. end;
  2376. else
  2377. InternalError(2020012910);
  2378. end;
  2379. taicpu(hp1).opcode := A_MOVZX;
  2380. taicpu(hp1).oper[1]^.reg := newreg(getregtype(CurrentReg), getsupreg(CurrentReg), R_SUBD)
  2381. end
  2382. else
  2383. begin
  2384. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2385. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2386. RemoveInstruction(hp1);
  2387. { The instruction after what was hp1 is now the immediate next instruction,
  2388. so we can continue to make optimisations if it's present }
  2389. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2390. Exit;
  2391. hp1 := hp2;
  2392. end;
  2393. end;
  2394. end;
  2395. end;
  2396. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2397. overwrites the original destination register. e.g.
  2398. movl ###,%reg2d
  2399. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2400. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2401. }
  2402. if (taicpu(p).oper[1]^.typ = top_reg) and
  2403. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2404. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2405. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2406. begin
  2407. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2408. begin
  2409. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2410. case taicpu(p).oper[0]^.typ of
  2411. top_const:
  2412. { We have something like:
  2413. movb $x, %regb
  2414. movzbl %regb,%regd
  2415. Change to:
  2416. movl $x, %regd
  2417. }
  2418. begin
  2419. case taicpu(hp1).opsize of
  2420. S_BW:
  2421. begin
  2422. convert_mov_value(A_MOVSX, $FF);
  2423. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2424. taicpu(p).opsize := S_W;
  2425. end;
  2426. S_BL:
  2427. begin
  2428. convert_mov_value(A_MOVSX, $FF);
  2429. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2430. taicpu(p).opsize := S_L;
  2431. end;
  2432. S_WL:
  2433. begin
  2434. convert_mov_value(A_MOVSX, $FFFF);
  2435. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2436. taicpu(p).opsize := S_L;
  2437. end;
  2438. {$ifdef x86_64}
  2439. S_BQ:
  2440. begin
  2441. convert_mov_value(A_MOVSX, $FF);
  2442. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2443. taicpu(p).opsize := S_Q;
  2444. end;
  2445. S_WQ:
  2446. begin
  2447. convert_mov_value(A_MOVSX, $FFFF);
  2448. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2449. taicpu(p).opsize := S_Q;
  2450. end;
  2451. S_LQ:
  2452. begin
  2453. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2454. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2455. taicpu(p).opsize := S_Q;
  2456. end;
  2457. {$endif x86_64}
  2458. else
  2459. { If hp1 was a MOV instruction, it should have been
  2460. optimised already }
  2461. InternalError(2020021001);
  2462. end;
  2463. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2464. RemoveInstruction(hp1);
  2465. Result := True;
  2466. Exit;
  2467. end;
  2468. top_ref:
  2469. { We have something like:
  2470. movb mem, %regb
  2471. movzbl %regb,%regd
  2472. Change to:
  2473. movzbl mem, %regd
  2474. }
  2475. if (taicpu(p).oper[0]^.ref^.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2476. begin
  2477. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2478. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  2479. RemoveCurrentP(p, hp1);
  2480. Result:=True;
  2481. Exit;
  2482. end;
  2483. else
  2484. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2485. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2486. Exit;
  2487. end;
  2488. end
  2489. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2490. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2491. optimised }
  2492. else
  2493. begin
  2494. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2495. RemoveCurrentP(p, hp1);
  2496. Result := True;
  2497. Exit;
  2498. end;
  2499. end;
  2500. if (taicpu(hp1).opcode = A_AND) and
  2501. (taicpu(p).oper[1]^.typ = top_reg) and
  2502. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2503. begin
  2504. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2505. begin
  2506. case taicpu(p).opsize of
  2507. S_L:
  2508. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2509. begin
  2510. { Optimize out:
  2511. mov x, %reg
  2512. and ffffffffh, %reg
  2513. }
  2514. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2515. RemoveInstruction(hp1);
  2516. Result:=true;
  2517. exit;
  2518. end;
  2519. S_Q: { TODO: Confirm if this is even possible }
  2520. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2521. begin
  2522. { Optimize out:
  2523. mov x, %reg
  2524. and ffffffffffffffffh, %reg
  2525. }
  2526. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2527. RemoveInstruction(hp1);
  2528. Result:=true;
  2529. exit;
  2530. end;
  2531. else
  2532. ;
  2533. end;
  2534. if ((taicpu(p).oper[0]^.typ=top_reg) or
  2535. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  2536. GetNextInstruction(hp1,hp2) and
  2537. MatchInstruction(hp2,A_TEST,[taicpu(p).opsize]) and
  2538. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) and
  2539. (MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2540. MatchOperand(taicpu(hp2).oper[0]^,-1)) and
  2541. GetNextInstruction(hp2,hp3) and
  2542. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2543. (taicpu(hp3).condition in [C_E,C_NE]) then
  2544. begin
  2545. TransferUsedRegs(TmpUsedRegs);
  2546. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2547. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2548. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2549. begin
  2550. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2551. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2552. taicpu(hp1).opcode:=A_TEST;
  2553. RemoveInstruction(hp2);
  2554. RemoveCurrentP(p, hp1);
  2555. Result:=true;
  2556. exit;
  2557. end;
  2558. end;
  2559. end
  2560. else if IsMOVZXAcceptable and
  2561. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  2562. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  2563. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  2564. then
  2565. begin
  2566. InputVal := debug_operstr(taicpu(p).oper[0]^);
  2567. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  2568. case taicpu(p).opsize of
  2569. S_B:
  2570. if (taicpu(hp1).oper[0]^.val = $ff) then
  2571. begin
  2572. { Convert:
  2573. movb x, %regl movb x, %regl
  2574. andw ffh, %regw andl ffh, %regd
  2575. To:
  2576. movzbw x, %regd movzbl x, %regd
  2577. (Identical registers, just different sizes)
  2578. }
  2579. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  2580. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  2581. case taicpu(hp1).opsize of
  2582. S_W: NewSize := S_BW;
  2583. S_L: NewSize := S_BL;
  2584. {$ifdef x86_64}
  2585. S_Q: NewSize := S_BQ;
  2586. {$endif x86_64}
  2587. else
  2588. InternalError(2018011510);
  2589. end;
  2590. end
  2591. else
  2592. NewSize := S_NO;
  2593. S_W:
  2594. if (taicpu(hp1).oper[0]^.val = $ffff) then
  2595. begin
  2596. { Convert:
  2597. movw x, %regw
  2598. andl ffffh, %regd
  2599. To:
  2600. movzwl x, %regd
  2601. (Identical registers, just different sizes)
  2602. }
  2603. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  2604. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  2605. case taicpu(hp1).opsize of
  2606. S_L: NewSize := S_WL;
  2607. {$ifdef x86_64}
  2608. S_Q: NewSize := S_WQ;
  2609. {$endif x86_64}
  2610. else
  2611. InternalError(2018011511);
  2612. end;
  2613. end
  2614. else
  2615. NewSize := S_NO;
  2616. else
  2617. NewSize := S_NO;
  2618. end;
  2619. if NewSize <> S_NO then
  2620. begin
  2621. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  2622. { The actual optimization }
  2623. taicpu(p).opcode := A_MOVZX;
  2624. taicpu(p).changeopsize(NewSize);
  2625. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  2626. { Safeguard if "and" is followed by a conditional command }
  2627. TransferUsedRegs(TmpUsedRegs);
  2628. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  2629. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  2630. begin
  2631. { At this point, the "and" command is effectively equivalent to
  2632. "test %reg,%reg". This will be handled separately by the
  2633. Peephole Optimizer. [Kit] }
  2634. DebugMsg(SPeepholeOptimization + PreMessage +
  2635. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2636. end
  2637. else
  2638. begin
  2639. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  2640. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2641. RemoveInstruction(hp1);
  2642. end;
  2643. Result := True;
  2644. Exit;
  2645. end;
  2646. end;
  2647. end;
  2648. if (taicpu(hp1).opcode = A_OR) and
  2649. (taicpu(p).oper[1]^.typ = top_reg) and
  2650. MatchOperand(taicpu(p).oper[0]^, 0) and
  2651. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  2652. begin
  2653. { mov 0, %reg
  2654. or ###,%reg
  2655. Change to (only if the flags are not used):
  2656. mov ###,%reg
  2657. }
  2658. TransferUsedRegs(TmpUsedRegs);
  2659. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2660. DoOptimisation := True;
  2661. { Even if the flags are used, we might be able to do the optimisation
  2662. if the conditions are predictable }
  2663. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2664. begin
  2665. { Only perform if ### = %reg (the same register) or equal to 0,
  2666. so %reg is guaranteed to still have a value of zero }
  2667. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  2668. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  2669. begin
  2670. hp2 := hp1;
  2671. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2672. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  2673. GetNextInstruction(hp2, hp3) do
  2674. begin
  2675. { Don't continue modifying if the flags state is getting changed }
  2676. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  2677. Break;
  2678. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  2679. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  2680. begin
  2681. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  2682. begin
  2683. { Condition is always true }
  2684. case taicpu(hp3).opcode of
  2685. A_Jcc:
  2686. begin
  2687. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  2688. { Check for jump shortcuts before we destroy the condition }
  2689. DoJumpOptimizations(hp3, TempBool);
  2690. MakeUnconditional(taicpu(hp3));
  2691. Result := True;
  2692. end;
  2693. A_CMOVcc:
  2694. begin
  2695. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  2696. taicpu(hp3).opcode := A_MOV;
  2697. taicpu(hp3).condition := C_None;
  2698. Result := True;
  2699. end;
  2700. A_SETcc:
  2701. begin
  2702. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  2703. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  2704. taicpu(hp3).opcode := A_MOV;
  2705. taicpu(hp3).ops := 2;
  2706. taicpu(hp3).condition := C_None;
  2707. taicpu(hp3).opsize := S_B;
  2708. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2709. taicpu(hp3).loadconst(0, 1);
  2710. Result := True;
  2711. end;
  2712. else
  2713. InternalError(2021090701);
  2714. end;
  2715. end
  2716. 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
  2717. begin
  2718. { Condition is always false }
  2719. case taicpu(hp3).opcode of
  2720. A_Jcc:
  2721. begin
  2722. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  2723. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  2724. RemoveInstruction(hp3);
  2725. Result := True;
  2726. { Since hp3 was deleted, hp2 must not be updated }
  2727. Continue;
  2728. end;
  2729. A_CMOVcc:
  2730. begin
  2731. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  2732. RemoveInstruction(hp3);
  2733. Result := True;
  2734. { Since hp3 was deleted, hp2 must not be updated }
  2735. Continue;
  2736. end;
  2737. A_SETcc:
  2738. begin
  2739. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  2740. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  2741. taicpu(hp3).opcode := A_MOV;
  2742. taicpu(hp3).ops := 2;
  2743. taicpu(hp3).condition := C_None;
  2744. taicpu(hp3).opsize := S_B;
  2745. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2746. taicpu(hp3).loadconst(0, 0);
  2747. Result := True;
  2748. end;
  2749. else
  2750. InternalError(2021090702);
  2751. end;
  2752. end
  2753. else
  2754. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  2755. DoOptimisation := False;
  2756. end;
  2757. hp2 := hp3;
  2758. end;
  2759. { Flags are still in use - don't optimise }
  2760. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2761. DoOptimisation := False;
  2762. end
  2763. else
  2764. DoOptimisation := False;
  2765. end;
  2766. if DoOptimisation then
  2767. begin
  2768. {$ifdef x86_64}
  2769. { OR only supports 32-bit sign-extended constants for 64-bit
  2770. instructions, so compensate for this if the constant is
  2771. encoded as a value greater than or equal to 2^31 }
  2772. if (taicpu(hp1).opsize = S_Q) and
  2773. (taicpu(hp1).oper[0]^.typ = top_const) and
  2774. (taicpu(hp1).oper[0]^.val >= $80000000) then
  2775. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  2776. {$endif x86_64}
  2777. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  2778. taicpu(hp1).opcode := A_MOV;
  2779. RemoveCurrentP(p, hp1);
  2780. Result := True;
  2781. Exit;
  2782. end;
  2783. end;
  2784. { Next instruction is also a MOV ? }
  2785. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  2786. begin
  2787. if MatchOpType(taicpu(p), top_const, top_ref) and
  2788. MatchOpType(taicpu(hp1), top_const, top_ref) and
  2789. TryConstMerge(p, hp1) then
  2790. begin
  2791. Result := True;
  2792. { In case we have four byte writes in a row, check for 2 more
  2793. right now so we don't have to wait for another iteration of
  2794. pass 1
  2795. }
  2796. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  2797. case taicpu(p).opsize of
  2798. S_W:
  2799. begin
  2800. if GetNextInstruction(p, hp1) and
  2801. MatchInstruction(hp1, A_MOV, [S_B]) and
  2802. MatchOpType(taicpu(hp1), top_const, top_ref) and
  2803. GetNextInstruction(hp1, hp2) and
  2804. MatchInstruction(hp2, A_MOV, [S_B]) and
  2805. MatchOpType(taicpu(hp2), top_const, top_ref) and
  2806. { Try to merge the two bytes }
  2807. TryConstMerge(hp1, hp2) then
  2808. { Now try to merge the two words (hp2 will get deleted) }
  2809. TryConstMerge(p, hp1);
  2810. end;
  2811. S_L:
  2812. begin
  2813. { Though this only really benefits x86_64 and not i386, it
  2814. gets a potential optimisation done faster and hence
  2815. reduces the number of times OptPass1MOV is entered }
  2816. if GetNextInstruction(p, hp1) and
  2817. MatchInstruction(hp1, A_MOV, [S_W]) and
  2818. MatchOpType(taicpu(hp1), top_const, top_ref) and
  2819. GetNextInstruction(hp1, hp2) and
  2820. MatchInstruction(hp2, A_MOV, [S_W]) and
  2821. MatchOpType(taicpu(hp2), top_const, top_ref) and
  2822. { Try to merge the two words }
  2823. TryConstMerge(hp1, hp2) then
  2824. { This will always fail on i386, so don't bother
  2825. calling it unless we're doing x86_64 }
  2826. {$ifdef x86_64}
  2827. { Now try to merge the two longwords (hp2 will get deleted) }
  2828. TryConstMerge(p, hp1)
  2829. {$endif x86_64}
  2830. ;
  2831. end;
  2832. else
  2833. ;
  2834. end;
  2835. Exit;
  2836. end;
  2837. if (taicpu(p).oper[1]^.typ = top_reg) and
  2838. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2839. begin
  2840. CurrentReg := taicpu(p).oper[1]^.reg;
  2841. TransferUsedRegs(TmpUsedRegs);
  2842. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2843. { we have
  2844. mov x, %treg
  2845. mov %treg, y
  2846. }
  2847. if not(RegInOp(CurrentReg, taicpu(hp1).oper[1]^)) then
  2848. if not(RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs)) then
  2849. { we've got
  2850. mov x, %treg
  2851. mov %treg, y
  2852. with %treg is not used after }
  2853. case taicpu(p).oper[0]^.typ Of
  2854. { top_reg is covered by DeepMOVOpt }
  2855. top_const:
  2856. begin
  2857. { change
  2858. mov const, %treg
  2859. mov %treg, y
  2860. to
  2861. mov const, y
  2862. }
  2863. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  2864. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  2865. begin
  2866. if taicpu(hp1).oper[1]^.typ=top_reg then
  2867. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2868. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  2869. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  2870. RemoveInstruction(hp1);
  2871. Result:=true;
  2872. Exit;
  2873. end;
  2874. end;
  2875. top_ref:
  2876. case taicpu(hp1).oper[1]^.typ of
  2877. top_reg:
  2878. begin
  2879. { change
  2880. mov mem, %treg
  2881. mov %treg, %reg
  2882. to
  2883. mov mem, %reg"
  2884. }
  2885. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2886. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  2887. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  2888. RemoveInstruction(hp1);
  2889. Result:=true;
  2890. Exit;
  2891. end;
  2892. top_ref:
  2893. begin
  2894. {$ifdef x86_64}
  2895. { Look for the following to simplify:
  2896. mov x(mem1), %reg
  2897. mov %reg, y(mem2)
  2898. mov x+8(mem1), %reg
  2899. mov %reg, y+8(mem2)
  2900. Change to:
  2901. movdqu x(mem1), %xmmreg
  2902. movdqu %xmmreg, y(mem2)
  2903. }
  2904. SourceRef := taicpu(p).oper[0]^.ref^;
  2905. TargetRef := taicpu(hp1).oper[1]^.ref^;
  2906. if (taicpu(p).opsize = S_Q) and
  2907. GetNextInstruction(hp1, hp2) and
  2908. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  2909. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  2910. begin
  2911. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  2912. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2913. Inc(SourceRef.offset, 8);
  2914. if UseAVX then
  2915. begin
  2916. MovAligned := A_VMOVDQA;
  2917. MovUnaligned := A_VMOVDQU;
  2918. end
  2919. else
  2920. begin
  2921. MovAligned := A_MOVDQA;
  2922. MovUnaligned := A_MOVDQU;
  2923. end;
  2924. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  2925. begin
  2926. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  2927. Inc(TargetRef.offset, 8);
  2928. if GetNextInstruction(hp2, hp3) and
  2929. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  2930. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  2931. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  2932. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  2933. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  2934. begin
  2935. CurrentReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  2936. if CurrentReg <> NR_NO then
  2937. begin
  2938. { Remember that the offsets are 8 ahead }
  2939. if ((SourceRef.offset mod 16) = 8) and
  2940. (
  2941. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2942. (SourceRef.base = current_procinfo.framepointer) or
  2943. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  2944. ) then
  2945. taicpu(p).opcode := MovAligned
  2946. else
  2947. taicpu(p).opcode := MovUnaligned;
  2948. taicpu(p).opsize := S_XMM;
  2949. taicpu(p).oper[1]^.reg := CurrentReg;
  2950. if ((TargetRef.offset mod 16) = 8) and
  2951. (
  2952. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2953. (TargetRef.base = current_procinfo.framepointer) or
  2954. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  2955. ) then
  2956. taicpu(hp1).opcode := MovAligned
  2957. else
  2958. taicpu(hp1).opcode := MovUnaligned;
  2959. taicpu(hp1).opsize := S_XMM;
  2960. taicpu(hp1).oper[0]^.reg := CurrentReg;
  2961. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  2962. RemoveInstruction(hp2);
  2963. RemoveInstruction(hp3);
  2964. Result := True;
  2965. Exit;
  2966. end;
  2967. end;
  2968. end
  2969. else
  2970. begin
  2971. { See if the next references are 8 less rather than 8 greater }
  2972. Dec(SourceRef.offset, 16); { -8 the other way }
  2973. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  2974. begin
  2975. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  2976. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  2977. if GetNextInstruction(hp2, hp3) and
  2978. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  2979. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  2980. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  2981. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  2982. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  2983. begin
  2984. CurrentReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  2985. if CurrentReg <> NR_NO then
  2986. begin
  2987. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  2988. if ((SourceRef.offset mod 16) = 0) and
  2989. (
  2990. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2991. (SourceRef.base = current_procinfo.framepointer) or
  2992. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  2993. ) then
  2994. taicpu(hp2).opcode := MovAligned
  2995. else
  2996. taicpu(hp2).opcode := MovUnaligned;
  2997. taicpu(hp2).opsize := S_XMM;
  2998. taicpu(hp2).oper[1]^.reg := CurrentReg;
  2999. if ((TargetRef.offset mod 16) = 0) and
  3000. (
  3001. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3002. (TargetRef.base = current_procinfo.framepointer) or
  3003. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3004. ) then
  3005. taicpu(hp3).opcode := MovAligned
  3006. else
  3007. taicpu(hp3).opcode := MovUnaligned;
  3008. taicpu(hp3).opsize := S_XMM;
  3009. taicpu(hp3).oper[0]^.reg := CurrentReg;
  3010. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3011. RemoveInstruction(hp1);
  3012. RemoveCurrentP(p, hp2);
  3013. Result := True;
  3014. Exit;
  3015. end;
  3016. end;
  3017. end;
  3018. end;
  3019. end;
  3020. {$endif x86_64}
  3021. end;
  3022. else
  3023. { The write target should be a reg or a ref }
  3024. InternalError(2021091601);
  3025. end;
  3026. else
  3027. ;
  3028. end
  3029. else
  3030. { %treg is used afterwards, but all eventualities
  3031. other than the first MOV instruction being a constant
  3032. are covered by DeepMOVOpt, so only check for that }
  3033. if (taicpu(p).oper[0]^.typ = top_const) and
  3034. (
  3035. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3036. not (cs_opt_size in current_settings.optimizerswitches) or
  3037. (taicpu(hp1).opsize = S_B)
  3038. ) and
  3039. (
  3040. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3041. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3042. ) then
  3043. begin
  3044. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3045. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3046. end;
  3047. end;
  3048. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3049. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3050. { mov reg1, mem1 or mov mem1, reg1
  3051. mov mem2, reg2 mov reg2, mem2}
  3052. begin
  3053. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3054. { mov reg1, mem1 or mov mem1, reg1
  3055. mov mem2, reg1 mov reg2, mem1}
  3056. begin
  3057. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3058. { Removes the second statement from
  3059. mov reg1, mem1/reg2
  3060. mov mem1/reg2, reg1 }
  3061. begin
  3062. if taicpu(p).oper[0]^.typ=top_reg then
  3063. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3064. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3065. RemoveInstruction(hp1);
  3066. Result:=true;
  3067. exit;
  3068. end
  3069. else
  3070. begin
  3071. TransferUsedRegs(TmpUsedRegs);
  3072. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3073. if (taicpu(p).oper[1]^.typ = top_ref) and
  3074. { mov reg1, mem1
  3075. mov mem2, reg1 }
  3076. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3077. GetNextInstruction(hp1, hp2) and
  3078. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3079. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3080. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3081. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3082. { change to
  3083. mov reg1, mem1 mov reg1, mem1
  3084. mov mem2, reg1 cmp reg1, mem2
  3085. cmp mem1, reg1
  3086. }
  3087. begin
  3088. RemoveInstruction(hp2);
  3089. taicpu(hp1).opcode := A_CMP;
  3090. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3091. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3092. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3093. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3094. end;
  3095. end;
  3096. end
  3097. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3098. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3099. begin
  3100. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3101. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3102. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3103. end
  3104. else
  3105. begin
  3106. TransferUsedRegs(TmpUsedRegs);
  3107. if GetNextInstruction(hp1, hp2) and
  3108. MatchOpType(taicpu(p),top_ref,top_reg) and
  3109. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3110. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3111. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3112. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3113. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3114. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3115. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3116. { mov mem1, %reg1
  3117. mov %reg1, mem2
  3118. mov mem2, reg2
  3119. to:
  3120. mov mem1, reg2
  3121. mov reg2, mem2}
  3122. begin
  3123. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3124. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3125. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3126. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3127. RemoveInstruction(hp2);
  3128. Result := True;
  3129. end
  3130. {$ifdef i386}
  3131. { this is enabled for i386 only, as the rules to create the reg sets below
  3132. are too complicated for x86-64, so this makes this code too error prone
  3133. on x86-64
  3134. }
  3135. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3136. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3137. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3138. { mov mem1, reg1 mov mem1, reg1
  3139. mov reg1, mem2 mov reg1, mem2
  3140. mov mem2, reg2 mov mem2, reg1
  3141. to: to:
  3142. mov mem1, reg1 mov mem1, reg1
  3143. mov mem1, reg2 mov reg1, mem2
  3144. mov reg1, mem2
  3145. or (if mem1 depends on reg1
  3146. and/or if mem2 depends on reg2)
  3147. to:
  3148. mov mem1, reg1
  3149. mov reg1, mem2
  3150. mov reg1, reg2
  3151. }
  3152. begin
  3153. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3154. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3155. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3156. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3157. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3158. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3159. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3160. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3161. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3162. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3163. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3164. end
  3165. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3166. begin
  3167. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3168. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3169. end
  3170. else
  3171. begin
  3172. RemoveInstruction(hp2);
  3173. end
  3174. {$endif i386}
  3175. ;
  3176. end;
  3177. end
  3178. { movl [mem1],reg1
  3179. movl [mem1],reg2
  3180. to
  3181. movl [mem1],reg1
  3182. movl reg1,reg2
  3183. }
  3184. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3185. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3186. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3187. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3188. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3189. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3190. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3191. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3192. begin
  3193. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3194. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3195. end;
  3196. { movl const1,[mem1]
  3197. movl [mem1],reg1
  3198. to
  3199. movl const1,reg1
  3200. movl reg1,[mem1]
  3201. }
  3202. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3203. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3204. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3205. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3206. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3207. begin
  3208. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3209. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3210. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3211. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3212. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3213. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3214. Result:=true;
  3215. exit;
  3216. end;
  3217. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3218. end;
  3219. { search further than the next instruction for a mov (as long as it's not a jump) }
  3220. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3221. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3222. (taicpu(p).oper[1]^.typ = top_reg) and
  3223. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3224. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3225. begin
  3226. { we work with hp2 here, so hp1 can be still used later on when
  3227. checking for GetNextInstruction_p }
  3228. hp3 := hp1;
  3229. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3230. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3231. { Saves on a large number of dereferences }
  3232. ActiveReg := taicpu(p).oper[1]^.reg;
  3233. TransferUsedRegs(TmpUsedRegs);
  3234. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3235. while GetNextInstructionUsingRegCond(hp3,hp2,ActiveReg,CrossJump) and
  3236. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3237. (hp2.typ=ait_instruction) do
  3238. begin
  3239. case taicpu(hp2).opcode of
  3240. A_POP:
  3241. if MatchOperand(taicpu(hp2).oper[0]^,ActiveReg) then
  3242. begin
  3243. if not CrossJump and
  3244. not RegUsedBetween(ActiveReg, p, hp2) then
  3245. begin
  3246. { We can remove the original MOV since the register
  3247. wasn't used between it and its popping from the stack }
  3248. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3249. RemoveCurrentp(p, hp1);
  3250. Result := True;
  3251. Exit;
  3252. end;
  3253. { Can't go any further }
  3254. Break;
  3255. end;
  3256. A_MOV:
  3257. if MatchOperand(taicpu(hp2).oper[0]^,ActiveReg) and
  3258. ((taicpu(p).oper[0]^.typ=top_const) or
  3259. ((taicpu(p).oper[0]^.typ=top_reg) and
  3260. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3261. )
  3262. ) then
  3263. begin
  3264. { we have
  3265. mov x, %treg
  3266. mov %treg, y
  3267. }
  3268. { We don't need to call UpdateUsedRegs for every instruction between
  3269. p and hp2 because the register we're concerned about will not
  3270. become deallocated (otherwise GetNextInstructionUsingReg would
  3271. have stopped at an earlier instruction). [Kit] }
  3272. TempRegUsed :=
  3273. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3274. RegReadByInstruction(ActiveReg, hp3) or
  3275. RegUsedAfterInstruction(ActiveReg, hp2, TmpUsedRegs);
  3276. case taicpu(p).oper[0]^.typ Of
  3277. top_reg:
  3278. begin
  3279. { change
  3280. mov %reg, %treg
  3281. mov %treg, y
  3282. to
  3283. mov %reg, y
  3284. }
  3285. CurrentReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3286. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3287. if MatchOperand(taicpu(hp2).oper[1]^, CurrentReg) then
  3288. begin
  3289. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3290. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3291. if TempRegUsed then
  3292. begin
  3293. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3294. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  3295. { Set the start of the next GetNextInstructionUsingRegCond search
  3296. to start at the entry right before hp2 (which is about to be removed) }
  3297. hp3 := tai(hp2.Previous);
  3298. RemoveInstruction(hp2);
  3299. { See if there's more we can optimise }
  3300. Continue;
  3301. end
  3302. else
  3303. begin
  3304. RemoveInstruction(hp2);
  3305. { We can remove the original MOV too }
  3306. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3307. RemoveCurrentP(p, hp1);
  3308. Result:=true;
  3309. Exit;
  3310. end;
  3311. end
  3312. else
  3313. begin
  3314. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  3315. taicpu(hp2).loadReg(0, CurrentReg);
  3316. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(CurrentReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3317. { Check to see if the register also appears in the reference }
  3318. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3319. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, ActiveReg, CurrentReg);
  3320. { Don't remove the first instruction if the temporary register is in use }
  3321. if not TempRegUsed and
  3322. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3323. not RegInOp(ActiveReg, taicpu(hp2).oper[1]^) then
  3324. begin
  3325. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3326. RemoveCurrentP(p, hp1);
  3327. Result:=true;
  3328. Exit;
  3329. end;
  3330. { No need to set Result to True here. If there's another instruction later
  3331. on that can be optimised, it will be detected when the main Pass 1 loop
  3332. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3333. end;
  3334. end;
  3335. top_const:
  3336. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3337. begin
  3338. { change
  3339. mov const, %treg
  3340. mov %treg, y
  3341. to
  3342. mov const, y
  3343. }
  3344. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3345. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3346. begin
  3347. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3348. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3349. if TempRegUsed then
  3350. begin
  3351. { Don't remove the first instruction if the temporary register is in use }
  3352. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3353. { No need to set Result to True. If there's another instruction later on
  3354. that can be optimised, it will be detected when the main Pass 1 loop
  3355. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3356. end
  3357. else
  3358. begin
  3359. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3360. RemoveCurrentP(p, hp1);
  3361. Result:=true;
  3362. Exit;
  3363. end;
  3364. end;
  3365. end;
  3366. else
  3367. Internalerror(2019103001);
  3368. end;
  3369. end
  3370. else
  3371. if MatchOperand(taicpu(hp2).oper[1]^, ActiveReg) then
  3372. begin
  3373. if not CrossJump and
  3374. not RegUsedBetween(ActiveReg, p, hp2) and
  3375. not RegReadByInstruction(ActiveReg, hp2) then
  3376. begin
  3377. { Register is not used before it is overwritten }
  3378. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3379. RemoveCurrentp(p, hp1);
  3380. Result := True;
  3381. Exit;
  3382. end;
  3383. if (taicpu(p).oper[0]^.typ = top_const) and
  3384. (taicpu(hp2).oper[0]^.typ = top_const) then
  3385. begin
  3386. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3387. begin
  3388. { Same value - register hasn't changed }
  3389. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3390. RemoveInstruction(hp2);
  3391. Result := True;
  3392. { See if there's more we can optimise }
  3393. Continue;
  3394. end;
  3395. end;
  3396. end;
  3397. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  3398. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  3399. MatchOperand(taicpu(hp2).oper[0]^, ActiveReg) and
  3400. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, ActiveReg) then
  3401. begin
  3402. {
  3403. Change from:
  3404. mov ###, %reg
  3405. ...
  3406. movs/z %reg,%reg (Same register, just different sizes)
  3407. To:
  3408. movs/z ###, %reg (Longer version)
  3409. ...
  3410. (remove)
  3411. }
  3412. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  3413. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  3414. { Keep the first instruction as mov if ### is a constant }
  3415. if taicpu(p).oper[0]^.typ = top_const then
  3416. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  3417. else
  3418. begin
  3419. taicpu(p).opcode := taicpu(hp2).opcode;
  3420. taicpu(p).opsize := taicpu(hp2).opsize;
  3421. end;
  3422. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  3423. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  3424. RemoveInstruction(hp2);
  3425. Result := True;
  3426. Exit;
  3427. end;
  3428. else
  3429. { Move down to the MatchOpType if-block below };
  3430. end;
  3431. { Also catches MOV/S/Z instructions that aren't modified }
  3432. if taicpu(p).oper[0]^.typ = top_reg then
  3433. begin
  3434. CurrentReg := taicpu(p).oper[0]^.reg;
  3435. if
  3436. not RegModifiedByInstruction(CurrentReg, hp3) and
  3437. not RegModifiedBetween(CurrentReg, hp3, hp2) and
  3438. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  3439. begin
  3440. Result := True;
  3441. { Just in case something didn't get modified (e.g. an
  3442. implicit register). Also, if it does read from this
  3443. register, then there's no longer an advantage to
  3444. changing the register on subsequent instructions.}
  3445. if not RegReadByInstruction(ActiveReg, hp2) then
  3446. begin
  3447. { If a conditional jump was crossed, do not delete
  3448. the original MOV no matter what }
  3449. if not CrossJump and
  3450. { RegEndOfLife returns True if the register is
  3451. deallocated before the next instruction or has
  3452. been loaded with a new value }
  3453. RegEndOfLife(ActiveReg, taicpu(hp2)) then
  3454. begin
  3455. { We can remove the original MOV }
  3456. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  3457. RemoveCurrentp(p, hp1);
  3458. Exit;
  3459. end;
  3460. if not RegModifiedByInstruction(ActiveReg, hp2) then
  3461. begin
  3462. { See if there's more we can optimise }
  3463. hp3 := hp2;
  3464. Continue;
  3465. end;
  3466. end;
  3467. end;
  3468. end;
  3469. { Break out of the while loop under normal circumstances }
  3470. Break;
  3471. end;
  3472. end;
  3473. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  3474. (taicpu(p).oper[1]^.typ = top_reg) and
  3475. (taicpu(p).opsize = S_L) and
  3476. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  3477. (taicpu(hp2).opcode = A_AND) and
  3478. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  3479. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3480. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  3481. ) then
  3482. begin
  3483. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  3484. begin
  3485. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  3486. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  3487. begin
  3488. { Optimize out:
  3489. mov x, %reg
  3490. and ffffffffh, %reg
  3491. }
  3492. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  3493. RemoveInstruction(hp2);
  3494. Result:=true;
  3495. exit;
  3496. end;
  3497. end;
  3498. end;
  3499. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  3500. x >= RetOffset) as it doesn't do anything (it writes either to a
  3501. parameter or to the temporary storage room for the function
  3502. result)
  3503. }
  3504. if IsExitCode(hp1) and
  3505. (taicpu(p).oper[1]^.typ = top_ref) and
  3506. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  3507. (
  3508. (
  3509. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  3510. not (
  3511. assigned(current_procinfo.procdef.funcretsym) and
  3512. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  3513. )
  3514. ) or
  3515. { Also discard writes to the stack that are below the base pointer,
  3516. as this is temporary storage rather than a function result on the
  3517. stack, say. }
  3518. (
  3519. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  3520. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  3521. )
  3522. ) then
  3523. begin
  3524. RemoveCurrentp(p, hp1);
  3525. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  3526. RemoveLastDeallocForFuncRes(p);
  3527. Result:=true;
  3528. exit;
  3529. end;
  3530. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  3531. begin
  3532. if MatchOpType(taicpu(p),top_reg,top_ref) and
  3533. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3534. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3535. begin
  3536. { change
  3537. mov reg1, mem1
  3538. test/cmp x, mem1
  3539. to
  3540. mov reg1, mem1
  3541. test/cmp x, reg1
  3542. }
  3543. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  3544. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  3545. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3546. Result := True;
  3547. Exit;
  3548. end;
  3549. if DoMovCmpMemOpt(p, hp1, True) then
  3550. begin
  3551. Result := True;
  3552. Exit;
  3553. end;
  3554. end;
  3555. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  3556. { If the flags register is in use, don't change the instruction to an
  3557. ADD otherwise this will scramble the flags. [Kit] }
  3558. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  3559. begin
  3560. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  3561. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3562. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3563. ) or
  3564. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3565. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3566. )
  3567. ) then
  3568. { mov reg1,ref
  3569. lea reg2,[reg1,reg2]
  3570. to
  3571. add reg2,ref}
  3572. begin
  3573. TransferUsedRegs(TmpUsedRegs);
  3574. { reg1 may not be used afterwards }
  3575. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3576. begin
  3577. Taicpu(hp1).opcode:=A_ADD;
  3578. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3579. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3580. RemoveCurrentp(p, hp1);
  3581. result:=true;
  3582. exit;
  3583. end;
  3584. end;
  3585. { If the LEA instruction can be converted into an arithmetic instruction,
  3586. it may be possible to then fold it in the next optimisation, otherwise
  3587. there's nothing more that can be optimised here. }
  3588. if not ConvertLEA(taicpu(hp1)) then
  3589. Exit;
  3590. end;
  3591. if (taicpu(p).oper[1]^.typ = top_reg) and
  3592. (hp1.typ = ait_instruction) and
  3593. GetNextInstruction(hp1, hp2) and
  3594. MatchInstruction(hp2,A_MOV,[]) and
  3595. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  3596. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  3597. (
  3598. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  3599. {$ifdef x86_64}
  3600. or
  3601. (
  3602. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  3603. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  3604. )
  3605. {$endif x86_64}
  3606. ) then
  3607. begin
  3608. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  3609. (taicpu(hp2).oper[0]^.typ=top_reg) then
  3610. { change movsX/movzX reg/ref, reg2
  3611. add/sub/or/... reg3/$const, reg2
  3612. mov reg2 reg/ref
  3613. dealloc reg2
  3614. to
  3615. add/sub/or/... reg3/$const, reg/ref }
  3616. begin
  3617. TransferUsedRegs(TmpUsedRegs);
  3618. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3619. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3620. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3621. begin
  3622. { by example:
  3623. movswl %si,%eax movswl %si,%eax p
  3624. decl %eax addl %edx,%eax hp1
  3625. movw %ax,%si movw %ax,%si hp2
  3626. ->
  3627. movswl %si,%eax movswl %si,%eax p
  3628. decw %eax addw %edx,%eax hp1
  3629. movw %ax,%si movw %ax,%si hp2
  3630. }
  3631. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  3632. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3633. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3634. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3635. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3636. {
  3637. ->
  3638. movswl %si,%eax movswl %si,%eax p
  3639. decw %si addw %dx,%si hp1
  3640. movw %ax,%si movw %ax,%si hp2
  3641. }
  3642. case taicpu(hp1).ops of
  3643. 1:
  3644. begin
  3645. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3646. if taicpu(hp1).oper[0]^.typ=top_reg then
  3647. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3648. end;
  3649. 2:
  3650. begin
  3651. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3652. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3653. (taicpu(hp1).opcode<>A_SHL) and
  3654. (taicpu(hp1).opcode<>A_SHR) and
  3655. (taicpu(hp1).opcode<>A_SAR) then
  3656. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3657. end;
  3658. else
  3659. internalerror(2008042701);
  3660. end;
  3661. {
  3662. ->
  3663. decw %si addw %dx,%si p
  3664. }
  3665. RemoveInstruction(hp2);
  3666. RemoveCurrentP(p, hp1);
  3667. Result:=True;
  3668. Exit;
  3669. end;
  3670. end;
  3671. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3672. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  3673. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  3674. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  3675. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  3676. )
  3677. {$ifdef i386}
  3678. { byte registers of esi, edi, ebp, esp are not available on i386 }
  3679. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3680. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3681. {$endif i386}
  3682. then
  3683. { change movsX/movzX reg/ref, reg2
  3684. add/sub/or/... regX/$const, reg2
  3685. mov reg2, reg3
  3686. dealloc reg2
  3687. to
  3688. movsX/movzX reg/ref, reg3
  3689. add/sub/or/... reg3/$const, reg3
  3690. }
  3691. begin
  3692. TransferUsedRegs(TmpUsedRegs);
  3693. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3694. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3695. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3696. begin
  3697. { by example:
  3698. movswl %si,%eax movswl %si,%eax p
  3699. decl %eax addl %edx,%eax hp1
  3700. movw %ax,%si movw %ax,%si hp2
  3701. ->
  3702. movswl %si,%eax movswl %si,%eax p
  3703. decw %eax addw %edx,%eax hp1
  3704. movw %ax,%si movw %ax,%si hp2
  3705. }
  3706. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  3707. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3708. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3709. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3710. { limit size of constants as well to avoid assembler errors, but
  3711. check opsize to avoid overflow when left shifting the 1 }
  3712. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  3713. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  3714. {$ifdef x86_64}
  3715. { Be careful of, for example:
  3716. movl %reg1,%reg2
  3717. addl %reg3,%reg2
  3718. movq %reg2,%reg4
  3719. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  3720. }
  3721. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  3722. begin
  3723. taicpu(hp2).changeopsize(S_L);
  3724. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  3725. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  3726. end;
  3727. {$endif x86_64}
  3728. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3729. taicpu(p).changeopsize(taicpu(hp2).opsize);
  3730. if taicpu(p).oper[0]^.typ=top_reg then
  3731. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3732. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  3733. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  3734. {
  3735. ->
  3736. movswl %si,%eax movswl %si,%eax p
  3737. decw %si addw %dx,%si hp1
  3738. movw %ax,%si movw %ax,%si hp2
  3739. }
  3740. case taicpu(hp1).ops of
  3741. 1:
  3742. begin
  3743. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3744. if taicpu(hp1).oper[0]^.typ=top_reg then
  3745. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3746. end;
  3747. 2:
  3748. begin
  3749. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3750. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3751. (taicpu(hp1).opcode<>A_SHL) and
  3752. (taicpu(hp1).opcode<>A_SHR) and
  3753. (taicpu(hp1).opcode<>A_SAR) then
  3754. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3755. end;
  3756. else
  3757. internalerror(2018111801);
  3758. end;
  3759. {
  3760. ->
  3761. decw %si addw %dx,%si p
  3762. }
  3763. RemoveInstruction(hp2);
  3764. end;
  3765. end;
  3766. end;
  3767. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  3768. GetNextInstruction(hp1, hp2) and
  3769. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  3770. MatchOperand(Taicpu(p).oper[0]^,0) and
  3771. (Taicpu(p).oper[1]^.typ = top_reg) and
  3772. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  3773. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  3774. { mov reg1,0
  3775. bts reg1,operand1 --> mov reg1,operand2
  3776. or reg1,operand2 bts reg1,operand1}
  3777. begin
  3778. Taicpu(hp2).opcode:=A_MOV;
  3779. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  3780. asml.remove(hp1);
  3781. insertllitem(hp2,hp2.next,hp1);
  3782. RemoveCurrentp(p, hp1);
  3783. Result:=true;
  3784. exit;
  3785. end;
  3786. {
  3787. mov ref,reg0
  3788. <op> reg0,reg1
  3789. dealloc reg0
  3790. to
  3791. <op> ref,reg1
  3792. }
  3793. if MatchOpType(taicpu(p),top_ref,top_reg) and
  3794. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  3795. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3796. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  3797. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  3798. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  3799. begin
  3800. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  3801. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  3802. RemoveCurrentp(p, hp1);
  3803. Result:=true;
  3804. exit;
  3805. end;
  3806. {$ifdef x86_64}
  3807. { Convert:
  3808. movq x(ref),%reg64
  3809. shrq y,%reg64
  3810. To:
  3811. movq x+4(ref),%reg32
  3812. shrq y-32,%reg32 (Remove if y = 32)
  3813. }
  3814. if (taicpu(p).opsize = S_Q) and
  3815. (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  3816. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFB) and
  3817. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  3818. MatchOpType(taicpu(hp1), top_const, top_reg) and
  3819. (taicpu(hp1).oper[0]^.val >= 32) and
  3820. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  3821. begin
  3822. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  3823. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  3824. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  3825. { Convert to 32-bit }
  3826. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3827. taicpu(p).opsize := S_L;
  3828. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  3829. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  3830. if (taicpu(hp1).oper[0]^.val = 32) then
  3831. begin
  3832. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  3833. RemoveInstruction(hp1);
  3834. end
  3835. else
  3836. begin
  3837. { This will potentially open up more arithmetic operations since
  3838. the peephole optimizer now has a big hint that only the lower
  3839. 32 bits are currently in use (and opcodes are smaller in size) }
  3840. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3841. taicpu(hp1).opsize := S_L;
  3842. Dec(taicpu(hp1).oper[0]^.val, 32);
  3843. DebugMsg(SPeepholeOptimization + PreMessage +
  3844. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  3845. end;
  3846. Result := True;
  3847. Exit;
  3848. end;
  3849. {$endif x86_64}
  3850. end;
  3851. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  3852. var
  3853. hp1 : tai;
  3854. begin
  3855. Result:=false;
  3856. if taicpu(p).ops <> 2 then
  3857. exit;
  3858. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  3859. GetNextInstruction(p,hp1) then
  3860. begin
  3861. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  3862. (taicpu(hp1).ops = 2) then
  3863. begin
  3864. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3865. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3866. { movXX reg1, mem1 or movXX mem1, reg1
  3867. movXX mem2, reg2 movXX reg2, mem2}
  3868. begin
  3869. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3870. { movXX reg1, mem1 or movXX mem1, reg1
  3871. movXX mem2, reg1 movXX reg2, mem1}
  3872. begin
  3873. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3874. begin
  3875. { Removes the second statement from
  3876. movXX reg1, mem1/reg2
  3877. movXX mem1/reg2, reg1
  3878. }
  3879. if taicpu(p).oper[0]^.typ=top_reg then
  3880. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3881. { Removes the second statement from
  3882. movXX mem1/reg1, reg2
  3883. movXX reg2, mem1/reg1
  3884. }
  3885. if (taicpu(p).oper[1]^.typ=top_reg) and
  3886. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  3887. begin
  3888. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  3889. RemoveInstruction(hp1);
  3890. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  3891. Result:=true;
  3892. exit;
  3893. end
  3894. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  3895. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  3896. begin
  3897. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  3898. RemoveInstruction(hp1);
  3899. Result:=true;
  3900. exit;
  3901. end;
  3902. end
  3903. end;
  3904. end;
  3905. end;
  3906. end;
  3907. end;
  3908. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  3909. var
  3910. hp1 : tai;
  3911. begin
  3912. result:=false;
  3913. { replace
  3914. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  3915. MovX %mreg2,%mreg1
  3916. dealloc %mreg2
  3917. by
  3918. <Op>X %mreg2,%mreg1
  3919. ?
  3920. }
  3921. if GetNextInstruction(p,hp1) and
  3922. { we mix single and double opperations here because we assume that the compiler
  3923. generates vmovapd only after double operations and vmovaps only after single operations }
  3924. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  3925. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3926. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  3927. (taicpu(p).oper[0]^.typ=top_reg) then
  3928. begin
  3929. TransferUsedRegs(TmpUsedRegs);
  3930. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3931. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3932. begin
  3933. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  3934. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  3935. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  3936. RemoveInstruction(hp1);
  3937. result:=true;
  3938. end;
  3939. end;
  3940. end;
  3941. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  3942. var
  3943. hp1, p_label, p_dist, hp1_dist: tai;
  3944. JumpLabel, JumpLabel_dist: TAsmLabel;
  3945. FirstValue, SecondValue: TCGInt;
  3946. begin
  3947. Result := False;
  3948. if (taicpu(p).oper[0]^.typ = top_const) and
  3949. (taicpu(p).oper[0]^.val <> -1) then
  3950. begin
  3951. { Convert unsigned maximum constants to -1 to aid optimisation }
  3952. case taicpu(p).opsize of
  3953. S_B:
  3954. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  3955. begin
  3956. taicpu(p).oper[0]^.val := -1;
  3957. Result := True;
  3958. Exit;
  3959. end;
  3960. S_W:
  3961. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  3962. begin
  3963. taicpu(p).oper[0]^.val := -1;
  3964. Result := True;
  3965. Exit;
  3966. end;
  3967. S_L:
  3968. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  3969. begin
  3970. taicpu(p).oper[0]^.val := -1;
  3971. Result := True;
  3972. Exit;
  3973. end;
  3974. {$ifdef x86_64}
  3975. S_Q:
  3976. { Storing anything greater than $7FFFFFFF is not possible so do
  3977. nothing };
  3978. {$endif x86_64}
  3979. else
  3980. InternalError(2021121001);
  3981. end;
  3982. end;
  3983. if GetNextInstruction(p, hp1) and
  3984. TrySwapMovCmp(p, hp1) then
  3985. begin
  3986. Result := True;
  3987. Exit;
  3988. end;
  3989. { Search for:
  3990. test $x,(reg/ref)
  3991. jne @lbl1
  3992. test $y,(reg/ref) (same register or reference)
  3993. jne @lbl1
  3994. Change to:
  3995. test $(x or y),(reg/ref)
  3996. jne @lbl1
  3997. (Note, this doesn't work with je instead of jne)
  3998. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  3999. Also search for:
  4000. test $x,(reg/ref)
  4001. je @lbl1
  4002. test $y,(reg/ref)
  4003. je/jne @lbl2
  4004. If (x or y) = x, then the second jump is deterministic
  4005. }
  4006. if (
  4007. (
  4008. (taicpu(p).oper[0]^.typ = top_const) or
  4009. (
  4010. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4011. (taicpu(p).oper[0]^.typ = top_reg) and
  4012. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4013. )
  4014. ) and
  4015. MatchInstruction(hp1, A_JCC, [])
  4016. ) then
  4017. begin
  4018. if (taicpu(p).oper[0]^.typ = top_reg) and
  4019. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4020. FirstValue := -1
  4021. else
  4022. FirstValue := taicpu(p).oper[0]^.val;
  4023. { If we have several test/jne's in a row, it might be the case that
  4024. the second label doesn't go to the same location, but the one
  4025. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4026. so accommodate for this with a while loop.
  4027. }
  4028. hp1_dist := hp1;
  4029. if GetNextInstruction(hp1, p_dist) and
  4030. (p_dist.typ = ait_instruction) and
  4031. (
  4032. (
  4033. (taicpu(p_dist).opcode = A_TEST) and
  4034. (
  4035. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4036. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4037. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4038. )
  4039. ) or
  4040. (
  4041. { cmp 0,%reg = test %reg,%reg }
  4042. (taicpu(p_dist).opcode = A_CMP) and
  4043. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4044. )
  4045. ) and
  4046. { Make sure the destination operands are actually the same }
  4047. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4048. GetNextInstruction(p_dist, hp1_dist) and
  4049. MatchInstruction(hp1_dist, A_JCC, []) then
  4050. begin
  4051. if
  4052. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4053. (
  4054. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4055. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4056. ) then
  4057. SecondValue := -1
  4058. else
  4059. SecondValue := taicpu(p_dist).oper[0]^.val;
  4060. { If both of the TEST constants are identical, delete the second
  4061. TEST that is unnecessary. }
  4062. if (FirstValue = SecondValue) then
  4063. begin
  4064. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4065. RemoveInstruction(p_dist);
  4066. { Don't let the flags register become deallocated and reallocated between the jumps }
  4067. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4068. Result := True;
  4069. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4070. begin
  4071. { Since the second jump's condition is a subset of the first, we
  4072. know it will never branch because the first jump dominates it.
  4073. Get it out of the way now rather than wait for the jump
  4074. optimisations for a speed boost. }
  4075. if IsJumpToLabel(taicpu(hp1_dist)) then
  4076. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4077. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4078. RemoveInstruction(hp1_dist);
  4079. end
  4080. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4081. begin
  4082. { If the inverse of the first condition is a subset of the second,
  4083. the second one will definitely branch if the first one doesn't }
  4084. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4085. MakeUnconditional(taicpu(hp1_dist));
  4086. RemoveDeadCodeAfterJump(hp1_dist);
  4087. end;
  4088. Exit;
  4089. end;
  4090. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4091. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4092. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4093. then the second jump will never branch, so it can also be
  4094. removed regardless of where it goes }
  4095. (
  4096. (FirstValue = -1) or
  4097. (SecondValue = -1) or
  4098. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4099. ) then
  4100. begin
  4101. { Same jump location... can be a register since nothing's changed }
  4102. { If any of the entries are equivalent to test %reg,%reg, then the
  4103. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  4104. taicpu(p).loadconst(0, FirstValue or SecondValue);
  4105. if IsJumpToLabel(taicpu(hp1_dist)) then
  4106. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4107. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  4108. RemoveInstruction(hp1_dist);
  4109. { Only remove the second test if no jumps or other conditional instructions follow }
  4110. TransferUsedRegs(TmpUsedRegs);
  4111. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4112. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4113. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  4114. RemoveInstruction(p_dist);
  4115. Result := True;
  4116. Exit;
  4117. end;
  4118. end;
  4119. end;
  4120. { Search for:
  4121. test %reg,%reg
  4122. j(c1) @lbl1
  4123. ...
  4124. @lbl:
  4125. test %reg,%reg (same register)
  4126. j(c2) @lbl2
  4127. If c2 is a subset of c1, change to:
  4128. test %reg,%reg
  4129. j(c1) @lbl2
  4130. (@lbl1 may become a dead label as a result)
  4131. }
  4132. if (taicpu(p).oper[1]^.typ = top_reg) and
  4133. (taicpu(p).oper[0]^.typ = top_reg) and
  4134. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  4135. MatchInstruction(hp1, A_JCC, []) and
  4136. IsJumpToLabel(taicpu(hp1)) then
  4137. begin
  4138. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4139. p_label := nil;
  4140. if Assigned(JumpLabel) then
  4141. p_label := getlabelwithsym(JumpLabel);
  4142. if Assigned(p_label) and
  4143. GetNextInstruction(p_label, p_dist) and
  4144. MatchInstruction(p_dist, A_TEST, []) and
  4145. { It's fine if the second test uses smaller sub-registers }
  4146. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  4147. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  4148. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  4149. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  4150. GetNextInstruction(p_dist, hp1_dist) and
  4151. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4152. begin
  4153. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4154. if JumpLabel = JumpLabel_dist then
  4155. { This is an infinite loop }
  4156. Exit;
  4157. { Best optimisation when the first condition is a subset (or equal) of the second }
  4158. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  4159. begin
  4160. { Any registers used here will already be allocated }
  4161. if Assigned(JumpLabel_dist) then
  4162. JumpLabel_dist.IncRefs;
  4163. if Assigned(JumpLabel) then
  4164. JumpLabel.DecRefs;
  4165. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  4166. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  4167. Result := True;
  4168. Exit;
  4169. end;
  4170. end;
  4171. end;
  4172. end;
  4173. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  4174. var
  4175. hp1, hp2: tai;
  4176. ActiveReg: TRegister;
  4177. OldOffset: asizeint;
  4178. ThisConst: TCGInt;
  4179. function RegDeallocated: Boolean;
  4180. begin
  4181. TransferUsedRegs(TmpUsedRegs);
  4182. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4183. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4184. end;
  4185. begin
  4186. result:=false;
  4187. hp1 := nil;
  4188. { replace
  4189. addX const,%reg1
  4190. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4191. dealloc %reg1
  4192. by
  4193. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  4194. }
  4195. if MatchOpType(taicpu(p),top_const,top_reg) then
  4196. begin
  4197. ActiveReg := taicpu(p).oper[1]^.reg;
  4198. { Ensures the entire register was updated }
  4199. if (taicpu(p).opsize >= S_L) and
  4200. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  4201. MatchInstruction(hp1,A_LEA,[]) and
  4202. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  4203. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  4204. (
  4205. { Cover the case where the register in the reference is also the destination register }
  4206. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  4207. (
  4208. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  4209. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  4210. RegDeallocated
  4211. )
  4212. ) then
  4213. begin
  4214. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  4215. {$push}
  4216. {$R-}{$Q-}
  4217. { Explicitly disable overflow checking for these offset calculation
  4218. as those do not matter for the final result }
  4219. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  4220. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  4221. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  4222. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4223. {$pop}
  4224. {$ifdef x86_64}
  4225. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  4226. begin
  4227. { Overflow; abort }
  4228. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  4229. end
  4230. else
  4231. {$endif x86_64}
  4232. begin
  4233. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  4234. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  4235. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  4236. RemoveCurrentP(p, hp1)
  4237. else
  4238. RemoveCurrentP(p);
  4239. result:=true;
  4240. Exit;
  4241. end;
  4242. end;
  4243. if (
  4244. { Save calling GetNextInstructionUsingReg again }
  4245. Assigned(hp1) or
  4246. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  4247. ) and
  4248. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  4249. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  4250. begin
  4251. if taicpu(hp1).oper[0]^.typ = top_const then
  4252. begin
  4253. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  4254. if taicpu(hp1).opcode = A_ADD then
  4255. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  4256. else
  4257. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  4258. Result := True;
  4259. { Handle any overflows }
  4260. case taicpu(p).opsize of
  4261. S_B:
  4262. taicpu(p).oper[0]^.val := ThisConst and $FF;
  4263. S_W:
  4264. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  4265. S_L:
  4266. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  4267. {$ifdef x86_64}
  4268. S_Q:
  4269. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  4270. { Overflow; abort }
  4271. Result := False
  4272. else
  4273. taicpu(p).oper[0]^.val := ThisConst;
  4274. {$endif x86_64}
  4275. else
  4276. InternalError(2021102610);
  4277. end;
  4278. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  4279. if Result then
  4280. begin
  4281. if (taicpu(p).oper[0]^.val < 0) and
  4282. (
  4283. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  4284. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  4285. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  4286. ) then
  4287. begin
  4288. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  4289. taicpu(p).opcode := A_SUB;
  4290. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  4291. end
  4292. else
  4293. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  4294. RemoveInstruction(hp1);
  4295. end;
  4296. end
  4297. else
  4298. begin
  4299. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  4300. TransferUsedRegs(TmpUsedRegs);
  4301. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4302. hp2 := p;
  4303. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  4304. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  4305. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  4306. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  4307. begin
  4308. { Move the constant addition to after the reg/ref addition to improve optimisation }
  4309. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  4310. Asml.Remove(p);
  4311. Asml.InsertAfter(p, hp1);
  4312. p := hp1;
  4313. Result := True;
  4314. end;
  4315. end;
  4316. end;
  4317. end;
  4318. end;
  4319. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  4320. var
  4321. hp1: tai;
  4322. ref: Integer;
  4323. saveref: treference;
  4324. TempReg: TRegister;
  4325. Multiple: TCGInt;
  4326. begin
  4327. Result:=false;
  4328. { removes seg register prefixes from LEA operations, as they
  4329. don't do anything}
  4330. taicpu(p).oper[0]^.ref^.Segment:=NR_NO;
  4331. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  4332. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4333. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  4334. (
  4335. { do not mess with leas accessing the stack pointer
  4336. unless it's a null operation }
  4337. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  4338. (
  4339. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  4340. (taicpu(p).oper[0]^.ref^.offset = 0)
  4341. )
  4342. ) and
  4343. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  4344. begin
  4345. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  4346. begin
  4347. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  4348. begin
  4349. hp1:=taicpu.op_reg_reg(A_MOV,taicpu(p).opsize,taicpu(p).oper[0]^.ref^.base,
  4350. taicpu(p).oper[1]^.reg);
  4351. InsertLLItem(p.previous,p.next, hp1);
  4352. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',hp1);
  4353. p.free;
  4354. p:=hp1;
  4355. end
  4356. else
  4357. begin
  4358. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  4359. RemoveCurrentP(p);
  4360. end;
  4361. Result:=true;
  4362. exit;
  4363. end
  4364. else if (
  4365. { continue to use lea to adjust the stack pointer,
  4366. it is the recommended way, but only if not optimizing for size }
  4367. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  4368. (cs_opt_size in current_settings.optimizerswitches)
  4369. ) and
  4370. { If the flags register is in use, don't change the instruction
  4371. to an ADD otherwise this will scramble the flags. [Kit] }
  4372. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  4373. ConvertLEA(taicpu(p)) then
  4374. begin
  4375. Result:=true;
  4376. exit;
  4377. end;
  4378. end;
  4379. if GetNextInstruction(p,hp1) and
  4380. (hp1.typ=ait_instruction) then
  4381. begin
  4382. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  4383. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4384. MatchOpType(Taicpu(hp1),top_reg,top_reg) and
  4385. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) then
  4386. begin
  4387. TransferUsedRegs(TmpUsedRegs);
  4388. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4389. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4390. begin
  4391. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4392. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  4393. RemoveInstruction(hp1);
  4394. result:=true;
  4395. exit;
  4396. end;
  4397. end;
  4398. { changes
  4399. lea <ref1>, reg1
  4400. <op> ...,<ref. with reg1>,...
  4401. to
  4402. <op> ...,<ref1>,... }
  4403. if (taicpu(p).oper[1]^.reg<>current_procinfo.framepointer) and
  4404. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) and
  4405. not(MatchInstruction(hp1,A_LEA,[])) then
  4406. begin
  4407. { find a reference which uses reg1 }
  4408. 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
  4409. ref:=0
  4410. 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
  4411. ref:=1
  4412. else
  4413. ref:=-1;
  4414. if (ref<>-1) and
  4415. { reg1 must be either the base or the index }
  4416. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  4417. begin
  4418. { reg1 can be removed from the reference }
  4419. saveref:=taicpu(hp1).oper[ref]^.ref^;
  4420. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  4421. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  4422. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  4423. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  4424. else
  4425. Internalerror(2019111201);
  4426. { check if the can insert all data of the lea into the second instruction }
  4427. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4428. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  4429. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  4430. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  4431. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  4432. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4433. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  4434. {$ifdef x86_64}
  4435. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  4436. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  4437. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  4438. )
  4439. {$endif x86_64}
  4440. then
  4441. begin
  4442. { reg1 might not used by the second instruction after it is remove from the reference }
  4443. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  4444. begin
  4445. TransferUsedRegs(TmpUsedRegs);
  4446. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4447. { reg1 is not updated so it might not be used afterwards }
  4448. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4449. begin
  4450. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  4451. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  4452. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4453. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4454. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4455. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  4456. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  4457. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  4458. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  4459. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  4460. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4461. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4462. RemoveCurrentP(p, hp1);
  4463. result:=true;
  4464. exit;
  4465. end
  4466. end;
  4467. end;
  4468. { recover }
  4469. taicpu(hp1).oper[ref]^.ref^:=saveref;
  4470. end;
  4471. end;
  4472. end;
  4473. { for now, we do not mess with the stack pointer, thought it might be usefull to remove
  4474. unneeded lea sequences on the stack pointer, it needs to be tested in detail }
  4475. if (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) and
  4476. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  4477. begin
  4478. { Check common LEA/LEA conditions }
  4479. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  4480. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  4481. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  4482. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  4483. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  4484. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  4485. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  4486. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  4487. (
  4488. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  4489. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  4490. ) and (
  4491. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  4492. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4493. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  4494. ) then
  4495. begin
  4496. { changes
  4497. lea (regX,scale), reg1
  4498. lea offset(reg1,reg1), reg1
  4499. to
  4500. lea offset(regX,scale*2), reg1
  4501. and
  4502. lea (regX,scale1), reg1
  4503. lea offset(reg1,scale2), reg1
  4504. to
  4505. lea offset(regX,scale1*scale2), reg1
  4506. ... so long as the final scale does not exceed 8
  4507. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  4508. }
  4509. if (taicpu(p).oper[0]^.ref^.offset = 0) and
  4510. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4511. (
  4512. (
  4513. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4514. ) or (
  4515. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4516. (
  4517. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  4518. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  4519. )
  4520. )
  4521. ) and (
  4522. (
  4523. { lea (reg1,scale2), reg1 variant }
  4524. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  4525. (
  4526. (
  4527. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  4528. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  4529. ) or (
  4530. { lea (regX,regX), reg1 variant }
  4531. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4532. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  4533. )
  4534. )
  4535. ) or (
  4536. { lea (reg1,reg1), reg1 variant }
  4537. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4538. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  4539. )
  4540. ) then
  4541. begin
  4542. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  4543. { Make everything homogeneous to make calculations easier }
  4544. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  4545. begin
  4546. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  4547. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  4548. taicpu(p).oper[0]^.ref^.scalefactor := 2
  4549. else
  4550. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  4551. taicpu(p).oper[0]^.ref^.base := NR_NO;
  4552. end;
  4553. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  4554. begin
  4555. { Just to prevent miscalculations }
  4556. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  4557. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  4558. else
  4559. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  4560. end
  4561. else
  4562. begin
  4563. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  4564. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  4565. end;
  4566. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  4567. RemoveCurrentP(p);
  4568. result:=true;
  4569. exit;
  4570. end
  4571. { changes
  4572. lea offset1(regX), reg1
  4573. lea offset2(reg1), reg1
  4574. to
  4575. lea offset1+offset2(regX), reg1 }
  4576. else if
  4577. (
  4578. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4579. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  4580. ) or (
  4581. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4582. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  4583. (
  4584. (
  4585. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4586. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4587. ) or (
  4588. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4589. (
  4590. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4591. (
  4592. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4593. (
  4594. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  4595. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  4596. )
  4597. )
  4598. )
  4599. )
  4600. )
  4601. ) then
  4602. begin
  4603. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  4604. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  4605. begin
  4606. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  4607. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4608. { if the register is used as index and base, we have to increase for base as well
  4609. and adapt base }
  4610. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  4611. begin
  4612. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4613. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4614. end;
  4615. end
  4616. else
  4617. begin
  4618. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4619. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4620. end;
  4621. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4622. begin
  4623. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  4624. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4625. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4626. end;
  4627. RemoveCurrentP(p);
  4628. result:=true;
  4629. exit;
  4630. end;
  4631. end;
  4632. { Change:
  4633. leal/q $x(%reg1),%reg2
  4634. ...
  4635. shll/q $y,%reg2
  4636. To:
  4637. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  4638. }
  4639. if MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  4640. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4641. (taicpu(hp1).oper[0]^.val <= 3) then
  4642. begin
  4643. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  4644. TransferUsedRegs(TmpUsedRegs);
  4645. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4646. TempReg := taicpu(hp1).oper[1]^.reg; { Store locally to reduce the number of dereferences }
  4647. if
  4648. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  4649. (this works even if scalefactor is zero) }
  4650. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  4651. { Ensure offset doesn't go out of bounds }
  4652. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  4653. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  4654. MatchOperand(taicpu(p).oper[1]^, TempReg) and
  4655. (
  4656. (
  4657. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, TempReg) and
  4658. (
  4659. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4660. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  4661. (
  4662. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  4663. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4664. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  4665. )
  4666. )
  4667. ) or (
  4668. (
  4669. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  4670. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  4671. ) and
  4672. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, TempReg)
  4673. )
  4674. ) then
  4675. begin
  4676. repeat
  4677. with taicpu(p).oper[0]^.ref^ do
  4678. begin
  4679. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  4680. if index = base then
  4681. begin
  4682. if Multiple > 4 then
  4683. { Optimisation will no longer work because resultant
  4684. scale factor will exceed 8 }
  4685. Break;
  4686. base := NR_NO;
  4687. scalefactor := 2;
  4688. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  4689. end
  4690. else if (base <> NR_NO) and (base <> NR_INVALID) then
  4691. begin
  4692. { Scale factor only works on the index register }
  4693. index := base;
  4694. base := NR_NO;
  4695. end;
  4696. { For safety }
  4697. if scalefactor <= 1 then
  4698. begin
  4699. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  4700. scalefactor := Multiple;
  4701. end
  4702. else
  4703. begin
  4704. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  4705. scalefactor := scalefactor * Multiple;
  4706. end;
  4707. offset := offset * Multiple;
  4708. end;
  4709. RemoveInstruction(hp1);
  4710. Result := True;
  4711. Exit;
  4712. { This repeat..until loop exists for the benefit of Break }
  4713. until True;
  4714. end;
  4715. end;
  4716. end;
  4717. end;
  4718. function TX86AsmOptimizer.DoSubAddOpt(var p: tai): Boolean;
  4719. var
  4720. hp1 : tai;
  4721. begin
  4722. DoSubAddOpt := False;
  4723. if taicpu(p).oper[0]^.typ <> top_const then
  4724. { Should have been confirmed before calling }
  4725. InternalError(2021102601);
  4726. if GetLastInstruction(p, hp1) and
  4727. (hp1.typ = ait_instruction) and
  4728. (taicpu(hp1).opsize = taicpu(p).opsize) then
  4729. case taicpu(hp1).opcode Of
  4730. A_DEC:
  4731. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4732. begin
  4733. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+1);
  4734. RemoveInstruction(hp1);
  4735. end;
  4736. A_SUB:
  4737. if (taicpu(hp1).oper[0]^.typ = top_const) and
  4738. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  4739. begin
  4740. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val);
  4741. RemoveInstruction(hp1);
  4742. end;
  4743. A_ADD:
  4744. begin
  4745. if (taicpu(hp1).oper[0]^.typ = top_const) and
  4746. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  4747. begin
  4748. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  4749. RemoveInstruction(hp1);
  4750. if (taicpu(p).oper[0]^.val = 0) then
  4751. begin
  4752. hp1 := tai(p.next);
  4753. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  4754. if not GetLastInstruction(hp1, p) then
  4755. p := hp1;
  4756. DoSubAddOpt := True;
  4757. end
  4758. end;
  4759. end;
  4760. else
  4761. ;
  4762. end;
  4763. end;
  4764. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  4765. begin
  4766. Result := False;
  4767. if UpdateTmpUsedRegs then
  4768. TransferUsedRegs(TmpUsedRegs);
  4769. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4770. { The x86 assemblers have difficulty comparing values against absolute addresses }
  4771. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  4772. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  4773. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  4774. (
  4775. (
  4776. (taicpu(hp1).opcode = A_TEST)
  4777. ) or (
  4778. (taicpu(hp1).opcode = A_CMP) and
  4779. { A sanity check more than anything }
  4780. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  4781. )
  4782. ) then
  4783. begin
  4784. { change
  4785. mov mem, %reg
  4786. cmp/test x, %reg / test %reg,%reg
  4787. (reg deallocated)
  4788. to
  4789. cmp/test x, mem / cmp 0, mem
  4790. }
  4791. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4792. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  4793. begin
  4794. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  4795. if (taicpu(hp1).opcode = A_TEST) and
  4796. (
  4797. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  4798. MatchOperand(taicpu(hp1).oper[0]^, -1)
  4799. ) then
  4800. begin
  4801. taicpu(hp1).opcode := A_CMP;
  4802. taicpu(hp1).loadconst(0, 0);
  4803. end;
  4804. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  4805. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  4806. RemoveCurrentP(p, hp1);
  4807. Result := True;
  4808. Exit;
  4809. end;
  4810. end;
  4811. end;
  4812. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  4813. var
  4814. hp1, hp2: tai;
  4815. ActiveReg: TRegister;
  4816. OldOffset: asizeint;
  4817. ThisConst: TCGInt;
  4818. function RegDeallocated: Boolean;
  4819. begin
  4820. TransferUsedRegs(TmpUsedRegs);
  4821. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4822. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4823. end;
  4824. begin
  4825. Result:=false;
  4826. hp1 := nil;
  4827. { replace
  4828. subX const,%reg1
  4829. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4830. dealloc %reg1
  4831. by
  4832. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  4833. }
  4834. if MatchOpType(taicpu(p),top_const,top_reg) then
  4835. begin
  4836. ActiveReg := taicpu(p).oper[1]^.reg;
  4837. { Ensures the entire register was updated }
  4838. if (taicpu(p).opsize >= S_L) and
  4839. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  4840. MatchInstruction(hp1,A_LEA,[]) and
  4841. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  4842. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  4843. (
  4844. { Cover the case where the register in the reference is also the destination register }
  4845. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  4846. (
  4847. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  4848. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  4849. RegDeallocated
  4850. )
  4851. ) then
  4852. begin
  4853. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  4854. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  4855. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  4856. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  4857. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4858. {$ifdef x86_64}
  4859. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  4860. begin
  4861. { Overflow; abort }
  4862. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  4863. end
  4864. else
  4865. {$endif x86_64}
  4866. begin
  4867. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  4868. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  4869. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  4870. RemoveCurrentP(p, hp1)
  4871. else
  4872. RemoveCurrentP(p);
  4873. result:=true;
  4874. Exit;
  4875. end;
  4876. end;
  4877. if (
  4878. { Save calling GetNextInstructionUsingReg again }
  4879. Assigned(hp1) or
  4880. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  4881. ) and
  4882. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  4883. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  4884. begin
  4885. if taicpu(hp1).oper[0]^.typ = top_const then
  4886. begin
  4887. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  4888. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  4889. Result := True;
  4890. { Handle any overflows }
  4891. case taicpu(p).opsize of
  4892. S_B:
  4893. taicpu(p).oper[0]^.val := ThisConst and $FF;
  4894. S_W:
  4895. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  4896. S_L:
  4897. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  4898. {$ifdef x86_64}
  4899. S_Q:
  4900. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  4901. { Overflow; abort }
  4902. Result := False
  4903. else
  4904. taicpu(p).oper[0]^.val := ThisConst;
  4905. {$endif x86_64}
  4906. else
  4907. InternalError(2021102610);
  4908. end;
  4909. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  4910. if Result then
  4911. begin
  4912. if (taicpu(p).oper[0]^.val < 0) and
  4913. (
  4914. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  4915. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  4916. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  4917. ) then
  4918. begin
  4919. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  4920. taicpu(p).opcode := A_SUB;
  4921. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  4922. end
  4923. else
  4924. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  4925. RemoveInstruction(hp1);
  4926. end;
  4927. end
  4928. else
  4929. begin
  4930. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  4931. TransferUsedRegs(TmpUsedRegs);
  4932. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4933. hp2 := p;
  4934. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  4935. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  4936. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  4937. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  4938. begin
  4939. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  4940. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  4941. Asml.Remove(p);
  4942. Asml.InsertAfter(p, hp1);
  4943. p := hp1;
  4944. Result := True;
  4945. Exit;
  4946. end;
  4947. end;
  4948. end;
  4949. { * change "subl $2, %esp; pushw x" to "pushl x"}
  4950. { * change "sub/add const1, reg" or "dec reg" followed by
  4951. "sub const2, reg" to one "sub ..., reg" }
  4952. {$ifdef i386}
  4953. if (taicpu(p).oper[0]^.val = 2) and
  4954. (ActiveReg = NR_ESP) and
  4955. { Don't do the sub/push optimization if the sub }
  4956. { comes from setting up the stack frame (JM) }
  4957. (not(GetLastInstruction(p,hp1)) or
  4958. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  4959. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  4960. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  4961. begin
  4962. hp1 := tai(p.next);
  4963. while Assigned(hp1) and
  4964. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  4965. not RegReadByInstruction(NR_ESP,hp1) and
  4966. not RegModifiedByInstruction(NR_ESP,hp1) do
  4967. hp1 := tai(hp1.next);
  4968. if Assigned(hp1) and
  4969. MatchInstruction(hp1,A_PUSH,[S_W]) then
  4970. begin
  4971. taicpu(hp1).changeopsize(S_L);
  4972. if taicpu(hp1).oper[0]^.typ=top_reg then
  4973. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  4974. hp1 := tai(p.next);
  4975. RemoveCurrentp(p, hp1);
  4976. Result:=true;
  4977. exit;
  4978. end;
  4979. end;
  4980. {$endif i386}
  4981. if DoSubAddOpt(p) then
  4982. Result:=true;
  4983. end;
  4984. end;
  4985. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  4986. var
  4987. TmpBool1,TmpBool2 : Boolean;
  4988. tmpref : treference;
  4989. hp1,hp2: tai;
  4990. mask: tcgint;
  4991. begin
  4992. Result:=false;
  4993. { All these optimisations work on "shl/sal const,%reg" }
  4994. if not MatchOpType(taicpu(p),top_const,top_reg) then
  4995. Exit;
  4996. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4997. (taicpu(p).oper[0]^.val <= 3) then
  4998. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  4999. begin
  5000. { should we check the next instruction? }
  5001. TmpBool1 := True;
  5002. { have we found an add/sub which could be
  5003. integrated in the lea? }
  5004. TmpBool2 := False;
  5005. reference_reset(tmpref,2,[]);
  5006. TmpRef.index := taicpu(p).oper[1]^.reg;
  5007. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5008. while TmpBool1 and
  5009. GetNextInstruction(p, hp1) and
  5010. (tai(hp1).typ = ait_instruction) and
  5011. ((((taicpu(hp1).opcode = A_ADD) or
  5012. (taicpu(hp1).opcode = A_SUB)) and
  5013. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  5014. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  5015. (((taicpu(hp1).opcode = A_INC) or
  5016. (taicpu(hp1).opcode = A_DEC)) and
  5017. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5018. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  5019. ((taicpu(hp1).opcode = A_LEA) and
  5020. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5021. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  5022. (not GetNextInstruction(hp1,hp2) or
  5023. not instrReadsFlags(hp2)) Do
  5024. begin
  5025. TmpBool1 := False;
  5026. if taicpu(hp1).opcode=A_LEA then
  5027. begin
  5028. if (TmpRef.base = NR_NO) and
  5029. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  5030. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  5031. (taicpu(hp1).oper[0]^.ref^.segment=NR_NO) and
  5032. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  5033. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  5034. begin
  5035. TmpBool1 := True;
  5036. TmpBool2 := True;
  5037. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  5038. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  5039. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  5040. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  5041. RemoveInstruction(hp1);
  5042. end
  5043. end
  5044. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  5045. begin
  5046. TmpBool1 := True;
  5047. TmpBool2 := True;
  5048. case taicpu(hp1).opcode of
  5049. A_ADD:
  5050. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5051. A_SUB:
  5052. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5053. else
  5054. internalerror(2019050536);
  5055. end;
  5056. RemoveInstruction(hp1);
  5057. end
  5058. else
  5059. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5060. (((taicpu(hp1).opcode = A_ADD) and
  5061. (TmpRef.base = NR_NO)) or
  5062. (taicpu(hp1).opcode = A_INC) or
  5063. (taicpu(hp1).opcode = A_DEC)) then
  5064. begin
  5065. TmpBool1 := True;
  5066. TmpBool2 := True;
  5067. case taicpu(hp1).opcode of
  5068. A_ADD:
  5069. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  5070. A_INC:
  5071. inc(TmpRef.offset);
  5072. A_DEC:
  5073. dec(TmpRef.offset);
  5074. else
  5075. internalerror(2019050535);
  5076. end;
  5077. RemoveInstruction(hp1);
  5078. end;
  5079. end;
  5080. if TmpBool2
  5081. {$ifndef x86_64}
  5082. or
  5083. ((current_settings.optimizecputype < cpu_Pentium2) and
  5084. (taicpu(p).oper[0]^.val <= 3) and
  5085. not(cs_opt_size in current_settings.optimizerswitches))
  5086. {$endif x86_64}
  5087. then
  5088. begin
  5089. if not(TmpBool2) and
  5090. (taicpu(p).oper[0]^.val=1) then
  5091. begin
  5092. hp1:=taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5093. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  5094. end
  5095. else
  5096. hp1:=taicpu.op_ref_reg(A_LEA, taicpu(p).opsize, TmpRef,
  5097. taicpu(p).oper[1]^.reg);
  5098. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  5099. InsertLLItem(p.previous, p.next, hp1);
  5100. p.free;
  5101. p := hp1;
  5102. end;
  5103. end
  5104. {$ifndef x86_64}
  5105. else if (current_settings.optimizecputype < cpu_Pentium2) then
  5106. begin
  5107. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  5108. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  5109. (unlike shl, which is only Tairable in the U pipe) }
  5110. if taicpu(p).oper[0]^.val=1 then
  5111. begin
  5112. hp1 := taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5113. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg);
  5114. InsertLLItem(p.previous, p.next, hp1);
  5115. p.free;
  5116. p := hp1;
  5117. end
  5118. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  5119. "shl $3, %reg" to "lea (,%reg,8), %reg }
  5120. else if (taicpu(p).opsize = S_L) and
  5121. (taicpu(p).oper[0]^.val<= 3) then
  5122. begin
  5123. reference_reset(tmpref,2,[]);
  5124. TmpRef.index := taicpu(p).oper[1]^.reg;
  5125. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5126. hp1 := taicpu.Op_ref_reg(A_LEA,S_L,TmpRef, taicpu(p).oper[1]^.reg);
  5127. InsertLLItem(p.previous, p.next, hp1);
  5128. p.free;
  5129. p := hp1;
  5130. end;
  5131. end
  5132. {$endif x86_64}
  5133. else if
  5134. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  5135. (
  5136. (
  5137. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  5138. SetAndTest(hp1, hp2)
  5139. {$ifdef x86_64}
  5140. ) or
  5141. (
  5142. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  5143. GetNextInstruction(hp1, hp2) and
  5144. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  5145. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  5146. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  5147. {$endif x86_64}
  5148. )
  5149. ) and
  5150. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  5151. begin
  5152. { Change:
  5153. shl x, %reg1
  5154. mov -(1<<x), %reg2
  5155. and %reg2, %reg1
  5156. Or:
  5157. shl x, %reg1
  5158. and -(1<<x), %reg1
  5159. To just:
  5160. shl x, %reg1
  5161. Since the and operation only zeroes bits that are already zero from the shl operation
  5162. }
  5163. case taicpu(p).oper[0]^.val of
  5164. 8:
  5165. mask:=$FFFFFFFFFFFFFF00;
  5166. 16:
  5167. mask:=$FFFFFFFFFFFF0000;
  5168. 32:
  5169. mask:=$FFFFFFFF00000000;
  5170. 63:
  5171. { Constant pre-calculated to prevent overflow errors with Int64 }
  5172. mask:=$8000000000000000;
  5173. else
  5174. begin
  5175. if taicpu(p).oper[0]^.val >= 64 then
  5176. { Shouldn't happen realistically, since the register
  5177. is guaranteed to be set to zero at this point }
  5178. mask := 0
  5179. else
  5180. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  5181. end;
  5182. end;
  5183. if taicpu(hp1).oper[0]^.val = mask then
  5184. begin
  5185. { Everything checks out, perform the optimisation, as long as
  5186. the FLAGS register isn't being used}
  5187. TransferUsedRegs(TmpUsedRegs);
  5188. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5189. {$ifdef x86_64}
  5190. if (hp1 <> hp2) then
  5191. begin
  5192. { "shl/mov/and" version }
  5193. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  5194. { Don't do the optimisation if the FLAGS register is in use }
  5195. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  5196. begin
  5197. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  5198. { Don't remove the 'mov' instruction if its register is used elsewhere }
  5199. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  5200. begin
  5201. RemoveInstruction(hp1);
  5202. Result := True;
  5203. end;
  5204. { Only set Result to True if the 'mov' instruction was removed }
  5205. RemoveInstruction(hp2);
  5206. end;
  5207. end
  5208. else
  5209. {$endif x86_64}
  5210. begin
  5211. { "shl/and" version }
  5212. { Don't do the optimisation if the FLAGS register is in use }
  5213. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  5214. begin
  5215. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  5216. RemoveInstruction(hp1);
  5217. Result := True;
  5218. end;
  5219. end;
  5220. Exit;
  5221. end
  5222. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  5223. begin
  5224. { Even if the mask doesn't allow for its removal, we might be
  5225. able to optimise the mask for the "shl/and" version, which
  5226. may permit other peephole optimisations }
  5227. {$ifdef DEBUG_AOPTCPU}
  5228. mask := taicpu(hp1).oper[0]^.val and mask;
  5229. if taicpu(hp1).oper[0]^.val <> mask then
  5230. begin
  5231. DebugMsg(
  5232. SPeepholeOptimization +
  5233. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  5234. ' to $' + debug_tostr(mask) +
  5235. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  5236. taicpu(hp1).oper[0]^.val := mask;
  5237. end;
  5238. {$else DEBUG_AOPTCPU}
  5239. { If debugging is off, just set the operand even if it's the same }
  5240. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  5241. {$endif DEBUG_AOPTCPU}
  5242. end;
  5243. end;
  5244. {
  5245. change
  5246. shl/sal const,reg
  5247. <op> ...(...,reg,1),...
  5248. into
  5249. <op> ...(...,reg,1 shl const),...
  5250. if const in 1..3
  5251. }
  5252. if MatchOpType(taicpu(p), top_const, top_reg) and
  5253. (taicpu(p).oper[0]^.val in [1..3]) and
  5254. GetNextInstruction(p, hp1) and
  5255. MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  5256. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  5257. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  5258. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  5259. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  5260. begin
  5261. TransferUsedRegs(TmpUsedRegs);
  5262. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5263. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  5264. begin
  5265. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  5266. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  5267. RemoveCurrentP(p);
  5268. Result:=true;
  5269. end;
  5270. end;
  5271. end;
  5272. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  5273. var
  5274. CurrentRef: TReference;
  5275. FullReg: TRegister;
  5276. hp1, hp2: tai;
  5277. begin
  5278. Result := False;
  5279. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  5280. Exit;
  5281. { We assume you've checked if the operand is actually a reference by
  5282. this point. If it isn't, you'll most likely get an access violation }
  5283. CurrentRef := first_mov.oper[1]^.ref^;
  5284. { Memory must be aligned }
  5285. if (CurrentRef.offset mod 4) <> 0 then
  5286. Exit;
  5287. Inc(CurrentRef.offset);
  5288. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5289. if MatchOperand(second_mov.oper[0]^, 0) and
  5290. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  5291. GetNextInstruction(second_mov, hp1) and
  5292. (hp1.typ = ait_instruction) and
  5293. (taicpu(hp1).opcode = A_MOV) and
  5294. MatchOpType(taicpu(hp1), top_const, top_ref) and
  5295. (taicpu(hp1).oper[0]^.val = 0) then
  5296. begin
  5297. Inc(CurrentRef.offset);
  5298. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  5299. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  5300. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  5301. begin
  5302. case taicpu(hp1).opsize of
  5303. S_B:
  5304. if GetNextInstruction(hp1, hp2) and
  5305. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  5306. MatchOpType(taicpu(hp2), top_const, top_ref) and
  5307. (taicpu(hp2).oper[0]^.val = 0) then
  5308. begin
  5309. Inc(CurrentRef.offset);
  5310. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5311. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  5312. (taicpu(hp2).opsize = S_B) then
  5313. begin
  5314. RemoveInstruction(hp1);
  5315. RemoveInstruction(hp2);
  5316. first_mov.opsize := S_L;
  5317. if first_mov.oper[0]^.typ = top_reg then
  5318. begin
  5319. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  5320. { Reuse second_mov as a MOVZX instruction }
  5321. second_mov.opcode := A_MOVZX;
  5322. second_mov.opsize := S_BL;
  5323. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5324. second_mov.loadreg(1, FullReg);
  5325. first_mov.oper[0]^.reg := FullReg;
  5326. asml.Remove(second_mov);
  5327. asml.InsertBefore(second_mov, first_mov);
  5328. end
  5329. else
  5330. { It's a value }
  5331. begin
  5332. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  5333. RemoveInstruction(second_mov);
  5334. end;
  5335. Result := True;
  5336. Exit;
  5337. end;
  5338. end;
  5339. S_W:
  5340. begin
  5341. RemoveInstruction(hp1);
  5342. first_mov.opsize := S_L;
  5343. if first_mov.oper[0]^.typ = top_reg then
  5344. begin
  5345. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  5346. { Reuse second_mov as a MOVZX instruction }
  5347. second_mov.opcode := A_MOVZX;
  5348. second_mov.opsize := S_BL;
  5349. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5350. second_mov.loadreg(1, FullReg);
  5351. first_mov.oper[0]^.reg := FullReg;
  5352. asml.Remove(second_mov);
  5353. asml.InsertBefore(second_mov, first_mov);
  5354. end
  5355. else
  5356. { It's a value }
  5357. begin
  5358. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  5359. RemoveInstruction(second_mov);
  5360. end;
  5361. Result := True;
  5362. Exit;
  5363. end;
  5364. else
  5365. ;
  5366. end;
  5367. end;
  5368. end;
  5369. end;
  5370. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  5371. { returns true if a "continue" should be done after this optimization }
  5372. var
  5373. hp1, hp2: tai;
  5374. begin
  5375. Result := false;
  5376. if MatchOpType(taicpu(p),top_ref) and
  5377. GetNextInstruction(p, hp1) and
  5378. (hp1.typ = ait_instruction) and
  5379. (((taicpu(hp1).opcode = A_FLD) and
  5380. (taicpu(p).opcode = A_FSTP)) or
  5381. ((taicpu(p).opcode = A_FISTP) and
  5382. (taicpu(hp1).opcode = A_FILD))) and
  5383. MatchOpType(taicpu(hp1),top_ref) and
  5384. (taicpu(hp1).opsize = taicpu(p).opsize) and
  5385. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  5386. begin
  5387. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  5388. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  5389. GetNextInstruction(hp1, hp2) and
  5390. (hp2.typ = ait_instruction) and
  5391. IsExitCode(hp2) and
  5392. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  5393. not(assigned(current_procinfo.procdef.funcretsym) and
  5394. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  5395. (taicpu(p).oper[0]^.ref^.index = NR_NO) then
  5396. begin
  5397. RemoveInstruction(hp1);
  5398. RemoveCurrentP(p, hp2);
  5399. RemoveLastDeallocForFuncRes(p);
  5400. Result := true;
  5401. end
  5402. else
  5403. { we can do this only in fast math mode as fstp is rounding ...
  5404. ... still disabled as it breaks the compiler and/or rtl }
  5405. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  5406. { ... or if another fstp equal to the first one follows }
  5407. (GetNextInstruction(hp1,hp2) and
  5408. (hp2.typ = ait_instruction) and
  5409. (taicpu(p).opcode=taicpu(hp2).opcode) and
  5410. (taicpu(p).opsize=taicpu(hp2).opsize))
  5411. ) and
  5412. { fst can't store an extended/comp value }
  5413. (taicpu(p).opsize <> S_FX) and
  5414. (taicpu(p).opsize <> S_IQ) then
  5415. begin
  5416. if (taicpu(p).opcode = A_FSTP) then
  5417. taicpu(p).opcode := A_FST
  5418. else
  5419. taicpu(p).opcode := A_FIST;
  5420. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  5421. RemoveInstruction(hp1);
  5422. end;
  5423. end;
  5424. end;
  5425. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  5426. var
  5427. hp1, hp2: tai;
  5428. begin
  5429. result:=false;
  5430. if MatchOpType(taicpu(p),top_reg) and
  5431. GetNextInstruction(p, hp1) and
  5432. (hp1.typ = Ait_Instruction) and
  5433. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5434. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  5435. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  5436. { change to
  5437. fld reg fxxx reg,st
  5438. fxxxp st, st1 (hp1)
  5439. Remark: non commutative operations must be reversed!
  5440. }
  5441. begin
  5442. case taicpu(hp1).opcode Of
  5443. A_FMULP,A_FADDP,
  5444. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  5445. begin
  5446. case taicpu(hp1).opcode Of
  5447. A_FADDP: taicpu(hp1).opcode := A_FADD;
  5448. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  5449. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  5450. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  5451. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  5452. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  5453. else
  5454. internalerror(2019050534);
  5455. end;
  5456. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  5457. taicpu(hp1).oper[1]^.reg := NR_ST;
  5458. RemoveCurrentP(p, hp1);
  5459. Result:=true;
  5460. exit;
  5461. end;
  5462. else
  5463. ;
  5464. end;
  5465. end
  5466. else
  5467. if MatchOpType(taicpu(p),top_ref) and
  5468. GetNextInstruction(p, hp2) and
  5469. (hp2.typ = Ait_Instruction) and
  5470. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  5471. (taicpu(p).opsize in [S_FS, S_FL]) and
  5472. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  5473. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  5474. if GetLastInstruction(p, hp1) and
  5475. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  5476. MatchOpType(taicpu(hp1),top_ref) and
  5477. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  5478. if ((taicpu(hp2).opcode = A_FMULP) or
  5479. (taicpu(hp2).opcode = A_FADDP)) then
  5480. { change to
  5481. fld/fst mem1 (hp1) fld/fst mem1
  5482. fld mem1 (p) fadd/
  5483. faddp/ fmul st, st
  5484. fmulp st, st1 (hp2) }
  5485. begin
  5486. RemoveCurrentP(p, hp1);
  5487. if (taicpu(hp2).opcode = A_FADDP) then
  5488. taicpu(hp2).opcode := A_FADD
  5489. else
  5490. taicpu(hp2).opcode := A_FMUL;
  5491. taicpu(hp2).oper[1]^.reg := NR_ST;
  5492. end
  5493. else
  5494. { change to
  5495. fld/fst mem1 (hp1) fld/fst mem1
  5496. fld mem1 (p) fld st}
  5497. begin
  5498. taicpu(p).changeopsize(S_FL);
  5499. taicpu(p).loadreg(0,NR_ST);
  5500. end
  5501. else
  5502. begin
  5503. case taicpu(hp2).opcode Of
  5504. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  5505. { change to
  5506. fld/fst mem1 (hp1) fld/fst mem1
  5507. fld mem2 (p) fxxx mem2
  5508. fxxxp st, st1 (hp2) }
  5509. begin
  5510. case taicpu(hp2).opcode Of
  5511. A_FADDP: taicpu(p).opcode := A_FADD;
  5512. A_FMULP: taicpu(p).opcode := A_FMUL;
  5513. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  5514. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  5515. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  5516. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  5517. else
  5518. internalerror(2019050533);
  5519. end;
  5520. RemoveInstruction(hp2);
  5521. end
  5522. else
  5523. ;
  5524. end
  5525. end
  5526. end;
  5527. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  5528. begin
  5529. Result := condition_in(cond1, cond2) or
  5530. { Not strictly subsets due to the actual flags checked, but because we're
  5531. comparing integers, E is a subset of AE and GE and their aliases }
  5532. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  5533. end;
  5534. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  5535. var
  5536. v: TCGInt;
  5537. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  5538. FirstMatch: Boolean;
  5539. NewReg: TRegister;
  5540. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  5541. begin
  5542. Result:=false;
  5543. { All these optimisations need a next instruction }
  5544. if not GetNextInstruction(p, hp1) then
  5545. Exit;
  5546. { Search for:
  5547. cmp ###,###
  5548. j(c1) @lbl1
  5549. ...
  5550. @lbl:
  5551. cmp ###.### (same comparison as above)
  5552. j(c2) @lbl2
  5553. If c1 is a subset of c2, change to:
  5554. cmp ###,###
  5555. j(c2) @lbl2
  5556. (@lbl1 may become a dead label as a result)
  5557. }
  5558. { Also handle cases where there are multiple jumps in a row }
  5559. p_jump := hp1;
  5560. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  5561. begin
  5562. if IsJumpToLabel(taicpu(p_jump)) then
  5563. begin
  5564. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  5565. p_label := nil;
  5566. if Assigned(JumpLabel) then
  5567. p_label := getlabelwithsym(JumpLabel);
  5568. if Assigned(p_label) and
  5569. GetNextInstruction(p_label, p_dist) and
  5570. MatchInstruction(p_dist, A_CMP, []) and
  5571. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  5572. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5573. GetNextInstruction(p_dist, hp1_dist) and
  5574. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5575. begin
  5576. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5577. if JumpLabel = JumpLabel_dist then
  5578. { This is an infinite loop }
  5579. Exit;
  5580. { Best optimisation when the first condition is a subset (or equal) of the second }
  5581. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  5582. begin
  5583. { Any registers used here will already be allocated }
  5584. if Assigned(JumpLabel_dist) then
  5585. JumpLabel_dist.IncRefs;
  5586. if Assigned(JumpLabel) then
  5587. JumpLabel.DecRefs;
  5588. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  5589. taicpu(p_jump).condition := taicpu(hp1_dist).condition;
  5590. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  5591. Result := True;
  5592. { Don't exit yet. Since p and p_jump haven't actually been
  5593. removed, we can check for more on this iteration }
  5594. end
  5595. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  5596. GetNextInstruction(hp1_dist, hp1_label) and
  5597. SkipAligns(hp1_label, hp1_label) and
  5598. (hp1_label.typ = ait_label) then
  5599. begin
  5600. JumpLabel_far := tai_label(hp1_label).labsym;
  5601. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  5602. { This is an infinite loop }
  5603. Exit;
  5604. if Assigned(JumpLabel_far) then
  5605. begin
  5606. { In this situation, if the first jump branches, the second one will never,
  5607. branch so change the destination label to after the second jump }
  5608. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  5609. if Assigned(JumpLabel) then
  5610. JumpLabel.DecRefs;
  5611. JumpLabel_far.IncRefs;
  5612. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  5613. Result := True;
  5614. { Don't exit yet. Since p and p_jump haven't actually been
  5615. removed, we can check for more on this iteration }
  5616. Continue;
  5617. end;
  5618. end;
  5619. end;
  5620. end;
  5621. { Search for:
  5622. cmp ###,###
  5623. j(c1) @lbl1
  5624. cmp ###,### (same as first)
  5625. Remove second cmp
  5626. }
  5627. if GetNextInstruction(p_jump, hp2) and
  5628. (
  5629. (
  5630. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  5631. (
  5632. (
  5633. MatchOpType(taicpu(p), top_const, top_reg) and
  5634. MatchOpType(taicpu(hp2), top_const, top_reg) and
  5635. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  5636. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  5637. ) or (
  5638. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  5639. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  5640. )
  5641. )
  5642. ) or (
  5643. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  5644. MatchOperand(taicpu(p).oper[0]^, 0) and
  5645. (taicpu(p).oper[1]^.typ = top_reg) and
  5646. MatchInstruction(hp2, A_TEST, []) and
  5647. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  5648. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  5649. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  5650. )
  5651. ) then
  5652. begin
  5653. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  5654. RemoveInstruction(hp2);
  5655. Result := True;
  5656. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  5657. end;
  5658. GetNextInstruction(p_jump, p_jump);
  5659. end;
  5660. {
  5661. Try to optimise the following:
  5662. cmp $x,### ($x and $y can be registers or constants)
  5663. je @lbl1 (only reference)
  5664. cmp $y,### (### are identical)
  5665. @Lbl:
  5666. sete %reg1
  5667. Change to:
  5668. cmp $x,###
  5669. sete %reg2 (allocate new %reg2)
  5670. cmp $y,###
  5671. sete %reg1
  5672. orb %reg2,%reg1
  5673. (dealloc %reg2)
  5674. This adds an instruction (so don't perform under -Os), but it removes
  5675. a conditional branch.
  5676. }
  5677. if not (cs_opt_size in current_settings.optimizerswitches) and
  5678. (
  5679. (hp1 = p_jump) or
  5680. GetNextInstruction(p, hp1)
  5681. ) and
  5682. MatchInstruction(hp1, A_Jcc, []) and
  5683. IsJumpToLabel(taicpu(hp1)) and
  5684. (taicpu(hp1).condition in [C_E, C_Z]) and
  5685. GetNextInstruction(hp1, hp2) and
  5686. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  5687. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  5688. { The first operand of CMP instructions can only be a register or
  5689. immediate anyway, so no need to check }
  5690. GetNextInstruction(hp2, p_label) and
  5691. (p_label.typ = ait_label) and
  5692. (tai_label(p_label).labsym.getrefs = 1) and
  5693. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  5694. GetNextInstruction(p_label, p_dist) and
  5695. MatchInstruction(p_dist, A_SETcc, []) and
  5696. (taicpu(p_dist).condition in [C_E, C_Z]) and
  5697. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  5698. begin
  5699. TransferUsedRegs(TmpUsedRegs);
  5700. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5701. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5702. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  5703. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5704. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  5705. { Get the instruction after the SETcc instruction so we can
  5706. allocate a new register over the entire range }
  5707. GetNextInstruction(p_dist, hp1_dist) then
  5708. begin
  5709. { Register can appear in p if it's not used afterwards, so only
  5710. allocate between hp1 and hp1_dist }
  5711. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  5712. if NewReg <> NR_NO then
  5713. begin
  5714. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  5715. { Change the jump instruction into a SETcc instruction }
  5716. taicpu(hp1).opcode := A_SETcc;
  5717. taicpu(hp1).opsize := S_B;
  5718. taicpu(hp1).loadreg(0, NewReg);
  5719. { This is now a dead label }
  5720. tai_label(p_label).labsym.decrefs;
  5721. { Prefer adding before the next instruction so the FLAGS
  5722. register is deallicated first }
  5723. AsmL.InsertBefore(
  5724. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  5725. hp1_dist
  5726. );
  5727. Result := True;
  5728. { Don't exit yet, as p wasn't changed and hp1, while
  5729. modified, is still intact and might be optimised by the
  5730. SETcc optimisation below }
  5731. end;
  5732. end;
  5733. end;
  5734. if taicpu(p).oper[0]^.typ = top_const then
  5735. begin
  5736. if (taicpu(p).oper[0]^.val = 0) and
  5737. (taicpu(p).oper[1]^.typ = top_reg) and
  5738. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  5739. begin
  5740. hp2 := p;
  5741. FirstMatch := True;
  5742. { When dealing with "cmp $0,%reg", only ZF and SF contain
  5743. anything meaningful once it's converted to "test %reg,%reg";
  5744. additionally, some jumps will always (or never) branch, so
  5745. evaluate every jump immediately following the
  5746. comparison, optimising the conditions if possible.
  5747. Similarly with SETcc... those that are always set to 0 or 1
  5748. are changed to MOV instructions }
  5749. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  5750. (
  5751. GetNextInstruction(hp2, hp1) and
  5752. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  5753. ) do
  5754. begin
  5755. FirstMatch := False;
  5756. case taicpu(hp1).condition of
  5757. C_B, C_C, C_NAE, C_O:
  5758. { For B/NAE:
  5759. Will never branch since an unsigned integer can never be below zero
  5760. For C/O:
  5761. Result cannot overflow because 0 is being subtracted
  5762. }
  5763. begin
  5764. if taicpu(hp1).opcode = A_Jcc then
  5765. begin
  5766. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  5767. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  5768. RemoveInstruction(hp1);
  5769. { Since hp1 was deleted, hp2 must not be updated }
  5770. Continue;
  5771. end
  5772. else
  5773. begin
  5774. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  5775. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  5776. taicpu(hp1).opcode := A_MOV;
  5777. taicpu(hp1).ops := 2;
  5778. taicpu(hp1).condition := C_None;
  5779. taicpu(hp1).opsize := S_B;
  5780. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  5781. taicpu(hp1).loadconst(0, 0);
  5782. end;
  5783. end;
  5784. C_BE, C_NA:
  5785. begin
  5786. { Will only branch if equal to zero }
  5787. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  5788. taicpu(hp1).condition := C_E;
  5789. end;
  5790. C_A, C_NBE:
  5791. begin
  5792. { Will only branch if not equal to zero }
  5793. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  5794. taicpu(hp1).condition := C_NE;
  5795. end;
  5796. C_AE, C_NB, C_NC, C_NO:
  5797. begin
  5798. { Will always branch }
  5799. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  5800. if taicpu(hp1).opcode = A_Jcc then
  5801. begin
  5802. MakeUnconditional(taicpu(hp1));
  5803. { Any jumps/set that follow will now be dead code }
  5804. RemoveDeadCodeAfterJump(taicpu(hp1));
  5805. Break;
  5806. end
  5807. else
  5808. begin
  5809. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  5810. taicpu(hp1).opcode := A_MOV;
  5811. taicpu(hp1).ops := 2;
  5812. taicpu(hp1).condition := C_None;
  5813. taicpu(hp1).opsize := S_B;
  5814. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  5815. taicpu(hp1).loadconst(0, 1);
  5816. end;
  5817. end;
  5818. C_None:
  5819. InternalError(2020012201);
  5820. C_P, C_PE, C_NP, C_PO:
  5821. { We can't handle parity checks and they should never be generated
  5822. after a general-purpose CMP (it's used in some floating-point
  5823. comparisons that don't use CMP) }
  5824. InternalError(2020012202);
  5825. else
  5826. { Zero/Equality, Sign, their complements and all of the
  5827. signed comparisons do not need to be converted };
  5828. end;
  5829. hp2 := hp1;
  5830. end;
  5831. { Convert the instruction to a TEST }
  5832. taicpu(p).opcode := A_TEST;
  5833. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  5834. Result := True;
  5835. Exit;
  5836. end
  5837. else if (taicpu(p).oper[0]^.val = 1) and
  5838. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  5839. (taicpu(hp1).condition in [C_L, C_NGE]) then
  5840. begin
  5841. { Convert; To:
  5842. cmp $1,r/m cmp $0,r/m
  5843. jl @lbl jle @lbl
  5844. }
  5845. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  5846. taicpu(p).oper[0]^.val := 0;
  5847. taicpu(hp1).condition := C_LE;
  5848. { If the instruction is now "cmp $0,%reg", convert it to a
  5849. TEST (and effectively do the work of the "cmp $0,%reg" in
  5850. the block above)
  5851. If it's a reference, we can get away with not setting
  5852. Result to True because he haven't evaluated the jump
  5853. in this pass yet.
  5854. }
  5855. if (taicpu(p).oper[1]^.typ = top_reg) then
  5856. begin
  5857. taicpu(p).opcode := A_TEST;
  5858. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  5859. Result := True;
  5860. end;
  5861. Exit;
  5862. end
  5863. else if (taicpu(p).oper[1]^.typ = top_reg)
  5864. {$ifdef x86_64}
  5865. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  5866. {$endif x86_64}
  5867. then
  5868. begin
  5869. { cmp register,$8000 neg register
  5870. je target --> jo target
  5871. .... only if register is deallocated before jump.}
  5872. case Taicpu(p).opsize of
  5873. S_B: v:=$80;
  5874. S_W: v:=$8000;
  5875. S_L: v:=qword($80000000);
  5876. else
  5877. internalerror(2013112905);
  5878. end;
  5879. if (taicpu(p).oper[0]^.val=v) and
  5880. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  5881. (Taicpu(hp1).condition in [C_E,C_NE]) then
  5882. begin
  5883. TransferUsedRegs(TmpUsedRegs);
  5884. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  5885. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  5886. begin
  5887. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  5888. Taicpu(p).opcode:=A_NEG;
  5889. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  5890. Taicpu(p).clearop(1);
  5891. Taicpu(p).ops:=1;
  5892. if Taicpu(hp1).condition=C_E then
  5893. Taicpu(hp1).condition:=C_O
  5894. else
  5895. Taicpu(hp1).condition:=C_NO;
  5896. Result:=true;
  5897. exit;
  5898. end;
  5899. end;
  5900. end;
  5901. end;
  5902. if TrySwapMovCmp(p, hp1) then
  5903. begin
  5904. Result := True;
  5905. Exit;
  5906. end;
  5907. end;
  5908. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  5909. var
  5910. hp1: tai;
  5911. begin
  5912. {
  5913. remove the second (v)pxor from
  5914. pxor reg,reg
  5915. ...
  5916. pxor reg,reg
  5917. }
  5918. Result:=false;
  5919. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  5920. MatchOpType(taicpu(p),top_reg,top_reg) and
  5921. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  5922. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  5923. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  5924. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  5925. begin
  5926. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  5927. RemoveInstruction(hp1);
  5928. Result:=true;
  5929. Exit;
  5930. end
  5931. {
  5932. replace
  5933. pxor reg1,reg1
  5934. movapd/s reg1,reg2
  5935. dealloc reg1
  5936. by
  5937. pxor reg2,reg2
  5938. }
  5939. else if GetNextInstruction(p,hp1) and
  5940. { we mix single and double opperations here because we assume that the compiler
  5941. generates vmovapd only after double operations and vmovaps only after single operations }
  5942. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  5943. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  5944. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5945. (taicpu(p).oper[0]^.typ=top_reg) then
  5946. begin
  5947. TransferUsedRegs(TmpUsedRegs);
  5948. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5949. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5950. begin
  5951. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  5952. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5953. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  5954. RemoveInstruction(hp1);
  5955. result:=true;
  5956. end;
  5957. end;
  5958. end;
  5959. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  5960. var
  5961. hp1: tai;
  5962. begin
  5963. {
  5964. remove the second (v)pxor from
  5965. (v)pxor reg,reg
  5966. ...
  5967. (v)pxor reg,reg
  5968. }
  5969. Result:=false;
  5970. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  5971. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  5972. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  5973. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  5974. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  5975. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  5976. begin
  5977. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2PXor done',hp1);
  5978. RemoveInstruction(hp1);
  5979. Result:=true;
  5980. Exit;
  5981. end
  5982. else
  5983. Result:=OptPass1VOP(p);
  5984. end;
  5985. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  5986. var
  5987. hp1 : tai;
  5988. begin
  5989. result:=false;
  5990. { replace
  5991. IMul const,%mreg1,%mreg2
  5992. Mov %reg2,%mreg3
  5993. dealloc %mreg3
  5994. by
  5995. Imul const,%mreg1,%mreg23
  5996. }
  5997. if (taicpu(p).ops=3) and
  5998. GetNextInstruction(p,hp1) and
  5999. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6000. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6001. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6002. begin
  6003. TransferUsedRegs(TmpUsedRegs);
  6004. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6005. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6006. begin
  6007. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6008. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  6009. RemoveInstruction(hp1);
  6010. result:=true;
  6011. end;
  6012. end;
  6013. end;
  6014. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  6015. var
  6016. hp1 : tai;
  6017. begin
  6018. result:=false;
  6019. { replace
  6020. IMul %reg0,%reg1,%reg2
  6021. Mov %reg2,%reg3
  6022. dealloc %reg2
  6023. by
  6024. Imul %reg0,%reg1,%reg3
  6025. }
  6026. if GetNextInstruction(p,hp1) and
  6027. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6028. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6029. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6030. begin
  6031. TransferUsedRegs(TmpUsedRegs);
  6032. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6033. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6034. begin
  6035. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6036. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  6037. RemoveInstruction(hp1);
  6038. result:=true;
  6039. end;
  6040. end;
  6041. end;
  6042. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  6043. var
  6044. hp1: tai;
  6045. begin
  6046. Result:=false;
  6047. { get rid of
  6048. (v)cvtss2sd reg0,<reg1,>reg2
  6049. (v)cvtss2sd reg2,<reg2,>reg0
  6050. }
  6051. if GetNextInstruction(p,hp1) and
  6052. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  6053. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  6054. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  6055. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  6056. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  6057. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  6058. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  6059. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  6060. )
  6061. ) then
  6062. begin
  6063. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  6064. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  6065. begin
  6066. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  6067. RemoveCurrentP(p);
  6068. RemoveInstruction(hp1);
  6069. end
  6070. else
  6071. begin
  6072. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  6073. if taicpu(hp1).opcode=A_CVTSD2SS then
  6074. begin
  6075. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  6076. taicpu(p).opcode:=A_MOVAPS;
  6077. end
  6078. else
  6079. begin
  6080. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  6081. taicpu(p).opcode:=A_VMOVAPS;
  6082. end;
  6083. taicpu(p).ops:=2;
  6084. RemoveInstruction(hp1);
  6085. end;
  6086. Result:=true;
  6087. Exit;
  6088. end;
  6089. end;
  6090. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  6091. var
  6092. hp1, hp2, hp3, hp4, hp5: tai;
  6093. ThisReg: TRegister;
  6094. begin
  6095. Result := False;
  6096. if not GetNextInstruction(p,hp1) or (hp1.typ <> ait_instruction) then
  6097. Exit;
  6098. {
  6099. convert
  6100. j<c> .L1
  6101. mov 1,reg
  6102. jmp .L2
  6103. .L1
  6104. mov 0,reg
  6105. .L2
  6106. into
  6107. mov 0,reg
  6108. set<not(c)> reg
  6109. take care of alignment and that the mov 0,reg is not converted into a xor as this
  6110. would destroy the flag contents
  6111. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  6112. executed at the same time as a previous comparison.
  6113. set<not(c)> reg
  6114. movzx reg, reg
  6115. }
  6116. if MatchInstruction(hp1,A_MOV,[]) and
  6117. (taicpu(hp1).oper[0]^.typ = top_const) and
  6118. (
  6119. (
  6120. (taicpu(hp1).oper[1]^.typ = top_reg)
  6121. {$ifdef i386}
  6122. { Under i386, ESI, EDI, EBP and ESP
  6123. don't have an 8-bit representation }
  6124. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6125. {$endif i386}
  6126. ) or (
  6127. {$ifdef i386}
  6128. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  6129. {$endif i386}
  6130. (taicpu(hp1).opsize = S_B)
  6131. )
  6132. ) and
  6133. GetNextInstruction(hp1,hp2) and
  6134. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  6135. GetNextInstruction(hp2,hp3) and
  6136. SkipAligns(hp3, hp3) and
  6137. (hp3.typ=ait_label) and
  6138. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  6139. GetNextInstruction(hp3,hp4) and
  6140. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  6141. (taicpu(hp4).oper[0]^.typ = top_const) and
  6142. (
  6143. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  6144. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  6145. ) and
  6146. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  6147. GetNextInstruction(hp4,hp5) and
  6148. SkipAligns(hp5, hp5) and
  6149. (hp5.typ=ait_label) and
  6150. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  6151. begin
  6152. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6153. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6154. tai_label(hp3).labsym.DecRefs;
  6155. { If this isn't the only reference to the middle label, we can
  6156. still make a saving - only that the first jump and everything
  6157. that follows will remain. }
  6158. if (tai_label(hp3).labsym.getrefs = 0) then
  6159. begin
  6160. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6161. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  6162. else
  6163. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  6164. { remove jump, first label and second MOV (also catching any aligns) }
  6165. repeat
  6166. if not GetNextInstruction(hp2, hp3) then
  6167. InternalError(2021040810);
  6168. RemoveInstruction(hp2);
  6169. hp2 := hp3;
  6170. until hp2 = hp5;
  6171. { Don't decrement reference count before the removal loop
  6172. above, otherwise GetNextInstruction won't stop on the
  6173. the label }
  6174. tai_label(hp5).labsym.DecRefs;
  6175. end
  6176. else
  6177. begin
  6178. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6179. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  6180. else
  6181. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  6182. end;
  6183. taicpu(p).opcode:=A_SETcc;
  6184. taicpu(p).opsize:=S_B;
  6185. taicpu(p).is_jmp:=False;
  6186. if taicpu(hp1).opsize=S_B then
  6187. begin
  6188. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  6189. if taicpu(hp1).oper[1]^.typ = top_reg then
  6190. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  6191. RemoveInstruction(hp1);
  6192. end
  6193. else
  6194. begin
  6195. { Will be a register because the size can't be S_B otherwise }
  6196. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  6197. taicpu(p).loadreg(0, ThisReg);
  6198. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  6199. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  6200. begin
  6201. case taicpu(hp1).opsize of
  6202. S_W:
  6203. taicpu(hp1).opsize := S_BW;
  6204. S_L:
  6205. taicpu(hp1).opsize := S_BL;
  6206. {$ifdef x86_64}
  6207. S_Q:
  6208. begin
  6209. taicpu(hp1).opsize := S_BL;
  6210. { Change the destination register to 32-bit }
  6211. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  6212. end;
  6213. {$endif x86_64}
  6214. else
  6215. InternalError(2021040820);
  6216. end;
  6217. taicpu(hp1).opcode := A_MOVZX;
  6218. taicpu(hp1).loadreg(0, ThisReg);
  6219. end
  6220. else
  6221. begin
  6222. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  6223. { hp1 is already a MOV instruction with the correct register }
  6224. taicpu(hp1).loadconst(0, 0);
  6225. { Inserting it right before p will guarantee that the flags are also tracked }
  6226. asml.Remove(hp1);
  6227. asml.InsertBefore(hp1, p);
  6228. end;
  6229. end;
  6230. Result:=true;
  6231. exit;
  6232. end
  6233. end;
  6234. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  6235. var
  6236. hp1, hp2, hp3: tai;
  6237. SourceRef, TargetRef: TReference;
  6238. CurrentReg: TRegister;
  6239. begin
  6240. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  6241. if not UseAVX then
  6242. InternalError(2021100501);
  6243. Result := False;
  6244. { Look for the following to simplify:
  6245. vmovdqa/u x(mem1), %xmmreg
  6246. vmovdqa/u %xmmreg, y(mem2)
  6247. vmovdqa/u x+16(mem1), %xmmreg
  6248. vmovdqa/u %xmmreg, y+16(mem2)
  6249. Change to:
  6250. vmovdqa/u x(mem1), %ymmreg
  6251. vmovdqa/u %ymmreg, y(mem2)
  6252. vpxor %ymmreg, %ymmreg, %ymmreg
  6253. ( The VPXOR instruction is to zero the upper half, thus removing the
  6254. need to call the potentially expensive VZEROUPPER instruction. Other
  6255. peephole optimisations can remove VPXOR if it's unnecessary )
  6256. }
  6257. TransferUsedRegs(TmpUsedRegs);
  6258. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6259. { NOTE: In the optimisations below, if the references dictate that an
  6260. aligned move is possible (i.e. VMOVDQA), the existing instructions
  6261. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  6262. if (taicpu(p).opsize = S_XMM) and
  6263. MatchOpType(taicpu(p), top_ref, top_reg) and
  6264. GetNextInstruction(p, hp1) and
  6265. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6266. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  6267. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6268. begin
  6269. SourceRef := taicpu(p).oper[0]^.ref^;
  6270. TargetRef := taicpu(hp1).oper[1]^.ref^;
  6271. if GetNextInstruction(hp1, hp2) and
  6272. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6273. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  6274. begin
  6275. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  6276. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6277. Inc(SourceRef.offset, 16);
  6278. { Reuse the register in the first block move }
  6279. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  6280. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  6281. begin
  6282. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6283. Inc(TargetRef.offset, 16);
  6284. if GetNextInstruction(hp2, hp3) and
  6285. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6286. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6287. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6288. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6289. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6290. begin
  6291. { Update the register tracking to the new size }
  6292. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  6293. { Remember that the offsets are 16 ahead }
  6294. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6295. if not (
  6296. ((SourceRef.offset mod 32) = 16) and
  6297. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6298. ) then
  6299. taicpu(p).opcode := A_VMOVDQU;
  6300. taicpu(p).opsize := S_YMM;
  6301. taicpu(p).oper[1]^.reg := CurrentReg;
  6302. if not (
  6303. ((TargetRef.offset mod 32) = 16) and
  6304. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6305. ) then
  6306. taicpu(hp1).opcode := A_VMOVDQU;
  6307. taicpu(hp1).opsize := S_YMM;
  6308. taicpu(hp1).oper[0]^.reg := CurrentReg;
  6309. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  6310. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6311. if (pi_uses_ymm in current_procinfo.flags) then
  6312. RemoveInstruction(hp2)
  6313. else
  6314. begin
  6315. taicpu(hp2).opcode := A_VPXOR;
  6316. taicpu(hp2).opsize := S_YMM;
  6317. taicpu(hp2).loadreg(0, CurrentReg);
  6318. taicpu(hp2).loadreg(1, CurrentReg);
  6319. taicpu(hp2).loadreg(2, CurrentReg);
  6320. taicpu(hp2).ops := 3;
  6321. end;
  6322. RemoveInstruction(hp3);
  6323. Result := True;
  6324. Exit;
  6325. end;
  6326. end
  6327. else
  6328. begin
  6329. { See if the next references are 16 less rather than 16 greater }
  6330. Dec(SourceRef.offset, 32); { -16 the other way }
  6331. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  6332. begin
  6333. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6334. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  6335. if GetNextInstruction(hp2, hp3) and
  6336. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  6337. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6338. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6339. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6340. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6341. begin
  6342. { Update the register tracking to the new size }
  6343. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  6344. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  6345. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6346. if not(
  6347. ((SourceRef.offset mod 32) = 0) and
  6348. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6349. ) then
  6350. taicpu(hp2).opcode := A_VMOVDQU;
  6351. taicpu(hp2).opsize := S_YMM;
  6352. taicpu(hp2).oper[1]^.reg := CurrentReg;
  6353. if not (
  6354. ((TargetRef.offset mod 32) = 0) and
  6355. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6356. ) then
  6357. taicpu(hp3).opcode := A_VMOVDQU;
  6358. taicpu(hp3).opsize := S_YMM;
  6359. taicpu(hp3).oper[0]^.reg := CurrentReg;
  6360. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  6361. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6362. if (pi_uses_ymm in current_procinfo.flags) then
  6363. RemoveInstruction(hp1)
  6364. else
  6365. begin
  6366. taicpu(hp1).opcode := A_VPXOR;
  6367. taicpu(hp1).opsize := S_YMM;
  6368. taicpu(hp1).loadreg(0, CurrentReg);
  6369. taicpu(hp1).loadreg(1, CurrentReg);
  6370. taicpu(hp1).loadreg(2, CurrentReg);
  6371. taicpu(hp1).ops := 3;
  6372. Asml.Remove(hp1);
  6373. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  6374. end;
  6375. RemoveCurrentP(p, hp2);
  6376. Result := True;
  6377. Exit;
  6378. end;
  6379. end;
  6380. end;
  6381. end;
  6382. end;
  6383. end;
  6384. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  6385. var
  6386. hp2, hp3, first_assignment: tai;
  6387. IncCount, OperIdx: Integer;
  6388. OrigLabel: TAsmLabel;
  6389. begin
  6390. Count := 0;
  6391. Result := False;
  6392. first_assignment := nil;
  6393. if (LoopCount >= 20) then
  6394. begin
  6395. { Guard against infinite loops }
  6396. Exit;
  6397. end;
  6398. if (taicpu(p).oper[0]^.typ <> top_ref) or
  6399. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  6400. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  6401. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  6402. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  6403. Exit;
  6404. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  6405. {
  6406. change
  6407. jmp .L1
  6408. ...
  6409. .L1:
  6410. mov ##, ## ( multiple movs possible )
  6411. jmp/ret
  6412. into
  6413. mov ##, ##
  6414. jmp/ret
  6415. }
  6416. if not Assigned(hp1) then
  6417. begin
  6418. hp1 := GetLabelWithSym(OrigLabel);
  6419. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  6420. Exit;
  6421. end;
  6422. hp2 := hp1;
  6423. while Assigned(hp2) do
  6424. begin
  6425. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  6426. SkipLabels(hp2,hp2);
  6427. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  6428. Break;
  6429. case taicpu(hp2).opcode of
  6430. A_MOVSS:
  6431. begin
  6432. if taicpu(hp2).ops = 0 then
  6433. { Wrong MOVSS }
  6434. Break;
  6435. Inc(Count);
  6436. if Count >= 5 then
  6437. { Too many to be worthwhile }
  6438. Break;
  6439. GetNextInstruction(hp2, hp2);
  6440. Continue;
  6441. end;
  6442. A_MOV,
  6443. A_MOVD,
  6444. A_MOVQ,
  6445. A_MOVSX,
  6446. {$ifdef x86_64}
  6447. A_MOVSXD,
  6448. {$endif x86_64}
  6449. A_MOVZX,
  6450. A_MOVAPS,
  6451. A_MOVUPS,
  6452. A_MOVSD,
  6453. A_MOVAPD,
  6454. A_MOVUPD,
  6455. A_MOVDQA,
  6456. A_MOVDQU,
  6457. A_VMOVSS,
  6458. A_VMOVAPS,
  6459. A_VMOVUPS,
  6460. A_VMOVSD,
  6461. A_VMOVAPD,
  6462. A_VMOVUPD,
  6463. A_VMOVDQA,
  6464. A_VMOVDQU:
  6465. begin
  6466. Inc(Count);
  6467. if Count >= 5 then
  6468. { Too many to be worthwhile }
  6469. Break;
  6470. GetNextInstruction(hp2, hp2);
  6471. Continue;
  6472. end;
  6473. A_JMP:
  6474. begin
  6475. { Guard against infinite loops }
  6476. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  6477. Exit;
  6478. { Analyse this jump first in case it also duplicates assignments }
  6479. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  6480. begin
  6481. { Something did change! }
  6482. Result := True;
  6483. Inc(Count, IncCount);
  6484. if Count >= 5 then
  6485. begin
  6486. { Too many to be worthwhile }
  6487. Exit;
  6488. end;
  6489. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  6490. Break;
  6491. end;
  6492. Result := True;
  6493. Break;
  6494. end;
  6495. A_RET:
  6496. begin
  6497. Result := True;
  6498. Break;
  6499. end;
  6500. else
  6501. Break;
  6502. end;
  6503. end;
  6504. if Result then
  6505. begin
  6506. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  6507. if Count = 0 then
  6508. begin
  6509. Result := False;
  6510. Exit;
  6511. end;
  6512. hp3 := p;
  6513. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  6514. while True do
  6515. begin
  6516. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  6517. SkipLabels(hp1,hp1);
  6518. if (hp1.typ <> ait_instruction) then
  6519. InternalError(2021040720);
  6520. case taicpu(hp1).opcode of
  6521. A_JMP:
  6522. begin
  6523. { Change the original jump to the new destination }
  6524. OrigLabel.decrefs;
  6525. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  6526. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  6527. { Set p to the first duplicated assignment so it can get optimised if needs be }
  6528. if not Assigned(first_assignment) then
  6529. InternalError(2021040810)
  6530. else
  6531. p := first_assignment;
  6532. Exit;
  6533. end;
  6534. A_RET:
  6535. begin
  6536. { Now change the jump into a RET instruction }
  6537. ConvertJumpToRET(p, hp1);
  6538. { Set p to the first duplicated assignment so it can get optimised if needs be }
  6539. if not Assigned(first_assignment) then
  6540. InternalError(2021040811)
  6541. else
  6542. p := first_assignment;
  6543. Exit;
  6544. end;
  6545. else
  6546. begin
  6547. { Duplicate the MOV instruction }
  6548. hp3:=tai(hp1.getcopy);
  6549. if first_assignment = nil then
  6550. first_assignment := hp3;
  6551. asml.InsertBefore(hp3, p);
  6552. { Make sure the compiler knows about any final registers written here }
  6553. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  6554. with taicpu(hp3).oper[OperIdx]^ do
  6555. begin
  6556. case typ of
  6557. top_ref:
  6558. begin
  6559. if (ref^.base <> NR_NO) and
  6560. (getsupreg(ref^.base) <> RS_ESP) and
  6561. (getsupreg(ref^.base) <> RS_EBP)
  6562. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  6563. then
  6564. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  6565. if (ref^.index <> NR_NO) and
  6566. (getsupreg(ref^.index) <> RS_ESP) and
  6567. (getsupreg(ref^.index) <> RS_EBP)
  6568. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  6569. (ref^.index <> ref^.base) then
  6570. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  6571. end;
  6572. top_reg:
  6573. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  6574. else
  6575. ;
  6576. end;
  6577. end;
  6578. end;
  6579. end;
  6580. if not GetNextInstruction(hp1, hp1) then
  6581. { Should have dropped out earlier }
  6582. InternalError(2021040710);
  6583. end;
  6584. end;
  6585. end;
  6586. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  6587. var
  6588. hp2: tai;
  6589. X: Integer;
  6590. const
  6591. WriteOp: array[0..3] of set of TInsChange = (
  6592. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  6593. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  6594. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  6595. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  6596. RegWriteFlags: array[0..7] of set of TInsChange = (
  6597. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  6598. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  6599. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  6600. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  6601. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  6602. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  6603. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  6604. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  6605. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  6606. begin
  6607. { If we have something like:
  6608. cmp ###,%reg1
  6609. mov 0,%reg2
  6610. And no modified registers are shared, move the instruction to before
  6611. the comparison as this means it can be optimised without worrying
  6612. about the FLAGS register. (CMP/MOV is generated by
  6613. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  6614. As long as the second instruction doesn't use the flags or one of the
  6615. registers used by CMP or TEST (also check any references that use the
  6616. registers), then it can be moved prior to the comparison.
  6617. }
  6618. Result := False;
  6619. if (hp1.typ <> ait_instruction) or
  6620. taicpu(hp1).is_jmp or
  6621. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  6622. Exit;
  6623. { NOP is a pipeline fence, likely marking the beginning of the function
  6624. epilogue, so drop out. Similarly, drop out if POP or RET are
  6625. encountered }
  6626. if MatchInstruction(hp1, A_NOP, A_POP, []) then
  6627. Exit;
  6628. if (taicpu(hp1).opcode = A_MOVSS) and
  6629. (taicpu(hp1).ops = 0) then
  6630. { Wrong MOVSS }
  6631. Exit;
  6632. { Check for writes to specific registers first }
  6633. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  6634. for X := 0 to 7 do
  6635. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  6636. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  6637. Exit;
  6638. for X := 0 to taicpu(hp1).ops - 1 do
  6639. begin
  6640. { Check to see if this operand writes to something }
  6641. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  6642. { And matches something in the CMP/TEST instruction }
  6643. (
  6644. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  6645. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  6646. (
  6647. { If it's a register, make sure the register written to doesn't
  6648. appear in the cmp instruction as part of a reference }
  6649. (taicpu(hp1).oper[X]^.typ = top_reg) and
  6650. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  6651. )
  6652. ) then
  6653. Exit;
  6654. end;
  6655. { The instruction can be safely moved }
  6656. asml.Remove(hp1);
  6657. { Try to insert after the last instructions where the FLAGS register is not yet in use }
  6658. if not GetLastInstruction(p, hp2) then
  6659. asml.InsertBefore(hp1, p)
  6660. else
  6661. asml.InsertAfter(hp1, hp2);
  6662. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  6663. for X := 0 to taicpu(hp1).ops - 1 do
  6664. case taicpu(hp1).oper[X]^.typ of
  6665. top_reg:
  6666. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  6667. top_ref:
  6668. begin
  6669. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  6670. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  6671. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  6672. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  6673. end;
  6674. else
  6675. ;
  6676. end;
  6677. if taicpu(hp1).opcode = A_LEA then
  6678. { The flags will be overwritten by the CMP/TEST instruction }
  6679. ConvertLEA(taicpu(hp1));
  6680. Result := True;
  6681. end;
  6682. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  6683. function IsXCHGAcceptable: Boolean; inline;
  6684. begin
  6685. { Always accept if optimising for size }
  6686. Result := (cs_opt_size in current_settings.optimizerswitches) or
  6687. (
  6688. {$ifdef x86_64}
  6689. { XCHG takes 3 cycles on AMD Athlon64 }
  6690. (current_settings.optimizecputype >= cpu_core_i)
  6691. {$else x86_64}
  6692. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  6693. than 3, so it becomes a saving compared to three MOVs with two of
  6694. them able to execute simultaneously. [Kit] }
  6695. (current_settings.optimizecputype >= cpu_PentiumM)
  6696. {$endif x86_64}
  6697. );
  6698. end;
  6699. var
  6700. NewRef: TReference;
  6701. hp1, hp2, hp3, hp4: Tai;
  6702. {$ifndef x86_64}
  6703. OperIdx: Integer;
  6704. {$endif x86_64}
  6705. NewInstr : Taicpu;
  6706. NewAligh : Tai_align;
  6707. DestLabel: TAsmLabel;
  6708. function TryMovArith2Lea(InputInstr: tai): Boolean;
  6709. var
  6710. NextInstr: tai;
  6711. begin
  6712. Result := False;
  6713. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  6714. if not GetNextInstruction(InputInstr, NextInstr) or
  6715. (
  6716. { The FLAGS register isn't always tracked properly, so do not
  6717. perform this optimisation if a conditional statement follows }
  6718. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  6719. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  6720. ) then
  6721. begin
  6722. reference_reset(NewRef, 1, []);
  6723. NewRef.base := taicpu(p).oper[0]^.reg;
  6724. NewRef.scalefactor := 1;
  6725. if taicpu(InputInstr).opcode = A_ADD then
  6726. begin
  6727. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  6728. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  6729. end
  6730. else
  6731. begin
  6732. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  6733. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  6734. end;
  6735. taicpu(p).opcode := A_LEA;
  6736. taicpu(p).loadref(0, NewRef);
  6737. RemoveInstruction(InputInstr);
  6738. Result := True;
  6739. end;
  6740. end;
  6741. begin
  6742. Result:=false;
  6743. { This optimisation adds an instruction, so only do it for speed }
  6744. if not (cs_opt_size in current_settings.optimizerswitches) and
  6745. MatchOpType(taicpu(p), top_const, top_reg) and
  6746. (taicpu(p).oper[0]^.val = 0) then
  6747. begin
  6748. { To avoid compiler warning }
  6749. DestLabel := nil;
  6750. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  6751. InternalError(2021040750);
  6752. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  6753. Exit;
  6754. case hp1.typ of
  6755. ait_label:
  6756. begin
  6757. { Change:
  6758. mov $0,%reg mov $0,%reg
  6759. @Lbl1: @Lbl1:
  6760. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  6761. je @Lbl2 jne @Lbl2
  6762. To: To:
  6763. mov $0,%reg mov $0,%reg
  6764. jmp @Lbl2 jmp @Lbl3
  6765. (align) (align)
  6766. @Lbl1: @Lbl1:
  6767. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  6768. je @Lbl2 je @Lbl2
  6769. @Lbl3: <-- Only if label exists
  6770. (Not if it's optimised for size)
  6771. }
  6772. if not GetNextInstruction(hp1, hp2) then
  6773. Exit;
  6774. if not (cs_opt_size in current_settings.optimizerswitches) and
  6775. (hp2.typ = ait_instruction) and
  6776. (
  6777. { Register sizes must exactly match }
  6778. (
  6779. (taicpu(hp2).opcode = A_CMP) and
  6780. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  6781. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  6782. ) or (
  6783. (taicpu(hp2).opcode = A_TEST) and
  6784. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  6785. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  6786. )
  6787. ) and GetNextInstruction(hp2, hp3) and
  6788. (hp3.typ = ait_instruction) and
  6789. (taicpu(hp3).opcode = A_JCC) and
  6790. (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
  6791. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  6792. begin
  6793. { Check condition of jump }
  6794. { Always true? }
  6795. if condition_in(C_E, taicpu(hp3).condition) then
  6796. begin
  6797. { Copy label symbol and obtain matching label entry for the
  6798. conditional jump, as this will be our destination}
  6799. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  6800. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  6801. Result := True;
  6802. end
  6803. { Always false? }
  6804. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  6805. begin
  6806. { This is only worth it if there's a jump to take }
  6807. case hp2.typ of
  6808. ait_instruction:
  6809. begin
  6810. if taicpu(hp2).opcode = A_JMP then
  6811. begin
  6812. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  6813. { An unconditional jump follows the conditional jump which will always be false,
  6814. so use this jump's destination for the new jump }
  6815. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  6816. Result := True;
  6817. end
  6818. else if taicpu(hp2).opcode = A_JCC then
  6819. begin
  6820. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  6821. if condition_in(C_E, taicpu(hp2).condition) then
  6822. begin
  6823. { A second conditional jump follows the conditional jump which will always be false,
  6824. while the second jump is always True, so use this jump's destination for the new jump }
  6825. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  6826. Result := True;
  6827. end;
  6828. { Don't risk it if the jump isn't always true (Result remains False) }
  6829. end;
  6830. end;
  6831. else
  6832. { If anything else don't optimise };
  6833. end;
  6834. end;
  6835. if Result then
  6836. begin
  6837. { Just so we have something to insert as a paremeter}
  6838. reference_reset(NewRef, 1, []);
  6839. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  6840. { Now actually load the correct parameter }
  6841. NewInstr.loadsymbol(0, DestLabel, 0);
  6842. { Get instruction before original label (may not be p under -O3) }
  6843. if not GetLastInstruction(hp1, hp2) then
  6844. { Shouldn't fail here }
  6845. InternalError(2021040701);
  6846. DestLabel.increfs;
  6847. AsmL.InsertAfter(NewInstr, hp2);
  6848. { Add new alignment field }
  6849. (* AsmL.InsertAfter(
  6850. cai_align.create_max(
  6851. current_settings.alignment.jumpalign,
  6852. current_settings.alignment.jumpalignskipmax
  6853. ),
  6854. NewInstr
  6855. ); *)
  6856. end;
  6857. Exit;
  6858. end;
  6859. end;
  6860. else
  6861. ;
  6862. end;
  6863. end;
  6864. if not GetNextInstruction(p, hp1) then
  6865. Exit;
  6866. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  6867. and DoMovCmpMemOpt(p, hp1, True) then
  6868. begin
  6869. Result := True;
  6870. Exit;
  6871. end
  6872. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  6873. begin
  6874. { Sometimes the MOVs that OptPass2JMP produces can be improved
  6875. further, but we can't just put this jump optimisation in pass 1
  6876. because it tends to perform worse when conditional jumps are
  6877. nearby (e.g. when converting CMOV instructions). [Kit] }
  6878. if OptPass2JMP(hp1) then
  6879. { call OptPass1MOV once to potentially merge any MOVs that were created }
  6880. Result := OptPass1MOV(p)
  6881. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  6882. returned True and the instruction is still a MOV, thus checking
  6883. the optimisations below }
  6884. { If OptPass2JMP returned False, no optimisations were done to
  6885. the jump and there are no further optimisations that can be done
  6886. to the MOV instruction on this pass }
  6887. end
  6888. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  6889. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  6890. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  6891. (taicpu(hp1).oper[1]^.typ = top_reg) and
  6892. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  6893. begin
  6894. { Change:
  6895. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  6896. addl/q $x,%reg2 subl/q $x,%reg2
  6897. To:
  6898. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  6899. }
  6900. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6901. { be lazy, checking separately for sub would be slightly better }
  6902. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  6903. begin
  6904. TransferUsedRegs(TmpUsedRegs);
  6905. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6906. if TryMovArith2Lea(hp1) then
  6907. begin
  6908. Result := True;
  6909. Exit;
  6910. end
  6911. end
  6912. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  6913. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  6914. { Same as above, but also adds or subtracts to %reg2 in between.
  6915. It's still valid as long as the flags aren't in use }
  6916. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  6917. MatchOpType(taicpu(hp2), top_const, top_reg) and
  6918. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  6919. { be lazy, checking separately for sub would be slightly better }
  6920. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  6921. begin
  6922. TransferUsedRegs(TmpUsedRegs);
  6923. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6924. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6925. if TryMovArith2Lea(hp2) then
  6926. begin
  6927. Result := True;
  6928. Exit;
  6929. end;
  6930. end;
  6931. end
  6932. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  6933. {$ifdef x86_64}
  6934. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  6935. {$else x86_64}
  6936. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  6937. {$endif x86_64}
  6938. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6939. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  6940. { mov reg1, reg2 mov reg1, reg2
  6941. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  6942. begin
  6943. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  6944. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  6945. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  6946. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  6947. TransferUsedRegs(TmpUsedRegs);
  6948. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6949. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  6950. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  6951. then
  6952. begin
  6953. RemoveCurrentP(p, hp1);
  6954. Result:=true;
  6955. end;
  6956. exit;
  6957. end
  6958. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  6959. IsXCHGAcceptable and
  6960. { XCHG doesn't support 8-byte registers }
  6961. (taicpu(p).opsize <> S_B) and
  6962. MatchInstruction(hp1, A_MOV, []) and
  6963. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6964. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  6965. GetNextInstruction(hp1, hp2) and
  6966. MatchInstruction(hp2, A_MOV, []) and
  6967. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  6968. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  6969. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  6970. begin
  6971. { mov %reg1,%reg2
  6972. mov %reg3,%reg1 -> xchg %reg3,%reg1
  6973. mov %reg2,%reg3
  6974. (%reg2 not used afterwards)
  6975. Note that xchg takes 3 cycles to execute, and generally mov's take
  6976. only one cycle apiece, but the first two mov's can be executed in
  6977. parallel, only taking 2 cycles overall. Older processors should
  6978. therefore only optimise for size. [Kit]
  6979. }
  6980. TransferUsedRegs(TmpUsedRegs);
  6981. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6982. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6983. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  6984. begin
  6985. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  6986. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  6987. taicpu(hp1).opcode := A_XCHG;
  6988. RemoveCurrentP(p, hp1);
  6989. RemoveInstruction(hp2);
  6990. Result := True;
  6991. Exit;
  6992. end;
  6993. end
  6994. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  6995. MatchInstruction(hp1, A_SAR, []) then
  6996. begin
  6997. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  6998. begin
  6999. { the use of %edx also covers the opsize being S_L }
  7000. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  7001. begin
  7002. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  7003. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  7004. (taicpu(p).oper[1]^.reg = NR_EDX) then
  7005. begin
  7006. { Change:
  7007. movl %eax,%edx
  7008. sarl $31,%edx
  7009. To:
  7010. cltd
  7011. }
  7012. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  7013. RemoveInstruction(hp1);
  7014. taicpu(p).opcode := A_CDQ;
  7015. taicpu(p).opsize := S_NO;
  7016. taicpu(p).clearop(1);
  7017. taicpu(p).clearop(0);
  7018. taicpu(p).ops:=0;
  7019. Result := True;
  7020. end
  7021. else if (cs_opt_size in current_settings.optimizerswitches) and
  7022. (taicpu(p).oper[0]^.reg = NR_EDX) and
  7023. (taicpu(p).oper[1]^.reg = NR_EAX) then
  7024. begin
  7025. { Change:
  7026. movl %edx,%eax
  7027. sarl $31,%edx
  7028. To:
  7029. movl %edx,%eax
  7030. cltd
  7031. Note that this creates a dependency between the two instructions,
  7032. so only perform if optimising for size.
  7033. }
  7034. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  7035. taicpu(hp1).opcode := A_CDQ;
  7036. taicpu(hp1).opsize := S_NO;
  7037. taicpu(hp1).clearop(1);
  7038. taicpu(hp1).clearop(0);
  7039. taicpu(hp1).ops:=0;
  7040. end;
  7041. {$ifndef x86_64}
  7042. end
  7043. { Don't bother if CMOV is supported, because a more optimal
  7044. sequence would have been generated for the Abs() intrinsic }
  7045. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  7046. { the use of %eax also covers the opsize being S_L }
  7047. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  7048. (taicpu(p).oper[0]^.reg = NR_EAX) and
  7049. (taicpu(p).oper[1]^.reg = NR_EDX) and
  7050. GetNextInstruction(hp1, hp2) and
  7051. MatchInstruction(hp2, A_XOR, [S_L]) and
  7052. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  7053. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  7054. GetNextInstruction(hp2, hp3) and
  7055. MatchInstruction(hp3, A_SUB, [S_L]) and
  7056. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  7057. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  7058. begin
  7059. { Change:
  7060. movl %eax,%edx
  7061. sarl $31,%eax
  7062. xorl %eax,%edx
  7063. subl %eax,%edx
  7064. (Instruction that uses %edx)
  7065. (%eax deallocated)
  7066. (%edx deallocated)
  7067. To:
  7068. cltd
  7069. xorl %edx,%eax <-- Note the registers have swapped
  7070. subl %edx,%eax
  7071. (Instruction that uses %eax) <-- %eax rather than %edx
  7072. }
  7073. TransferUsedRegs(TmpUsedRegs);
  7074. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7075. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7076. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7077. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  7078. begin
  7079. if GetNextInstruction(hp3, hp4) and
  7080. not RegModifiedByInstruction(NR_EDX, hp4) and
  7081. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  7082. begin
  7083. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  7084. taicpu(p).opcode := A_CDQ;
  7085. taicpu(p).clearop(1);
  7086. taicpu(p).clearop(0);
  7087. taicpu(p).ops:=0;
  7088. RemoveInstruction(hp1);
  7089. taicpu(hp2).loadreg(0, NR_EDX);
  7090. taicpu(hp2).loadreg(1, NR_EAX);
  7091. taicpu(hp3).loadreg(0, NR_EDX);
  7092. taicpu(hp3).loadreg(1, NR_EAX);
  7093. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  7094. { Convert references in the following instruction (hp4) from %edx to %eax }
  7095. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  7096. with taicpu(hp4).oper[OperIdx]^ do
  7097. case typ of
  7098. top_reg:
  7099. if getsupreg(reg) = RS_EDX then
  7100. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7101. top_ref:
  7102. begin
  7103. if getsupreg(reg) = RS_EDX then
  7104. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7105. if getsupreg(reg) = RS_EDX then
  7106. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7107. end;
  7108. else
  7109. ;
  7110. end;
  7111. end;
  7112. end;
  7113. {$else x86_64}
  7114. end;
  7115. end
  7116. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  7117. { the use of %rdx also covers the opsize being S_Q }
  7118. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  7119. begin
  7120. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  7121. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  7122. (taicpu(p).oper[1]^.reg = NR_RDX) then
  7123. begin
  7124. { Change:
  7125. movq %rax,%rdx
  7126. sarq $63,%rdx
  7127. To:
  7128. cqto
  7129. }
  7130. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  7131. RemoveInstruction(hp1);
  7132. taicpu(p).opcode := A_CQO;
  7133. taicpu(p).opsize := S_NO;
  7134. taicpu(p).clearop(1);
  7135. taicpu(p).clearop(0);
  7136. taicpu(p).ops:=0;
  7137. Result := True;
  7138. end
  7139. else if (cs_opt_size in current_settings.optimizerswitches) and
  7140. (taicpu(p).oper[0]^.reg = NR_RDX) and
  7141. (taicpu(p).oper[1]^.reg = NR_RAX) then
  7142. begin
  7143. { Change:
  7144. movq %rdx,%rax
  7145. sarq $63,%rdx
  7146. To:
  7147. movq %rdx,%rax
  7148. cqto
  7149. Note that this creates a dependency between the two instructions,
  7150. so only perform if optimising for size.
  7151. }
  7152. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  7153. taicpu(hp1).opcode := A_CQO;
  7154. taicpu(hp1).opsize := S_NO;
  7155. taicpu(hp1).clearop(1);
  7156. taicpu(hp1).clearop(0);
  7157. taicpu(hp1).ops:=0;
  7158. {$endif x86_64}
  7159. end;
  7160. end;
  7161. end
  7162. else if MatchInstruction(hp1, A_MOV, []) and
  7163. (taicpu(hp1).oper[1]^.typ = top_reg) then
  7164. { Though "GetNextInstruction" could be factored out, along with
  7165. the instructions that depend on hp2, it is an expensive call that
  7166. should be delayed for as long as possible, hence we do cheaper
  7167. checks first that are likely to be False. [Kit] }
  7168. begin
  7169. if (
  7170. (
  7171. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  7172. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  7173. (
  7174. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7175. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  7176. )
  7177. ) or
  7178. (
  7179. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  7180. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  7181. (
  7182. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7183. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  7184. )
  7185. )
  7186. ) and
  7187. GetNextInstruction(hp1, hp2) and
  7188. MatchInstruction(hp2, A_SAR, []) and
  7189. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  7190. begin
  7191. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  7192. begin
  7193. { Change:
  7194. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  7195. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  7196. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  7197. To:
  7198. movl r/m,%eax <- Note the change in register
  7199. cltd
  7200. }
  7201. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  7202. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  7203. taicpu(p).loadreg(1, NR_EAX);
  7204. taicpu(hp1).opcode := A_CDQ;
  7205. taicpu(hp1).clearop(1);
  7206. taicpu(hp1).clearop(0);
  7207. taicpu(hp1).ops:=0;
  7208. RemoveInstruction(hp2);
  7209. (*
  7210. {$ifdef x86_64}
  7211. end
  7212. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  7213. { This code sequence does not get generated - however it might become useful
  7214. if and when 128-bit signed integer types make an appearance, so the code
  7215. is kept here for when it is eventually needed. [Kit] }
  7216. (
  7217. (
  7218. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  7219. (
  7220. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7221. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  7222. )
  7223. ) or
  7224. (
  7225. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  7226. (
  7227. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7228. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  7229. )
  7230. )
  7231. ) and
  7232. GetNextInstruction(hp1, hp2) and
  7233. MatchInstruction(hp2, A_SAR, [S_Q]) and
  7234. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  7235. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  7236. begin
  7237. { Change:
  7238. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  7239. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  7240. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  7241. To:
  7242. movq r/m,%rax <- Note the change in register
  7243. cqto
  7244. }
  7245. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  7246. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  7247. taicpu(p).loadreg(1, NR_RAX);
  7248. taicpu(hp1).opcode := A_CQO;
  7249. taicpu(hp1).clearop(1);
  7250. taicpu(hp1).clearop(0);
  7251. taicpu(hp1).ops:=0;
  7252. RemoveInstruction(hp2);
  7253. {$endif x86_64}
  7254. *)
  7255. end;
  7256. end;
  7257. {$ifdef x86_64}
  7258. end
  7259. else if (taicpu(p).opsize = S_L) and
  7260. (taicpu(p).oper[1]^.typ = top_reg) and
  7261. (
  7262. MatchInstruction(hp1, A_MOV,[]) and
  7263. (taicpu(hp1).opsize = S_L) and
  7264. (taicpu(hp1).oper[1]^.typ = top_reg)
  7265. ) and (
  7266. GetNextInstruction(hp1, hp2) and
  7267. (tai(hp2).typ=ait_instruction) and
  7268. (taicpu(hp2).opsize = S_Q) and
  7269. (
  7270. (
  7271. MatchInstruction(hp2, A_ADD,[]) and
  7272. (taicpu(hp2).opsize = S_Q) and
  7273. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7274. (
  7275. (
  7276. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7277. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7278. ) or (
  7279. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7280. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7281. )
  7282. )
  7283. ) or (
  7284. MatchInstruction(hp2, A_LEA,[]) and
  7285. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  7286. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  7287. (
  7288. (
  7289. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7290. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7291. ) or (
  7292. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7293. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  7294. )
  7295. ) and (
  7296. (
  7297. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7298. ) or (
  7299. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7300. )
  7301. )
  7302. )
  7303. )
  7304. ) and (
  7305. GetNextInstruction(hp2, hp3) and
  7306. MatchInstruction(hp3, A_SHR,[]) and
  7307. (taicpu(hp3).opsize = S_Q) and
  7308. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7309. (taicpu(hp3).oper[0]^.val = 1) and
  7310. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  7311. ) then
  7312. begin
  7313. { Change movl x, reg1d movl x, reg1d
  7314. movl y, reg2d movl y, reg2d
  7315. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  7316. shrq $1, reg1q shrq $1, reg1q
  7317. ( reg1d and reg2d can be switched around in the first two instructions )
  7318. To movl x, reg1d
  7319. addl y, reg1d
  7320. rcrl $1, reg1d
  7321. This corresponds to the common expression (x + y) shr 1, where
  7322. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  7323. smaller code, but won't account for x + y causing an overflow). [Kit]
  7324. }
  7325. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  7326. { Change first MOV command to have the same register as the final output }
  7327. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  7328. else
  7329. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  7330. { Change second MOV command to an ADD command. This is easier than
  7331. converting the existing command because it means we don't have to
  7332. touch 'y', which might be a complicated reference, and also the
  7333. fact that the third command might either be ADD or LEA. [Kit] }
  7334. taicpu(hp1).opcode := A_ADD;
  7335. { Delete old ADD/LEA instruction }
  7336. RemoveInstruction(hp2);
  7337. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  7338. taicpu(hp3).opcode := A_RCR;
  7339. taicpu(hp3).changeopsize(S_L);
  7340. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  7341. {$endif x86_64}
  7342. end;
  7343. end;
  7344. {$push}
  7345. {$q-}{$r-}
  7346. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  7347. var
  7348. ThisReg: TRegister;
  7349. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  7350. TargetSubReg: TSubRegister;
  7351. hp1, hp2: tai;
  7352. RegInUse, RegChanged, p_removed: Boolean;
  7353. { Store list of found instructions so we don't have to call
  7354. GetNextInstructionUsingReg multiple times }
  7355. InstrList: array of taicpu;
  7356. InstrMax, Index: Integer;
  7357. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  7358. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  7359. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  7360. WorkingValue: TCgInt;
  7361. PreMessage: string;
  7362. { Data flow analysis }
  7363. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  7364. BitwiseOnly, OrXorUsed,
  7365. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  7366. function CheckOverflowConditions: Boolean;
  7367. begin
  7368. Result := True;
  7369. if (TestValSignedMax > SignedUpperLimit) then
  7370. UpperSignedOverflow := True;
  7371. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  7372. LowerSignedOverflow := True;
  7373. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  7374. LowerUnsignedOverflow := True;
  7375. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  7376. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  7377. begin
  7378. { Absolute overflow }
  7379. Result := False;
  7380. Exit;
  7381. end;
  7382. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  7383. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  7384. ShiftDownOverflow := True;
  7385. if (TestValMin < 0) or (TestValMax < 0) then
  7386. begin
  7387. LowerUnsignedOverflow := True;
  7388. UpperUnsignedOverflow := True;
  7389. end;
  7390. end;
  7391. procedure AdjustFinalLoad;
  7392. begin
  7393. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  7394. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  7395. begin
  7396. { Convert the output MOVZX to a MOV }
  7397. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7398. begin
  7399. { Or remove it completely! }
  7400. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  7401. { Be careful; if p = hp1 and p was also removed, p
  7402. will become a dangling pointer }
  7403. if p = hp1 then
  7404. begin
  7405. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  7406. p_removed := True;
  7407. end
  7408. else
  7409. RemoveInstruction(hp1);
  7410. end
  7411. else
  7412. begin
  7413. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  7414. taicpu(hp1).opcode := A_MOV;
  7415. taicpu(hp1).oper[0]^.reg := ThisReg;
  7416. taicpu(hp1).opsize := TargetSize;
  7417. end;
  7418. end
  7419. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  7420. begin
  7421. { Need to change the size of the output }
  7422. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  7423. taicpu(hp1).oper[0]^.reg := ThisReg;
  7424. taicpu(hp1).opsize := S_BL;
  7425. end;
  7426. end;
  7427. function CompressInstructions: Boolean;
  7428. var
  7429. LocalIndex: Integer;
  7430. begin
  7431. Result := False;
  7432. { The objective here is to try to find a combination that
  7433. removes one of the MOV/Z instructions. }
  7434. if (
  7435. (taicpu(p).oper[0]^.typ <> top_reg) or
  7436. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  7437. ) and
  7438. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7439. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7440. begin
  7441. { Make a preference to remove the second MOVZX instruction }
  7442. case taicpu(hp1).opsize of
  7443. S_BL, S_WL:
  7444. begin
  7445. TargetSize := S_L;
  7446. TargetSubReg := R_SUBD;
  7447. end;
  7448. S_BW:
  7449. begin
  7450. TargetSize := S_W;
  7451. TargetSubReg := R_SUBW;
  7452. end;
  7453. else
  7454. InternalError(2020112302);
  7455. end;
  7456. end
  7457. else
  7458. begin
  7459. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  7460. begin
  7461. { Exceeded lower bound but not upper bound }
  7462. TargetSize := MaxSize;
  7463. end
  7464. else if not LowerUnsignedOverflow then
  7465. begin
  7466. { Size didn't exceed lower bound }
  7467. TargetSize := MinSize;
  7468. end
  7469. else
  7470. Exit;
  7471. end;
  7472. case TargetSize of
  7473. S_B:
  7474. TargetSubReg := R_SUBL;
  7475. S_W:
  7476. TargetSubReg := R_SUBW;
  7477. S_L:
  7478. TargetSubReg := R_SUBD;
  7479. else
  7480. InternalError(2020112350);
  7481. end;
  7482. { Update the register to its new size }
  7483. setsubreg(ThisReg, TargetSubReg);
  7484. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7485. begin
  7486. { Check to see if the active register is used afterwards;
  7487. if not, we can change it and make a saving. }
  7488. RegInUse := False;
  7489. TransferUsedRegs(TmpUsedRegs);
  7490. { The target register may be marked as in use to cross
  7491. a jump to a distant label, so exclude it }
  7492. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  7493. hp2 := p;
  7494. repeat
  7495. { Explicitly check for the excluded register (don't include the first
  7496. instruction as it may be reading from here }
  7497. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  7498. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  7499. begin
  7500. RegInUse := True;
  7501. Break;
  7502. end;
  7503. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  7504. if not GetNextInstruction(hp2, hp2) then
  7505. InternalError(2020112340);
  7506. until (hp2 = hp1);
  7507. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  7508. { We might still be able to get away with this }
  7509. RegInUse := not
  7510. (
  7511. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  7512. (hp2.typ = ait_instruction) and
  7513. (
  7514. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  7515. instruction that doesn't actually contain ThisReg }
  7516. (cs_opt_level3 in current_settings.optimizerswitches) or
  7517. RegInInstruction(ThisReg, hp2)
  7518. ) and
  7519. RegLoadedWithNewValue(ThisReg, hp2)
  7520. );
  7521. if not RegInUse then
  7522. begin
  7523. { Force the register size to the same as this instruction so it can be removed}
  7524. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  7525. begin
  7526. TargetSize := S_L;
  7527. TargetSubReg := R_SUBD;
  7528. end
  7529. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  7530. begin
  7531. TargetSize := S_W;
  7532. TargetSubReg := R_SUBW;
  7533. end;
  7534. ThisReg := taicpu(hp1).oper[1]^.reg;
  7535. setsubreg(ThisReg, TargetSubReg);
  7536. RegChanged := True;
  7537. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  7538. TransferUsedRegs(TmpUsedRegs);
  7539. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  7540. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  7541. if p = hp1 then
  7542. begin
  7543. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  7544. p_removed := True;
  7545. end
  7546. else
  7547. RemoveInstruction(hp1);
  7548. { Instruction will become "mov %reg,%reg" }
  7549. if not p_removed and (taicpu(p).opcode = A_MOV) and
  7550. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  7551. begin
  7552. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  7553. RemoveCurrentP(p);
  7554. p_removed := True;
  7555. end
  7556. else
  7557. taicpu(p).oper[1]^.reg := ThisReg;
  7558. Result := True;
  7559. end
  7560. else
  7561. begin
  7562. if TargetSize <> MaxSize then
  7563. begin
  7564. { Since the register is in use, we have to force it to
  7565. MaxSize otherwise part of it may become undefined later on }
  7566. TargetSize := MaxSize;
  7567. case TargetSize of
  7568. S_B:
  7569. TargetSubReg := R_SUBL;
  7570. S_W:
  7571. TargetSubReg := R_SUBW;
  7572. S_L:
  7573. TargetSubReg := R_SUBD;
  7574. else
  7575. InternalError(2020112351);
  7576. end;
  7577. setsubreg(ThisReg, TargetSubReg);
  7578. end;
  7579. AdjustFinalLoad;
  7580. end;
  7581. end
  7582. else
  7583. AdjustFinalLoad;
  7584. if not p_removed then
  7585. begin
  7586. if TargetSize = MinSize then
  7587. begin
  7588. { Convert the input MOVZX to a MOV }
  7589. if (taicpu(p).oper[0]^.typ = top_reg) and
  7590. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  7591. begin
  7592. { Or remove it completely! }
  7593. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  7594. DebugMsg(SPeepholeOptimization + tostr(InstrMax), p);
  7595. RemoveCurrentP(p);
  7596. p_removed := True;
  7597. end
  7598. else
  7599. begin
  7600. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  7601. taicpu(p).opcode := A_MOV;
  7602. taicpu(p).oper[1]^.reg := ThisReg;
  7603. taicpu(p).opsize := TargetSize;
  7604. end;
  7605. Result := True;
  7606. end
  7607. else if TargetSize <> MaxSize then
  7608. begin
  7609. case MaxSize of
  7610. S_L:
  7611. if TargetSize = S_W then
  7612. begin
  7613. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  7614. taicpu(p).opsize := S_BW;
  7615. taicpu(p).oper[1]^.reg := ThisReg;
  7616. Result := True;
  7617. end
  7618. else
  7619. InternalError(2020112341);
  7620. S_W:
  7621. if TargetSize = S_L then
  7622. begin
  7623. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  7624. taicpu(p).opsize := S_BL;
  7625. taicpu(p).oper[1]^.reg := ThisReg;
  7626. Result := True;
  7627. end
  7628. else
  7629. InternalError(2020112342);
  7630. else
  7631. ;
  7632. end;
  7633. end;
  7634. end;
  7635. { Now go through every instruction we found and change the
  7636. size. If TargetSize = MaxSize, then almost no changes are
  7637. needed and Result can remain False if it hasn't been set
  7638. yet.
  7639. If RegChanged is True, then the register requires changing
  7640. and so the point about TargetSize = MaxSize doesn't apply. }
  7641. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  7642. begin
  7643. for LocalIndex := 0 to InstrMax do
  7644. begin
  7645. { If p_removed is true, then the original MOV/Z was removed
  7646. and removing the AND instruction may not be safe if it
  7647. appears first }
  7648. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  7649. InternalError(2020112310);
  7650. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  7651. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  7652. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  7653. InstrList[LocalIndex].opsize := TargetSize;
  7654. end;
  7655. Result := True;
  7656. end;
  7657. end;
  7658. begin
  7659. Result := False;
  7660. p_removed := False;
  7661. ThisReg := taicpu(p).oper[1]^.reg;
  7662. { Check for:
  7663. movs/z ###,%ecx (or %cx or %rcx)
  7664. ...
  7665. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  7666. (dealloc %ecx)
  7667. Change to:
  7668. mov ###,%cl (if ### = %cl, then remove completely)
  7669. ...
  7670. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  7671. }
  7672. if (getsupreg(ThisReg) = RS_ECX) and
  7673. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  7674. (hp1.typ = ait_instruction) and
  7675. (
  7676. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  7677. instruction that doesn't actually contain ECX }
  7678. (cs_opt_level3 in current_settings.optimizerswitches) or
  7679. RegInInstruction(NR_ECX, hp1) or
  7680. (
  7681. { It's common for the shift/rotate's read/write register to be
  7682. initialised in between, so under -O2 and under, search ahead
  7683. one more instruction
  7684. }
  7685. GetNextInstruction(hp1, hp1) and
  7686. (hp1.typ = ait_instruction) and
  7687. RegInInstruction(NR_ECX, hp1)
  7688. )
  7689. ) and
  7690. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  7691. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  7692. begin
  7693. TransferUsedRegs(TmpUsedRegs);
  7694. hp2 := p;
  7695. repeat
  7696. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7697. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  7698. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  7699. begin
  7700. case taicpu(p).opsize of
  7701. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  7702. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  7703. begin
  7704. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  7705. RemoveCurrentP(p);
  7706. end
  7707. else
  7708. begin
  7709. taicpu(p).opcode := A_MOV;
  7710. taicpu(p).opsize := S_B;
  7711. taicpu(p).oper[1]^.reg := NR_CL;
  7712. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  7713. end;
  7714. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  7715. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  7716. begin
  7717. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  7718. RemoveCurrentP(p);
  7719. end
  7720. else
  7721. begin
  7722. taicpu(p).opcode := A_MOV;
  7723. taicpu(p).opsize := S_W;
  7724. taicpu(p).oper[1]^.reg := NR_CX;
  7725. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  7726. end;
  7727. {$ifdef x86_64}
  7728. S_LQ:
  7729. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  7730. begin
  7731. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  7732. RemoveCurrentP(p);
  7733. end
  7734. else
  7735. begin
  7736. taicpu(p).opcode := A_MOV;
  7737. taicpu(p).opsize := S_L;
  7738. taicpu(p).oper[1]^.reg := NR_ECX;
  7739. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  7740. end;
  7741. {$endif x86_64}
  7742. else
  7743. InternalError(2021120401);
  7744. end;
  7745. Result := True;
  7746. Exit;
  7747. end;
  7748. end;
  7749. { This is anything but quick! }
  7750. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  7751. Exit;
  7752. SetLength(InstrList, 0);
  7753. InstrMax := -1;
  7754. case taicpu(p).opsize of
  7755. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  7756. begin
  7757. {$if defined(i386) or defined(i8086)}
  7758. { If the target size is 8-bit, make sure we can actually encode it }
  7759. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  7760. Exit;
  7761. {$endif i386 or i8086}
  7762. LowerLimit := $FF;
  7763. SignedLowerLimit := $7F;
  7764. SignedLowerLimitBottom := -128;
  7765. MinSize := S_B;
  7766. if taicpu(p).opsize = S_BW then
  7767. begin
  7768. MaxSize := S_W;
  7769. UpperLimit := $FFFF;
  7770. SignedUpperLimit := $7FFF;
  7771. SignedUpperLimitBottom := -32768;
  7772. end
  7773. else
  7774. begin
  7775. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  7776. MaxSize := S_L;
  7777. UpperLimit := $FFFFFFFF;
  7778. SignedUpperLimit := $7FFFFFFF;
  7779. SignedUpperLimitBottom := -2147483648;
  7780. end;
  7781. end;
  7782. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  7783. begin
  7784. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  7785. LowerLimit := $FFFF;
  7786. SignedLowerLimit := $7FFF;
  7787. SignedLowerLimitBottom := -32768;
  7788. UpperLimit := $FFFFFFFF;
  7789. SignedUpperLimit := $7FFFFFFF;
  7790. SignedUpperLimitBottom := -2147483648;
  7791. MinSize := S_W;
  7792. MaxSize := S_L;
  7793. end;
  7794. {$ifdef x86_64}
  7795. S_LQ:
  7796. begin
  7797. { Both the lower and upper limits are set to 32-bit. If a limit
  7798. is breached, then optimisation is impossible }
  7799. LowerLimit := $FFFFFFFF;
  7800. SignedLowerLimit := $7FFFFFFF;
  7801. SignedLowerLimitBottom := -2147483648;
  7802. UpperLimit := $FFFFFFFF;
  7803. SignedUpperLimit := $7FFFFFFF;
  7804. SignedUpperLimitBottom := -2147483648;
  7805. MinSize := S_L;
  7806. MaxSize := S_L;
  7807. end;
  7808. {$endif x86_64}
  7809. else
  7810. InternalError(2020112301);
  7811. end;
  7812. TestValMin := 0;
  7813. TestValMax := LowerLimit;
  7814. TestValSignedMax := SignedLowerLimit;
  7815. TryShiftDownLimit := LowerLimit;
  7816. TryShiftDown := S_NO;
  7817. ShiftDownOverflow := False;
  7818. RegChanged := False;
  7819. BitwiseOnly := True;
  7820. OrXorUsed := False;
  7821. UpperSignedOverflow := False;
  7822. LowerSignedOverflow := False;
  7823. UpperUnsignedOverflow := False;
  7824. LowerUnsignedOverflow := False;
  7825. hp1 := p;
  7826. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  7827. (hp1.typ = ait_instruction) and
  7828. (
  7829. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  7830. instruction that doesn't actually contain ThisReg }
  7831. (cs_opt_level3 in current_settings.optimizerswitches) or
  7832. { This allows this Movx optimisation to work through the SETcc instructions
  7833. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  7834. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  7835. skip over these SETcc instructions). }
  7836. (taicpu(hp1).opcode = A_SETcc) or
  7837. RegInInstruction(ThisReg, hp1)
  7838. ) do
  7839. begin
  7840. case taicpu(hp1).opcode of
  7841. A_INC,A_DEC:
  7842. begin
  7843. { Has to be an exact match on the register }
  7844. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  7845. Break;
  7846. if taicpu(hp1).opcode = A_INC then
  7847. begin
  7848. Inc(TestValMin);
  7849. Inc(TestValMax);
  7850. Inc(TestValSignedMax);
  7851. end
  7852. else
  7853. begin
  7854. Dec(TestValMin);
  7855. Dec(TestValMax);
  7856. Dec(TestValSignedMax);
  7857. end;
  7858. end;
  7859. A_TEST, A_CMP:
  7860. begin
  7861. if (
  7862. { Too high a risk of non-linear behaviour that breaks DFA
  7863. here, unless it's cmp $0,%reg, which is equivalent to
  7864. test %reg,%reg }
  7865. OrXorUsed and
  7866. (taicpu(hp1).opcode = A_CMP) and
  7867. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  7868. ) or
  7869. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  7870. { Has to be an exact match on the register }
  7871. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  7872. (
  7873. { Permit "test %reg,%reg" }
  7874. (taicpu(hp1).opcode = A_TEST) and
  7875. (taicpu(hp1).oper[0]^.typ = top_reg) and
  7876. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  7877. ) or
  7878. (taicpu(hp1).oper[0]^.typ <> top_const) or
  7879. { Make sure the comparison value is not smaller than the
  7880. smallest allowed signed value for the minimum size (e.g.
  7881. -128 for 8-bit) }
  7882. not (
  7883. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  7884. { Is it in the negative range? }
  7885. (
  7886. (taicpu(hp1).oper[0]^.val < 0) and
  7887. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  7888. )
  7889. ) then
  7890. Break;
  7891. { Check to see if the active register is used afterwards }
  7892. TransferUsedRegs(TmpUsedRegs);
  7893. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  7894. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  7895. begin
  7896. { Make sure the comparison or any previous instructions
  7897. hasn't pushed the test values outside of the range of
  7898. MinSize }
  7899. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  7900. begin
  7901. { Exceeded lower bound but not upper bound }
  7902. TargetSize := MaxSize;
  7903. end
  7904. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  7905. begin
  7906. { Size didn't exceed lower bound }
  7907. TargetSize := MinSize;
  7908. end
  7909. else
  7910. Break;
  7911. case TargetSize of
  7912. S_B:
  7913. TargetSubReg := R_SUBL;
  7914. S_W:
  7915. TargetSubReg := R_SUBW;
  7916. S_L:
  7917. TargetSubReg := R_SUBD;
  7918. else
  7919. InternalError(2021051002);
  7920. end;
  7921. { Update the register to its new size }
  7922. setsubreg(ThisReg, TargetSubReg);
  7923. taicpu(hp1).oper[1]^.reg := ThisReg;
  7924. taicpu(hp1).opsize := MinSize;
  7925. { Convert the input MOVZX to a MOV }
  7926. if (taicpu(p).oper[0]^.typ = top_reg) and
  7927. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  7928. begin
  7929. { Or remove it completely! }
  7930. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  7931. RemoveCurrentP(p);
  7932. p_removed := True;
  7933. end
  7934. else
  7935. begin
  7936. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  7937. taicpu(p).opcode := A_MOV;
  7938. taicpu(p).oper[1]^.reg := ThisReg;
  7939. taicpu(p).opsize := MinSize;
  7940. end;
  7941. if (InstrMax >= 0) then
  7942. begin
  7943. for Index := 0 to InstrMax do
  7944. begin
  7945. { If p_removed is true, then the original MOV/Z was removed
  7946. and removing the AND instruction may not be safe if it
  7947. appears first }
  7948. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  7949. InternalError(2020112311);
  7950. if InstrList[Index].oper[0]^.typ = top_reg then
  7951. InstrList[Index].oper[0]^.reg := ThisReg;
  7952. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  7953. InstrList[Index].opsize := MinSize;
  7954. end;
  7955. end;
  7956. Result := True;
  7957. Exit;
  7958. end;
  7959. end;
  7960. A_SETcc:
  7961. begin
  7962. { This allows this Movx optimisation to work through the SETcc instructions
  7963. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  7964. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  7965. skip over these SETcc instructions). }
  7966. if (cs_opt_level3 in current_settings.optimizerswitches) or
  7967. { Of course, break out if the current register is used }
  7968. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  7969. Break
  7970. else
  7971. { We must use Continue so the instruction doesn't get added
  7972. to InstrList }
  7973. Continue;
  7974. end;
  7975. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  7976. begin
  7977. if
  7978. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  7979. { Has to be an exact match on the register }
  7980. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  7981. (
  7982. (
  7983. (taicpu(hp1).oper[0]^.typ = top_const) and
  7984. (
  7985. (
  7986. (taicpu(hp1).opcode = A_SHL) and
  7987. (
  7988. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  7989. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  7990. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  7991. )
  7992. ) or (
  7993. (taicpu(hp1).opcode <> A_SHL) and
  7994. (
  7995. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  7996. { Is it in the negative range? }
  7997. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  7998. )
  7999. )
  8000. )
  8001. ) or (
  8002. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  8003. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  8004. )
  8005. ) then
  8006. Break;
  8007. { Only process OR and XOR if there are only bitwise operations,
  8008. since otherwise they can too easily fool the data flow
  8009. analysis (they can cause non-linear behaviour) }
  8010. case taicpu(hp1).opcode of
  8011. A_ADD:
  8012. begin
  8013. if OrXorUsed then
  8014. { Too high a risk of non-linear behaviour that breaks DFA here }
  8015. Break
  8016. else
  8017. BitwiseOnly := False;
  8018. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8019. begin
  8020. TestValMin := TestValMin * 2;
  8021. TestValMax := TestValMax * 2;
  8022. TestValSignedMax := TestValSignedMax * 2;
  8023. end
  8024. else
  8025. begin
  8026. WorkingValue := taicpu(hp1).oper[0]^.val;
  8027. TestValMin := TestValMin + WorkingValue;
  8028. TestValMax := TestValMax + WorkingValue;
  8029. TestValSignedMax := TestValSignedMax + WorkingValue;
  8030. end;
  8031. end;
  8032. A_SUB:
  8033. begin
  8034. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8035. begin
  8036. TestValMin := 0;
  8037. TestValMax := 0;
  8038. TestValSignedMax := 0;
  8039. end
  8040. else
  8041. begin
  8042. if OrXorUsed then
  8043. { Too high a risk of non-linear behaviour that breaks DFA here }
  8044. Break
  8045. else
  8046. BitwiseOnly := False;
  8047. WorkingValue := taicpu(hp1).oper[0]^.val;
  8048. TestValMin := TestValMin - WorkingValue;
  8049. TestValMax := TestValMax - WorkingValue;
  8050. TestValSignedMax := TestValSignedMax - WorkingValue;
  8051. end;
  8052. end;
  8053. A_AND:
  8054. if (taicpu(hp1).oper[0]^.typ = top_const) then
  8055. begin
  8056. { we might be able to go smaller if AND appears first }
  8057. if InstrMax = -1 then
  8058. case MinSize of
  8059. S_B:
  8060. ;
  8061. S_W:
  8062. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8063. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8064. begin
  8065. TryShiftDown := S_B;
  8066. TryShiftDownLimit := $FF;
  8067. end;
  8068. S_L:
  8069. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8070. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8071. begin
  8072. TryShiftDown := S_B;
  8073. TryShiftDownLimit := $FF;
  8074. end
  8075. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  8076. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  8077. begin
  8078. TryShiftDown := S_W;
  8079. TryShiftDownLimit := $FFFF;
  8080. end;
  8081. else
  8082. InternalError(2020112320);
  8083. end;
  8084. WorkingValue := taicpu(hp1).oper[0]^.val;
  8085. TestValMin := TestValMin and WorkingValue;
  8086. TestValMax := TestValMax and WorkingValue;
  8087. TestValSignedMax := TestValSignedMax and WorkingValue;
  8088. end;
  8089. A_OR:
  8090. begin
  8091. if not BitwiseOnly then
  8092. Break;
  8093. OrXorUsed := True;
  8094. WorkingValue := taicpu(hp1).oper[0]^.val;
  8095. TestValMin := TestValMin or WorkingValue;
  8096. TestValMax := TestValMax or WorkingValue;
  8097. TestValSignedMax := TestValSignedMax or WorkingValue;
  8098. end;
  8099. A_XOR:
  8100. begin
  8101. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8102. begin
  8103. TestValMin := 0;
  8104. TestValMax := 0;
  8105. TestValSignedMax := 0;
  8106. end
  8107. else
  8108. begin
  8109. if not BitwiseOnly then
  8110. Break;
  8111. OrXorUsed := True;
  8112. WorkingValue := taicpu(hp1).oper[0]^.val;
  8113. TestValMin := TestValMin xor WorkingValue;
  8114. TestValMax := TestValMax xor WorkingValue;
  8115. TestValSignedMax := TestValSignedMax xor WorkingValue;
  8116. end;
  8117. end;
  8118. A_SHL:
  8119. begin
  8120. BitwiseOnly := False;
  8121. WorkingValue := taicpu(hp1).oper[0]^.val;
  8122. TestValMin := TestValMin shl WorkingValue;
  8123. TestValMax := TestValMax shl WorkingValue;
  8124. TestValSignedMax := TestValSignedMax shl WorkingValue;
  8125. end;
  8126. A_SHR,
  8127. { The first instruction was MOVZX, so the value won't be negative }
  8128. A_SAR:
  8129. begin
  8130. if InstrMax <> -1 then
  8131. BitwiseOnly := False
  8132. else
  8133. { we might be able to go smaller if SHR appears first }
  8134. case MinSize of
  8135. S_B:
  8136. ;
  8137. S_W:
  8138. if (taicpu(hp1).oper[0]^.val >= 8) then
  8139. begin
  8140. TryShiftDown := S_B;
  8141. TryShiftDownLimit := $FF;
  8142. TryShiftDownSignedLimit := $7F;
  8143. TryShiftDownSignedLimitLower := -128;
  8144. end;
  8145. S_L:
  8146. if (taicpu(hp1).oper[0]^.val >= 24) then
  8147. begin
  8148. TryShiftDown := S_B;
  8149. TryShiftDownLimit := $FF;
  8150. TryShiftDownSignedLimit := $7F;
  8151. TryShiftDownSignedLimitLower := -128;
  8152. end
  8153. else if (taicpu(hp1).oper[0]^.val >= 16) then
  8154. begin
  8155. TryShiftDown := S_W;
  8156. TryShiftDownLimit := $FFFF;
  8157. TryShiftDownSignedLimit := $7FFF;
  8158. TryShiftDownSignedLimitLower := -32768;
  8159. end;
  8160. else
  8161. InternalError(2020112321);
  8162. end;
  8163. WorkingValue := taicpu(hp1).oper[0]^.val;
  8164. if taicpu(hp1).opcode = A_SAR then
  8165. begin
  8166. TestValMin := SarInt64(TestValMin, WorkingValue);
  8167. TestValMax := SarInt64(TestValMax, WorkingValue);
  8168. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  8169. end
  8170. else
  8171. begin
  8172. TestValMin := TestValMin shr WorkingValue;
  8173. TestValMax := TestValMax shr WorkingValue;
  8174. TestValSignedMax := TestValSignedMax shr WorkingValue;
  8175. end;
  8176. end;
  8177. else
  8178. InternalError(2020112303);
  8179. end;
  8180. end;
  8181. (*
  8182. A_IMUL:
  8183. case taicpu(hp1).ops of
  8184. 2:
  8185. begin
  8186. if not MatchOpType(hp1, top_reg, top_reg) or
  8187. { Has to be an exact match on the register }
  8188. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  8189. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  8190. Break;
  8191. TestValMin := TestValMin * TestValMin;
  8192. TestValMax := TestValMax * TestValMax;
  8193. TestValSignedMax := TestValSignedMax * TestValMax;
  8194. end;
  8195. 3:
  8196. begin
  8197. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8198. { Has to be an exact match on the register }
  8199. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8200. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8201. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8202. { Is it in the negative range? }
  8203. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8204. Break;
  8205. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  8206. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  8207. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  8208. end;
  8209. else
  8210. Break;
  8211. end;
  8212. A_IDIV:
  8213. case taicpu(hp1).ops of
  8214. 3:
  8215. begin
  8216. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8217. { Has to be an exact match on the register }
  8218. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8219. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8220. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8221. { Is it in the negative range? }
  8222. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8223. Break;
  8224. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  8225. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  8226. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  8227. end;
  8228. else
  8229. Break;
  8230. end;
  8231. *)
  8232. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  8233. begin
  8234. { If there are no instructions in between, then we might be able to make a saving }
  8235. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  8236. Break;
  8237. { We have something like:
  8238. movzbw %dl,%dx
  8239. ...
  8240. movswl %dx,%edx
  8241. Change the latter to a zero-extension then enter the
  8242. A_MOVZX case branch.
  8243. }
  8244. {$ifdef x86_64}
  8245. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8246. begin
  8247. { this becomes a zero extension from 32-bit to 64-bit, but
  8248. the upper 32 bits are already zero, so just delete the
  8249. instruction }
  8250. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  8251. RemoveInstruction(hp1);
  8252. Result := True;
  8253. Exit;
  8254. end
  8255. else
  8256. {$endif x86_64}
  8257. begin
  8258. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  8259. taicpu(hp1).opcode := A_MOVZX;
  8260. {$ifdef x86_64}
  8261. case taicpu(hp1).opsize of
  8262. S_BQ:
  8263. begin
  8264. taicpu(hp1).opsize := S_BL;
  8265. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8266. end;
  8267. S_WQ:
  8268. begin
  8269. taicpu(hp1).opsize := S_WL;
  8270. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8271. end;
  8272. S_LQ:
  8273. begin
  8274. taicpu(hp1).opcode := A_MOV;
  8275. taicpu(hp1).opsize := S_L;
  8276. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8277. { In this instance, we need to break out because the
  8278. instruction is no longer MOVZX or MOVSXD }
  8279. Result := True;
  8280. Exit;
  8281. end;
  8282. else
  8283. ;
  8284. end;
  8285. {$endif x86_64}
  8286. Result := CompressInstructions;
  8287. Exit;
  8288. end;
  8289. end;
  8290. A_MOVZX:
  8291. begin
  8292. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  8293. Break;
  8294. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  8295. begin
  8296. if (InstrMax = -1) and
  8297. { Will return false if the second parameter isn't ThisReg
  8298. (can happen on -O2 and under) }
  8299. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8300. begin
  8301. { The two MOVZX instructions are adjacent, so remove the first one }
  8302. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  8303. RemoveCurrentP(p);
  8304. Result := True;
  8305. Exit;
  8306. end;
  8307. Break;
  8308. end;
  8309. Result := CompressInstructions;
  8310. Exit;
  8311. end;
  8312. else
  8313. { This includes ADC, SBB and IDIV }
  8314. Break;
  8315. end;
  8316. if not CheckOverflowConditions then
  8317. Break;
  8318. { Contains highest index (so instruction count - 1) }
  8319. Inc(InstrMax);
  8320. if InstrMax > High(InstrList) then
  8321. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  8322. InstrList[InstrMax] := taicpu(hp1);
  8323. end;
  8324. end;
  8325. {$pop}
  8326. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  8327. var
  8328. hp1 : tai;
  8329. begin
  8330. Result:=false;
  8331. if (taicpu(p).ops >= 2) and
  8332. ((taicpu(p).oper[0]^.typ = top_const) or
  8333. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  8334. (taicpu(p).oper[1]^.typ = top_reg) and
  8335. ((taicpu(p).ops = 2) or
  8336. ((taicpu(p).oper[2]^.typ = top_reg) and
  8337. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  8338. GetLastInstruction(p,hp1) and
  8339. MatchInstruction(hp1,A_MOV,[]) and
  8340. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8341. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8342. begin
  8343. TransferUsedRegs(TmpUsedRegs);
  8344. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  8345. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  8346. { change
  8347. mov reg1,reg2
  8348. imul y,reg2 to imul y,reg1,reg2 }
  8349. begin
  8350. taicpu(p).ops := 3;
  8351. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  8352. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  8353. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  8354. RemoveInstruction(hp1);
  8355. result:=true;
  8356. end;
  8357. end;
  8358. end;
  8359. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  8360. var
  8361. ThisLabel: TAsmLabel;
  8362. begin
  8363. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  8364. ThisLabel.decrefs;
  8365. taicpu(p).opcode := A_RET;
  8366. taicpu(p).is_jmp := false;
  8367. taicpu(p).ops := taicpu(ret_p).ops;
  8368. case taicpu(ret_p).ops of
  8369. 0:
  8370. taicpu(p).clearop(0);
  8371. 1:
  8372. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  8373. else
  8374. internalerror(2016041301);
  8375. end;
  8376. { If the original label is now dead, it might turn out that the label
  8377. immediately follows p. As a result, everything beyond it, which will
  8378. be just some final register configuration and a RET instruction, is
  8379. now dead code. [Kit] }
  8380. { NOTE: This is much faster than introducing a OptPass2RET routine and
  8381. running RemoveDeadCodeAfterJump for each RET instruction, because
  8382. this optimisation rarely happens and most RETs appear at the end of
  8383. routines where there is nothing that can be stripped. [Kit] }
  8384. if not ThisLabel.is_used then
  8385. RemoveDeadCodeAfterJump(p);
  8386. end;
  8387. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  8388. var
  8389. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  8390. Unconditional, PotentialModified: Boolean;
  8391. OperPtr: POper;
  8392. NewRef: TReference;
  8393. InstrList: array of taicpu;
  8394. InstrMax, Index: Integer;
  8395. const
  8396. {$ifdef DEBUG_AOPTCPU}
  8397. SNoFlags: shortstring = ' so the flags aren''t modified';
  8398. {$else DEBUG_AOPTCPU}
  8399. SNoFlags = '';
  8400. {$endif DEBUG_AOPTCPU}
  8401. begin
  8402. Result:=false;
  8403. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  8404. begin
  8405. if MatchInstruction(hp1, A_TEST, [S_B]) and
  8406. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8407. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  8408. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  8409. GetNextInstruction(hp1, hp2) and
  8410. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  8411. { Change from: To:
  8412. set(C) %reg j(~C) label
  8413. test %reg,%reg/cmp $0,%reg
  8414. je label
  8415. set(C) %reg j(C) label
  8416. test %reg,%reg/cmp $0,%reg
  8417. jne label
  8418. (Also do something similar with sete/setne instead of je/jne)
  8419. }
  8420. begin
  8421. { Before we do anything else, we need to check the instructions
  8422. in between SETcc and TEST to make sure they don't modify the
  8423. FLAGS register - if -O2 or under, there won't be any
  8424. instructions between SET and TEST }
  8425. TransferUsedRegs(TmpUsedRegs);
  8426. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8427. if (cs_opt_level3 in current_settings.optimizerswitches) then
  8428. begin
  8429. next := p;
  8430. SetLength(InstrList, 0);
  8431. InstrMax := -1;
  8432. PotentialModified := False;
  8433. { Make a note of every instruction that modifies the FLAGS
  8434. register }
  8435. while GetNextInstruction(next, next) and (next <> hp1) do
  8436. begin
  8437. if next.typ <> ait_instruction then
  8438. { GetNextInstructionUsingReg should have returned False }
  8439. InternalError(2021051701);
  8440. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  8441. begin
  8442. case taicpu(next).opcode of
  8443. A_SETcc,
  8444. A_CMOVcc,
  8445. A_Jcc:
  8446. begin
  8447. if PotentialModified then
  8448. { Not safe because the flags were modified earlier }
  8449. Exit
  8450. else
  8451. { Condition is the same as the initial SETcc, so this is safe
  8452. (don't add to instruction list though) }
  8453. Continue;
  8454. end;
  8455. A_ADD:
  8456. begin
  8457. if (taicpu(next).opsize = S_B) or
  8458. { LEA doesn't support 8-bit operands }
  8459. (taicpu(next).oper[1]^.typ <> top_reg) or
  8460. { Must write to a register }
  8461. (taicpu(next).oper[0]^.typ = top_ref) then
  8462. { Require a constant or a register }
  8463. Exit;
  8464. PotentialModified := True;
  8465. end;
  8466. A_SUB:
  8467. begin
  8468. if (taicpu(next).opsize = S_B) or
  8469. { LEA doesn't support 8-bit operands }
  8470. (taicpu(next).oper[1]^.typ <> top_reg) or
  8471. { Must write to a register }
  8472. (taicpu(next).oper[0]^.typ <> top_const) or
  8473. (taicpu(next).oper[0]^.val = $80000000) then
  8474. { Can't subtract a register with LEA - also
  8475. check that the value isn't -2^31, as this
  8476. can't be negated }
  8477. Exit;
  8478. PotentialModified := True;
  8479. end;
  8480. A_SAL,
  8481. A_SHL:
  8482. begin
  8483. if (taicpu(next).opsize = S_B) or
  8484. { LEA doesn't support 8-bit operands }
  8485. (taicpu(next).oper[1]^.typ <> top_reg) or
  8486. { Must write to a register }
  8487. (taicpu(next).oper[0]^.typ <> top_const) or
  8488. (taicpu(next).oper[0]^.val < 0) or
  8489. (taicpu(next).oper[0]^.val > 3) then
  8490. Exit;
  8491. PotentialModified := True;
  8492. end;
  8493. A_IMUL:
  8494. begin
  8495. if (taicpu(next).ops <> 3) or
  8496. (taicpu(next).oper[1]^.typ <> top_reg) or
  8497. { Must write to a register }
  8498. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  8499. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  8500. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  8501. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  8502. Exit
  8503. else
  8504. PotentialModified := True;
  8505. end;
  8506. else
  8507. { Don't know how to change this, so abort }
  8508. Exit;
  8509. end;
  8510. { Contains highest index (so instruction count - 1) }
  8511. Inc(InstrMax);
  8512. if InstrMax > High(InstrList) then
  8513. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  8514. InstrList[InstrMax] := taicpu(next);
  8515. end;
  8516. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  8517. end;
  8518. if not Assigned(next) or (next <> hp1) then
  8519. { It should be equal to hp1 }
  8520. InternalError(2021051702);
  8521. { Cycle through each instruction and check to see if we can
  8522. change them to versions that don't modify the flags }
  8523. if (InstrMax >= 0) then
  8524. begin
  8525. for Index := 0 to InstrMax do
  8526. case InstrList[Index].opcode of
  8527. A_ADD:
  8528. begin
  8529. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  8530. InstrList[Index].opcode := A_LEA;
  8531. reference_reset(NewRef, 1, []);
  8532. NewRef.base := InstrList[Index].oper[1]^.reg;
  8533. if InstrList[Index].oper[0]^.typ = top_reg then
  8534. begin
  8535. NewRef.index := InstrList[Index].oper[0]^.reg;
  8536. NewRef.scalefactor := 1;
  8537. end
  8538. else
  8539. NewRef.offset := InstrList[Index].oper[0]^.val;
  8540. InstrList[Index].loadref(0, NewRef);
  8541. end;
  8542. A_SUB:
  8543. begin
  8544. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  8545. InstrList[Index].opcode := A_LEA;
  8546. reference_reset(NewRef, 1, []);
  8547. NewRef.base := InstrList[Index].oper[1]^.reg;
  8548. NewRef.offset := -InstrList[Index].oper[0]^.val;
  8549. InstrList[Index].loadref(0, NewRef);
  8550. end;
  8551. A_SHL,
  8552. A_SAL:
  8553. begin
  8554. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  8555. InstrList[Index].opcode := A_LEA;
  8556. reference_reset(NewRef, 1, []);
  8557. NewRef.index := InstrList[Index].oper[1]^.reg;
  8558. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  8559. InstrList[Index].loadref(0, NewRef);
  8560. end;
  8561. A_IMUL:
  8562. begin
  8563. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  8564. InstrList[Index].opcode := A_LEA;
  8565. reference_reset(NewRef, 1, []);
  8566. NewRef.index := InstrList[Index].oper[1]^.reg;
  8567. case InstrList[Index].oper[0]^.val of
  8568. 2, 4, 8:
  8569. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  8570. else {3, 5 and 9}
  8571. begin
  8572. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  8573. NewRef.base := InstrList[Index].oper[1]^.reg;
  8574. end;
  8575. end;
  8576. InstrList[Index].loadref(0, NewRef);
  8577. end;
  8578. else
  8579. InternalError(2021051710);
  8580. end;
  8581. end;
  8582. { Mark the FLAGS register as used across this whole block }
  8583. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  8584. end;
  8585. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  8586. JumpC := taicpu(hp2).condition;
  8587. Unconditional := False;
  8588. if conditions_equal(JumpC, C_E) then
  8589. SetC := inverse_cond(taicpu(p).condition)
  8590. else if conditions_equal(JumpC, C_NE) then
  8591. SetC := taicpu(p).condition
  8592. else
  8593. { We've got something weird here (and inefficent) }
  8594. begin
  8595. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  8596. SetC := C_NONE;
  8597. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  8598. if condition_in(C_AE, JumpC) then
  8599. Unconditional := True
  8600. else
  8601. { Not sure what to do with this jump - drop out }
  8602. Exit;
  8603. end;
  8604. RemoveInstruction(hp1);
  8605. if Unconditional then
  8606. MakeUnconditional(taicpu(hp2))
  8607. else
  8608. begin
  8609. if SetC = C_NONE then
  8610. InternalError(2018061402);
  8611. taicpu(hp2).SetCondition(SetC);
  8612. end;
  8613. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  8614. TmpUsedRegs }
  8615. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  8616. begin
  8617. RemoveCurrentp(p, hp2);
  8618. if taicpu(hp2).opcode = A_SETcc then
  8619. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  8620. else
  8621. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  8622. end
  8623. else
  8624. if taicpu(hp2).opcode = A_SETcc then
  8625. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  8626. else
  8627. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  8628. Result := True;
  8629. end
  8630. else if
  8631. { Make sure the instructions are adjacent }
  8632. (
  8633. not (cs_opt_level3 in current_settings.optimizerswitches) or
  8634. GetNextInstruction(p, hp1)
  8635. ) and
  8636. MatchInstruction(hp1, A_MOV, [S_B]) and
  8637. { Writing to memory is allowed }
  8638. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  8639. begin
  8640. {
  8641. Watch out for sequences such as:
  8642. set(c)b %regb
  8643. movb %regb,(ref)
  8644. movb $0,1(ref)
  8645. movb $0,2(ref)
  8646. movb $0,3(ref)
  8647. Much more efficient to turn it into:
  8648. movl $0,%regl
  8649. set(c)b %regb
  8650. movl %regl,(ref)
  8651. Or:
  8652. set(c)b %regb
  8653. movzbl %regb,%regl
  8654. movl %regl,(ref)
  8655. }
  8656. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  8657. GetNextInstruction(hp1, hp2) and
  8658. MatchInstruction(hp2, A_MOV, [S_B]) and
  8659. (taicpu(hp2).oper[1]^.typ = top_ref) and
  8660. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  8661. begin
  8662. { Don't do anything else except set Result to True }
  8663. end
  8664. else
  8665. begin
  8666. if taicpu(p).oper[0]^.typ = top_reg then
  8667. begin
  8668. TransferUsedRegs(TmpUsedRegs);
  8669. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8670. end;
  8671. { If it's not a register, it's a memory address }
  8672. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  8673. begin
  8674. { Even if the register is still in use, we can minimise the
  8675. pipeline stall by changing the MOV into another SETcc. }
  8676. taicpu(hp1).opcode := A_SETcc;
  8677. taicpu(hp1).condition := taicpu(p).condition;
  8678. if taicpu(hp1).oper[1]^.typ = top_ref then
  8679. begin
  8680. { Swapping the operand pointers like this is probably a
  8681. bit naughty, but it is far faster than using loadoper
  8682. to transfer the reference from oper[1] to oper[0] if
  8683. you take into account the extra procedure calls and
  8684. the memory allocation and deallocation required }
  8685. OperPtr := taicpu(hp1).oper[1];
  8686. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  8687. taicpu(hp1).oper[0] := OperPtr;
  8688. end
  8689. else
  8690. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  8691. taicpu(hp1).clearop(1);
  8692. taicpu(hp1).ops := 1;
  8693. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  8694. end
  8695. else
  8696. begin
  8697. if taicpu(hp1).oper[1]^.typ = top_reg then
  8698. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  8699. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  8700. RemoveInstruction(hp1);
  8701. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  8702. end
  8703. end;
  8704. Result := True;
  8705. end;
  8706. end;
  8707. end;
  8708. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  8709. var
  8710. hp1: tai;
  8711. Count: Integer;
  8712. OrigLabel: TAsmLabel;
  8713. begin
  8714. result := False;
  8715. { Sometimes, the optimisations below can permit this }
  8716. RemoveDeadCodeAfterJump(p);
  8717. 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
  8718. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  8719. begin
  8720. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8721. { Also a side-effect of optimisations }
  8722. if CollapseZeroDistJump(p, OrigLabel) then
  8723. begin
  8724. Result := True;
  8725. Exit;
  8726. end;
  8727. hp1 := GetLabelWithSym(OrigLabel);
  8728. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  8729. begin
  8730. case taicpu(hp1).opcode of
  8731. A_RET:
  8732. {
  8733. change
  8734. jmp .L1
  8735. ...
  8736. .L1:
  8737. ret
  8738. into
  8739. ret
  8740. }
  8741. begin
  8742. ConvertJumpToRET(p, hp1);
  8743. result:=true;
  8744. end;
  8745. { Check any kind of direct assignment instruction }
  8746. A_MOV,
  8747. A_MOVD,
  8748. A_MOVQ,
  8749. A_MOVSX,
  8750. {$ifdef x86_64}
  8751. A_MOVSXD,
  8752. {$endif x86_64}
  8753. A_MOVZX,
  8754. A_MOVAPS,
  8755. A_MOVUPS,
  8756. A_MOVSD,
  8757. A_MOVAPD,
  8758. A_MOVUPD,
  8759. A_MOVDQA,
  8760. A_MOVDQU,
  8761. A_VMOVSS,
  8762. A_VMOVAPS,
  8763. A_VMOVUPS,
  8764. A_VMOVSD,
  8765. A_VMOVAPD,
  8766. A_VMOVUPD,
  8767. A_VMOVDQA,
  8768. A_VMOVDQU:
  8769. if ((current_settings.optimizerswitches * [cs_opt_level3, cs_opt_size]) <> [cs_opt_size]) and
  8770. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  8771. begin
  8772. Result := True;
  8773. Exit;
  8774. end;
  8775. else
  8776. ;
  8777. end;
  8778. end;
  8779. end;
  8780. end;
  8781. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  8782. begin
  8783. CanBeCMOV:=assigned(p) and
  8784. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  8785. { we can't use cmov ref,reg because
  8786. ref could be nil and cmov still throws an exception
  8787. if ref=nil but the mov isn't done (FK)
  8788. or ((taicpu(p).oper[0]^.typ = top_ref) and
  8789. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  8790. }
  8791. (taicpu(p).oper[1]^.typ = top_reg) and
  8792. (
  8793. (taicpu(p).oper[0]^.typ = top_reg) or
  8794. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  8795. it is not expected that this can cause a seg. violation }
  8796. (
  8797. (taicpu(p).oper[0]^.typ = top_ref) and
  8798. IsRefSafe(taicpu(p).oper[0]^.ref)
  8799. )
  8800. );
  8801. end;
  8802. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  8803. var
  8804. hp1,hp2: tai;
  8805. {$ifndef i8086}
  8806. hp3,hp4,hpmov2, hp5: tai;
  8807. l : Longint;
  8808. condition : TAsmCond;
  8809. {$endif i8086}
  8810. carryadd_opcode : TAsmOp;
  8811. symbol: TAsmSymbol;
  8812. reg: tsuperregister;
  8813. increg, tmpreg: TRegister;
  8814. begin
  8815. result:=false;
  8816. if GetNextInstruction(p,hp1) and (hp1.typ=ait_instruction) then
  8817. begin
  8818. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8819. if (
  8820. (
  8821. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  8822. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  8823. (Taicpu(hp1).oper[0]^.val=1)
  8824. ) or
  8825. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  8826. ) and
  8827. GetNextInstruction(hp1,hp2) and
  8828. SkipAligns(hp2, hp2) and
  8829. (hp2.typ = ait_label) and
  8830. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  8831. { jb @@1 cmc
  8832. inc/dec operand --> adc/sbb operand,0
  8833. @@1:
  8834. ... and ...
  8835. jnb @@1
  8836. inc/dec operand --> adc/sbb operand,0
  8837. @@1: }
  8838. begin
  8839. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  8840. begin
  8841. case taicpu(hp1).opcode of
  8842. A_INC,
  8843. A_ADD:
  8844. carryadd_opcode:=A_ADC;
  8845. A_DEC,
  8846. A_SUB:
  8847. carryadd_opcode:=A_SBB;
  8848. else
  8849. InternalError(2021011001);
  8850. end;
  8851. Taicpu(p).clearop(0);
  8852. Taicpu(p).ops:=0;
  8853. Taicpu(p).is_jmp:=false;
  8854. Taicpu(p).opcode:=A_CMC;
  8855. Taicpu(p).condition:=C_NONE;
  8856. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  8857. Taicpu(hp1).ops:=2;
  8858. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  8859. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  8860. else
  8861. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  8862. Taicpu(hp1).loadconst(0,0);
  8863. Taicpu(hp1).opcode:=carryadd_opcode;
  8864. result:=true;
  8865. exit;
  8866. end
  8867. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  8868. begin
  8869. case taicpu(hp1).opcode of
  8870. A_INC,
  8871. A_ADD:
  8872. carryadd_opcode:=A_ADC;
  8873. A_DEC,
  8874. A_SUB:
  8875. carryadd_opcode:=A_SBB;
  8876. else
  8877. InternalError(2021011002);
  8878. end;
  8879. Taicpu(hp1).ops:=2;
  8880. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  8881. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  8882. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  8883. else
  8884. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  8885. Taicpu(hp1).loadconst(0,0);
  8886. Taicpu(hp1).opcode:=carryadd_opcode;
  8887. RemoveCurrentP(p, hp1);
  8888. result:=true;
  8889. exit;
  8890. end
  8891. {
  8892. jcc @@1 setcc tmpreg
  8893. inc/dec/add/sub operand -> (movzx tmpreg)
  8894. @@1: add/sub tmpreg,operand
  8895. While this increases code size slightly, it makes the code much faster if the
  8896. jump is unpredictable
  8897. }
  8898. else if not(cs_opt_size in current_settings.optimizerswitches) then
  8899. begin
  8900. { search for an available register which is volatile }
  8901. for reg in tcpuregisterset do
  8902. begin
  8903. if
  8904. {$if defined(i386) or defined(i8086)}
  8905. { Only use registers whose lowest 8-bits can Be accessed }
  8906. (reg in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) and
  8907. {$endif i386 or i8086}
  8908. (reg in paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption)) and
  8909. not(reg in UsedRegs[R_INTREGISTER].GetUsedRegs)
  8910. { We don't need to check if tmpreg is in hp1 or not, because
  8911. it will be marked as in use at p (if not, this is
  8912. indictive of a compiler bug). }
  8913. then
  8914. begin
  8915. TAsmLabel(symbol).decrefs;
  8916. increg := newreg(R_INTREGISTER,reg,R_SUBL);
  8917. Taicpu(p).clearop(0);
  8918. Taicpu(p).ops:=1;
  8919. Taicpu(p).is_jmp:=false;
  8920. Taicpu(p).opcode:=A_SETcc;
  8921. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  8922. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  8923. Taicpu(p).loadreg(0,increg);
  8924. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  8925. begin
  8926. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  8927. R_SUBW:
  8928. begin
  8929. tmpreg := newreg(R_INTREGISTER,reg,R_SUBW);
  8930. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  8931. end;
  8932. R_SUBD:
  8933. begin
  8934. tmpreg := newreg(R_INTREGISTER,reg,R_SUBD);
  8935. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  8936. end;
  8937. {$ifdef x86_64}
  8938. R_SUBQ:
  8939. begin
  8940. { MOVZX doesn't have a 64-bit variant, because
  8941. the 32-bit version implicitly zeroes the
  8942. upper 32-bits of the destination register }
  8943. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,
  8944. newreg(R_INTREGISTER,reg,R_SUBD));
  8945. tmpreg := newreg(R_INTREGISTER,reg,R_SUBQ);
  8946. end;
  8947. {$endif x86_64}
  8948. else
  8949. Internalerror(2020030601);
  8950. end;
  8951. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  8952. asml.InsertAfter(hp2,p);
  8953. end
  8954. else
  8955. tmpreg := increg;
  8956. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  8957. begin
  8958. Taicpu(hp1).ops:=2;
  8959. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  8960. end;
  8961. Taicpu(hp1).loadreg(0,tmpreg);
  8962. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  8963. Result := True;
  8964. { p is no longer a Jcc instruction, so exit }
  8965. Exit;
  8966. end;
  8967. end;
  8968. end;
  8969. end;
  8970. { Detect the following:
  8971. jmp<cond> @Lbl1
  8972. jmp @Lbl2
  8973. ...
  8974. @Lbl1:
  8975. ret
  8976. Change to:
  8977. jmp<inv_cond> @Lbl2
  8978. ret
  8979. }
  8980. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  8981. begin
  8982. hp2:=getlabelwithsym(TAsmLabel(symbol));
  8983. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  8984. MatchInstruction(hp2,A_RET,[S_NO]) then
  8985. begin
  8986. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  8987. { Change label address to that of the unconditional jump }
  8988. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  8989. TAsmLabel(symbol).DecRefs;
  8990. taicpu(hp1).opcode := A_RET;
  8991. taicpu(hp1).is_jmp := false;
  8992. taicpu(hp1).ops := taicpu(hp2).ops;
  8993. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  8994. case taicpu(hp2).ops of
  8995. 0:
  8996. taicpu(hp1).clearop(0);
  8997. 1:
  8998. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  8999. else
  9000. internalerror(2016041302);
  9001. end;
  9002. end;
  9003. {$ifndef i8086}
  9004. end
  9005. {
  9006. convert
  9007. j<c> .L1
  9008. mov 1,reg
  9009. jmp .L2
  9010. .L1
  9011. mov 0,reg
  9012. .L2
  9013. into
  9014. mov 0,reg
  9015. set<not(c)> reg
  9016. take care of alignment and that the mov 0,reg is not converted into a xor as this
  9017. would destroy the flag contents
  9018. }
  9019. else if MatchInstruction(hp1,A_MOV,[]) and
  9020. MatchOpType(taicpu(hp1),top_const,top_reg) and
  9021. {$ifdef i386}
  9022. (
  9023. { Under i386, ESI, EDI, EBP and ESP
  9024. don't have an 8-bit representation }
  9025. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  9026. ) and
  9027. {$endif i386}
  9028. (taicpu(hp1).oper[0]^.val=1) and
  9029. GetNextInstruction(hp1,hp2) and
  9030. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  9031. GetNextInstruction(hp2,hp3) and
  9032. { skip align }
  9033. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  9034. (hp3.typ=ait_label) and
  9035. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  9036. (tai_label(hp3).labsym.getrefs=1) and
  9037. GetNextInstruction(hp3,hp4) and
  9038. MatchInstruction(hp4,A_MOV,[]) and
  9039. MatchOpType(taicpu(hp4),top_const,top_reg) and
  9040. (taicpu(hp4).oper[0]^.val=0) and
  9041. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  9042. GetNextInstruction(hp4,hp5) and
  9043. (hp5.typ=ait_label) and
  9044. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  9045. (tai_label(hp5).labsym.getrefs=1) then
  9046. begin
  9047. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  9048. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  9049. { remove last label }
  9050. RemoveInstruction(hp5);
  9051. { remove second label }
  9052. RemoveInstruction(hp3);
  9053. { if align is present remove it }
  9054. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  9055. RemoveInstruction(hp3);
  9056. { remove jmp }
  9057. RemoveInstruction(hp2);
  9058. if taicpu(hp1).opsize=S_B then
  9059. RemoveInstruction(hp1)
  9060. else
  9061. taicpu(hp1).loadconst(0,0);
  9062. taicpu(hp4).opcode:=A_SETcc;
  9063. taicpu(hp4).opsize:=S_B;
  9064. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  9065. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  9066. taicpu(hp4).opercnt:=1;
  9067. taicpu(hp4).ops:=1;
  9068. taicpu(hp4).freeop(1);
  9069. RemoveCurrentP(p);
  9070. Result:=true;
  9071. exit;
  9072. end
  9073. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  9074. begin
  9075. { check for
  9076. jCC xxx
  9077. <several movs>
  9078. xxx:
  9079. }
  9080. l:=0;
  9081. while assigned(hp1) and
  9082. CanBeCMOV(hp1) and
  9083. { stop on labels }
  9084. not(hp1.typ=ait_label) do
  9085. begin
  9086. inc(l);
  9087. GetNextInstruction(hp1,hp1);
  9088. end;
  9089. if assigned(hp1) then
  9090. begin
  9091. if FindLabel(tasmlabel(symbol),hp1) then
  9092. begin
  9093. if (l<=4) and (l>0) then
  9094. begin
  9095. condition:=inverse_cond(taicpu(p).condition);
  9096. UpdateUsedRegs(tai(p.next));
  9097. GetNextInstruction(p,hp1);
  9098. repeat
  9099. if not Assigned(hp1) then
  9100. InternalError(2018062900);
  9101. taicpu(hp1).opcode:=A_CMOVcc;
  9102. taicpu(hp1).condition:=condition;
  9103. UpdateUsedRegs(tai(hp1.next));
  9104. GetNextInstruction(hp1,hp1);
  9105. until not(CanBeCMOV(hp1));
  9106. { Remember what hp1 is in case there's multiple aligns to get rid of }
  9107. hp2 := hp1;
  9108. repeat
  9109. if not Assigned(hp2) then
  9110. InternalError(2018062910);
  9111. case hp2.typ of
  9112. ait_label:
  9113. { What we expected - break out of the loop (it won't be a dead label at the top of
  9114. a cluster because that was optimised at an earlier stage) }
  9115. Break;
  9116. ait_align:
  9117. { Go to the next entry until a label is found (may be multiple aligns before it) }
  9118. begin
  9119. hp2 := tai(hp2.Next);
  9120. Continue;
  9121. end;
  9122. else
  9123. begin
  9124. { Might be a comment or temporary allocation entry }
  9125. if not (hp2.typ in SkipInstr) then
  9126. InternalError(2018062911);
  9127. hp2 := tai(hp2.Next);
  9128. Continue;
  9129. end;
  9130. end;
  9131. until False;
  9132. { Now we can safely decrement the reference count }
  9133. tasmlabel(symbol).decrefs;
  9134. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  9135. { Remove the original jump }
  9136. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  9137. UpdateUsedRegs(tai(hp2.next));
  9138. GetNextInstruction(hp2, p); { Instruction after the label }
  9139. { Remove the label if this is its final reference }
  9140. if (tasmlabel(symbol).getrefs=0) then
  9141. StripLabelFast(hp1);
  9142. if Assigned(p) then
  9143. result:=true;
  9144. exit;
  9145. end;
  9146. end
  9147. else
  9148. begin
  9149. { check further for
  9150. jCC xxx
  9151. <several movs 1>
  9152. jmp yyy
  9153. xxx:
  9154. <several movs 2>
  9155. yyy:
  9156. }
  9157. { hp2 points to jmp yyy }
  9158. hp2:=hp1;
  9159. { skip hp1 to xxx (or an align right before it) }
  9160. GetNextInstruction(hp1, hp1);
  9161. if assigned(hp2) and
  9162. assigned(hp1) and
  9163. (l<=3) and
  9164. (hp2.typ=ait_instruction) and
  9165. (taicpu(hp2).is_jmp) and
  9166. (taicpu(hp2).condition=C_None) and
  9167. { real label and jump, no further references to the
  9168. label are allowed }
  9169. (tasmlabel(symbol).getrefs=1) and
  9170. FindLabel(tasmlabel(symbol),hp1) then
  9171. begin
  9172. l:=0;
  9173. { skip hp1 to <several moves 2> }
  9174. if (hp1.typ = ait_align) then
  9175. GetNextInstruction(hp1, hp1);
  9176. GetNextInstruction(hp1, hpmov2);
  9177. hp1 := hpmov2;
  9178. while assigned(hp1) and
  9179. CanBeCMOV(hp1) do
  9180. begin
  9181. inc(l);
  9182. GetNextInstruction(hp1, hp1);
  9183. end;
  9184. { hp1 points to yyy (or an align right before it) }
  9185. hp3 := hp1;
  9186. if assigned(hp1) and
  9187. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  9188. begin
  9189. condition:=inverse_cond(taicpu(p).condition);
  9190. UpdateUsedRegs(tai(p.next));
  9191. GetNextInstruction(p,hp1);
  9192. repeat
  9193. taicpu(hp1).opcode:=A_CMOVcc;
  9194. taicpu(hp1).condition:=condition;
  9195. UpdateUsedRegs(tai(hp1.next));
  9196. GetNextInstruction(hp1,hp1);
  9197. until not(assigned(hp1)) or
  9198. not(CanBeCMOV(hp1));
  9199. condition:=inverse_cond(condition);
  9200. if GetLastInstruction(hpmov2,hp1) then
  9201. UpdateUsedRegs(tai(hp1.next));
  9202. hp1 := hpmov2;
  9203. { hp1 is now at <several movs 2> }
  9204. while Assigned(hp1) and CanBeCMOV(hp1) do
  9205. begin
  9206. taicpu(hp1).opcode:=A_CMOVcc;
  9207. taicpu(hp1).condition:=condition;
  9208. UpdateUsedRegs(tai(hp1.next));
  9209. GetNextInstruction(hp1,hp1);
  9210. end;
  9211. hp1 := p;
  9212. { Get first instruction after label }
  9213. UpdateUsedRegs(tai(hp3.next));
  9214. GetNextInstruction(hp3, p);
  9215. if assigned(p) and (hp3.typ = ait_align) then
  9216. GetNextInstruction(p, p);
  9217. { Don't dereference yet, as doing so will cause
  9218. GetNextInstruction to skip the label and
  9219. optional align marker. [Kit] }
  9220. GetNextInstruction(hp2, hp4);
  9221. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  9222. { remove jCC }
  9223. RemoveInstruction(hp1);
  9224. { Now we can safely decrement it }
  9225. tasmlabel(symbol).decrefs;
  9226. { Remove label xxx (it will have a ref of zero due to the initial check }
  9227. StripLabelFast(hp4);
  9228. { remove jmp }
  9229. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  9230. RemoveInstruction(hp2);
  9231. { As before, now we can safely decrement it }
  9232. tasmlabel(symbol).decrefs;
  9233. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  9234. if tasmlabel(symbol).getrefs = 0 then
  9235. StripLabelFast(hp3);
  9236. if Assigned(p) then
  9237. result:=true;
  9238. exit;
  9239. end;
  9240. end;
  9241. end;
  9242. end;
  9243. {$endif i8086}
  9244. end;
  9245. end;
  9246. end;
  9247. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  9248. var
  9249. hp1,hp2,hp3: tai;
  9250. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  9251. NewSize: TOpSize;
  9252. NewRegSize: TSubRegister;
  9253. Limit: TCgInt;
  9254. SwapOper: POper;
  9255. begin
  9256. result:=false;
  9257. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  9258. GetNextInstruction(p,hp1) and
  9259. (hp1.typ = ait_instruction);
  9260. if reg_and_hp1_is_instr and
  9261. (
  9262. (taicpu(hp1).opcode <> A_LEA) or
  9263. { If the LEA instruction can be converted into an arithmetic instruction,
  9264. it may be possible to then fold it. }
  9265. (
  9266. { If the flags register is in use, don't change the instruction
  9267. to an ADD otherwise this will scramble the flags. [Kit] }
  9268. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  9269. ConvertLEA(taicpu(hp1))
  9270. )
  9271. ) and
  9272. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  9273. GetNextInstruction(hp1,hp2) and
  9274. MatchInstruction(hp2,A_MOV,[]) and
  9275. (taicpu(hp2).oper[0]^.typ = top_reg) and
  9276. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  9277. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  9278. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  9279. {$ifdef i386}
  9280. { not all registers have byte size sub registers on i386 }
  9281. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  9282. {$endif i386}
  9283. (((taicpu(hp1).ops=2) and
  9284. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  9285. ((taicpu(hp1).ops=1) and
  9286. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  9287. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  9288. begin
  9289. { change movsX/movzX reg/ref, reg2
  9290. add/sub/or/... reg3/$const, reg2
  9291. mov reg2 reg/ref
  9292. to add/sub/or/... reg3/$const, reg/ref }
  9293. { by example:
  9294. movswl %si,%eax movswl %si,%eax p
  9295. decl %eax addl %edx,%eax hp1
  9296. movw %ax,%si movw %ax,%si hp2
  9297. ->
  9298. movswl %si,%eax movswl %si,%eax p
  9299. decw %eax addw %edx,%eax hp1
  9300. movw %ax,%si movw %ax,%si hp2
  9301. }
  9302. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  9303. {
  9304. ->
  9305. movswl %si,%eax movswl %si,%eax p
  9306. decw %si addw %dx,%si hp1
  9307. movw %ax,%si movw %ax,%si hp2
  9308. }
  9309. case taicpu(hp1).ops of
  9310. 1:
  9311. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  9312. 2:
  9313. begin
  9314. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  9315. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9316. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  9317. end;
  9318. else
  9319. internalerror(2008042702);
  9320. end;
  9321. {
  9322. ->
  9323. decw %si addw %dx,%si p
  9324. }
  9325. DebugMsg(SPeepholeOptimization + 'var3',p);
  9326. RemoveCurrentP(p, hp1);
  9327. RemoveInstruction(hp2);
  9328. Result := True;
  9329. Exit;
  9330. end;
  9331. if reg_and_hp1_is_instr and
  9332. (taicpu(hp1).opcode = A_MOV) and
  9333. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9334. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  9335. {$ifdef x86_64}
  9336. { check for implicit extension to 64 bit }
  9337. or
  9338. ((taicpu(p).opsize in [S_BL,S_WL]) and
  9339. (taicpu(hp1).opsize=S_Q) and
  9340. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  9341. )
  9342. {$endif x86_64}
  9343. )
  9344. then
  9345. begin
  9346. { change
  9347. movx %reg1,%reg2
  9348. mov %reg2,%reg3
  9349. dealloc %reg2
  9350. into
  9351. movx %reg,%reg3
  9352. }
  9353. TransferUsedRegs(TmpUsedRegs);
  9354. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9355. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  9356. begin
  9357. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  9358. {$ifdef x86_64}
  9359. if (taicpu(p).opsize in [S_BL,S_WL]) and
  9360. (taicpu(hp1).opsize=S_Q) then
  9361. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  9362. else
  9363. {$endif x86_64}
  9364. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  9365. RemoveInstruction(hp1);
  9366. Result := True;
  9367. Exit;
  9368. end;
  9369. end;
  9370. if reg_and_hp1_is_instr and
  9371. ((taicpu(hp1).opcode=A_MOV) or
  9372. (taicpu(hp1).opcode=A_ADD) or
  9373. (taicpu(hp1).opcode=A_SUB) or
  9374. (taicpu(hp1).opcode=A_CMP) or
  9375. (taicpu(hp1).opcode=A_OR) or
  9376. (taicpu(hp1).opcode=A_XOR) or
  9377. (taicpu(hp1).opcode=A_AND)
  9378. ) and
  9379. (taicpu(hp1).oper[1]^.typ = top_reg) then
  9380. begin
  9381. AndTest := (taicpu(hp1).opcode=A_AND) and
  9382. GetNextInstruction(hp1, hp2) and
  9383. (hp2.typ = ait_instruction) and
  9384. (
  9385. (
  9386. (taicpu(hp2).opcode=A_TEST) and
  9387. (
  9388. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  9389. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  9390. (
  9391. { If the AND and TEST instructions share a constant, this is also valid }
  9392. (taicpu(hp1).oper[0]^.typ = top_const) and
  9393. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  9394. )
  9395. ) and
  9396. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  9397. ) or
  9398. (
  9399. (taicpu(hp2).opcode=A_CMP) and
  9400. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  9401. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  9402. )
  9403. );
  9404. { change
  9405. movx (oper),%reg2
  9406. and $x,%reg2
  9407. test %reg2,%reg2
  9408. dealloc %reg2
  9409. into
  9410. op %reg1,%reg3
  9411. if the second op accesses only the bits stored in reg1
  9412. }
  9413. if ((taicpu(p).oper[0]^.typ=top_reg) or
  9414. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  9415. (taicpu(hp1).oper[0]^.typ = top_const) and
  9416. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  9417. AndTest then
  9418. begin
  9419. { Check if the AND constant is in range }
  9420. case taicpu(p).opsize of
  9421. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9422. begin
  9423. NewSize := S_B;
  9424. Limit := $FF;
  9425. end;
  9426. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9427. begin
  9428. NewSize := S_W;
  9429. Limit := $FFFF;
  9430. end;
  9431. {$ifdef x86_64}
  9432. S_LQ:
  9433. begin
  9434. NewSize := S_L;
  9435. Limit := $FFFFFFFF;
  9436. end;
  9437. {$endif x86_64}
  9438. else
  9439. InternalError(2021120303);
  9440. end;
  9441. if (
  9442. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  9443. { Check for negative operands }
  9444. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  9445. ) and
  9446. GetNextInstruction(hp2,hp3) and
  9447. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  9448. (taicpu(hp3).condition in [C_E,C_NE]) then
  9449. begin
  9450. TransferUsedRegs(TmpUsedRegs);
  9451. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9452. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9453. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  9454. begin
  9455. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  9456. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  9457. taicpu(hp1).opcode := A_TEST;
  9458. taicpu(hp1).opsize := NewSize;
  9459. RemoveInstruction(hp2);
  9460. RemoveCurrentP(p, hp1);
  9461. Result:=true;
  9462. exit;
  9463. end;
  9464. end;
  9465. end;
  9466. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  9467. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  9468. (taicpu(hp1).opsize=S_B)) or
  9469. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  9470. (taicpu(hp1).opsize=S_W))
  9471. {$ifdef x86_64}
  9472. or ((taicpu(p).opsize=S_LQ) and
  9473. (taicpu(hp1).opsize=S_L))
  9474. {$endif x86_64}
  9475. ) and
  9476. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  9477. begin
  9478. { change
  9479. movx %reg1,%reg2
  9480. op %reg2,%reg3
  9481. dealloc %reg2
  9482. into
  9483. op %reg1,%reg3
  9484. if the second op accesses only the bits stored in reg1
  9485. }
  9486. TransferUsedRegs(TmpUsedRegs);
  9487. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9488. if AndTest then
  9489. begin
  9490. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  9491. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  9492. end
  9493. else
  9494. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  9495. if not RegUsed then
  9496. begin
  9497. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  9498. if taicpu(p).oper[0]^.typ=top_reg then
  9499. begin
  9500. case taicpu(hp1).opsize of
  9501. S_B:
  9502. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  9503. S_W:
  9504. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  9505. S_L:
  9506. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  9507. else
  9508. Internalerror(2020102301);
  9509. end;
  9510. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  9511. end
  9512. else
  9513. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  9514. RemoveCurrentP(p);
  9515. if AndTest then
  9516. RemoveInstruction(hp2);
  9517. result:=true;
  9518. exit;
  9519. end;
  9520. end
  9521. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  9522. (
  9523. { Bitwise operations only }
  9524. (taicpu(hp1).opcode=A_AND) or
  9525. (taicpu(hp1).opcode=A_TEST) or
  9526. (
  9527. (taicpu(hp1).oper[0]^.typ = top_const) and
  9528. (
  9529. (taicpu(hp1).opcode=A_OR) or
  9530. (taicpu(hp1).opcode=A_XOR)
  9531. )
  9532. )
  9533. ) and
  9534. (
  9535. (taicpu(hp1).oper[0]^.typ = top_const) or
  9536. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  9537. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  9538. ) then
  9539. begin
  9540. { change
  9541. movx %reg2,%reg2
  9542. op const,%reg2
  9543. into
  9544. op const,%reg2 (smaller version)
  9545. movx %reg2,%reg2
  9546. also change
  9547. movx %reg1,%reg2
  9548. and/test (oper),%reg2
  9549. dealloc %reg2
  9550. into
  9551. and/test (oper),%reg1
  9552. }
  9553. case taicpu(p).opsize of
  9554. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9555. begin
  9556. NewSize := S_B;
  9557. NewRegSize := R_SUBL;
  9558. Limit := $FF;
  9559. end;
  9560. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9561. begin
  9562. NewSize := S_W;
  9563. NewRegSize := R_SUBW;
  9564. Limit := $FFFF;
  9565. end;
  9566. {$ifdef x86_64}
  9567. S_LQ:
  9568. begin
  9569. NewSize := S_L;
  9570. NewRegSize := R_SUBD;
  9571. Limit := $FFFFFFFF;
  9572. end;
  9573. {$endif x86_64}
  9574. else
  9575. Internalerror(2021120302);
  9576. end;
  9577. TransferUsedRegs(TmpUsedRegs);
  9578. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9579. if AndTest then
  9580. begin
  9581. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  9582. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  9583. end
  9584. else
  9585. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  9586. if
  9587. (
  9588. (taicpu(p).opcode = A_MOVZX) and
  9589. (
  9590. (taicpu(hp1).opcode=A_AND) or
  9591. (taicpu(hp1).opcode=A_TEST)
  9592. ) and
  9593. not (
  9594. { If both are references, then the final instruction will have
  9595. both operands as references, which is not allowed }
  9596. (taicpu(p).oper[0]^.typ = top_ref) and
  9597. (taicpu(hp1).oper[0]^.typ = top_ref)
  9598. ) and
  9599. not RegUsed
  9600. ) or
  9601. (
  9602. (
  9603. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  9604. not RegUsed
  9605. ) and
  9606. (taicpu(p).oper[0]^.typ = top_reg) and
  9607. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  9608. (taicpu(hp1).oper[0]^.typ = top_const) and
  9609. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  9610. ) then
  9611. begin
  9612. {$if defined(i386) or defined(i8086)}
  9613. { If the target size is 8-bit, make sure we can actually encode it }
  9614. 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
  9615. Exit;
  9616. {$endif i386 or i8086}
  9617. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  9618. taicpu(hp1).opsize := NewSize;
  9619. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  9620. if AndTest then
  9621. begin
  9622. RemoveInstruction(hp2);
  9623. if not RegUsed then
  9624. begin
  9625. taicpu(hp1).opcode := A_TEST;
  9626. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  9627. begin
  9628. { Make sure the reference is the second operand }
  9629. SwapOper := taicpu(hp1).oper[0];
  9630. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  9631. taicpu(hp1).oper[1] := SwapOper;
  9632. end;
  9633. end;
  9634. end;
  9635. case taicpu(hp1).oper[0]^.typ of
  9636. top_reg:
  9637. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  9638. top_const:
  9639. { For the AND/TEST case }
  9640. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  9641. else
  9642. ;
  9643. end;
  9644. if RegUsed then
  9645. begin
  9646. AsmL.Remove(p);
  9647. AsmL.InsertAfter(p, hp1);
  9648. p := hp1;
  9649. end
  9650. else
  9651. RemoveCurrentP(p, hp1);
  9652. result:=true;
  9653. exit;
  9654. end;
  9655. end;
  9656. end;
  9657. if reg_and_hp1_is_instr and
  9658. (taicpu(p).oper[0]^.typ = top_reg) and
  9659. (
  9660. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  9661. ) and
  9662. (taicpu(hp1).oper[0]^.typ = top_const) and
  9663. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  9664. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  9665. { Minimum shift value allowed is the bit difference between the sizes }
  9666. (taicpu(hp1).oper[0]^.val >=
  9667. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  9668. 8 * (
  9669. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  9670. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  9671. )
  9672. ) then
  9673. begin
  9674. { For:
  9675. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  9676. shl/sal ##, %reg1
  9677. Remove the movsx/movzx instruction if the shift overwrites the
  9678. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  9679. }
  9680. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  9681. RemoveCurrentP(p, hp1);
  9682. Result := True;
  9683. Exit;
  9684. end
  9685. else if reg_and_hp1_is_instr and
  9686. (taicpu(p).oper[0]^.typ = top_reg) and
  9687. (
  9688. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  9689. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  9690. ) and
  9691. (taicpu(hp1).oper[0]^.typ = top_const) and
  9692. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  9693. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  9694. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  9695. (taicpu(hp1).oper[0]^.val <
  9696. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  9697. 8 * (
  9698. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  9699. )
  9700. ) then
  9701. begin
  9702. { For:
  9703. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  9704. sar ##, %reg1 shr ##, %reg1
  9705. Move the shift to before the movx instruction if the shift value
  9706. is not too large.
  9707. }
  9708. asml.Remove(hp1);
  9709. asml.InsertBefore(hp1, p);
  9710. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  9711. case taicpu(p).opsize of
  9712. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  9713. taicpu(hp1).opsize := S_B;
  9714. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  9715. taicpu(hp1).opsize := S_W;
  9716. {$ifdef x86_64}
  9717. S_LQ:
  9718. taicpu(hp1).opsize := S_L;
  9719. {$endif}
  9720. else
  9721. InternalError(2020112401);
  9722. end;
  9723. if (taicpu(hp1).opcode = A_SHR) then
  9724. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  9725. else
  9726. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  9727. Result := True;
  9728. end;
  9729. if reg_and_hp1_is_instr and
  9730. (taicpu(p).oper[0]^.typ = top_reg) and
  9731. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  9732. (
  9733. (taicpu(hp1).opcode = taicpu(p).opcode)
  9734. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  9735. {$ifdef x86_64}
  9736. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  9737. {$endif x86_64}
  9738. ) then
  9739. begin
  9740. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  9741. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  9742. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  9743. begin
  9744. {
  9745. For example:
  9746. movzbw %al,%ax
  9747. movzwl %ax,%eax
  9748. Compress into:
  9749. movzbl %al,%eax
  9750. }
  9751. RegUsed := False;
  9752. case taicpu(p).opsize of
  9753. S_BW:
  9754. case taicpu(hp1).opsize of
  9755. S_WL:
  9756. begin
  9757. taicpu(p).opsize := S_BL;
  9758. RegUsed := True;
  9759. end;
  9760. {$ifdef x86_64}
  9761. S_WQ:
  9762. begin
  9763. if taicpu(p).opcode = A_MOVZX then
  9764. begin
  9765. taicpu(p).opsize := S_BL;
  9766. { 64-bit zero extension is implicit, so change to the 32-bit register }
  9767. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9768. end
  9769. else
  9770. taicpu(p).opsize := S_BQ;
  9771. RegUsed := True;
  9772. end;
  9773. {$endif x86_64}
  9774. else
  9775. ;
  9776. end;
  9777. {$ifdef x86_64}
  9778. S_BL:
  9779. case taicpu(hp1).opsize of
  9780. S_LQ:
  9781. begin
  9782. if taicpu(p).opcode = A_MOVZX then
  9783. begin
  9784. taicpu(p).opsize := S_BL;
  9785. { 64-bit zero extension is implicit, so change to the 32-bit register }
  9786. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9787. end
  9788. else
  9789. taicpu(p).opsize := S_BQ;
  9790. RegUsed := True;
  9791. end;
  9792. else
  9793. ;
  9794. end;
  9795. S_WL:
  9796. case taicpu(hp1).opsize of
  9797. S_LQ:
  9798. begin
  9799. if taicpu(p).opcode = A_MOVZX then
  9800. begin
  9801. taicpu(p).opsize := S_WL;
  9802. { 64-bit zero extension is implicit, so change to the 32-bit register }
  9803. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9804. end
  9805. else
  9806. taicpu(p).opsize := S_WQ;
  9807. RegUsed := True;
  9808. end;
  9809. else
  9810. ;
  9811. end;
  9812. {$endif x86_64}
  9813. else
  9814. ;
  9815. end;
  9816. if RegUsed then
  9817. begin
  9818. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  9819. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  9820. RemoveInstruction(hp1);
  9821. Result := True;
  9822. Exit;
  9823. end;
  9824. end;
  9825. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  9826. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  9827. GetNextInstruction(hp1, hp2) and
  9828. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  9829. (
  9830. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  9831. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  9832. {$ifdef x86_64}
  9833. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  9834. {$endif x86_64}
  9835. ) and
  9836. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  9837. (
  9838. (
  9839. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9840. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  9841. ) or
  9842. (
  9843. { Only allow the operands in reverse order for TEST instructions }
  9844. (taicpu(hp2).opcode = A_TEST) and
  9845. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  9846. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  9847. )
  9848. ) then
  9849. begin
  9850. {
  9851. For example:
  9852. movzbl %al,%eax
  9853. movzbl (ref),%edx
  9854. andl %edx,%eax
  9855. (%edx deallocated)
  9856. Change to:
  9857. andb (ref),%al
  9858. movzbl %al,%eax
  9859. Rules are:
  9860. - First two instructions have the same opcode and opsize
  9861. - First instruction's operands are the same super-register
  9862. - Second instruction operates on a different register
  9863. - Third instruction is AND, OR, XOR or TEST
  9864. - Third instruction's operands are the destination registers of the first two instructions
  9865. - Third instruction writes to the destination register of the first instruction (except with TEST)
  9866. - Second instruction's destination register is deallocated afterwards
  9867. }
  9868. TransferUsedRegs(TmpUsedRegs);
  9869. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9870. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9871. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  9872. begin
  9873. case taicpu(p).opsize of
  9874. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9875. NewSize := S_B;
  9876. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9877. NewSize := S_W;
  9878. {$ifdef x86_64}
  9879. S_LQ:
  9880. NewSize := S_L;
  9881. {$endif x86_64}
  9882. else
  9883. InternalError(2021120301);
  9884. end;
  9885. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  9886. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  9887. taicpu(hp2).opsize := NewSize;
  9888. RemoveInstruction(hp1);
  9889. { With TEST, it's best to keep the MOVX instruction at the top }
  9890. if (taicpu(hp2).opcode <> A_TEST) then
  9891. begin
  9892. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  9893. asml.Remove(p);
  9894. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  9895. asml.InsertAfter(p, hp2);
  9896. p := hp2;
  9897. end
  9898. else
  9899. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  9900. Result := True;
  9901. Exit;
  9902. end;
  9903. end;
  9904. end;
  9905. if taicpu(p).opcode=A_MOVZX then
  9906. begin
  9907. { removes superfluous And's after movzx's }
  9908. if reg_and_hp1_is_instr and
  9909. (taicpu(hp1).opcode = A_AND) and
  9910. MatchOpType(taicpu(hp1),top_const,top_reg) and
  9911. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  9912. {$ifdef x86_64}
  9913. { check for implicit extension to 64 bit }
  9914. or
  9915. ((taicpu(p).opsize in [S_BL,S_WL]) and
  9916. (taicpu(hp1).opsize=S_Q) and
  9917. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  9918. )
  9919. {$endif x86_64}
  9920. )
  9921. then
  9922. begin
  9923. case taicpu(p).opsize Of
  9924. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9925. if (taicpu(hp1).oper[0]^.val = $ff) then
  9926. begin
  9927. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  9928. RemoveInstruction(hp1);
  9929. Result:=true;
  9930. exit;
  9931. end;
  9932. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9933. if (taicpu(hp1).oper[0]^.val = $ffff) then
  9934. begin
  9935. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  9936. RemoveInstruction(hp1);
  9937. Result:=true;
  9938. exit;
  9939. end;
  9940. {$ifdef x86_64}
  9941. S_LQ:
  9942. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  9943. begin
  9944. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  9945. RemoveInstruction(hp1);
  9946. Result:=true;
  9947. exit;
  9948. end;
  9949. {$endif x86_64}
  9950. else
  9951. ;
  9952. end;
  9953. { we cannot get rid of the and, but can we get rid of the movz ?}
  9954. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  9955. begin
  9956. case taicpu(p).opsize Of
  9957. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9958. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  9959. begin
  9960. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  9961. RemoveCurrentP(p,hp1);
  9962. Result:=true;
  9963. exit;
  9964. end;
  9965. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9966. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  9967. begin
  9968. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  9969. RemoveCurrentP(p,hp1);
  9970. Result:=true;
  9971. exit;
  9972. end;
  9973. {$ifdef x86_64}
  9974. S_LQ:
  9975. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  9976. begin
  9977. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  9978. RemoveCurrentP(p,hp1);
  9979. Result:=true;
  9980. exit;
  9981. end;
  9982. {$endif x86_64}
  9983. else
  9984. ;
  9985. end;
  9986. end;
  9987. end;
  9988. { changes some movzx constructs to faster synonyms (all examples
  9989. are given with eax/ax, but are also valid for other registers)}
  9990. if MatchOpType(taicpu(p),top_reg,top_reg) then
  9991. begin
  9992. case taicpu(p).opsize of
  9993. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  9994. (the machine code is equivalent to movzbl %al,%eax), but the
  9995. code generator still generates that assembler instruction and
  9996. it is silently converted. This should probably be checked.
  9997. [Kit] }
  9998. S_BW:
  9999. begin
  10000. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10001. (
  10002. not IsMOVZXAcceptable
  10003. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  10004. or (
  10005. (cs_opt_size in current_settings.optimizerswitches) and
  10006. (taicpu(p).oper[1]^.reg = NR_AX)
  10007. )
  10008. ) then
  10009. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  10010. begin
  10011. DebugMsg(SPeepholeOptimization + 'var7',p);
  10012. taicpu(p).opcode := A_AND;
  10013. taicpu(p).changeopsize(S_W);
  10014. taicpu(p).loadConst(0,$ff);
  10015. Result := True;
  10016. end
  10017. else if not IsMOVZXAcceptable and
  10018. GetNextInstruction(p, hp1) and
  10019. (tai(hp1).typ = ait_instruction) and
  10020. (taicpu(hp1).opcode = A_AND) and
  10021. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10022. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10023. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  10024. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  10025. begin
  10026. DebugMsg(SPeepholeOptimization + 'var8',p);
  10027. taicpu(p).opcode := A_MOV;
  10028. taicpu(p).changeopsize(S_W);
  10029. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  10030. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10031. Result := True;
  10032. end;
  10033. end;
  10034. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  10035. S_BL:
  10036. begin
  10037. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10038. (
  10039. not IsMOVZXAcceptable
  10040. { and $0xff,%eax has a smaller encoding but risks a partial write penalty }
  10041. or (
  10042. (cs_opt_size in current_settings.optimizerswitches) and
  10043. (taicpu(p).oper[1]^.reg = NR_EAX)
  10044. )
  10045. ) then
  10046. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  10047. begin
  10048. DebugMsg(SPeepholeOptimization + 'var9',p);
  10049. taicpu(p).opcode := A_AND;
  10050. taicpu(p).changeopsize(S_L);
  10051. taicpu(p).loadConst(0,$ff);
  10052. Result := True;
  10053. end
  10054. else if not IsMOVZXAcceptable and
  10055. GetNextInstruction(p, hp1) and
  10056. (tai(hp1).typ = ait_instruction) and
  10057. (taicpu(hp1).opcode = A_AND) and
  10058. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10059. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10060. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  10061. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  10062. begin
  10063. DebugMsg(SPeepholeOptimization + 'var10',p);
  10064. taicpu(p).opcode := A_MOV;
  10065. taicpu(p).changeopsize(S_L);
  10066. { do not use R_SUBWHOLE
  10067. as movl %rdx,%eax
  10068. is invalid in assembler PM }
  10069. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10070. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10071. Result := True;
  10072. end;
  10073. end;
  10074. {$endif i8086}
  10075. S_WL:
  10076. if not IsMOVZXAcceptable then
  10077. begin
  10078. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  10079. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  10080. begin
  10081. DebugMsg(SPeepholeOptimization + 'var11',p);
  10082. taicpu(p).opcode := A_AND;
  10083. taicpu(p).changeopsize(S_L);
  10084. taicpu(p).loadConst(0,$ffff);
  10085. Result := True;
  10086. end
  10087. else if GetNextInstruction(p, hp1) and
  10088. (tai(hp1).typ = ait_instruction) and
  10089. (taicpu(hp1).opcode = A_AND) and
  10090. (taicpu(hp1).oper[0]^.typ = top_const) and
  10091. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10092. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10093. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  10094. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  10095. begin
  10096. DebugMsg(SPeepholeOptimization + 'var12',p);
  10097. taicpu(p).opcode := A_MOV;
  10098. taicpu(p).changeopsize(S_L);
  10099. { do not use R_SUBWHOLE
  10100. as movl %rdx,%eax
  10101. is invalid in assembler PM }
  10102. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10103. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10104. Result := True;
  10105. end;
  10106. end;
  10107. else
  10108. InternalError(2017050705);
  10109. end;
  10110. end
  10111. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  10112. begin
  10113. if GetNextInstruction(p, hp1) and
  10114. (tai(hp1).typ = ait_instruction) and
  10115. (taicpu(hp1).opcode = A_AND) and
  10116. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10117. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10118. begin
  10119. //taicpu(p).opcode := A_MOV;
  10120. case taicpu(p).opsize Of
  10121. S_BL:
  10122. begin
  10123. DebugMsg(SPeepholeOptimization + 'var13',p);
  10124. taicpu(hp1).changeopsize(S_L);
  10125. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10126. end;
  10127. S_WL:
  10128. begin
  10129. DebugMsg(SPeepholeOptimization + 'var14',p);
  10130. taicpu(hp1).changeopsize(S_L);
  10131. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10132. end;
  10133. S_BW:
  10134. begin
  10135. DebugMsg(SPeepholeOptimization + 'var15',p);
  10136. taicpu(hp1).changeopsize(S_W);
  10137. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10138. end;
  10139. else
  10140. Internalerror(2017050704)
  10141. end;
  10142. Result := True;
  10143. end;
  10144. end;
  10145. end;
  10146. end;
  10147. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  10148. var
  10149. hp1, hp2 : tai;
  10150. MaskLength : Cardinal;
  10151. MaskedBits : TCgInt;
  10152. ActiveReg : TRegister;
  10153. begin
  10154. Result:=false;
  10155. { There are no optimisations for reference targets }
  10156. if (taicpu(p).oper[1]^.typ <> top_reg) then
  10157. Exit;
  10158. while GetNextInstruction(p, hp1) and
  10159. (hp1.typ = ait_instruction) do
  10160. begin
  10161. if (taicpu(p).oper[0]^.typ = top_const) then
  10162. begin
  10163. case taicpu(hp1).opcode of
  10164. A_AND:
  10165. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10166. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10167. { the second register must contain the first one, so compare their subreg types }
  10168. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  10169. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  10170. { change
  10171. and const1, reg
  10172. and const2, reg
  10173. to
  10174. and (const1 and const2), reg
  10175. }
  10176. begin
  10177. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  10178. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  10179. RemoveCurrentP(p, hp1);
  10180. Result:=true;
  10181. exit;
  10182. end;
  10183. A_CMP:
  10184. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  10185. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  10186. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10187. { Just check that the condition on the next instruction is compatible }
  10188. GetNextInstruction(hp1, hp2) and
  10189. (hp2.typ = ait_instruction) and
  10190. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  10191. then
  10192. { change
  10193. and 2^n, reg
  10194. cmp 2^n, reg
  10195. j(c) / set(c) / cmov(c) (c is equal or not equal)
  10196. to
  10197. and 2^n, reg
  10198. test reg, reg
  10199. j(~c) / set(~c) / cmov(~c)
  10200. }
  10201. begin
  10202. { Keep TEST instruction in, rather than remove it, because
  10203. it may trigger other optimisations such as MovAndTest2Test }
  10204. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  10205. taicpu(hp1).opcode := A_TEST;
  10206. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  10207. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  10208. Result := True;
  10209. Exit;
  10210. end;
  10211. A_MOVZX:
  10212. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10213. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  10214. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10215. (
  10216. (
  10217. (taicpu(p).opsize=S_W) and
  10218. (taicpu(hp1).opsize=S_BW)
  10219. ) or
  10220. (
  10221. (taicpu(p).opsize=S_L) and
  10222. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  10223. )
  10224. {$ifdef x86_64}
  10225. or
  10226. (
  10227. (taicpu(p).opsize=S_Q) and
  10228. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  10229. )
  10230. {$endif x86_64}
  10231. ) then
  10232. begin
  10233. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10234. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  10235. ) or
  10236. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10237. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  10238. then
  10239. begin
  10240. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  10241. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  10242. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  10243. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  10244. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  10245. }
  10246. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  10247. RemoveInstruction(hp1);
  10248. { See if there are other optimisations possible }
  10249. Continue;
  10250. end;
  10251. end;
  10252. A_SHL:
  10253. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10254. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  10255. begin
  10256. {$ifopt R+}
  10257. {$define RANGE_WAS_ON}
  10258. {$R-}
  10259. {$endif}
  10260. { get length of potential and mask }
  10261. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  10262. { really a mask? }
  10263. {$ifdef RANGE_WAS_ON}
  10264. {$R+}
  10265. {$endif}
  10266. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  10267. { unmasked part shifted out? }
  10268. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  10269. begin
  10270. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  10271. RemoveCurrentP(p, hp1);
  10272. Result:=true;
  10273. exit;
  10274. end;
  10275. end;
  10276. A_SHR:
  10277. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10278. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  10279. (taicpu(hp1).oper[0]^.val <= 63) then
  10280. begin
  10281. { Does SHR combined with the AND cover all the bits?
  10282. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  10283. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  10284. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  10285. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  10286. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  10287. begin
  10288. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  10289. RemoveCurrentP(p, hp1);
  10290. Result := True;
  10291. Exit;
  10292. end;
  10293. end;
  10294. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10295. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  10296. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10297. begin
  10298. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  10299. (
  10300. (
  10301. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10302. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  10303. ) or (
  10304. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10305. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  10306. {$ifdef x86_64}
  10307. ) or (
  10308. (taicpu(hp1).opsize = S_LQ) and
  10309. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  10310. {$endif x86_64}
  10311. )
  10312. ) then
  10313. begin
  10314. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  10315. begin
  10316. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  10317. RemoveInstruction(hp1);
  10318. { See if there are other optimisations possible }
  10319. Continue;
  10320. end;
  10321. { The super-registers are the same though.
  10322. Note that this change by itself doesn't improve
  10323. code speed, but it opens up other optimisations. }
  10324. {$ifdef x86_64}
  10325. { Convert 64-bit register to 32-bit }
  10326. case taicpu(hp1).opsize of
  10327. S_BQ:
  10328. begin
  10329. taicpu(hp1).opsize := S_BL;
  10330. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  10331. end;
  10332. S_WQ:
  10333. begin
  10334. taicpu(hp1).opsize := S_WL;
  10335. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  10336. end
  10337. else
  10338. ;
  10339. end;
  10340. {$endif x86_64}
  10341. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  10342. taicpu(hp1).opcode := A_MOVZX;
  10343. { See if there are other optimisations possible }
  10344. Continue;
  10345. end;
  10346. end;
  10347. else
  10348. ;
  10349. end;
  10350. end
  10351. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  10352. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  10353. begin
  10354. {$ifdef x86_64}
  10355. if (taicpu(p).opsize = S_Q) then
  10356. begin
  10357. { Never necessary }
  10358. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  10359. RemoveCurrentP(p, hp1);
  10360. Result := True;
  10361. Exit;
  10362. end;
  10363. {$endif x86_64}
  10364. { Forward check to determine necessity of and %reg,%reg }
  10365. TransferUsedRegs(TmpUsedRegs);
  10366. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10367. { Saves on a bunch of dereferences }
  10368. ActiveReg := taicpu(p).oper[1]^.reg;
  10369. case taicpu(hp1).opcode of
  10370. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10371. if (
  10372. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10373. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10374. ) and
  10375. (
  10376. (taicpu(hp1).opcode <> A_MOV) or
  10377. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  10378. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  10379. ) and
  10380. not (
  10381. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  10382. (taicpu(hp1).opcode = A_MOV) and
  10383. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  10384. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  10385. ) and
  10386. (
  10387. (
  10388. (taicpu(hp1).oper[0]^.typ = top_reg) and
  10389. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  10390. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  10391. ) or
  10392. (
  10393. {$ifdef x86_64}
  10394. (
  10395. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  10396. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  10397. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  10398. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  10399. ) and
  10400. {$endif x86_64}
  10401. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  10402. )
  10403. ) then
  10404. begin
  10405. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  10406. RemoveCurrentP(p, hp1);
  10407. Result := True;
  10408. Exit;
  10409. end;
  10410. A_ADD,
  10411. A_AND,
  10412. A_BSF,
  10413. A_BSR,
  10414. A_BTC,
  10415. A_BTR,
  10416. A_BTS,
  10417. A_OR,
  10418. A_SUB,
  10419. A_XOR:
  10420. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  10421. if (
  10422. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10423. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10424. ) and
  10425. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  10426. begin
  10427. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  10428. RemoveCurrentP(p, hp1);
  10429. Result := True;
  10430. Exit;
  10431. end;
  10432. A_CMP,
  10433. A_TEST:
  10434. if (
  10435. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10436. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10437. ) and
  10438. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  10439. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  10440. begin
  10441. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  10442. RemoveCurrentP(p, hp1);
  10443. Result := True;
  10444. Exit;
  10445. end;
  10446. A_BSWAP,
  10447. A_NEG,
  10448. A_NOT:
  10449. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  10450. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  10451. begin
  10452. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  10453. RemoveCurrentP(p, hp1);
  10454. Result := True;
  10455. Exit;
  10456. end;
  10457. else
  10458. ;
  10459. end;
  10460. end;
  10461. if (taicpu(hp1).is_jmp) and
  10462. (taicpu(hp1).opcode<>A_JMP) and
  10463. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  10464. begin
  10465. { change
  10466. and x, reg
  10467. jxx
  10468. to
  10469. test x, reg
  10470. jxx
  10471. if reg is deallocated before the
  10472. jump, but only if it's a conditional jump (PFV)
  10473. }
  10474. taicpu(p).opcode := A_TEST;
  10475. Exit;
  10476. end;
  10477. Break;
  10478. end;
  10479. { Lone AND tests }
  10480. if (taicpu(p).oper[0]^.typ = top_const) then
  10481. begin
  10482. {
  10483. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  10484. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  10485. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  10486. }
  10487. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  10488. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  10489. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  10490. begin
  10491. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  10492. if taicpu(p).opsize = S_L then
  10493. begin
  10494. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  10495. Result := True;
  10496. end;
  10497. end;
  10498. end;
  10499. { Backward check to determine necessity of and %reg,%reg }
  10500. if (taicpu(p).oper[0]^.typ = top_reg) and
  10501. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  10502. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  10503. GetLastInstruction(p, hp2) and
  10504. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  10505. { Check size of adjacent instruction to determine if the AND is
  10506. effectively a null operation }
  10507. (
  10508. (taicpu(p).opsize = taicpu(hp2).opsize) or
  10509. { Note: Don't include S_Q }
  10510. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  10511. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  10512. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  10513. ) then
  10514. begin
  10515. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  10516. { If GetNextInstruction returned False, hp1 will be nil }
  10517. RemoveCurrentP(p, hp1);
  10518. Result := True;
  10519. Exit;
  10520. end;
  10521. end;
  10522. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  10523. var
  10524. hp1: tai; NewRef: TReference;
  10525. { This entire nested function is used in an if-statement below, but we
  10526. want to avoid all the used reg transfers and GetNextInstruction calls
  10527. until we really have to check }
  10528. function MemRegisterNotUsedLater: Boolean; inline;
  10529. var
  10530. hp2: tai;
  10531. begin
  10532. TransferUsedRegs(TmpUsedRegs);
  10533. hp2 := p;
  10534. repeat
  10535. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  10536. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  10537. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  10538. end;
  10539. begin
  10540. Result := False;
  10541. if not GetNextInstruction(p, hp1) or (hp1.typ <> ait_instruction) then
  10542. Exit;
  10543. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) then
  10544. begin
  10545. { Change:
  10546. add %reg2,%reg1
  10547. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  10548. To:
  10549. mov/s/z #(%reg1,%reg2),%reg1
  10550. }
  10551. if MatchOpType(taicpu(p), top_reg, top_reg) and
  10552. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  10553. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  10554. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  10555. (
  10556. (
  10557. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  10558. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  10559. { r/esp cannot be an index }
  10560. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  10561. ) or (
  10562. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  10563. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  10564. )
  10565. ) and (
  10566. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  10567. (
  10568. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  10569. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  10570. MemRegisterNotUsedLater
  10571. )
  10572. ) then
  10573. begin
  10574. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  10575. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  10576. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  10577. RemoveCurrentp(p, hp1);
  10578. Result := True;
  10579. Exit;
  10580. end;
  10581. { Change:
  10582. addl/q $x,%reg1
  10583. movl/q %reg1,%reg2
  10584. To:
  10585. leal/q $x(%reg1),%reg2
  10586. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  10587. Breaks the dependency chain.
  10588. }
  10589. if MatchOpType(taicpu(p),top_const,top_reg) and
  10590. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  10591. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10592. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  10593. (
  10594. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  10595. not (cs_opt_size in current_settings.optimizerswitches) or
  10596. (
  10597. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  10598. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  10599. )
  10600. ) then
  10601. begin
  10602. { Change the MOV instruction to a LEA instruction, and update the
  10603. first operand }
  10604. reference_reset(NewRef, 1, []);
  10605. NewRef.base := taicpu(p).oper[1]^.reg;
  10606. NewRef.scalefactor := 1;
  10607. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  10608. taicpu(hp1).opcode := A_LEA;
  10609. taicpu(hp1).loadref(0, NewRef);
  10610. TransferUsedRegs(TmpUsedRegs);
  10611. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10612. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  10613. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  10614. begin
  10615. { Move what is now the LEA instruction to before the SUB instruction }
  10616. Asml.Remove(hp1);
  10617. Asml.InsertBefore(hp1, p);
  10618. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  10619. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  10620. p := hp1;
  10621. end
  10622. else
  10623. begin
  10624. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  10625. RemoveCurrentP(p, hp1);
  10626. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', p);
  10627. end;
  10628. Result := True;
  10629. end;
  10630. end;
  10631. end;
  10632. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  10633. var
  10634. SubReg: TSubRegister;
  10635. begin
  10636. Result:=false;
  10637. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  10638. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  10639. with taicpu(p).oper[0]^.ref^ do
  10640. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  10641. begin
  10642. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  10643. begin
  10644. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  10645. taicpu(p).opcode := A_ADD;
  10646. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  10647. Result := True;
  10648. end
  10649. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  10650. begin
  10651. if (base <> NR_NO) then
  10652. begin
  10653. if (scalefactor <= 1) then
  10654. begin
  10655. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  10656. taicpu(p).opcode := A_ADD;
  10657. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  10658. Result := True;
  10659. end;
  10660. end
  10661. else
  10662. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  10663. if (scalefactor in [2, 4, 8]) then
  10664. begin
  10665. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  10666. taicpu(p).loadconst(0, BsrByte(scalefactor));
  10667. taicpu(p).opcode := A_SHL;
  10668. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  10669. Result := True;
  10670. end;
  10671. end;
  10672. end;
  10673. end;
  10674. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  10675. var
  10676. hp1: tai; NewRef: TReference;
  10677. begin
  10678. { Change:
  10679. subl/q $x,%reg1
  10680. movl/q %reg1,%reg2
  10681. To:
  10682. leal/q $-x(%reg1),%reg2
  10683. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  10684. Breaks the dependency chain and potentially permits the removal of
  10685. a CMP instruction if one follows.
  10686. }
  10687. Result := False;
  10688. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  10689. MatchOpType(taicpu(p),top_const,top_reg) and
  10690. GetNextInstruction(p, hp1) and
  10691. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  10692. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10693. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  10694. (
  10695. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  10696. not (cs_opt_size in current_settings.optimizerswitches) or
  10697. (
  10698. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  10699. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  10700. )
  10701. ) then
  10702. begin
  10703. { Change the MOV instruction to a LEA instruction, and update the
  10704. first operand }
  10705. reference_reset(NewRef, 1, []);
  10706. NewRef.base := taicpu(p).oper[1]^.reg;
  10707. NewRef.scalefactor := 1;
  10708. NewRef.offset := -taicpu(p).oper[0]^.val;
  10709. taicpu(hp1).opcode := A_LEA;
  10710. taicpu(hp1).loadref(0, NewRef);
  10711. TransferUsedRegs(TmpUsedRegs);
  10712. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10713. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  10714. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  10715. begin
  10716. { Move what is now the LEA instruction to before the SUB instruction }
  10717. Asml.Remove(hp1);
  10718. Asml.InsertBefore(hp1, p);
  10719. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  10720. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  10721. p := hp1;
  10722. end
  10723. else
  10724. begin
  10725. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  10726. RemoveCurrentP(p, hp1);
  10727. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', p);
  10728. end;
  10729. Result := True;
  10730. end;
  10731. end;
  10732. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  10733. begin
  10734. { we can skip all instructions not messing with the stack pointer }
  10735. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  10736. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  10737. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  10738. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  10739. ({(taicpu(hp1).ops=0) or }
  10740. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  10741. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  10742. ) and }
  10743. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  10744. )
  10745. ) do
  10746. GetNextInstruction(hp1,hp1);
  10747. Result:=assigned(hp1);
  10748. end;
  10749. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  10750. var
  10751. hp1, hp2, hp3, hp4, hp5: tai;
  10752. begin
  10753. Result:=false;
  10754. hp5:=nil;
  10755. { replace
  10756. leal(q) x(<stackpointer>),<stackpointer>
  10757. call procname
  10758. leal(q) -x(<stackpointer>),<stackpointer>
  10759. ret
  10760. by
  10761. jmp procname
  10762. but do it only on level 4 because it destroys stack back traces
  10763. }
  10764. if (cs_opt_level4 in current_settings.optimizerswitches) and
  10765. MatchOpType(taicpu(p),top_ref,top_reg) and
  10766. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  10767. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  10768. { the -8 or -24 are not required, but bail out early if possible,
  10769. higher values are unlikely }
  10770. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  10771. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  10772. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  10773. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  10774. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and
  10775. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  10776. GetNextInstruction(p, hp1) and
  10777. { Take a copy of hp1 }
  10778. SetAndTest(hp1, hp4) and
  10779. { trick to skip label }
  10780. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  10781. SkipSimpleInstructions(hp1) and
  10782. MatchInstruction(hp1,A_CALL,[S_NO]) and
  10783. GetNextInstruction(hp1, hp2) and
  10784. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  10785. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  10786. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  10787. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  10788. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  10789. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  10790. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  10791. (taicpu(hp2).oper[0]^.ref^.segment=NR_NO) and
  10792. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  10793. GetNextInstruction(hp2, hp3) and
  10794. { trick to skip label }
  10795. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  10796. (MatchInstruction(hp3,A_RET,[S_NO]) or
  10797. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  10798. SetAndTest(hp3,hp5) and
  10799. GetNextInstruction(hp3,hp3) and
  10800. MatchInstruction(hp3,A_RET,[S_NO])
  10801. )
  10802. ) and
  10803. (taicpu(hp3).ops=0) then
  10804. begin
  10805. taicpu(hp1).opcode := A_JMP;
  10806. taicpu(hp1).is_jmp := true;
  10807. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  10808. RemoveCurrentP(p, hp4);
  10809. RemoveInstruction(hp2);
  10810. RemoveInstruction(hp3);
  10811. if Assigned(hp5) then
  10812. begin
  10813. AsmL.Remove(hp5);
  10814. ASmL.InsertBefore(hp5,hp1)
  10815. end;
  10816. Result:=true;
  10817. end;
  10818. end;
  10819. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  10820. {$ifdef x86_64}
  10821. var
  10822. hp1, hp2, hp3, hp4, hp5: tai;
  10823. {$endif x86_64}
  10824. begin
  10825. Result:=false;
  10826. {$ifdef x86_64}
  10827. hp5:=nil;
  10828. { replace
  10829. push %rax
  10830. call procname
  10831. pop %rcx
  10832. ret
  10833. by
  10834. jmp procname
  10835. but do it only on level 4 because it destroys stack back traces
  10836. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  10837. for all supported calling conventions
  10838. }
  10839. if (cs_opt_level4 in current_settings.optimizerswitches) and
  10840. MatchOpType(taicpu(p),top_reg) and
  10841. (taicpu(p).oper[0]^.reg=NR_RAX) and
  10842. GetNextInstruction(p, hp1) and
  10843. { Take a copy of hp1 }
  10844. SetAndTest(hp1, hp4) and
  10845. { trick to skip label }
  10846. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  10847. SkipSimpleInstructions(hp1) and
  10848. MatchInstruction(hp1,A_CALL,[S_NO]) and
  10849. GetNextInstruction(hp1, hp2) and
  10850. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  10851. MatchOpType(taicpu(hp2),top_reg) and
  10852. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  10853. GetNextInstruction(hp2, hp3) and
  10854. { trick to skip label }
  10855. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  10856. (MatchInstruction(hp3,A_RET,[S_NO]) or
  10857. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  10858. SetAndTest(hp3,hp5) and
  10859. GetNextInstruction(hp3,hp3) and
  10860. MatchInstruction(hp3,A_RET,[S_NO])
  10861. )
  10862. ) and
  10863. (taicpu(hp3).ops=0) then
  10864. begin
  10865. taicpu(hp1).opcode := A_JMP;
  10866. taicpu(hp1).is_jmp := true;
  10867. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  10868. RemoveCurrentP(p, hp4);
  10869. RemoveInstruction(hp2);
  10870. RemoveInstruction(hp3);
  10871. if Assigned(hp5) then
  10872. begin
  10873. AsmL.Remove(hp5);
  10874. ASmL.InsertBefore(hp5,hp1)
  10875. end;
  10876. Result:=true;
  10877. end;
  10878. {$endif x86_64}
  10879. end;
  10880. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  10881. var
  10882. Value, RegName: string;
  10883. begin
  10884. Result:=false;
  10885. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  10886. begin
  10887. case taicpu(p).oper[0]^.val of
  10888. 0:
  10889. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  10890. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  10891. begin
  10892. { change "mov $0,%reg" into "xor %reg,%reg" }
  10893. taicpu(p).opcode := A_XOR;
  10894. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  10895. Result := True;
  10896. {$ifdef x86_64}
  10897. end
  10898. else if (taicpu(p).opsize = S_Q) then
  10899. begin
  10900. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  10901. { The actual optimization }
  10902. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  10903. taicpu(p).changeopsize(S_L);
  10904. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  10905. Result := True;
  10906. end;
  10907. $1..$FFFFFFFF:
  10908. begin
  10909. { Code size reduction by J. Gareth "Kit" Moreton }
  10910. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  10911. case taicpu(p).opsize of
  10912. S_Q:
  10913. begin
  10914. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  10915. Value := debug_tostr(taicpu(p).oper[0]^.val);
  10916. { The actual optimization }
  10917. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  10918. taicpu(p).changeopsize(S_L);
  10919. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  10920. Result := True;
  10921. end;
  10922. else
  10923. { Do nothing };
  10924. end;
  10925. {$endif x86_64}
  10926. end;
  10927. -1:
  10928. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  10929. if (cs_opt_size in current_settings.optimizerswitches) and
  10930. (taicpu(p).opsize <> S_B) and
  10931. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  10932. begin
  10933. { change "mov $-1,%reg" into "or $-1,%reg" }
  10934. { NOTES:
  10935. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  10936. - This operation creates a false dependency on the register, so only do it when optimising for size
  10937. - 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
  10938. }
  10939. taicpu(p).opcode := A_OR;
  10940. Result := True;
  10941. end;
  10942. else
  10943. { Do nothing };
  10944. end;
  10945. end;
  10946. end;
  10947. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  10948. var
  10949. hp1: tai;
  10950. begin
  10951. { Detect:
  10952. andw x, %ax (0 <= x < $8000)
  10953. ...
  10954. movzwl %ax,%eax
  10955. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  10956. }
  10957. Result := False; if MatchOpType(taicpu(p), top_const, top_reg) and
  10958. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  10959. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  10960. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  10961. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  10962. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  10963. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  10964. begin
  10965. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  10966. taicpu(hp1).opcode := A_CWDE;
  10967. taicpu(hp1).clearop(0);
  10968. taicpu(hp1).clearop(1);
  10969. taicpu(hp1).ops := 0;
  10970. { A change was made, but not with p, so move forward 1 }
  10971. p := tai(p.Next);
  10972. Result := True;
  10973. end;
  10974. end;
  10975. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  10976. begin
  10977. Result := False;
  10978. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  10979. Exit;
  10980. { Convert:
  10981. movswl %ax,%eax -> cwtl
  10982. movslq %eax,%rax -> cdqe
  10983. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  10984. refer to the same opcode and depends only on the assembler's
  10985. current operand-size attribute. [Kit]
  10986. }
  10987. with taicpu(p) do
  10988. case opsize of
  10989. S_WL:
  10990. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  10991. begin
  10992. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  10993. opcode := A_CWDE;
  10994. clearop(0);
  10995. clearop(1);
  10996. ops := 0;
  10997. Result := True;
  10998. end;
  10999. {$ifdef x86_64}
  11000. S_LQ:
  11001. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  11002. begin
  11003. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  11004. opcode := A_CDQE;
  11005. clearop(0);
  11006. clearop(1);
  11007. ops := 0;
  11008. Result := True;
  11009. end;
  11010. {$endif x86_64}
  11011. else
  11012. ;
  11013. end;
  11014. end;
  11015. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  11016. var
  11017. hp1: tai;
  11018. begin
  11019. { Detect:
  11020. shr x, %ax (x > 0)
  11021. ...
  11022. movzwl %ax,%eax
  11023. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  11024. }
  11025. Result := False;
  11026. if MatchOpType(taicpu(p), top_const, top_reg) and
  11027. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  11028. (taicpu(p).oper[0]^.val > 0) and
  11029. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11030. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11031. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11032. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11033. begin
  11034. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  11035. taicpu(hp1).opcode := A_CWDE;
  11036. taicpu(hp1).clearop(0);
  11037. taicpu(hp1).clearop(1);
  11038. taicpu(hp1).ops := 0;
  11039. { A change was made, but not with p, so move forward 1 }
  11040. p := tai(p.Next);
  11041. Result := True;
  11042. end;
  11043. end;
  11044. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  11045. var
  11046. hp1, hp2: tai;
  11047. Opposite, SecondOpposite: TAsmOp;
  11048. NewCond: TAsmCond;
  11049. begin
  11050. Result := False;
  11051. { Change:
  11052. add/sub 128,(dest)
  11053. To:
  11054. sub/add -128,(dest)
  11055. This generaally takes fewer bytes to encode because -128 can be stored
  11056. in a signed byte, whereas +128 cannot.
  11057. }
  11058. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  11059. begin
  11060. if taicpu(p).opcode = A_ADD then
  11061. Opposite := A_SUB
  11062. else
  11063. Opposite := A_ADD;
  11064. { Be careful if the flags are in use, because the CF flag inverts
  11065. when changing from ADD to SUB and vice versa }
  11066. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11067. GetNextInstruction(p, hp1) then
  11068. begin
  11069. TransferUsedRegs(TmpUsedRegs);
  11070. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  11071. hp2 := hp1;
  11072. { Scan ahead to check if everything's safe }
  11073. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  11074. begin
  11075. if (hp1.typ <> ait_instruction) then
  11076. { Probably unsafe since the flags are still in use }
  11077. Exit;
  11078. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  11079. { Stop searching at an unconditional jump }
  11080. Break;
  11081. if not
  11082. (
  11083. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  11084. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  11085. ) and
  11086. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  11087. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  11088. Exit;
  11089. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11090. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  11091. { Move to the next instruction }
  11092. GetNextInstruction(hp1, hp1);
  11093. end;
  11094. while Assigned(hp2) and (hp2 <> hp1) do
  11095. begin
  11096. NewCond := C_None;
  11097. case taicpu(hp2).condition of
  11098. C_A, C_NBE:
  11099. NewCond := C_BE;
  11100. C_B, C_C, C_NAE:
  11101. NewCond := C_AE;
  11102. C_AE, C_NB, C_NC:
  11103. NewCond := C_B;
  11104. C_BE, C_NA:
  11105. NewCond := C_A;
  11106. else
  11107. { No change needed };
  11108. end;
  11109. if NewCond <> C_None then
  11110. begin
  11111. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  11112. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  11113. taicpu(hp2).condition := NewCond;
  11114. end
  11115. else
  11116. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  11117. begin
  11118. { Because of the flipping of the carry bit, to ensure
  11119. the operation remains equivalent, ADC becomes SBB
  11120. and vice versa, and the constant is not-inverted.
  11121. If multiple ADCs or SBBs appear in a row, each one
  11122. changed causes the carry bit to invert, so they all
  11123. need to be flipped }
  11124. if taicpu(hp2).opcode = A_ADC then
  11125. SecondOpposite := A_SBB
  11126. else
  11127. SecondOpposite := A_ADC;
  11128. if taicpu(hp2).oper[0]^.typ <> top_const then
  11129. { Should have broken out of this optimisation already }
  11130. InternalError(2021112901);
  11131. 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]^) + ' -> ' +
  11132. 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);
  11133. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  11134. taicpu(hp2).opcode := SecondOpposite;
  11135. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  11136. end;
  11137. { Move to the next instruction }
  11138. GetNextInstruction(hp2, hp2);
  11139. end;
  11140. if (hp2 <> hp1) then
  11141. InternalError(2021111501);
  11142. end;
  11143. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  11144. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  11145. taicpu(p).opcode := Opposite;
  11146. taicpu(p).oper[0]^.val := -128;
  11147. { No further optimisations can be made on this instruction, so move
  11148. onto the next one to save time }
  11149. p := tai(p.Next);
  11150. UpdateUsedRegs(p);
  11151. Result := True;
  11152. Exit;
  11153. end;
  11154. { Detect:
  11155. add/sub %reg2,(dest)
  11156. add/sub x, (dest)
  11157. (dest can be a register or a reference)
  11158. Swap the instructions to minimise a pipeline stall. This reverses the
  11159. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  11160. optimisations could be made.
  11161. }
  11162. if (taicpu(p).oper[0]^.typ = top_reg) and
  11163. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  11164. (
  11165. (
  11166. (taicpu(p).oper[1]^.typ = top_reg) and
  11167. { We can try searching further ahead if we're writing to a register }
  11168. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  11169. ) or
  11170. (
  11171. (taicpu(p).oper[1]^.typ = top_ref) and
  11172. GetNextInstruction(p, hp1)
  11173. )
  11174. ) and
  11175. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  11176. (taicpu(hp1).oper[0]^.typ = top_const) and
  11177. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  11178. begin
  11179. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  11180. TransferUsedRegs(TmpUsedRegs);
  11181. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11182. hp2 := p;
  11183. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  11184. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  11185. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  11186. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  11187. begin
  11188. asml.remove(hp1);
  11189. asml.InsertBefore(hp1, p);
  11190. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  11191. Result := True;
  11192. end;
  11193. end;
  11194. end;
  11195. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  11196. begin
  11197. Result:=false;
  11198. { change "cmp $0, %reg" to "test %reg, %reg" }
  11199. if MatchOpType(taicpu(p),top_const,top_reg) and
  11200. (taicpu(p).oper[0]^.val = 0) then
  11201. begin
  11202. taicpu(p).opcode := A_TEST;
  11203. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  11204. Result:=true;
  11205. end;
  11206. end;
  11207. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  11208. var
  11209. IsTestConstX : Boolean;
  11210. hp1,hp2 : tai;
  11211. begin
  11212. Result:=false;
  11213. { removes the line marked with (x) from the sequence
  11214. and/or/xor/add/sub/... $x, %y
  11215. test/or %y, %y | test $-1, %y (x)
  11216. j(n)z _Label
  11217. as the first instruction already adjusts the ZF
  11218. %y operand may also be a reference }
  11219. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  11220. MatchOperand(taicpu(p).oper[0]^,-1);
  11221. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  11222. GetLastInstruction(p, hp1) and
  11223. (tai(hp1).typ = ait_instruction) and
  11224. GetNextInstruction(p,hp2) and
  11225. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  11226. case taicpu(hp1).opcode Of
  11227. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  11228. { These two instructions set the zero flag if the result is zero }
  11229. A_POPCNT, A_LZCNT:
  11230. begin
  11231. if (
  11232. { With POPCNT, an input of zero will set the zero flag
  11233. because the population count of zero is zero }
  11234. (taicpu(hp1).opcode = A_POPCNT) and
  11235. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  11236. (
  11237. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  11238. { Faster than going through the second half of the 'or'
  11239. condition below }
  11240. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  11241. )
  11242. ) or (
  11243. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  11244. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11245. { and in case of carry for A(E)/B(E)/C/NC }
  11246. (
  11247. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  11248. (
  11249. (taicpu(hp1).opcode <> A_ADD) and
  11250. (taicpu(hp1).opcode <> A_SUB) and
  11251. (taicpu(hp1).opcode <> A_LZCNT)
  11252. )
  11253. )
  11254. ) then
  11255. begin
  11256. RemoveCurrentP(p, hp2);
  11257. Result:=true;
  11258. Exit;
  11259. end;
  11260. end;
  11261. A_SHL, A_SAL, A_SHR, A_SAR:
  11262. begin
  11263. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  11264. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  11265. { therefore, it's only safe to do this optimization for }
  11266. { shifts by a (nonzero) constant }
  11267. (taicpu(hp1).oper[0]^.typ = top_const) and
  11268. (taicpu(hp1).oper[0]^.val <> 0) and
  11269. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11270. { and in case of carry for A(E)/B(E)/C/NC }
  11271. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11272. begin
  11273. RemoveCurrentP(p, hp2);
  11274. Result:=true;
  11275. Exit;
  11276. end;
  11277. end;
  11278. A_DEC, A_INC, A_NEG:
  11279. begin
  11280. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  11281. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11282. { and in case of carry for A(E)/B(E)/C/NC }
  11283. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11284. begin
  11285. RemoveCurrentP(p, hp2);
  11286. Result:=true;
  11287. Exit;
  11288. end;
  11289. end
  11290. else
  11291. ;
  11292. end; { case }
  11293. { change "test $-1,%reg" into "test %reg,%reg" }
  11294. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  11295. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  11296. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  11297. if MatchInstruction(p, A_OR, []) and
  11298. { Can only match if they're both registers }
  11299. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  11300. begin
  11301. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  11302. taicpu(p).opcode := A_TEST;
  11303. { No need to set Result to True, as we've done all the optimisations we can }
  11304. end;
  11305. end;
  11306. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  11307. var
  11308. hp1,hp3 : tai;
  11309. {$ifndef x86_64}
  11310. hp2 : taicpu;
  11311. {$endif x86_64}
  11312. begin
  11313. Result:=false;
  11314. hp3:=nil;
  11315. {$ifndef x86_64}
  11316. { don't do this on modern CPUs, this really hurts them due to
  11317. broken call/ret pairing }
  11318. if (current_settings.optimizecputype < cpu_Pentium2) and
  11319. not(cs_create_pic in current_settings.moduleswitches) and
  11320. GetNextInstruction(p, hp1) and
  11321. MatchInstruction(hp1,A_JMP,[S_NO]) and
  11322. MatchOpType(taicpu(hp1),top_ref) and
  11323. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  11324. begin
  11325. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  11326. InsertLLItem(p.previous, p, hp2);
  11327. taicpu(p).opcode := A_JMP;
  11328. taicpu(p).is_jmp := true;
  11329. RemoveInstruction(hp1);
  11330. Result:=true;
  11331. end
  11332. else
  11333. {$endif x86_64}
  11334. { replace
  11335. call procname
  11336. ret
  11337. by
  11338. jmp procname
  11339. but do it only on level 4 because it destroys stack back traces
  11340. else if the subroutine is marked as no return, remove the ret
  11341. }
  11342. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  11343. (po_noreturn in current_procinfo.procdef.procoptions)) and
  11344. GetNextInstruction(p, hp1) and
  11345. (MatchInstruction(hp1,A_RET,[S_NO]) or
  11346. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  11347. SetAndTest(hp1,hp3) and
  11348. GetNextInstruction(hp1,hp1) and
  11349. MatchInstruction(hp1,A_RET,[S_NO])
  11350. )
  11351. ) and
  11352. (taicpu(hp1).ops=0) then
  11353. begin
  11354. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11355. { we might destroy stack alignment here if we do not do a call }
  11356. (target_info.stackalign<=sizeof(SizeUInt)) then
  11357. begin
  11358. taicpu(p).opcode := A_JMP;
  11359. taicpu(p).is_jmp := true;
  11360. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  11361. end
  11362. else
  11363. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  11364. RemoveInstruction(hp1);
  11365. if Assigned(hp3) then
  11366. begin
  11367. AsmL.Remove(hp3);
  11368. AsmL.InsertBefore(hp3,p)
  11369. end;
  11370. Result:=true;
  11371. end;
  11372. end;
  11373. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  11374. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  11375. begin
  11376. case OpSize of
  11377. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11378. Result := (Val <= $FF) and (Val >= -128);
  11379. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11380. Result := (Val <= $FFFF) and (Val >= -32768);
  11381. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  11382. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  11383. else
  11384. Result := True;
  11385. end;
  11386. end;
  11387. var
  11388. hp1, hp2 : tai;
  11389. SizeChange: Boolean;
  11390. PreMessage: string;
  11391. begin
  11392. Result := False;
  11393. if (taicpu(p).oper[0]^.typ = top_reg) and
  11394. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11395. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  11396. begin
  11397. { Change (using movzbl %al,%eax as an example):
  11398. movzbl %al, %eax movzbl %al, %eax
  11399. cmpl x, %eax testl %eax,%eax
  11400. To:
  11401. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  11402. movzbl %al, %eax movzbl %al, %eax
  11403. Smaller instruction and minimises pipeline stall as the CPU
  11404. doesn't have to wait for the register to get zero-extended. [Kit]
  11405. Also allow if the smaller of the two registers is being checked,
  11406. as this still removes the false dependency.
  11407. }
  11408. if
  11409. (
  11410. (
  11411. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  11412. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  11413. ) or (
  11414. { If MatchOperand returns True, they must both be registers }
  11415. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  11416. )
  11417. ) and
  11418. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  11419. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  11420. begin
  11421. 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);
  11422. asml.Remove(hp1);
  11423. asml.InsertBefore(hp1, p);
  11424. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  11425. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  11426. begin
  11427. taicpu(hp1).opcode := A_TEST;
  11428. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  11429. end;
  11430. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  11431. case taicpu(p).opsize of
  11432. S_BW, S_BL:
  11433. begin
  11434. SizeChange := taicpu(hp1).opsize <> S_B;
  11435. taicpu(hp1).changeopsize(S_B);
  11436. end;
  11437. S_WL:
  11438. begin
  11439. SizeChange := taicpu(hp1).opsize <> S_W;
  11440. taicpu(hp1).changeopsize(S_W);
  11441. end
  11442. else
  11443. InternalError(2020112701);
  11444. end;
  11445. UpdateUsedRegs(tai(p.Next));
  11446. { Check if the register is used aferwards - if not, we can
  11447. remove the movzx instruction completely }
  11448. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  11449. begin
  11450. { Hp1 is a better position than p for debugging purposes }
  11451. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  11452. RemoveCurrentp(p, hp1);
  11453. Result := True;
  11454. end;
  11455. if SizeChange then
  11456. DebugMsg(SPeepholeOptimization + PreMessage +
  11457. 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)
  11458. else
  11459. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  11460. Exit;
  11461. end;
  11462. { Change (using movzwl %ax,%eax as an example):
  11463. movzwl %ax, %eax
  11464. movb %al, (dest) (Register is smaller than read register in movz)
  11465. To:
  11466. movb %al, (dest) (Move one back to avoid a false dependency)
  11467. movzwl %ax, %eax
  11468. }
  11469. if (taicpu(hp1).opcode = A_MOV) and
  11470. (taicpu(hp1).oper[0]^.typ = top_reg) and
  11471. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  11472. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  11473. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  11474. begin
  11475. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  11476. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  11477. asml.Remove(hp1);
  11478. asml.InsertBefore(hp1, p);
  11479. if taicpu(hp1).oper[1]^.typ = top_reg then
  11480. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  11481. { Check if the register is used aferwards - if not, we can
  11482. remove the movzx instruction completely }
  11483. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  11484. begin
  11485. { Hp1 is a better position than p for debugging purposes }
  11486. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  11487. RemoveCurrentp(p, hp1);
  11488. Result := True;
  11489. end;
  11490. Exit;
  11491. end;
  11492. end;
  11493. end;
  11494. {$ifdef x86_64}
  11495. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  11496. var
  11497. PreMessage, RegName: string;
  11498. begin
  11499. { Code size reduction by J. Gareth "Kit" Moreton }
  11500. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  11501. as this removes the REX prefix }
  11502. Result := False;
  11503. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  11504. Exit;
  11505. if taicpu(p).oper[0]^.typ <> top_reg then
  11506. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  11507. InternalError(2018011500);
  11508. case taicpu(p).opsize of
  11509. S_Q:
  11510. begin
  11511. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  11512. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  11513. { The actual optimization }
  11514. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  11515. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11516. taicpu(p).changeopsize(S_L);
  11517. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  11518. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  11519. end;
  11520. else
  11521. ;
  11522. end;
  11523. end;
  11524. {$endif}
  11525. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  11526. var
  11527. XReg: TRegister;
  11528. begin
  11529. Result := False;
  11530. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  11531. Smaller encoding and slightly faster on some platforms (also works for
  11532. ZMM-sized registers) }
  11533. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  11534. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  11535. begin
  11536. XReg := taicpu(p).oper[0]^.reg;
  11537. if (taicpu(p).oper[1]^.reg = XReg) then
  11538. begin
  11539. taicpu(p).changeopsize(S_XMM);
  11540. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  11541. if (cs_opt_size in current_settings.optimizerswitches) then
  11542. begin
  11543. { Change input registers to %xmm0 to reduce size. Note that
  11544. there's a risk of a false dependency doing this, so only
  11545. optimise for size here }
  11546. XReg := NR_XMM0;
  11547. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  11548. end
  11549. else
  11550. begin
  11551. setsubreg(XReg, R_SUBMMX);
  11552. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  11553. end;
  11554. taicpu(p).oper[0]^.reg := XReg;
  11555. taicpu(p).oper[1]^.reg := XReg;
  11556. Result := True;
  11557. end;
  11558. end;
  11559. end;
  11560. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  11561. var
  11562. OperIdx: Integer;
  11563. begin
  11564. for OperIdx := 0 to p.ops - 1 do
  11565. if p.oper[OperIdx]^.typ = top_ref then
  11566. optimize_ref(p.oper[OperIdx]^.ref^, False);
  11567. end;
  11568. end.