aoptx86.pas 574 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,cclasses,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3,
  33. aoc_ForceNewIteration
  34. );
  35. TX86AsmOptimizer = class(TAsmOptimizer)
  36. { some optimizations are very expensive to check, so the
  37. pre opt pass can be used to set some flags, depending on the found
  38. instructions if it is worth to check a certain optimization }
  39. OptsToCheck : set of TOptsToCheck;
  40. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  41. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  42. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  43. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  44. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  45. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  46. potentially allowing further optimisation (although it might need to know if
  47. it crossed a conditional jump. }
  48. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  49. {
  50. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  51. the use of a register by allocs/dealloc, so it can ignore calls.
  52. In the following example, GetNextInstructionUsingReg will return the second movq,
  53. GetNextInstructionUsingRegTrackingUse won't.
  54. movq %rdi,%rax
  55. # Register rdi released
  56. # Register rdi allocated
  57. movq %rax,%rdi
  58. While in this example:
  59. movq %rdi,%rax
  60. call proc
  61. movq %rdi,%rax
  62. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  63. won't.
  64. }
  65. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  66. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  67. private
  68. function SkipSimpleInstructions(var hp1: tai): Boolean;
  69. protected
  70. class function IsMOVZXAcceptable: Boolean; static; inline;
  71. { Attempts to allocate a volatile integer register for use between p and hp,
  72. using AUsedRegs for the current register usage information. Returns NR_NO
  73. if no free register could be found }
  74. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  75. { Attempts to allocate a volatile MM register for use between p and hp,
  76. using AUsedRegs for the current register usage information. Returns NR_NO
  77. if no free register could be found }
  78. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  79. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  80. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  81. { checks whether reading the value in reg1 depends on the value of reg2. This
  82. is very similar to SuperRegisterEquals, except it takes into account that
  83. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  84. depend on the value in AH). }
  85. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  86. { Replaces all references to AOldReg in a memory reference to ANewReg }
  87. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  88. { Replaces all references to AOldReg in an operand to ANewReg }
  89. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  90. { Replaces all references to AOldReg in an instruction to ANewReg,
  91. except where the register is being written }
  92. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  93. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  94. or writes to a global symbol }
  95. class function IsRefSafe(const ref: PReference): Boolean; static;
  96. { Returns true if the given MOV instruction can be safely converted to CMOV }
  97. class function CanBeCMOV(p : tai) : boolean; static;
  98. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  99. conversion was successful }
  100. function ConvertLEA(const p : taicpu): Boolean;
  101. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  102. procedure DebugMsg(const s : string; p : tai);inline;
  103. class function IsExitCode(p : tai) : boolean; static;
  104. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  105. procedure RemoveLastDeallocForFuncRes(p : tai);
  106. function DoSubAddOpt(var p : tai) : Boolean;
  107. function DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  108. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  109. function PrePeepholeOptSxx(var p : tai) : boolean;
  110. function PrePeepholeOptIMUL(var p : tai) : boolean;
  111. function PrePeepholeOptAND(var p : tai) : boolean;
  112. function OptPass1Test(var p: tai): boolean;
  113. function OptPass1Add(var p: tai): boolean;
  114. function OptPass1AND(var p : tai) : boolean;
  115. function OptPass1_V_MOVAP(var p : tai) : boolean;
  116. function OptPass1VOP(var p : tai) : boolean;
  117. function OptPass1MOV(var p : tai) : boolean;
  118. function OptPass1Movx(var p : tai) : boolean;
  119. function OptPass1MOVXX(var p : tai) : boolean;
  120. function OptPass1OP(var p : tai) : boolean;
  121. function OptPass1LEA(var p : tai) : boolean;
  122. function OptPass1Sub(var p : tai) : boolean;
  123. function OptPass1SHLSAL(var p : tai) : boolean;
  124. function OptPass1FSTP(var p : tai) : boolean;
  125. function OptPass1FLD(var p : tai) : boolean;
  126. function OptPass1Cmp(var p : tai) : boolean;
  127. function OptPass1PXor(var p : tai) : boolean;
  128. function OptPass1VPXor(var p: tai): boolean;
  129. function OptPass1Imul(var p : tai) : boolean;
  130. function OptPass1Jcc(var p : tai) : boolean;
  131. function OptPass1SHXX(var p: tai): boolean;
  132. function OptPass1VMOVDQ(var p: tai): Boolean;
  133. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  134. function OptPass2Movx(var p : tai): Boolean;
  135. function OptPass2MOV(var p : tai) : boolean;
  136. function OptPass2Imul(var p : tai) : boolean;
  137. function OptPass2Jmp(var p : tai) : boolean;
  138. function OptPass2Jcc(var p : tai) : boolean;
  139. function OptPass2Lea(var p: tai): Boolean;
  140. function OptPass2SUB(var p: tai): Boolean;
  141. function OptPass2ADD(var p : tai): Boolean;
  142. function OptPass2SETcc(var p : tai) : boolean;
  143. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  144. function PostPeepholeOptMov(var p : tai) : Boolean;
  145. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  146. {$ifdef x86_64} { These post-peephole optimisations only affect 64-bit registers. [Kit] }
  147. function PostPeepholeOptXor(var p : tai) : Boolean;
  148. {$endif x86_64}
  149. function PostPeepholeOptAnd(var p : tai) : boolean;
  150. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  151. function PostPeepholeOptCmp(var p : tai) : Boolean;
  152. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  153. function PostPeepholeOptCall(var p : tai) : Boolean;
  154. function PostPeepholeOptLea(var p : tai) : Boolean;
  155. function PostPeepholeOptPush(var p: tai): Boolean;
  156. function PostPeepholeOptShr(var p : tai) : boolean;
  157. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  158. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  159. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  160. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  161. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  162. { Processor-dependent reference optimisation }
  163. class procedure OptimizeRefs(var p: taicpu); static;
  164. end;
  165. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  166. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  167. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  168. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  169. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  170. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  171. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  172. {$if max_operands>2}
  173. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  174. {$endif max_operands>2}
  175. function RefsEqual(const r1, r2: treference): boolean;
  176. { Note that Result is set to True if the references COULD overlap but the
  177. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  178. might still overlap because %reg2 could be equal to %reg1-4 }
  179. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  180. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  181. { returns true, if ref is a reference using only the registers passed as base and index
  182. and having an offset }
  183. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  184. implementation
  185. uses
  186. cutils,verbose,
  187. systems,
  188. globals,
  189. cpuinfo,
  190. procinfo,
  191. paramgr,
  192. aasmbase,
  193. aoptbase,aoptutils,
  194. symconst,symsym,
  195. cgx86,
  196. itcpugas;
  197. {$ifdef DEBUG_AOPTCPU}
  198. const
  199. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  200. {$else DEBUG_AOPTCPU}
  201. { Empty strings help the optimizer to remove string concatenations that won't
  202. ever appear to the user on release builds. [Kit] }
  203. const
  204. SPeepholeOptimization = '';
  205. {$endif DEBUG_AOPTCPU}
  206. LIST_STEP_SIZE = 4;
  207. type
  208. TJumpTrackingItem = class(TLinkedListItem)
  209. private
  210. FSymbol: TAsmSymbol;
  211. FRefs: LongInt;
  212. public
  213. constructor Create(ASymbol: TAsmSymbol);
  214. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  215. property Symbol: TAsmSymbol read FSymbol;
  216. property Refs: LongInt read FRefs;
  217. end;
  218. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  219. begin
  220. inherited Create;
  221. FSymbol := ASymbol;
  222. FRefs := 0;
  223. end;
  224. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  225. begin
  226. Inc(FRefs);
  227. end;
  228. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  229. begin
  230. result :=
  231. (instr.typ = ait_instruction) and
  232. (taicpu(instr).opcode = op) and
  233. ((opsize = []) or (taicpu(instr).opsize in opsize));
  234. end;
  235. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  236. begin
  237. result :=
  238. (instr.typ = ait_instruction) and
  239. ((taicpu(instr).opcode = op1) or
  240. (taicpu(instr).opcode = op2)
  241. ) and
  242. ((opsize = []) or (taicpu(instr).opsize in opsize));
  243. end;
  244. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  245. begin
  246. result :=
  247. (instr.typ = ait_instruction) and
  248. ((taicpu(instr).opcode = op1) or
  249. (taicpu(instr).opcode = op2) or
  250. (taicpu(instr).opcode = op3)
  251. ) and
  252. ((opsize = []) or (taicpu(instr).opsize in opsize));
  253. end;
  254. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  255. const opsize : topsizes) : boolean;
  256. var
  257. op : TAsmOp;
  258. begin
  259. result:=false;
  260. if (instr.typ <> ait_instruction) or
  261. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  262. exit;
  263. for op in ops do
  264. begin
  265. if taicpu(instr).opcode = op then
  266. begin
  267. result:=true;
  268. exit;
  269. end;
  270. end;
  271. end;
  272. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  273. begin
  274. result := (oper.typ = top_reg) and (oper.reg = reg);
  275. end;
  276. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  277. begin
  278. result := (oper.typ = top_const) and (oper.val = a);
  279. end;
  280. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  281. begin
  282. result := oper1.typ = oper2.typ;
  283. if result then
  284. case oper1.typ of
  285. top_const:
  286. Result:=oper1.val = oper2.val;
  287. top_reg:
  288. Result:=oper1.reg = oper2.reg;
  289. top_ref:
  290. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  291. else
  292. internalerror(2013102801);
  293. end
  294. end;
  295. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  296. begin
  297. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  298. if result then
  299. case oper1.typ of
  300. top_const:
  301. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  302. top_reg:
  303. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  304. top_ref:
  305. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  306. else
  307. internalerror(2020052401);
  308. end
  309. end;
  310. function RefsEqual(const r1, r2: treference): boolean;
  311. begin
  312. RefsEqual :=
  313. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  314. (r1.relsymbol = r2.relsymbol) and
  315. (r1.segment = r2.segment) and (r1.base = r2.base) and
  316. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  317. (r1.offset = r2.offset) and
  318. (r1.volatility + r2.volatility = []);
  319. end;
  320. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  321. begin
  322. if (r1.symbol<>r2.symbol) then
  323. { If the index registers are different, there's a chance one could
  324. be set so it equals the other symbol }
  325. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  326. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  327. (r1.relsymbol = r2.relsymbol) and
  328. (r1.segment = r2.segment) and (r1.base = r2.base) and
  329. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  330. (r1.volatility + r2.volatility = []) then
  331. { In this case, it all depends on the offsets }
  332. Exit(abs(r1.offset - r2.offset) < Range);
  333. { There's a chance things MIGHT overlap, so take no chances }
  334. Result := True;
  335. end;
  336. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  337. begin
  338. Result:=(ref.offset=0) and
  339. (ref.scalefactor in [0,1]) and
  340. (ref.segment=NR_NO) and
  341. (ref.symbol=nil) and
  342. (ref.relsymbol=nil) and
  343. ((base=NR_INVALID) or
  344. (ref.base=base)) and
  345. ((index=NR_INVALID) or
  346. (ref.index=index)) and
  347. (ref.volatility=[]);
  348. end;
  349. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  350. begin
  351. Result:=(ref.scalefactor in [0,1]) and
  352. (ref.segment=NR_NO) and
  353. (ref.symbol=nil) and
  354. (ref.relsymbol=nil) and
  355. ((base=NR_INVALID) or
  356. (ref.base=base)) and
  357. ((index=NR_INVALID) or
  358. (ref.index=index)) and
  359. (ref.volatility=[]);
  360. end;
  361. function InstrReadsFlags(p: tai): boolean;
  362. begin
  363. InstrReadsFlags := true;
  364. case p.typ of
  365. ait_instruction:
  366. if InsProp[taicpu(p).opcode].Ch*
  367. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  368. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  369. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  370. exit;
  371. ait_label:
  372. exit;
  373. else
  374. ;
  375. end;
  376. InstrReadsFlags := false;
  377. end;
  378. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  379. begin
  380. Next:=Current;
  381. repeat
  382. Result:=GetNextInstruction(Next,Next);
  383. until not (Result) or
  384. not(cs_opt_level3 in current_settings.optimizerswitches) or
  385. (Next.typ<>ait_instruction) or
  386. RegInInstruction(reg,Next) or
  387. is_calljmp(taicpu(Next).opcode);
  388. end;
  389. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  390. procedure TrackJump(Symbol: TAsmSymbol);
  391. var
  392. Search: TJumpTrackingItem;
  393. begin
  394. { See if an entry already exists in our jump tracking list
  395. (faster to search backwards due to the higher chance of
  396. matching destinations) }
  397. Search := TJumpTrackingItem(JumpTracking.Last);
  398. while Assigned(Search) do
  399. begin
  400. if Search.Symbol = Symbol then
  401. begin
  402. { Found it - remove it so it can be pushed to the front }
  403. JumpTracking.Remove(Search);
  404. Break;
  405. end;
  406. Search := TJumpTrackingItem(Search.Previous);
  407. end;
  408. if not Assigned(Search) then
  409. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  410. JumpTracking.Concat(Search);
  411. Search.IncRefs;
  412. end;
  413. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  414. var
  415. Search: TJumpTrackingItem;
  416. begin
  417. Result := False;
  418. { See if this label appears in the tracking list }
  419. Search := TJumpTrackingItem(JumpTracking.Last);
  420. while Assigned(Search) do
  421. begin
  422. if Search.Symbol = Symbol then
  423. begin
  424. { Found it - let's see what we can discover }
  425. if Search.Symbol.getrefs = Search.Refs then
  426. begin
  427. { Success - all the references are accounted for }
  428. JumpTracking.Remove(Search);
  429. Search.Free;
  430. { It is logically impossible for CrossJump to be false here
  431. because we must have run into a conditional jump for
  432. this label at some point }
  433. if not CrossJump then
  434. InternalError(2022041710);
  435. if JumpTracking.First = nil then
  436. { Tracking list is now empty - no more cross jumps }
  437. CrossJump := False;
  438. Result := True;
  439. Exit;
  440. end;
  441. { If the references don't match, it's possible to enter
  442. this label through other means, so drop out }
  443. Exit;
  444. end;
  445. Search := TJumpTrackingItem(Search.Previous);
  446. end;
  447. end;
  448. var
  449. Next_Label: tai;
  450. begin
  451. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  452. Next := Current;
  453. repeat
  454. Result := GetNextInstruction(Next,Next);
  455. if not Result then
  456. Break;
  457. if Next.typ = ait_align then
  458. Result := SkipAligns(Next, Next);
  459. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  460. if is_calljmpuncondret(taicpu(Next).opcode) then
  461. begin
  462. if (taicpu(Next).opcode = A_JMP) and
  463. { Remove dead code now to save time }
  464. RemoveDeadCodeAfterJump(taicpu(Next)) then
  465. { A jump was removed, but not the current instruction, and
  466. Result doesn't necessarily translate into an optimisation
  467. routine's Result, so use the "Force New Iteration" flag so
  468. mark a new pass }
  469. Include(OptsToCheck, aoc_ForceNewIteration);
  470. if not Assigned(JumpTracking) then
  471. begin
  472. { Cross-label optimisations often causes other optimisations
  473. to perform worse because they're not given the chance to
  474. optimise locally. In this case, don't do the cross-label
  475. optimisations yet, but flag them as a potential possibility
  476. for the next iteration of Pass 1 }
  477. if not NotFirstIteration then
  478. Include(OptsToCheck, aoc_ForceNewIteration);
  479. end
  480. else if IsJumpToLabel(taicpu(Next)) and
  481. GetNextInstruction(Next, Next_Label) and
  482. SkipAligns(Next_Label, Next_Label) then
  483. begin
  484. { If we have JMP .lbl, and the label after it has all of its
  485. references tracked, then this is probably an if-else style of
  486. block and we can keep tracking. If the label for this jump
  487. then appears later and is fully tracked, then it's the end
  488. of the if-else blocks and the code paths converge (thus
  489. marking the end of the cross-jump) }
  490. if (Next_Label.typ = ait_label) then
  491. begin
  492. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  493. begin
  494. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  495. Next := Next_Label;
  496. { CrossJump gets set to false by LabelAccountedFor if the
  497. list is completely emptied (as it indicates that all
  498. code paths have converged). We could avoid this nuance
  499. by moving the TrackJump call to before the
  500. LabelAccountedFor call, but this is slower in situations
  501. where LabelAccountedFor would return False due to the
  502. creation of a new object that is not used and destroyed
  503. soon after. }
  504. CrossJump := True;
  505. Continue;
  506. end;
  507. end
  508. else if (Next_Label.typ <> ait_marker) then
  509. { We just did a RemoveDeadCodeAfterJump, so either we find
  510. a label, the end of the procedure or some kind of marker}
  511. InternalError(2022041720);
  512. end;
  513. Result := False;
  514. Exit;
  515. end
  516. else
  517. begin
  518. if not Assigned(JumpTracking) then
  519. begin
  520. { Cross-label optimisations often causes other optimisations
  521. to perform worse because they're not given the chance to
  522. optimise locally. In this case, don't do the cross-label
  523. optimisations yet, but flag them as a potential possibility
  524. for the next iteration of Pass 1 }
  525. if not NotFirstIteration then
  526. Include(OptsToCheck, aoc_ForceNewIteration);
  527. end
  528. else if IsJumpToLabel(taicpu(Next)) then
  529. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  530. else
  531. { Conditional jumps should always be a jump to label }
  532. InternalError(2022041701);
  533. CrossJump := True;
  534. Continue;
  535. end;
  536. if Next.typ = ait_label then
  537. begin
  538. if not Assigned(JumpTracking) then
  539. begin
  540. { Cross-label optimisations often causes other optimisations
  541. to perform worse because they're not given the chance to
  542. optimise locally. In this case, don't do the cross-label
  543. optimisations yet, but flag them as a potential possibility
  544. for the next iteration of Pass 1 }
  545. if not NotFirstIteration then
  546. Include(OptsToCheck, aoc_ForceNewIteration);
  547. end
  548. else if LabelAccountedFor(tai_label(Next).labsym) then
  549. Continue;
  550. { If we reach here, we're at a label that hasn't been seen before
  551. (or JumpTracking was nil) }
  552. Break;
  553. end;
  554. until not Result or
  555. not (cs_opt_level3 in current_settings.optimizerswitches) or
  556. not (Next.typ in [ait_label, ait_instruction]) or
  557. RegInInstruction(reg,Next);
  558. end;
  559. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  560. begin
  561. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  562. begin
  563. Result:=GetNextInstruction(Current,Next);
  564. exit;
  565. end;
  566. Next:=tai(Current.Next);
  567. Result:=false;
  568. while assigned(Next) do
  569. begin
  570. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  571. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  572. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  573. exit
  574. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  575. begin
  576. Result:=true;
  577. exit;
  578. end;
  579. Next:=tai(Next.Next);
  580. end;
  581. end;
  582. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  583. begin
  584. Result:=RegReadByInstruction(reg,hp);
  585. end;
  586. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  587. var
  588. p: taicpu;
  589. opcount: longint;
  590. begin
  591. RegReadByInstruction := false;
  592. if hp.typ <> ait_instruction then
  593. exit;
  594. p := taicpu(hp);
  595. case p.opcode of
  596. A_CALL:
  597. regreadbyinstruction := true;
  598. A_IMUL:
  599. case p.ops of
  600. 1:
  601. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  602. (
  603. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  604. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  605. );
  606. 2,3:
  607. regReadByInstruction :=
  608. reginop(reg,p.oper[0]^) or
  609. reginop(reg,p.oper[1]^);
  610. else
  611. InternalError(2019112801);
  612. end;
  613. A_MUL:
  614. begin
  615. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  616. (
  617. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  618. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  619. );
  620. end;
  621. A_IDIV,A_DIV:
  622. begin
  623. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  624. (
  625. (getregtype(reg)=R_INTREGISTER) and
  626. (
  627. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  628. )
  629. );
  630. end;
  631. else
  632. begin
  633. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  634. begin
  635. RegReadByInstruction := false;
  636. exit;
  637. end;
  638. for opcount := 0 to p.ops-1 do
  639. if (p.oper[opCount]^.typ = top_ref) and
  640. RegInRef(reg,p.oper[opcount]^.ref^) then
  641. begin
  642. RegReadByInstruction := true;
  643. exit
  644. end;
  645. { special handling for SSE MOVSD }
  646. if (p.opcode=A_MOVSD) and (p.ops>0) then
  647. begin
  648. if p.ops<>2 then
  649. internalerror(2017042702);
  650. regReadByInstruction := reginop(reg,p.oper[0]^) or
  651. (
  652. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  653. );
  654. exit;
  655. end;
  656. with insprop[p.opcode] do
  657. begin
  658. case getregtype(reg) of
  659. R_INTREGISTER:
  660. begin
  661. case getsupreg(reg) of
  662. RS_EAX:
  663. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  664. begin
  665. RegReadByInstruction := true;
  666. exit
  667. end;
  668. RS_ECX:
  669. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  670. begin
  671. RegReadByInstruction := true;
  672. exit
  673. end;
  674. RS_EDX:
  675. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  676. begin
  677. RegReadByInstruction := true;
  678. exit
  679. end;
  680. RS_EBX:
  681. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  682. begin
  683. RegReadByInstruction := true;
  684. exit
  685. end;
  686. RS_ESP:
  687. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  688. begin
  689. RegReadByInstruction := true;
  690. exit
  691. end;
  692. RS_EBP:
  693. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  694. begin
  695. RegReadByInstruction := true;
  696. exit
  697. end;
  698. RS_ESI:
  699. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  700. begin
  701. RegReadByInstruction := true;
  702. exit
  703. end;
  704. RS_EDI:
  705. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  706. begin
  707. RegReadByInstruction := true;
  708. exit
  709. end;
  710. end;
  711. end;
  712. R_MMREGISTER:
  713. begin
  714. case getsupreg(reg) of
  715. RS_XMM0:
  716. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  717. begin
  718. RegReadByInstruction := true;
  719. exit
  720. end;
  721. end;
  722. end;
  723. else
  724. ;
  725. end;
  726. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  727. begin
  728. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  729. begin
  730. case p.condition of
  731. C_A,C_NBE, { CF=0 and ZF=0 }
  732. C_BE,C_NA: { CF=1 or ZF=1 }
  733. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  734. C_AE,C_NB,C_NC, { CF=0 }
  735. C_B,C_NAE,C_C: { CF=1 }
  736. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  737. C_NE,C_NZ, { ZF=0 }
  738. C_E,C_Z: { ZF=1 }
  739. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  740. C_G,C_NLE, { ZF=0 and SF=OF }
  741. C_LE,C_NG: { ZF=1 or SF<>OF }
  742. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  743. C_GE,C_NL, { SF=OF }
  744. C_L,C_NGE: { SF<>OF }
  745. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  746. C_NO, { OF=0 }
  747. C_O: { OF=1 }
  748. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  749. C_NP,C_PO, { PF=0 }
  750. C_P,C_PE: { PF=1 }
  751. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  752. C_NS, { SF=0 }
  753. C_S: { SF=1 }
  754. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  755. else
  756. internalerror(2017042701);
  757. end;
  758. if RegReadByInstruction then
  759. exit;
  760. end;
  761. case getsubreg(reg) of
  762. R_SUBW,R_SUBD,R_SUBQ:
  763. RegReadByInstruction :=
  764. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  765. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  766. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  767. R_SUBFLAGCARRY:
  768. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  769. R_SUBFLAGPARITY:
  770. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  771. R_SUBFLAGAUXILIARY:
  772. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  773. R_SUBFLAGZERO:
  774. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  775. R_SUBFLAGSIGN:
  776. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  777. R_SUBFLAGOVERFLOW:
  778. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  779. R_SUBFLAGINTERRUPT:
  780. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  781. R_SUBFLAGDIRECTION:
  782. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  783. else
  784. internalerror(2017042601);
  785. end;
  786. exit;
  787. end;
  788. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  789. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  790. (p.oper[0]^.reg=p.oper[1]^.reg) then
  791. exit;
  792. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  793. begin
  794. RegReadByInstruction := true;
  795. exit
  796. end;
  797. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  798. begin
  799. RegReadByInstruction := true;
  800. exit
  801. end;
  802. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  803. begin
  804. RegReadByInstruction := true;
  805. exit
  806. end;
  807. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  808. begin
  809. RegReadByInstruction := true;
  810. exit
  811. end;
  812. end;
  813. end;
  814. end;
  815. end;
  816. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  817. begin
  818. result:=false;
  819. if p1.typ<>ait_instruction then
  820. exit;
  821. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  822. exit(true);
  823. if (getregtype(reg)=R_INTREGISTER) and
  824. { change information for xmm movsd are not correct }
  825. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  826. begin
  827. case getsupreg(reg) of
  828. { RS_EAX = RS_RAX on x86-64 }
  829. RS_EAX:
  830. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  831. RS_ECX:
  832. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  833. RS_EDX:
  834. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  835. RS_EBX:
  836. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  837. RS_ESP:
  838. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  839. RS_EBP:
  840. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  841. RS_ESI:
  842. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  843. RS_EDI:
  844. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  845. else
  846. ;
  847. end;
  848. if result then
  849. exit;
  850. end
  851. else if getregtype(reg)=R_MMREGISTER then
  852. begin
  853. case getsupreg(reg) of
  854. RS_XMM0:
  855. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  856. else
  857. ;
  858. end;
  859. if result then
  860. exit;
  861. end
  862. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  863. begin
  864. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  865. exit(true);
  866. case getsubreg(reg) of
  867. R_SUBFLAGCARRY:
  868. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  869. R_SUBFLAGPARITY:
  870. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  871. R_SUBFLAGAUXILIARY:
  872. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  873. R_SUBFLAGZERO:
  874. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  875. R_SUBFLAGSIGN:
  876. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  877. R_SUBFLAGOVERFLOW:
  878. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  879. R_SUBFLAGINTERRUPT:
  880. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  881. R_SUBFLAGDIRECTION:
  882. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  883. R_SUBW,R_SUBD,R_SUBQ:
  884. { Everything except the direction bits }
  885. Result:=
  886. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  887. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  888. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  889. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  890. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  891. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  892. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  893. else
  894. ;
  895. end;
  896. if result then
  897. exit;
  898. end
  899. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  900. exit(true);
  901. Result:=inherited RegInInstruction(Reg, p1);
  902. end;
  903. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  904. const
  905. WriteOps: array[0..3] of set of TInsChange =
  906. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  907. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  908. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  909. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  910. var
  911. OperIdx: Integer;
  912. begin
  913. Result := False;
  914. if p1.typ <> ait_instruction then
  915. exit;
  916. with insprop[taicpu(p1).opcode] do
  917. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  918. begin
  919. case getsubreg(reg) of
  920. R_SUBW,R_SUBD,R_SUBQ:
  921. Result :=
  922. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  923. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  924. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  925. R_SUBFLAGCARRY:
  926. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  927. R_SUBFLAGPARITY:
  928. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  929. R_SUBFLAGAUXILIARY:
  930. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  931. R_SUBFLAGZERO:
  932. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  933. R_SUBFLAGSIGN:
  934. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  935. R_SUBFLAGOVERFLOW:
  936. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  937. R_SUBFLAGINTERRUPT:
  938. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  939. R_SUBFLAGDIRECTION:
  940. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  941. else
  942. internalerror(2017042602);
  943. end;
  944. exit;
  945. end;
  946. case taicpu(p1).opcode of
  947. A_CALL:
  948. { We could potentially set Result to False if the register in
  949. question is non-volatile for the subroutine's calling convention,
  950. but this would require detecting the calling convention in use and
  951. also assuming that the routine doesn't contain malformed assembly
  952. language, for example... so it could only be done under -O4 as it
  953. would be considered a side-effect. [Kit] }
  954. Result := True;
  955. A_MOVSD:
  956. { special handling for SSE MOVSD }
  957. if (taicpu(p1).ops>0) then
  958. begin
  959. if taicpu(p1).ops<>2 then
  960. internalerror(2017042703);
  961. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  962. end;
  963. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  964. so fix it here (FK)
  965. }
  966. A_VMOVSS,
  967. A_VMOVSD:
  968. begin
  969. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  970. exit;
  971. end;
  972. A_IMUL:
  973. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  974. else
  975. ;
  976. end;
  977. if Result then
  978. exit;
  979. with insprop[taicpu(p1).opcode] do
  980. begin
  981. if getregtype(reg)=R_INTREGISTER then
  982. begin
  983. case getsupreg(reg) of
  984. RS_EAX:
  985. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  986. begin
  987. Result := True;
  988. exit
  989. end;
  990. RS_ECX:
  991. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  992. begin
  993. Result := True;
  994. exit
  995. end;
  996. RS_EDX:
  997. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  998. begin
  999. Result := True;
  1000. exit
  1001. end;
  1002. RS_EBX:
  1003. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1004. begin
  1005. Result := True;
  1006. exit
  1007. end;
  1008. RS_ESP:
  1009. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1010. begin
  1011. Result := True;
  1012. exit
  1013. end;
  1014. RS_EBP:
  1015. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1016. begin
  1017. Result := True;
  1018. exit
  1019. end;
  1020. RS_ESI:
  1021. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1022. begin
  1023. Result := True;
  1024. exit
  1025. end;
  1026. RS_EDI:
  1027. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1028. begin
  1029. Result := True;
  1030. exit
  1031. end;
  1032. end;
  1033. end;
  1034. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1035. if (WriteOps[OperIdx]*Ch<>[]) and
  1036. { The register doesn't get modified inside a reference }
  1037. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1038. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1039. begin
  1040. Result := true;
  1041. exit
  1042. end;
  1043. end;
  1044. end;
  1045. {$ifdef DEBUG_AOPTCPU}
  1046. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1047. begin
  1048. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1049. end;
  1050. function debug_tostr(i: tcgint): string; inline;
  1051. begin
  1052. Result := tostr(i);
  1053. end;
  1054. function debug_regname(r: TRegister): string; inline;
  1055. begin
  1056. Result := '%' + std_regname(r);
  1057. end;
  1058. { Debug output function - creates a string representation of an operator }
  1059. function debug_operstr(oper: TOper): string;
  1060. begin
  1061. case oper.typ of
  1062. top_const:
  1063. Result := '$' + debug_tostr(oper.val);
  1064. top_reg:
  1065. Result := debug_regname(oper.reg);
  1066. top_ref:
  1067. begin
  1068. if oper.ref^.offset <> 0 then
  1069. Result := debug_tostr(oper.ref^.offset) + '('
  1070. else
  1071. Result := '(';
  1072. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1073. begin
  1074. Result := Result + debug_regname(oper.ref^.base);
  1075. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1076. Result := Result + ',' + debug_regname(oper.ref^.index);
  1077. end
  1078. else
  1079. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1080. Result := Result + debug_regname(oper.ref^.index);
  1081. if (oper.ref^.scalefactor > 1) then
  1082. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1083. else
  1084. Result := Result + ')';
  1085. end;
  1086. else
  1087. Result := '[UNKNOWN]';
  1088. end;
  1089. end;
  1090. function debug_op2str(opcode: tasmop): string; inline;
  1091. begin
  1092. Result := std_op2str[opcode];
  1093. end;
  1094. function debug_opsize2str(opsize: topsize): string; inline;
  1095. begin
  1096. Result := gas_opsize2str[opsize];
  1097. end;
  1098. {$else DEBUG_AOPTCPU}
  1099. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1100. begin
  1101. end;
  1102. function debug_tostr(i: tcgint): string; inline;
  1103. begin
  1104. Result := '';
  1105. end;
  1106. function debug_regname(r: TRegister): string; inline;
  1107. begin
  1108. Result := '';
  1109. end;
  1110. function debug_operstr(oper: TOper): string; inline;
  1111. begin
  1112. Result := '';
  1113. end;
  1114. function debug_op2str(opcode: tasmop): string; inline;
  1115. begin
  1116. Result := '';
  1117. end;
  1118. function debug_opsize2str(opsize: topsize): string; inline;
  1119. begin
  1120. Result := '';
  1121. end;
  1122. {$endif DEBUG_AOPTCPU}
  1123. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1124. begin
  1125. {$ifdef x86_64}
  1126. { Always fine on x86-64 }
  1127. Result := True;
  1128. {$else x86_64}
  1129. Result :=
  1130. {$ifdef i8086}
  1131. (current_settings.cputype >= cpu_386) and
  1132. {$endif i8086}
  1133. (
  1134. { Always accept if optimising for size }
  1135. (cs_opt_size in current_settings.optimizerswitches) or
  1136. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1137. (current_settings.optimizecputype >= cpu_Pentium2)
  1138. );
  1139. {$endif x86_64}
  1140. end;
  1141. { Attempts to allocate a volatile integer register for use between p and hp,
  1142. using AUsedRegs for the current register usage information. Returns NR_NO
  1143. if no free register could be found }
  1144. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1145. var
  1146. RegSet: TCPURegisterSet;
  1147. CurrentSuperReg: Integer;
  1148. CurrentReg: TRegister;
  1149. Currentp: tai;
  1150. Breakout: Boolean;
  1151. begin
  1152. Result := NR_NO;
  1153. RegSet :=
  1154. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1155. current_procinfo.saved_regs_int;
  1156. for CurrentSuperReg in RegSet do
  1157. begin
  1158. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1159. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1160. {$if defined(i386) or defined(i8086)}
  1161. { If the target size is 8-bit, make sure we can actually encode it }
  1162. and (
  1163. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1164. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1165. )
  1166. {$endif i386 or i8086}
  1167. then
  1168. begin
  1169. Currentp := p;
  1170. Breakout := False;
  1171. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1172. begin
  1173. case Currentp.typ of
  1174. ait_instruction:
  1175. begin
  1176. if RegInInstruction(CurrentReg, Currentp) then
  1177. begin
  1178. Breakout := True;
  1179. Break;
  1180. end;
  1181. { Cannot allocate across an unconditional jump }
  1182. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1183. Exit;
  1184. end;
  1185. ait_marker:
  1186. { Don't try anything more if a marker is hit }
  1187. Exit;
  1188. ait_regalloc:
  1189. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1190. begin
  1191. Breakout := True;
  1192. Break;
  1193. end;
  1194. else
  1195. ;
  1196. end;
  1197. end;
  1198. if Breakout then
  1199. { Try the next register }
  1200. Continue;
  1201. { We have a free register available }
  1202. Result := CurrentReg;
  1203. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1204. Exit;
  1205. end;
  1206. end;
  1207. end;
  1208. { Attempts to allocate a volatile MM register for use between p and hp,
  1209. using AUsedRegs for the current register usage information. Returns NR_NO
  1210. if no free register could be found }
  1211. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1212. var
  1213. RegSet: TCPURegisterSet;
  1214. CurrentSuperReg: Integer;
  1215. CurrentReg: TRegister;
  1216. Currentp: tai;
  1217. Breakout: Boolean;
  1218. begin
  1219. Result := NR_NO;
  1220. RegSet :=
  1221. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1222. current_procinfo.saved_regs_mm;
  1223. for CurrentSuperReg in RegSet do
  1224. begin
  1225. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1226. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1227. begin
  1228. Currentp := p;
  1229. Breakout := False;
  1230. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1231. begin
  1232. case Currentp.typ of
  1233. ait_instruction:
  1234. begin
  1235. if RegInInstruction(CurrentReg, Currentp) then
  1236. begin
  1237. Breakout := True;
  1238. Break;
  1239. end;
  1240. { Cannot allocate across an unconditional jump }
  1241. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1242. Exit;
  1243. end;
  1244. ait_marker:
  1245. { Don't try anything more if a marker is hit }
  1246. Exit;
  1247. ait_regalloc:
  1248. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1249. begin
  1250. Breakout := True;
  1251. Break;
  1252. end;
  1253. else
  1254. ;
  1255. end;
  1256. end;
  1257. if Breakout then
  1258. { Try the next register }
  1259. Continue;
  1260. { We have a free register available }
  1261. Result := CurrentReg;
  1262. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1263. Exit;
  1264. end;
  1265. end;
  1266. end;
  1267. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1268. begin
  1269. if not SuperRegistersEqual(reg1,reg2) then
  1270. exit(false);
  1271. if getregtype(reg1)<>R_INTREGISTER then
  1272. exit(true); {because SuperRegisterEqual is true}
  1273. case getsubreg(reg1) of
  1274. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1275. higher, it preserves the high bits, so the new value depends on
  1276. reg2's previous value. In other words, it is equivalent to doing:
  1277. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1278. R_SUBL:
  1279. exit(getsubreg(reg2)=R_SUBL);
  1280. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1281. higher, it actually does a:
  1282. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1283. R_SUBH:
  1284. exit(getsubreg(reg2)=R_SUBH);
  1285. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1286. bits of reg2:
  1287. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1288. R_SUBW:
  1289. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1290. { a write to R_SUBD always overwrites every other subregister,
  1291. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1292. R_SUBD,
  1293. R_SUBQ:
  1294. exit(true);
  1295. else
  1296. internalerror(2017042801);
  1297. end;
  1298. end;
  1299. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1300. begin
  1301. if not SuperRegistersEqual(reg1,reg2) then
  1302. exit(false);
  1303. if getregtype(reg1)<>R_INTREGISTER then
  1304. exit(true); {because SuperRegisterEqual is true}
  1305. case getsubreg(reg1) of
  1306. R_SUBL:
  1307. exit(getsubreg(reg2)<>R_SUBH);
  1308. R_SUBH:
  1309. exit(getsubreg(reg2)<>R_SUBL);
  1310. R_SUBW,
  1311. R_SUBD,
  1312. R_SUBQ:
  1313. exit(true);
  1314. else
  1315. internalerror(2017042802);
  1316. end;
  1317. end;
  1318. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1319. var
  1320. hp1 : tai;
  1321. l : TCGInt;
  1322. begin
  1323. result:=false;
  1324. { changes the code sequence
  1325. shr/sar const1, x
  1326. shl const2, x
  1327. to
  1328. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1329. if GetNextInstruction(p, hp1) and
  1330. MatchInstruction(hp1,A_SHL,[]) and
  1331. (taicpu(p).oper[0]^.typ = top_const) and
  1332. (taicpu(hp1).oper[0]^.typ = top_const) and
  1333. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1334. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1335. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1336. begin
  1337. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1338. not(cs_opt_size in current_settings.optimizerswitches) then
  1339. begin
  1340. { shr/sar const1, %reg
  1341. shl const2, %reg
  1342. with const1 > const2 }
  1343. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1344. taicpu(hp1).opcode := A_AND;
  1345. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1346. case taicpu(p).opsize Of
  1347. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1348. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1349. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1350. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1351. else
  1352. Internalerror(2017050703)
  1353. end;
  1354. end
  1355. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1356. not(cs_opt_size in current_settings.optimizerswitches) then
  1357. begin
  1358. { shr/sar const1, %reg
  1359. shl const2, %reg
  1360. with const1 < const2 }
  1361. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1362. taicpu(p).opcode := A_AND;
  1363. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1364. case taicpu(p).opsize Of
  1365. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1366. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1367. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1368. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1369. else
  1370. Internalerror(2017050702)
  1371. end;
  1372. end
  1373. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1374. begin
  1375. { shr/sar const1, %reg
  1376. shl const2, %reg
  1377. with const1 = const2 }
  1378. taicpu(p).opcode := A_AND;
  1379. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1380. case taicpu(p).opsize Of
  1381. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1382. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1383. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1384. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1385. else
  1386. Internalerror(2017050701)
  1387. end;
  1388. RemoveInstruction(hp1);
  1389. end;
  1390. end;
  1391. end;
  1392. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1393. var
  1394. opsize : topsize;
  1395. hp1 : tai;
  1396. tmpref : treference;
  1397. ShiftValue : Cardinal;
  1398. BaseValue : TCGInt;
  1399. begin
  1400. result:=false;
  1401. opsize:=taicpu(p).opsize;
  1402. { changes certain "imul const, %reg"'s to lea sequences }
  1403. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1404. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1405. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1406. if (taicpu(p).oper[0]^.val = 1) then
  1407. if (taicpu(p).ops = 2) then
  1408. { remove "imul $1, reg" }
  1409. begin
  1410. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1411. Result := RemoveCurrentP(p);
  1412. end
  1413. else
  1414. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1415. begin
  1416. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1417. InsertLLItem(p.previous, p.next, hp1);
  1418. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1419. p.free;
  1420. p := hp1;
  1421. end
  1422. else if ((taicpu(p).ops <= 2) or
  1423. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1424. not(cs_opt_size in current_settings.optimizerswitches) and
  1425. (not(GetNextInstruction(p, hp1)) or
  1426. not((tai(hp1).typ = ait_instruction) and
  1427. ((taicpu(hp1).opcode=A_Jcc) and
  1428. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1429. begin
  1430. {
  1431. imul X, reg1, reg2 to
  1432. lea (reg1,reg1,Y), reg2
  1433. shl ZZ,reg2
  1434. imul XX, reg1 to
  1435. lea (reg1,reg1,YY), reg1
  1436. shl ZZ,reg2
  1437. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1438. it does not exist as a separate optimization target in FPC though.
  1439. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1440. at most two zeros
  1441. }
  1442. reference_reset(tmpref,1,[]);
  1443. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1444. begin
  1445. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1446. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1447. TmpRef.base := taicpu(p).oper[1]^.reg;
  1448. TmpRef.index := taicpu(p).oper[1]^.reg;
  1449. if not(BaseValue in [3,5,9]) then
  1450. Internalerror(2018110101);
  1451. TmpRef.ScaleFactor := BaseValue-1;
  1452. if (taicpu(p).ops = 2) then
  1453. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1454. else
  1455. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1456. AsmL.InsertAfter(hp1,p);
  1457. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1458. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1459. RemoveCurrentP(p, hp1);
  1460. if ShiftValue>0 then
  1461. AsmL.InsertAfter(taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg),hp1);
  1462. end;
  1463. end;
  1464. end;
  1465. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1466. begin
  1467. Result := False;
  1468. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1469. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1470. begin
  1471. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1472. taicpu(p).opcode := A_MOV;
  1473. Result := True;
  1474. end;
  1475. end;
  1476. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1477. var
  1478. p: taicpu absolute hp; { Implicit typecast }
  1479. i: Integer;
  1480. begin
  1481. Result := False;
  1482. if not assigned(hp) or
  1483. (hp.typ <> ait_instruction) then
  1484. Exit;
  1485. Prefetch(insprop[p.opcode]);
  1486. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1487. with insprop[p.opcode] do
  1488. begin
  1489. case getsubreg(reg) of
  1490. R_SUBW,R_SUBD,R_SUBQ:
  1491. Result:=
  1492. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1493. uncommon flags are checked first }
  1494. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1495. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1496. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1497. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1498. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1499. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1500. R_SUBFLAGCARRY:
  1501. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1502. R_SUBFLAGPARITY:
  1503. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1504. R_SUBFLAGAUXILIARY:
  1505. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1506. R_SUBFLAGZERO:
  1507. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1508. R_SUBFLAGSIGN:
  1509. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1510. R_SUBFLAGOVERFLOW:
  1511. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1512. R_SUBFLAGINTERRUPT:
  1513. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1514. R_SUBFLAGDIRECTION:
  1515. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1516. else
  1517. internalerror(2017050501);
  1518. end;
  1519. exit;
  1520. end;
  1521. { Handle special cases first }
  1522. case p.opcode of
  1523. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1524. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1525. begin
  1526. Result :=
  1527. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1528. (p.oper[1]^.typ = top_reg) and
  1529. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1530. (
  1531. (p.oper[0]^.typ = top_const) or
  1532. (
  1533. (p.oper[0]^.typ = top_reg) and
  1534. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1535. ) or (
  1536. (p.oper[0]^.typ = top_ref) and
  1537. not RegInRef(reg,p.oper[0]^.ref^)
  1538. )
  1539. );
  1540. end;
  1541. A_MUL, A_IMUL:
  1542. Result :=
  1543. (
  1544. (p.ops=3) and { IMUL only }
  1545. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1546. (
  1547. (
  1548. (p.oper[1]^.typ=top_reg) and
  1549. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1550. ) or (
  1551. (p.oper[1]^.typ=top_ref) and
  1552. not RegInRef(reg,p.oper[1]^.ref^)
  1553. )
  1554. )
  1555. ) or (
  1556. (
  1557. (p.ops=1) and
  1558. (
  1559. (
  1560. (
  1561. (p.oper[0]^.typ=top_reg) and
  1562. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1563. )
  1564. ) or (
  1565. (p.oper[0]^.typ=top_ref) and
  1566. not RegInRef(reg,p.oper[0]^.ref^)
  1567. )
  1568. ) and (
  1569. (
  1570. (p.opsize=S_B) and
  1571. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1572. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1573. ) or (
  1574. (p.opsize=S_W) and
  1575. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1576. ) or (
  1577. (p.opsize=S_L) and
  1578. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1579. {$ifdef x86_64}
  1580. ) or (
  1581. (p.opsize=S_Q) and
  1582. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1583. {$endif x86_64}
  1584. )
  1585. )
  1586. )
  1587. );
  1588. A_CBW:
  1589. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1590. {$ifndef x86_64}
  1591. A_LDS:
  1592. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1593. A_LES:
  1594. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1595. {$endif not x86_64}
  1596. A_LFS:
  1597. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1598. A_LGS:
  1599. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1600. A_LSS:
  1601. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1602. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1603. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1604. A_LODSB:
  1605. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1606. A_LODSW:
  1607. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1608. {$ifdef x86_64}
  1609. A_LODSQ:
  1610. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1611. {$endif x86_64}
  1612. A_LODSD:
  1613. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1614. A_FSTSW, A_FNSTSW:
  1615. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1616. else
  1617. begin
  1618. with insprop[p.opcode] do
  1619. begin
  1620. if (
  1621. { xor %reg,%reg etc. is classed as a new value }
  1622. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1623. MatchOpType(p, top_reg, top_reg) and
  1624. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1625. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1626. ) then
  1627. begin
  1628. Result := True;
  1629. Exit;
  1630. end;
  1631. { Make sure the entire register is overwritten }
  1632. if (getregtype(reg) = R_INTREGISTER) then
  1633. begin
  1634. if (p.ops > 0) then
  1635. begin
  1636. if RegInOp(reg, p.oper[0]^) then
  1637. begin
  1638. if (p.oper[0]^.typ = top_ref) then
  1639. begin
  1640. if RegInRef(reg, p.oper[0]^.ref^) then
  1641. begin
  1642. Result := False;
  1643. Exit;
  1644. end;
  1645. end
  1646. else if (p.oper[0]^.typ = top_reg) then
  1647. begin
  1648. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1649. begin
  1650. Result := False;
  1651. Exit;
  1652. end
  1653. else if ([Ch_WOp1]*Ch<>[]) then
  1654. begin
  1655. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1656. Result := True
  1657. else
  1658. begin
  1659. Result := False;
  1660. Exit;
  1661. end;
  1662. end;
  1663. end;
  1664. end;
  1665. if (p.ops > 1) then
  1666. begin
  1667. if RegInOp(reg, p.oper[1]^) then
  1668. begin
  1669. if (p.oper[1]^.typ = top_ref) then
  1670. begin
  1671. if RegInRef(reg, p.oper[1]^.ref^) then
  1672. begin
  1673. Result := False;
  1674. Exit;
  1675. end;
  1676. end
  1677. else if (p.oper[1]^.typ = top_reg) then
  1678. begin
  1679. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1680. begin
  1681. Result := False;
  1682. Exit;
  1683. end
  1684. else if ([Ch_WOp2]*Ch<>[]) then
  1685. begin
  1686. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1687. Result := True
  1688. else
  1689. begin
  1690. Result := False;
  1691. Exit;
  1692. end;
  1693. end;
  1694. end;
  1695. end;
  1696. if (p.ops > 2) then
  1697. begin
  1698. if RegInOp(reg, p.oper[2]^) then
  1699. begin
  1700. if (p.oper[2]^.typ = top_ref) then
  1701. begin
  1702. if RegInRef(reg, p.oper[2]^.ref^) then
  1703. begin
  1704. Result := False;
  1705. Exit;
  1706. end;
  1707. end
  1708. else if (p.oper[2]^.typ = top_reg) then
  1709. begin
  1710. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1711. begin
  1712. Result := False;
  1713. Exit;
  1714. end
  1715. else if ([Ch_WOp3]*Ch<>[]) then
  1716. begin
  1717. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1718. Result := True
  1719. else
  1720. begin
  1721. Result := False;
  1722. Exit;
  1723. end;
  1724. end;
  1725. end;
  1726. end;
  1727. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1728. begin
  1729. if (p.oper[3]^.typ = top_ref) then
  1730. begin
  1731. if RegInRef(reg, p.oper[3]^.ref^) then
  1732. begin
  1733. Result := False;
  1734. Exit;
  1735. end;
  1736. end
  1737. else if (p.oper[3]^.typ = top_reg) then
  1738. begin
  1739. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1740. begin
  1741. Result := False;
  1742. Exit;
  1743. end
  1744. else if ([Ch_WOp4]*Ch<>[]) then
  1745. begin
  1746. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1747. Result := True
  1748. else
  1749. begin
  1750. Result := False;
  1751. Exit;
  1752. end;
  1753. end;
  1754. end;
  1755. end;
  1756. end;
  1757. end;
  1758. end;
  1759. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1760. case getsupreg(reg) of
  1761. RS_EAX:
  1762. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1763. begin
  1764. Result := True;
  1765. Exit;
  1766. end;
  1767. RS_ECX:
  1768. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1769. begin
  1770. Result := True;
  1771. Exit;
  1772. end;
  1773. RS_EDX:
  1774. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1775. begin
  1776. Result := True;
  1777. Exit;
  1778. end;
  1779. RS_EBX:
  1780. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1781. begin
  1782. Result := True;
  1783. Exit;
  1784. end;
  1785. RS_ESP:
  1786. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1787. begin
  1788. Result := True;
  1789. Exit;
  1790. end;
  1791. RS_EBP:
  1792. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1793. begin
  1794. Result := True;
  1795. Exit;
  1796. end;
  1797. RS_ESI:
  1798. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1799. begin
  1800. Result := True;
  1801. Exit;
  1802. end;
  1803. RS_EDI:
  1804. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1805. begin
  1806. Result := True;
  1807. Exit;
  1808. end;
  1809. else
  1810. ;
  1811. end;
  1812. end;
  1813. end;
  1814. end;
  1815. end;
  1816. end;
  1817. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1818. var
  1819. hp2,hp3 : tai;
  1820. begin
  1821. { some x86-64 issue a NOP before the real exit code }
  1822. if MatchInstruction(p,A_NOP,[]) then
  1823. GetNextInstruction(p,p);
  1824. result:=assigned(p) and (p.typ=ait_instruction) and
  1825. ((taicpu(p).opcode = A_RET) or
  1826. ((taicpu(p).opcode=A_LEAVE) and
  1827. GetNextInstruction(p,hp2) and
  1828. MatchInstruction(hp2,A_RET,[S_NO])
  1829. ) or
  1830. (((taicpu(p).opcode=A_LEA) and
  1831. MatchOpType(taicpu(p),top_ref,top_reg) and
  1832. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1833. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1834. ) and
  1835. GetNextInstruction(p,hp2) and
  1836. MatchInstruction(hp2,A_RET,[S_NO])
  1837. ) or
  1838. ((((taicpu(p).opcode=A_MOV) and
  1839. MatchOpType(taicpu(p),top_reg,top_reg) and
  1840. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1841. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1842. ((taicpu(p).opcode=A_LEA) and
  1843. MatchOpType(taicpu(p),top_ref,top_reg) and
  1844. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1845. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1846. )
  1847. ) and
  1848. GetNextInstruction(p,hp2) and
  1849. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1850. MatchOpType(taicpu(hp2),top_reg) and
  1851. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1852. GetNextInstruction(hp2,hp3) and
  1853. MatchInstruction(hp3,A_RET,[S_NO])
  1854. )
  1855. );
  1856. end;
  1857. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1858. begin
  1859. isFoldableArithOp := False;
  1860. case hp1.opcode of
  1861. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1862. isFoldableArithOp :=
  1863. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1864. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1865. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1866. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1867. (taicpu(hp1).oper[1]^.reg = reg);
  1868. A_INC,A_DEC,A_NEG,A_NOT:
  1869. isFoldableArithOp :=
  1870. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1871. (taicpu(hp1).oper[0]^.reg = reg);
  1872. else
  1873. ;
  1874. end;
  1875. end;
  1876. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1877. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1878. var
  1879. hp2: tai;
  1880. begin
  1881. hp2 := p;
  1882. repeat
  1883. hp2 := tai(hp2.previous);
  1884. if assigned(hp2) and
  1885. (hp2.typ = ait_regalloc) and
  1886. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1887. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1888. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1889. begin
  1890. RemoveInstruction(hp2);
  1891. break;
  1892. end;
  1893. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1894. end;
  1895. begin
  1896. case current_procinfo.procdef.returndef.typ of
  1897. arraydef,recorddef,pointerdef,
  1898. stringdef,enumdef,procdef,objectdef,errordef,
  1899. filedef,setdef,procvardef,
  1900. classrefdef,forwarddef:
  1901. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1902. orddef:
  1903. if current_procinfo.procdef.returndef.size <> 0 then
  1904. begin
  1905. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1906. { for int64/qword }
  1907. if current_procinfo.procdef.returndef.size = 8 then
  1908. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1909. end;
  1910. else
  1911. ;
  1912. end;
  1913. end;
  1914. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1915. var
  1916. hp1,hp2 : tai;
  1917. begin
  1918. result:=false;
  1919. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1920. begin
  1921. { vmova* reg1,reg1
  1922. =>
  1923. <nop> }
  1924. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1925. begin
  1926. RemoveCurrentP(p);
  1927. result:=true;
  1928. exit;
  1929. end
  1930. else if GetNextInstruction(p,hp1) then
  1931. begin
  1932. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1933. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1934. begin
  1935. { vmova* reg1,reg2
  1936. vmova* reg2,reg3
  1937. dealloc reg2
  1938. =>
  1939. vmova* reg1,reg3 }
  1940. TransferUsedRegs(TmpUsedRegs);
  1941. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1942. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1943. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1944. begin
  1945. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1946. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1947. RemoveInstruction(hp1);
  1948. result:=true;
  1949. exit;
  1950. end
  1951. { special case:
  1952. vmova* reg1,<op>
  1953. vmova* <op>,reg1
  1954. =>
  1955. vmova* reg1,<op> }
  1956. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1957. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1958. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1959. ) then
  1960. begin
  1961. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1962. RemoveInstruction(hp1);
  1963. result:=true;
  1964. exit;
  1965. end
  1966. end
  1967. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  1968. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  1969. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  1970. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  1971. ) and
  1972. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1973. begin
  1974. { vmova* reg1,reg2
  1975. vmovs* reg2,<op>
  1976. dealloc reg2
  1977. =>
  1978. vmovs* reg1,reg3 }
  1979. TransferUsedRegs(TmpUsedRegs);
  1980. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1981. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1982. begin
  1983. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  1984. taicpu(p).opcode:=taicpu(hp1).opcode;
  1985. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1986. RemoveInstruction(hp1);
  1987. result:=true;
  1988. exit;
  1989. end
  1990. end;
  1991. end;
  1992. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  1993. begin
  1994. if MatchInstruction(hp1,[A_VFMADDPD,
  1995. A_VFMADD132PD,
  1996. A_VFMADD132PS,
  1997. A_VFMADD132SD,
  1998. A_VFMADD132SS,
  1999. A_VFMADD213PD,
  2000. A_VFMADD213PS,
  2001. A_VFMADD213SD,
  2002. A_VFMADD213SS,
  2003. A_VFMADD231PD,
  2004. A_VFMADD231PS,
  2005. A_VFMADD231SD,
  2006. A_VFMADD231SS,
  2007. A_VFMADDSUB132PD,
  2008. A_VFMADDSUB132PS,
  2009. A_VFMADDSUB213PD,
  2010. A_VFMADDSUB213PS,
  2011. A_VFMADDSUB231PD,
  2012. A_VFMADDSUB231PS,
  2013. A_VFMSUB132PD,
  2014. A_VFMSUB132PS,
  2015. A_VFMSUB132SD,
  2016. A_VFMSUB132SS,
  2017. A_VFMSUB213PD,
  2018. A_VFMSUB213PS,
  2019. A_VFMSUB213SD,
  2020. A_VFMSUB213SS,
  2021. A_VFMSUB231PD,
  2022. A_VFMSUB231PS,
  2023. A_VFMSUB231SD,
  2024. A_VFMSUB231SS,
  2025. A_VFMSUBADD132PD,
  2026. A_VFMSUBADD132PS,
  2027. A_VFMSUBADD213PD,
  2028. A_VFMSUBADD213PS,
  2029. A_VFMSUBADD231PD,
  2030. A_VFMSUBADD231PS,
  2031. A_VFNMADD132PD,
  2032. A_VFNMADD132PS,
  2033. A_VFNMADD132SD,
  2034. A_VFNMADD132SS,
  2035. A_VFNMADD213PD,
  2036. A_VFNMADD213PS,
  2037. A_VFNMADD213SD,
  2038. A_VFNMADD213SS,
  2039. A_VFNMADD231PD,
  2040. A_VFNMADD231PS,
  2041. A_VFNMADD231SD,
  2042. A_VFNMADD231SS,
  2043. A_VFNMSUB132PD,
  2044. A_VFNMSUB132PS,
  2045. A_VFNMSUB132SD,
  2046. A_VFNMSUB132SS,
  2047. A_VFNMSUB213PD,
  2048. A_VFNMSUB213PS,
  2049. A_VFNMSUB213SD,
  2050. A_VFNMSUB213SS,
  2051. A_VFNMSUB231PD,
  2052. A_VFNMSUB231PS,
  2053. A_VFNMSUB231SD,
  2054. A_VFNMSUB231SS],[S_NO]) and
  2055. { we mix single and double opperations here because we assume that the compiler
  2056. generates vmovapd only after double operations and vmovaps only after single operations }
  2057. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  2058. GetNextInstruction(hp1,hp2) and
  2059. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2060. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2061. begin
  2062. TransferUsedRegs(TmpUsedRegs);
  2063. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2064. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2065. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2066. begin
  2067. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2068. RemoveCurrentP(p, hp1); // <-- Is this actually safe? hp1 is not necessarily the next instruction. [Kit]
  2069. RemoveInstruction(hp2);
  2070. end;
  2071. end
  2072. else if (hp1.typ = ait_instruction) and
  2073. GetNextInstruction(hp1, hp2) and
  2074. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2075. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2076. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2077. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  2078. (((taicpu(p).opcode=A_MOVAPS) and
  2079. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2080. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2081. ((taicpu(p).opcode=A_MOVAPD) and
  2082. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2083. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2084. ) then
  2085. { change
  2086. movapX reg,reg2
  2087. addsX/subsX/... reg3, reg2
  2088. movapX reg2,reg
  2089. to
  2090. addsX/subsX/... reg3,reg
  2091. }
  2092. begin
  2093. TransferUsedRegs(TmpUsedRegs);
  2094. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2095. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2096. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2097. begin
  2098. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2099. debug_op2str(taicpu(p).opcode)+' '+
  2100. debug_op2str(taicpu(hp1).opcode)+' '+
  2101. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2102. { we cannot eliminate the first move if
  2103. the operations uses the same register for source and dest }
  2104. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2105. RemoveCurrentP(p, nil);
  2106. p:=hp1;
  2107. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2108. RemoveInstruction(hp2);
  2109. result:=true;
  2110. end;
  2111. end
  2112. else if (hp1.typ = ait_instruction) and
  2113. (((taicpu(p).opcode=A_VMOVAPD) and
  2114. (taicpu(hp1).opcode=A_VCOMISD)) or
  2115. ((taicpu(p).opcode=A_VMOVAPS) and
  2116. ((taicpu(hp1).opcode=A_VCOMISS))
  2117. )
  2118. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2119. { change
  2120. movapX reg,reg1
  2121. vcomisX reg1,reg1
  2122. to
  2123. vcomisX reg,reg
  2124. }
  2125. begin
  2126. TransferUsedRegs(TmpUsedRegs);
  2127. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2128. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2129. begin
  2130. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2131. debug_op2str(taicpu(p).opcode)+' '+
  2132. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2133. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2134. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2135. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2136. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2137. RemoveCurrentP(p, nil);
  2138. result:=true;
  2139. exit;
  2140. end;
  2141. end
  2142. end;
  2143. end;
  2144. end;
  2145. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2146. var
  2147. hp1 : tai;
  2148. begin
  2149. result:=false;
  2150. { replace
  2151. V<Op>X %mreg1,%mreg2,%mreg3
  2152. VMovX %mreg3,%mreg4
  2153. dealloc %mreg3
  2154. by
  2155. V<Op>X %mreg1,%mreg2,%mreg4
  2156. ?
  2157. }
  2158. if GetNextInstruction(p,hp1) and
  2159. { we mix single and double operations here because we assume that the compiler
  2160. generates vmovapd only after double operations and vmovaps only after single operations }
  2161. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2162. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2163. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2164. begin
  2165. TransferUsedRegs(TmpUsedRegs);
  2166. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2167. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2168. begin
  2169. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2170. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2171. RemoveInstruction(hp1);
  2172. result:=true;
  2173. end;
  2174. end;
  2175. end;
  2176. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2177. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2178. begin
  2179. Result := False;
  2180. { For safety reasons, only check for exact register matches }
  2181. { Check base register }
  2182. if (ref.base = AOldReg) then
  2183. begin
  2184. ref.base := ANewReg;
  2185. Result := True;
  2186. end;
  2187. { Check index register }
  2188. if (ref.index = AOldReg) then
  2189. begin
  2190. ref.index := ANewReg;
  2191. Result := True;
  2192. end;
  2193. end;
  2194. { Replaces all references to AOldReg in an operand to ANewReg }
  2195. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2196. var
  2197. OldSupReg, NewSupReg: TSuperRegister;
  2198. OldSubReg, NewSubReg: TSubRegister;
  2199. OldRegType: TRegisterType;
  2200. ThisOper: POper;
  2201. begin
  2202. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2203. Result := False;
  2204. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2205. InternalError(2020011801);
  2206. OldSupReg := getsupreg(AOldReg);
  2207. OldSubReg := getsubreg(AOldReg);
  2208. OldRegType := getregtype(AOldReg);
  2209. NewSupReg := getsupreg(ANewReg);
  2210. NewSubReg := getsubreg(ANewReg);
  2211. if OldRegType <> getregtype(ANewReg) then
  2212. InternalError(2020011802);
  2213. if OldSubReg <> NewSubReg then
  2214. InternalError(2020011803);
  2215. case ThisOper^.typ of
  2216. top_reg:
  2217. if (
  2218. (ThisOper^.reg = AOldReg) or
  2219. (
  2220. (OldRegType = R_INTREGISTER) and
  2221. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2222. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2223. (
  2224. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2225. {$ifndef x86_64}
  2226. and (
  2227. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2228. don't have an 8-bit representation }
  2229. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2230. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2231. )
  2232. {$endif x86_64}
  2233. )
  2234. )
  2235. ) then
  2236. begin
  2237. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2238. Result := True;
  2239. end;
  2240. top_ref:
  2241. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2242. Result := True;
  2243. else
  2244. ;
  2245. end;
  2246. end;
  2247. { Replaces all references to AOldReg in an instruction to ANewReg }
  2248. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2249. const
  2250. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2251. var
  2252. OperIdx: Integer;
  2253. begin
  2254. Result := False;
  2255. for OperIdx := 0 to p.ops - 1 do
  2256. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2257. begin
  2258. { The shift and rotate instructions can only use CL }
  2259. if not (
  2260. (OperIdx = 0) and
  2261. { This second condition just helps to avoid unnecessarily
  2262. calling MatchInstruction for 10 different opcodes }
  2263. (p.oper[0]^.reg = NR_CL) and
  2264. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2265. ) then
  2266. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2267. end
  2268. else if p.oper[OperIdx]^.typ = top_ref then
  2269. { It's okay to replace registers in references that get written to }
  2270. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2271. end;
  2272. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2273. begin
  2274. with ref^ do
  2275. Result :=
  2276. (index = NR_NO) and
  2277. (
  2278. {$ifdef x86_64}
  2279. (
  2280. (base = NR_RIP) and
  2281. (refaddr in [addr_pic, addr_pic_no_got])
  2282. ) or
  2283. {$endif x86_64}
  2284. (base = NR_STACK_POINTER_REG) or
  2285. (base = current_procinfo.framepointer)
  2286. );
  2287. end;
  2288. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2289. var
  2290. l: asizeint;
  2291. begin
  2292. Result := False;
  2293. { Should have been checked previously }
  2294. if p.opcode <> A_LEA then
  2295. InternalError(2020072501);
  2296. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2297. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2298. not(cs_opt_size in current_settings.optimizerswitches) then
  2299. exit;
  2300. with p.oper[0]^.ref^ do
  2301. begin
  2302. if (base <> p.oper[1]^.reg) or
  2303. (index <> NR_NO) or
  2304. assigned(symbol) then
  2305. exit;
  2306. l:=offset;
  2307. if (l=1) and UseIncDec then
  2308. begin
  2309. p.opcode:=A_INC;
  2310. p.loadreg(0,p.oper[1]^.reg);
  2311. p.ops:=1;
  2312. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2313. end
  2314. else if (l=-1) and UseIncDec then
  2315. begin
  2316. p.opcode:=A_DEC;
  2317. p.loadreg(0,p.oper[1]^.reg);
  2318. p.ops:=1;
  2319. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2320. end
  2321. else
  2322. begin
  2323. if (l<0) and (l<>-2147483648) then
  2324. begin
  2325. p.opcode:=A_SUB;
  2326. p.loadConst(0,-l);
  2327. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2328. end
  2329. else
  2330. begin
  2331. p.opcode:=A_ADD;
  2332. p.loadConst(0,l);
  2333. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2334. end;
  2335. end;
  2336. end;
  2337. Result := True;
  2338. end;
  2339. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2340. var
  2341. CurrentReg, ReplaceReg: TRegister;
  2342. begin
  2343. Result := False;
  2344. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2345. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2346. case hp.opcode of
  2347. A_FSTSW, A_FNSTSW,
  2348. A_IN, A_INS, A_OUT, A_OUTS,
  2349. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2350. { These routines have explicit operands, but they are restricted in
  2351. what they can be (e.g. IN and OUT can only read from AL, AX or
  2352. EAX. }
  2353. Exit;
  2354. A_IMUL:
  2355. begin
  2356. { The 1-operand version writes to implicit registers
  2357. The 2-operand version reads from the first operator, and reads
  2358. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2359. the 3-operand version reads from a register that it doesn't write to
  2360. }
  2361. case hp.ops of
  2362. 1:
  2363. if (
  2364. (
  2365. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2366. ) or
  2367. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2368. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2369. begin
  2370. Result := True;
  2371. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2372. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2373. end;
  2374. 2:
  2375. { Only modify the first parameter }
  2376. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2377. begin
  2378. Result := True;
  2379. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2380. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2381. end;
  2382. 3:
  2383. { Only modify the second parameter }
  2384. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2385. begin
  2386. Result := True;
  2387. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2388. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2389. end;
  2390. else
  2391. InternalError(2020012901);
  2392. end;
  2393. end;
  2394. else
  2395. if (hp.ops > 0) and
  2396. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2397. begin
  2398. Result := True;
  2399. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2400. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2401. end;
  2402. end;
  2403. end;
  2404. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2405. var
  2406. hp1, hp2, hp3: tai;
  2407. DoOptimisation, TempBool: Boolean;
  2408. {$ifdef x86_64}
  2409. NewConst: TCGInt;
  2410. {$endif x86_64}
  2411. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2412. begin
  2413. if taicpu(hp1).opcode = signed_movop then
  2414. begin
  2415. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2416. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2417. end
  2418. else
  2419. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2420. end;
  2421. function TryConstMerge(var p1, p2: tai): Boolean;
  2422. var
  2423. ThisRef: TReference;
  2424. begin
  2425. Result := False;
  2426. ThisRef := taicpu(p2).oper[1]^.ref^;
  2427. { Only permit writes to the stack, since we can guarantee alignment with that }
  2428. if (ThisRef.index = NR_NO) and
  2429. (
  2430. (ThisRef.base = NR_STACK_POINTER_REG) or
  2431. (ThisRef.base = current_procinfo.framepointer)
  2432. ) then
  2433. begin
  2434. case taicpu(p).opsize of
  2435. S_B:
  2436. begin
  2437. { Word writes must be on a 2-byte boundary }
  2438. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2439. begin
  2440. { Reduce offset of second reference to see if it is sequential with the first }
  2441. Dec(ThisRef.offset, 1);
  2442. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2443. begin
  2444. { Make sure the constants aren't represented as a
  2445. negative number, as these won't merge properly }
  2446. taicpu(p1).opsize := S_W;
  2447. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2448. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2449. RemoveInstruction(p2);
  2450. Result := True;
  2451. end;
  2452. end;
  2453. end;
  2454. S_W:
  2455. begin
  2456. { Longword writes must be on a 4-byte boundary }
  2457. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2458. begin
  2459. { Reduce offset of second reference to see if it is sequential with the first }
  2460. Dec(ThisRef.offset, 2);
  2461. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2462. begin
  2463. { Make sure the constants aren't represented as a
  2464. negative number, as these won't merge properly }
  2465. taicpu(p1).opsize := S_L;
  2466. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2467. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2468. RemoveInstruction(p2);
  2469. Result := True;
  2470. end;
  2471. end;
  2472. end;
  2473. {$ifdef x86_64}
  2474. S_L:
  2475. begin
  2476. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2477. see if the constants can be encoded this way. }
  2478. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2479. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2480. { Quadword writes must be on an 8-byte boundary }
  2481. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2482. begin
  2483. { Reduce offset of second reference to see if it is sequential with the first }
  2484. Dec(ThisRef.offset, 4);
  2485. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2486. begin
  2487. { Make sure the constants aren't represented as a
  2488. negative number, as these won't merge properly }
  2489. taicpu(p1).opsize := S_Q;
  2490. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2491. taicpu(p1).oper[0]^.val := NewConst;
  2492. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2493. RemoveInstruction(p2);
  2494. Result := True;
  2495. end;
  2496. end;
  2497. end;
  2498. {$endif x86_64}
  2499. else
  2500. ;
  2501. end;
  2502. end;
  2503. end;
  2504. var
  2505. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2506. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2507. NewSize: topsize;
  2508. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2509. SourceRef, TargetRef: TReference;
  2510. MovAligned, MovUnaligned: TAsmOp;
  2511. ThisRef: TReference;
  2512. JumpTracking: TLinkedList;
  2513. begin
  2514. Result:=false;
  2515. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2516. { remove mov reg1,reg1? }
  2517. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2518. then
  2519. begin
  2520. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2521. { take care of the register (de)allocs following p }
  2522. RemoveCurrentP(p, hp1);
  2523. Result:=true;
  2524. exit;
  2525. end;
  2526. { All the next optimisations require a next instruction }
  2527. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2528. Exit;
  2529. { Prevent compiler warnings }
  2530. p_TargetReg := NR_NO;
  2531. if taicpu(p).oper[1]^.typ = top_reg then
  2532. begin
  2533. { Saves on a large number of dereferences }
  2534. p_TargetReg := taicpu(p).oper[1]^.reg;
  2535. { Look for:
  2536. mov %reg1,%reg2
  2537. ??? %reg2,r/m
  2538. Change to:
  2539. mov %reg1,%reg2
  2540. ??? %reg1,r/m
  2541. }
  2542. if taicpu(p).oper[0]^.typ = top_reg then
  2543. begin
  2544. if RegReadByInstruction(p_TargetReg, hp1) and
  2545. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2546. begin
  2547. { A change has occurred, just not in p }
  2548. Result := True;
  2549. TransferUsedRegs(TmpUsedRegs);
  2550. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2551. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2552. { Just in case something didn't get modified (e.g. an
  2553. implicit register) }
  2554. not RegReadByInstruction(p_TargetReg, hp1) then
  2555. begin
  2556. { We can remove the original MOV }
  2557. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2558. RemoveCurrentp(p, hp1);
  2559. { UsedRegs got updated by RemoveCurrentp }
  2560. Result := True;
  2561. Exit;
  2562. end;
  2563. { If we know a MOV instruction has become a null operation, we might as well
  2564. get rid of it now to save time. }
  2565. if (taicpu(hp1).opcode = A_MOV) and
  2566. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2567. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2568. { Just being a register is enough to confirm it's a null operation }
  2569. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2570. begin
  2571. Result := True;
  2572. { Speed-up to reduce a pipeline stall... if we had something like...
  2573. movl %eax,%edx
  2574. movw %dx,%ax
  2575. ... the second instruction would change to movw %ax,%ax, but
  2576. given that it is now %ax that's active rather than %eax,
  2577. penalties might occur due to a partial register write, so instead,
  2578. change it to a MOVZX instruction when optimising for speed.
  2579. }
  2580. if not (cs_opt_size in current_settings.optimizerswitches) and
  2581. IsMOVZXAcceptable and
  2582. (taicpu(hp1).opsize < taicpu(p).opsize)
  2583. {$ifdef x86_64}
  2584. { operations already implicitly set the upper 64 bits to zero }
  2585. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2586. {$endif x86_64}
  2587. then
  2588. begin
  2589. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2590. case taicpu(p).opsize of
  2591. S_W:
  2592. if taicpu(hp1).opsize = S_B then
  2593. taicpu(hp1).opsize := S_BL
  2594. else
  2595. InternalError(2020012911);
  2596. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2597. case taicpu(hp1).opsize of
  2598. S_B:
  2599. taicpu(hp1).opsize := S_BL;
  2600. S_W:
  2601. taicpu(hp1).opsize := S_WL;
  2602. else
  2603. InternalError(2020012912);
  2604. end;
  2605. else
  2606. InternalError(2020012910);
  2607. end;
  2608. taicpu(hp1).opcode := A_MOVZX;
  2609. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2610. end
  2611. else
  2612. begin
  2613. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2614. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2615. RemoveInstruction(hp1);
  2616. { The instruction after what was hp1 is now the immediate next instruction,
  2617. so we can continue to make optimisations if it's present }
  2618. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2619. Exit;
  2620. hp1 := hp2;
  2621. end;
  2622. end;
  2623. end;
  2624. end;
  2625. end;
  2626. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2627. overwrites the original destination register. e.g.
  2628. movl ###,%reg2d
  2629. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2630. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2631. }
  2632. if (taicpu(p).oper[1]^.typ = top_reg) and
  2633. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2634. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2635. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2636. begin
  2637. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2638. begin
  2639. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2640. case taicpu(p).oper[0]^.typ of
  2641. top_const:
  2642. { We have something like:
  2643. movb $x, %regb
  2644. movzbl %regb,%regd
  2645. Change to:
  2646. movl $x, %regd
  2647. }
  2648. begin
  2649. case taicpu(hp1).opsize of
  2650. S_BW:
  2651. begin
  2652. convert_mov_value(A_MOVSX, $FF);
  2653. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2654. taicpu(p).opsize := S_W;
  2655. end;
  2656. S_BL:
  2657. begin
  2658. convert_mov_value(A_MOVSX, $FF);
  2659. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2660. taicpu(p).opsize := S_L;
  2661. end;
  2662. S_WL:
  2663. begin
  2664. convert_mov_value(A_MOVSX, $FFFF);
  2665. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2666. taicpu(p).opsize := S_L;
  2667. end;
  2668. {$ifdef x86_64}
  2669. S_BQ:
  2670. begin
  2671. convert_mov_value(A_MOVSX, $FF);
  2672. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2673. taicpu(p).opsize := S_Q;
  2674. end;
  2675. S_WQ:
  2676. begin
  2677. convert_mov_value(A_MOVSX, $FFFF);
  2678. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2679. taicpu(p).opsize := S_Q;
  2680. end;
  2681. S_LQ:
  2682. begin
  2683. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2684. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2685. taicpu(p).opsize := S_Q;
  2686. end;
  2687. {$endif x86_64}
  2688. else
  2689. { If hp1 was a MOV instruction, it should have been
  2690. optimised already }
  2691. InternalError(2020021001);
  2692. end;
  2693. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2694. RemoveInstruction(hp1);
  2695. Result := True;
  2696. Exit;
  2697. end;
  2698. top_ref:
  2699. begin
  2700. { We have something like:
  2701. movb mem, %regb
  2702. movzbl %regb,%regd
  2703. Change to:
  2704. movzbl mem, %regd
  2705. }
  2706. ThisRef := taicpu(p).oper[0]^.ref^;
  2707. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2708. begin
  2709. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2710. taicpu(hp1).loadref(0, ThisRef);
  2711. { Make sure any registers in the references are properly tracked }
  2712. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2713. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2714. if (ThisRef.index <> NR_NO) then
  2715. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2716. RemoveCurrentP(p, hp1);
  2717. Result := True;
  2718. Exit;
  2719. end;
  2720. end;
  2721. else
  2722. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2723. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2724. Exit;
  2725. end;
  2726. end
  2727. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2728. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2729. optimised }
  2730. else
  2731. begin
  2732. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2733. RemoveCurrentP(p, hp1);
  2734. Result := True;
  2735. Exit;
  2736. end;
  2737. end;
  2738. if (taicpu(hp1).opcode = A_AND) and
  2739. (taicpu(p).oper[1]^.typ = top_reg) and
  2740. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2741. begin
  2742. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2743. begin
  2744. case taicpu(p).opsize of
  2745. S_L:
  2746. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2747. begin
  2748. { Optimize out:
  2749. mov x, %reg
  2750. and ffffffffh, %reg
  2751. }
  2752. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2753. RemoveInstruction(hp1);
  2754. Result:=true;
  2755. exit;
  2756. end;
  2757. S_Q: { TODO: Confirm if this is even possible }
  2758. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2759. begin
  2760. { Optimize out:
  2761. mov x, %reg
  2762. and ffffffffffffffffh, %reg
  2763. }
  2764. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2765. RemoveInstruction(hp1);
  2766. Result:=true;
  2767. exit;
  2768. end;
  2769. else
  2770. ;
  2771. end;
  2772. if ((taicpu(p).oper[0]^.typ=top_reg) or
  2773. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  2774. GetNextInstruction(hp1,hp2) and
  2775. MatchInstruction(hp2,A_TEST,[taicpu(p).opsize]) and
  2776. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) and
  2777. (MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2778. MatchOperand(taicpu(hp2).oper[0]^,-1)) and
  2779. GetNextInstruction(hp2,hp3) and
  2780. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2781. (taicpu(hp3).condition in [C_E,C_NE]) then
  2782. begin
  2783. TransferUsedRegs(TmpUsedRegs);
  2784. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2785. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2786. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2787. begin
  2788. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2789. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2790. taicpu(hp1).opcode:=A_TEST;
  2791. RemoveInstruction(hp2);
  2792. RemoveCurrentP(p, hp1);
  2793. Result:=true;
  2794. exit;
  2795. end;
  2796. end;
  2797. end
  2798. else if IsMOVZXAcceptable and
  2799. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  2800. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  2801. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  2802. then
  2803. begin
  2804. InputVal := debug_operstr(taicpu(p).oper[0]^);
  2805. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  2806. case taicpu(p).opsize of
  2807. S_B:
  2808. if (taicpu(hp1).oper[0]^.val = $ff) then
  2809. begin
  2810. { Convert:
  2811. movb x, %regl movb x, %regl
  2812. andw ffh, %regw andl ffh, %regd
  2813. To:
  2814. movzbw x, %regd movzbl x, %regd
  2815. (Identical registers, just different sizes)
  2816. }
  2817. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  2818. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  2819. case taicpu(hp1).opsize of
  2820. S_W: NewSize := S_BW;
  2821. S_L: NewSize := S_BL;
  2822. {$ifdef x86_64}
  2823. S_Q: NewSize := S_BQ;
  2824. {$endif x86_64}
  2825. else
  2826. InternalError(2018011510);
  2827. end;
  2828. end
  2829. else
  2830. NewSize := S_NO;
  2831. S_W:
  2832. if (taicpu(hp1).oper[0]^.val = $ffff) then
  2833. begin
  2834. { Convert:
  2835. movw x, %regw
  2836. andl ffffh, %regd
  2837. To:
  2838. movzwl x, %regd
  2839. (Identical registers, just different sizes)
  2840. }
  2841. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  2842. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  2843. case taicpu(hp1).opsize of
  2844. S_L: NewSize := S_WL;
  2845. {$ifdef x86_64}
  2846. S_Q: NewSize := S_WQ;
  2847. {$endif x86_64}
  2848. else
  2849. InternalError(2018011511);
  2850. end;
  2851. end
  2852. else
  2853. NewSize := S_NO;
  2854. else
  2855. NewSize := S_NO;
  2856. end;
  2857. if NewSize <> S_NO then
  2858. begin
  2859. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  2860. { The actual optimization }
  2861. taicpu(p).opcode := A_MOVZX;
  2862. taicpu(p).changeopsize(NewSize);
  2863. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  2864. { Safeguard if "and" is followed by a conditional command }
  2865. TransferUsedRegs(TmpUsedRegs);
  2866. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  2867. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  2868. begin
  2869. { At this point, the "and" command is effectively equivalent to
  2870. "test %reg,%reg". This will be handled separately by the
  2871. Peephole Optimizer. [Kit] }
  2872. DebugMsg(SPeepholeOptimization + PreMessage +
  2873. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2874. end
  2875. else
  2876. begin
  2877. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  2878. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2879. RemoveInstruction(hp1);
  2880. end;
  2881. Result := True;
  2882. Exit;
  2883. end;
  2884. end;
  2885. end;
  2886. if (taicpu(hp1).opcode = A_OR) and
  2887. (taicpu(p).oper[1]^.typ = top_reg) and
  2888. MatchOperand(taicpu(p).oper[0]^, 0) and
  2889. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  2890. begin
  2891. { mov 0, %reg
  2892. or ###,%reg
  2893. Change to (only if the flags are not used):
  2894. mov ###,%reg
  2895. }
  2896. TransferUsedRegs(TmpUsedRegs);
  2897. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2898. DoOptimisation := True;
  2899. { Even if the flags are used, we might be able to do the optimisation
  2900. if the conditions are predictable }
  2901. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2902. begin
  2903. { Only perform if ### = %reg (the same register) or equal to 0,
  2904. so %reg is guaranteed to still have a value of zero }
  2905. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  2906. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  2907. begin
  2908. hp2 := hp1;
  2909. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2910. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  2911. GetNextInstruction(hp2, hp3) do
  2912. begin
  2913. { Don't continue modifying if the flags state is getting changed }
  2914. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  2915. Break;
  2916. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  2917. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  2918. begin
  2919. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  2920. begin
  2921. { Condition is always true }
  2922. case taicpu(hp3).opcode of
  2923. A_Jcc:
  2924. begin
  2925. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  2926. { Check for jump shortcuts before we destroy the condition }
  2927. DoJumpOptimizations(hp3, TempBool);
  2928. MakeUnconditional(taicpu(hp3));
  2929. Result := True;
  2930. end;
  2931. A_CMOVcc:
  2932. begin
  2933. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  2934. taicpu(hp3).opcode := A_MOV;
  2935. taicpu(hp3).condition := C_None;
  2936. Result := True;
  2937. end;
  2938. A_SETcc:
  2939. begin
  2940. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  2941. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  2942. taicpu(hp3).opcode := A_MOV;
  2943. taicpu(hp3).ops := 2;
  2944. taicpu(hp3).condition := C_None;
  2945. taicpu(hp3).opsize := S_B;
  2946. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2947. taicpu(hp3).loadconst(0, 1);
  2948. Result := True;
  2949. end;
  2950. else
  2951. InternalError(2021090701);
  2952. end;
  2953. end
  2954. 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
  2955. begin
  2956. { Condition is always false }
  2957. case taicpu(hp3).opcode of
  2958. A_Jcc:
  2959. begin
  2960. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  2961. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  2962. RemoveInstruction(hp3);
  2963. Result := True;
  2964. { Since hp3 was deleted, hp2 must not be updated }
  2965. Continue;
  2966. end;
  2967. A_CMOVcc:
  2968. begin
  2969. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  2970. RemoveInstruction(hp3);
  2971. Result := True;
  2972. { Since hp3 was deleted, hp2 must not be updated }
  2973. Continue;
  2974. end;
  2975. A_SETcc:
  2976. begin
  2977. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  2978. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  2979. taicpu(hp3).opcode := A_MOV;
  2980. taicpu(hp3).ops := 2;
  2981. taicpu(hp3).condition := C_None;
  2982. taicpu(hp3).opsize := S_B;
  2983. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2984. taicpu(hp3).loadconst(0, 0);
  2985. Result := True;
  2986. end;
  2987. else
  2988. InternalError(2021090702);
  2989. end;
  2990. end
  2991. else
  2992. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  2993. DoOptimisation := False;
  2994. end;
  2995. hp2 := hp3;
  2996. end;
  2997. { Flags are still in use - don't optimise }
  2998. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2999. DoOptimisation := False;
  3000. end
  3001. else
  3002. DoOptimisation := False;
  3003. end;
  3004. if DoOptimisation then
  3005. begin
  3006. {$ifdef x86_64}
  3007. { OR only supports 32-bit sign-extended constants for 64-bit
  3008. instructions, so compensate for this if the constant is
  3009. encoded as a value greater than or equal to 2^31 }
  3010. if (taicpu(hp1).opsize = S_Q) and
  3011. (taicpu(hp1).oper[0]^.typ = top_const) and
  3012. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3013. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3014. {$endif x86_64}
  3015. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3016. taicpu(hp1).opcode := A_MOV;
  3017. RemoveCurrentP(p, hp1);
  3018. Result := True;
  3019. Exit;
  3020. end;
  3021. end;
  3022. { Next instruction is also a MOV ? }
  3023. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3024. begin
  3025. if MatchOpType(taicpu(p), top_const, top_ref) and
  3026. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3027. TryConstMerge(p, hp1) then
  3028. begin
  3029. Result := True;
  3030. { In case we have four byte writes in a row, check for 2 more
  3031. right now so we don't have to wait for another iteration of
  3032. pass 1
  3033. }
  3034. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3035. case taicpu(p).opsize of
  3036. S_W:
  3037. begin
  3038. if GetNextInstruction(p, hp1) and
  3039. MatchInstruction(hp1, A_MOV, [S_B]) and
  3040. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3041. GetNextInstruction(hp1, hp2) and
  3042. MatchInstruction(hp2, A_MOV, [S_B]) and
  3043. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3044. { Try to merge the two bytes }
  3045. TryConstMerge(hp1, hp2) then
  3046. { Now try to merge the two words (hp2 will get deleted) }
  3047. TryConstMerge(p, hp1);
  3048. end;
  3049. S_L:
  3050. begin
  3051. { Though this only really benefits x86_64 and not i386, it
  3052. gets a potential optimisation done faster and hence
  3053. reduces the number of times OptPass1MOV is entered }
  3054. if GetNextInstruction(p, hp1) and
  3055. MatchInstruction(hp1, A_MOV, [S_W]) and
  3056. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3057. GetNextInstruction(hp1, hp2) and
  3058. MatchInstruction(hp2, A_MOV, [S_W]) and
  3059. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3060. { Try to merge the two words }
  3061. TryConstMerge(hp1, hp2) then
  3062. { This will always fail on i386, so don't bother
  3063. calling it unless we're doing x86_64 }
  3064. {$ifdef x86_64}
  3065. { Now try to merge the two longwords (hp2 will get deleted) }
  3066. TryConstMerge(p, hp1)
  3067. {$endif x86_64}
  3068. ;
  3069. end;
  3070. else
  3071. ;
  3072. end;
  3073. Exit;
  3074. end;
  3075. if (taicpu(p).oper[1]^.typ = top_reg) and
  3076. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3077. begin
  3078. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3079. TransferUsedRegs(TmpUsedRegs);
  3080. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3081. { we have
  3082. mov x, %treg
  3083. mov %treg, y
  3084. }
  3085. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3086. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3087. { we've got
  3088. mov x, %treg
  3089. mov %treg, y
  3090. with %treg is not used after }
  3091. case taicpu(p).oper[0]^.typ Of
  3092. { top_reg is covered by DeepMOVOpt }
  3093. top_const:
  3094. begin
  3095. { change
  3096. mov const, %treg
  3097. mov %treg, y
  3098. to
  3099. mov const, y
  3100. }
  3101. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3102. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3103. begin
  3104. if taicpu(hp1).oper[1]^.typ=top_reg then
  3105. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3106. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3107. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3108. RemoveInstruction(hp1);
  3109. Result:=true;
  3110. Exit;
  3111. end;
  3112. end;
  3113. top_ref:
  3114. case taicpu(hp1).oper[1]^.typ of
  3115. top_reg:
  3116. begin
  3117. { change
  3118. mov mem, %treg
  3119. mov %treg, %reg
  3120. to
  3121. mov mem, %reg"
  3122. }
  3123. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3124. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3125. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3126. RemoveInstruction(hp1);
  3127. Result:=true;
  3128. Exit;
  3129. end;
  3130. top_ref:
  3131. begin
  3132. {$ifdef x86_64}
  3133. { Look for the following to simplify:
  3134. mov x(mem1), %reg
  3135. mov %reg, y(mem2)
  3136. mov x+8(mem1), %reg
  3137. mov %reg, y+8(mem2)
  3138. Change to:
  3139. movdqu x(mem1), %xmmreg
  3140. movdqu %xmmreg, y(mem2)
  3141. ...but only as long as the memory blocks don't overlap
  3142. }
  3143. SourceRef := taicpu(p).oper[0]^.ref^;
  3144. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3145. if (taicpu(p).opsize = S_Q) and
  3146. GetNextInstruction(hp1, hp2) and
  3147. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3148. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3149. begin
  3150. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3151. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3152. Inc(SourceRef.offset, 8);
  3153. if UseAVX then
  3154. begin
  3155. MovAligned := A_VMOVDQA;
  3156. MovUnaligned := A_VMOVDQU;
  3157. end
  3158. else
  3159. begin
  3160. MovAligned := A_MOVDQA;
  3161. MovUnaligned := A_MOVDQU;
  3162. end;
  3163. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3164. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3165. begin
  3166. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3167. Inc(TargetRef.offset, 8);
  3168. if GetNextInstruction(hp2, hp3) and
  3169. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3170. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3171. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3172. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3173. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3174. begin
  3175. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3176. if NewMMReg <> NR_NO then
  3177. begin
  3178. { Remember that the offsets are 8 ahead }
  3179. if ((SourceRef.offset mod 16) = 8) and
  3180. (
  3181. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3182. (SourceRef.base = current_procinfo.framepointer) or
  3183. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3184. ) then
  3185. taicpu(p).opcode := MovAligned
  3186. else
  3187. taicpu(p).opcode := MovUnaligned;
  3188. taicpu(p).opsize := S_XMM;
  3189. taicpu(p).oper[1]^.reg := NewMMReg;
  3190. if ((TargetRef.offset mod 16) = 8) and
  3191. (
  3192. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3193. (TargetRef.base = current_procinfo.framepointer) or
  3194. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3195. ) then
  3196. taicpu(hp1).opcode := MovAligned
  3197. else
  3198. taicpu(hp1).opcode := MovUnaligned;
  3199. taicpu(hp1).opsize := S_XMM;
  3200. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3201. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3202. RemoveInstruction(hp2);
  3203. RemoveInstruction(hp3);
  3204. Result := True;
  3205. Exit;
  3206. end;
  3207. end;
  3208. end
  3209. else
  3210. begin
  3211. { See if the next references are 8 less rather than 8 greater }
  3212. Dec(SourceRef.offset, 16); { -8 the other way }
  3213. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3214. begin
  3215. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3216. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3217. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3218. GetNextInstruction(hp2, hp3) and
  3219. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3220. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3221. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3222. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3223. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3224. begin
  3225. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3226. if NewMMReg <> NR_NO then
  3227. begin
  3228. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3229. if ((SourceRef.offset mod 16) = 0) and
  3230. (
  3231. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3232. (SourceRef.base = current_procinfo.framepointer) or
  3233. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3234. ) then
  3235. taicpu(hp2).opcode := MovAligned
  3236. else
  3237. taicpu(hp2).opcode := MovUnaligned;
  3238. taicpu(hp2).opsize := S_XMM;
  3239. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3240. if ((TargetRef.offset mod 16) = 0) and
  3241. (
  3242. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3243. (TargetRef.base = current_procinfo.framepointer) or
  3244. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3245. ) then
  3246. taicpu(hp3).opcode := MovAligned
  3247. else
  3248. taicpu(hp3).opcode := MovUnaligned;
  3249. taicpu(hp3).opsize := S_XMM;
  3250. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3251. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3252. RemoveInstruction(hp1);
  3253. RemoveCurrentP(p, hp2);
  3254. Result := True;
  3255. Exit;
  3256. end;
  3257. end;
  3258. end;
  3259. end;
  3260. end;
  3261. {$endif x86_64}
  3262. end;
  3263. else
  3264. { The write target should be a reg or a ref }
  3265. InternalError(2021091601);
  3266. end;
  3267. else
  3268. ;
  3269. end
  3270. else
  3271. { %treg is used afterwards, but all eventualities
  3272. other than the first MOV instruction being a constant
  3273. are covered by DeepMOVOpt, so only check for that }
  3274. if (taicpu(p).oper[0]^.typ = top_const) and
  3275. (
  3276. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3277. not (cs_opt_size in current_settings.optimizerswitches) or
  3278. (taicpu(hp1).opsize = S_B)
  3279. ) and
  3280. (
  3281. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3282. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3283. ) then
  3284. begin
  3285. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3286. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3287. end;
  3288. end;
  3289. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3290. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3291. { mov reg1, mem1 or mov mem1, reg1
  3292. mov mem2, reg2 mov reg2, mem2}
  3293. begin
  3294. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3295. { mov reg1, mem1 or mov mem1, reg1
  3296. mov mem2, reg1 mov reg2, mem1}
  3297. begin
  3298. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3299. { Removes the second statement from
  3300. mov reg1, mem1/reg2
  3301. mov mem1/reg2, reg1 }
  3302. begin
  3303. if taicpu(p).oper[0]^.typ=top_reg then
  3304. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3305. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3306. RemoveInstruction(hp1);
  3307. Result:=true;
  3308. exit;
  3309. end
  3310. else
  3311. begin
  3312. TransferUsedRegs(TmpUsedRegs);
  3313. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3314. if (taicpu(p).oper[1]^.typ = top_ref) and
  3315. { mov reg1, mem1
  3316. mov mem2, reg1 }
  3317. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3318. GetNextInstruction(hp1, hp2) and
  3319. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3320. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3321. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3322. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3323. { change to
  3324. mov reg1, mem1 mov reg1, mem1
  3325. mov mem2, reg1 cmp reg1, mem2
  3326. cmp mem1, reg1
  3327. }
  3328. begin
  3329. RemoveInstruction(hp2);
  3330. taicpu(hp1).opcode := A_CMP;
  3331. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3332. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3333. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3334. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3335. end;
  3336. end;
  3337. end
  3338. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3339. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3340. begin
  3341. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3342. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3343. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3344. end
  3345. else
  3346. begin
  3347. TransferUsedRegs(TmpUsedRegs);
  3348. if GetNextInstruction(hp1, hp2) and
  3349. MatchOpType(taicpu(p),top_ref,top_reg) and
  3350. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3351. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3352. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3353. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3354. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3355. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3356. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3357. { mov mem1, %reg1
  3358. mov %reg1, mem2
  3359. mov mem2, reg2
  3360. to:
  3361. mov mem1, reg2
  3362. mov reg2, mem2}
  3363. begin
  3364. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3365. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3366. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3367. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3368. RemoveInstruction(hp2);
  3369. Result := True;
  3370. end
  3371. {$ifdef i386}
  3372. { this is enabled for i386 only, as the rules to create the reg sets below
  3373. are too complicated for x86-64, so this makes this code too error prone
  3374. on x86-64
  3375. }
  3376. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3377. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3378. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3379. { mov mem1, reg1 mov mem1, reg1
  3380. mov reg1, mem2 mov reg1, mem2
  3381. mov mem2, reg2 mov mem2, reg1
  3382. to: to:
  3383. mov mem1, reg1 mov mem1, reg1
  3384. mov mem1, reg2 mov reg1, mem2
  3385. mov reg1, mem2
  3386. or (if mem1 depends on reg1
  3387. and/or if mem2 depends on reg2)
  3388. to:
  3389. mov mem1, reg1
  3390. mov reg1, mem2
  3391. mov reg1, reg2
  3392. }
  3393. begin
  3394. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3395. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3396. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3397. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3398. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3399. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3400. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3401. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3402. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3403. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3404. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3405. end
  3406. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3407. begin
  3408. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3409. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3410. end
  3411. else
  3412. begin
  3413. RemoveInstruction(hp2);
  3414. end
  3415. {$endif i386}
  3416. ;
  3417. end;
  3418. end
  3419. { movl [mem1],reg1
  3420. movl [mem1],reg2
  3421. to
  3422. movl [mem1],reg1
  3423. movl reg1,reg2
  3424. }
  3425. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3426. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3427. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3428. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3429. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3430. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3431. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3432. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3433. begin
  3434. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3435. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3436. end;
  3437. { movl const1,[mem1]
  3438. movl [mem1],reg1
  3439. to
  3440. movl const1,reg1
  3441. movl reg1,[mem1]
  3442. }
  3443. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3444. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3445. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3446. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3447. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3448. begin
  3449. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3450. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3451. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3452. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3453. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3454. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3455. Result:=true;
  3456. exit;
  3457. end;
  3458. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3459. { Change:
  3460. movl %reg1,%reg2
  3461. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3462. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3463. To:
  3464. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3465. movl x(%reg1),%reg1
  3466. movl %reg1,%regX
  3467. }
  3468. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3469. begin
  3470. p_SourceReg := taicpu(p).oper[0]^.reg;
  3471. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3472. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3473. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3474. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3475. GetNextInstruction(hp1, hp2) and
  3476. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3477. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3478. begin
  3479. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3480. if RegInRef(p_TargetReg, SourceRef) and
  3481. { If %reg1 also appears in the second reference, then it will
  3482. not refer to the same memory block as the first reference }
  3483. not RegInRef(p_SourceReg, SourceRef) then
  3484. begin
  3485. { Check to see if the references match if %reg2 is changed to %reg1 }
  3486. if SourceRef.base = p_TargetReg then
  3487. SourceRef.base := p_SourceReg;
  3488. if SourceRef.index = p_TargetReg then
  3489. SourceRef.index := p_SourceReg;
  3490. { RefsEqual also checks to ensure both references are non-volatile }
  3491. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3492. begin
  3493. taicpu(hp2).loadreg(0, p_SourceReg);
  3494. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3495. Result := True;
  3496. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3497. begin
  3498. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3499. RemoveCurrentP(p, hp1);
  3500. Exit;
  3501. end
  3502. else
  3503. begin
  3504. { Check to see if %reg2 is no longer in use }
  3505. TransferUsedRegs(TmpUsedRegs);
  3506. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3507. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3508. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3509. begin
  3510. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3511. RemoveCurrentP(p, hp1);
  3512. Exit;
  3513. end;
  3514. end;
  3515. { If we reach this point, p and hp1 weren't actually modified,
  3516. so we can do a bit more work on this pass }
  3517. end;
  3518. end;
  3519. end;
  3520. end;
  3521. end;
  3522. { search further than the next instruction for a mov (as long as it's not a jump) }
  3523. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3524. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3525. (taicpu(p).oper[1]^.typ = top_reg) and
  3526. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3527. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3528. begin
  3529. { we work with hp2 here, so hp1 can be still used later on when
  3530. checking for GetNextInstruction_p }
  3531. hp3 := hp1;
  3532. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3533. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3534. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3535. TransferUsedRegs(TmpUsedRegs);
  3536. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3537. if NotFirstIteration then
  3538. JumpTracking := TLinkedList.Create
  3539. else
  3540. JumpTracking := nil;
  3541. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3542. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3543. (hp2.typ=ait_instruction) do
  3544. begin
  3545. case taicpu(hp2).opcode of
  3546. A_POP:
  3547. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3548. begin
  3549. if not CrossJump and
  3550. not RegUsedBetween(p_TargetReg, p, hp2) then
  3551. begin
  3552. { We can remove the original MOV since the register
  3553. wasn't used between it and its popping from the stack }
  3554. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3555. RemoveCurrentp(p, hp1);
  3556. Result := True;
  3557. JumpTracking.Free;
  3558. Exit;
  3559. end;
  3560. { Can't go any further }
  3561. Break;
  3562. end;
  3563. A_MOV:
  3564. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3565. ((taicpu(p).oper[0]^.typ=top_const) or
  3566. ((taicpu(p).oper[0]^.typ=top_reg) and
  3567. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3568. )
  3569. ) then
  3570. begin
  3571. { we have
  3572. mov x, %treg
  3573. mov %treg, y
  3574. }
  3575. { We don't need to call UpdateUsedRegs for every instruction between
  3576. p and hp2 because the register we're concerned about will not
  3577. become deallocated (otherwise GetNextInstructionUsingReg would
  3578. have stopped at an earlier instruction). [Kit] }
  3579. TempRegUsed :=
  3580. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3581. RegReadByInstruction(p_TargetReg, hp3) or
  3582. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3583. case taicpu(p).oper[0]^.typ Of
  3584. top_reg:
  3585. begin
  3586. { change
  3587. mov %reg, %treg
  3588. mov %treg, y
  3589. to
  3590. mov %reg, y
  3591. }
  3592. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3593. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3594. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3595. begin
  3596. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3597. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3598. if TempRegUsed then
  3599. begin
  3600. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3601. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3602. { Set the start of the next GetNextInstructionUsingRegCond search
  3603. to start at the entry right before hp2 (which is about to be removed) }
  3604. hp3 := tai(hp2.Previous);
  3605. RemoveInstruction(hp2);
  3606. { See if there's more we can optimise }
  3607. Continue;
  3608. end
  3609. else
  3610. begin
  3611. RemoveInstruction(hp2);
  3612. { We can remove the original MOV too }
  3613. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3614. RemoveCurrentP(p, hp1);
  3615. Result:=true;
  3616. JumpTracking.Free;
  3617. Exit;
  3618. end;
  3619. end
  3620. else
  3621. begin
  3622. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3623. taicpu(hp2).loadReg(0, p_SourceReg);
  3624. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3625. { Check to see if the register also appears in the reference }
  3626. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3627. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  3628. { Don't remove the first instruction if the temporary register is in use }
  3629. if not TempRegUsed and
  3630. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3631. not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  3632. begin
  3633. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3634. RemoveCurrentP(p, hp1);
  3635. Result:=true;
  3636. JumpTracking.Free;
  3637. Exit;
  3638. end;
  3639. { No need to set Result to True here. If there's another instruction later
  3640. on that can be optimised, it will be detected when the main Pass 1 loop
  3641. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3642. end;
  3643. end;
  3644. top_const:
  3645. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3646. begin
  3647. { change
  3648. mov const, %treg
  3649. mov %treg, y
  3650. to
  3651. mov const, y
  3652. }
  3653. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3654. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3655. begin
  3656. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3657. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3658. if TempRegUsed then
  3659. begin
  3660. { Don't remove the first instruction if the temporary register is in use }
  3661. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3662. { No need to set Result to True. If there's another instruction later on
  3663. that can be optimised, it will be detected when the main Pass 1 loop
  3664. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3665. end
  3666. else
  3667. begin
  3668. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3669. RemoveCurrentP(p, hp1);
  3670. Result:=true;
  3671. Exit;
  3672. end;
  3673. end;
  3674. end;
  3675. else
  3676. Internalerror(2019103001);
  3677. end;
  3678. end
  3679. else
  3680. if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  3681. begin
  3682. if not CrossJump and
  3683. not RegUsedBetween(p_TargetReg, p, hp2) and
  3684. not RegReadByInstruction(p_TargetReg, hp2) then
  3685. begin
  3686. { Register is not used before it is overwritten }
  3687. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3688. RemoveCurrentp(p, hp1);
  3689. Result := True;
  3690. Exit;
  3691. end;
  3692. if (taicpu(p).oper[0]^.typ = top_const) and
  3693. (taicpu(hp2).oper[0]^.typ = top_const) then
  3694. begin
  3695. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3696. begin
  3697. { Same value - register hasn't changed }
  3698. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3699. RemoveInstruction(hp2);
  3700. Result := True;
  3701. { See if there's more we can optimise }
  3702. Continue;
  3703. end;
  3704. end;
  3705. end;
  3706. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  3707. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  3708. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  3709. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  3710. begin
  3711. {
  3712. Change from:
  3713. mov ###, %reg
  3714. ...
  3715. movs/z %reg,%reg (Same register, just different sizes)
  3716. To:
  3717. movs/z ###, %reg (Longer version)
  3718. ...
  3719. (remove)
  3720. }
  3721. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  3722. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  3723. { Keep the first instruction as mov if ### is a constant }
  3724. if taicpu(p).oper[0]^.typ = top_const then
  3725. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  3726. else
  3727. begin
  3728. taicpu(p).opcode := taicpu(hp2).opcode;
  3729. taicpu(p).opsize := taicpu(hp2).opsize;
  3730. end;
  3731. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  3732. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  3733. RemoveInstruction(hp2);
  3734. Result := True;
  3735. JumpTracking.Free;
  3736. Exit;
  3737. end;
  3738. else
  3739. { Move down to the MatchOpType if-block below };
  3740. end;
  3741. { Also catches MOV/S/Z instructions that aren't modified }
  3742. if taicpu(p).oper[0]^.typ = top_reg then
  3743. begin
  3744. p_SourceReg := taicpu(p).oper[0]^.reg;
  3745. if
  3746. not RegModifiedByInstruction(p_SourceReg, hp3) and
  3747. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  3748. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  3749. begin
  3750. Result := True;
  3751. { Just in case something didn't get modified (e.g. an
  3752. implicit register). Also, if it does read from this
  3753. register, then there's no longer an advantage to
  3754. changing the register on subsequent instructions.}
  3755. if not RegReadByInstruction(p_TargetReg, hp2) then
  3756. begin
  3757. { If a conditional jump was crossed, do not delete
  3758. the original MOV no matter what }
  3759. if not CrossJump and
  3760. { RegEndOfLife returns True if the register is
  3761. deallocated before the next instruction or has
  3762. been loaded with a new value }
  3763. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  3764. begin
  3765. { We can remove the original MOV }
  3766. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  3767. RemoveCurrentp(p, hp1);
  3768. JumpTracking.Free;
  3769. Result := True;
  3770. Exit;
  3771. end;
  3772. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  3773. begin
  3774. { See if there's more we can optimise }
  3775. hp3 := hp2;
  3776. Continue;
  3777. end;
  3778. end;
  3779. end;
  3780. end;
  3781. { Break out of the while loop under normal circumstances }
  3782. Break;
  3783. end;
  3784. JumpTracking.Free;
  3785. end;
  3786. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  3787. (taicpu(p).oper[1]^.typ = top_reg) and
  3788. (taicpu(p).opsize = S_L) and
  3789. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  3790. (taicpu(hp2).opcode = A_AND) and
  3791. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  3792. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3793. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  3794. ) then
  3795. begin
  3796. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  3797. begin
  3798. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  3799. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  3800. begin
  3801. { Optimize out:
  3802. mov x, %reg
  3803. and ffffffffh, %reg
  3804. }
  3805. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  3806. RemoveInstruction(hp2);
  3807. Result:=true;
  3808. exit;
  3809. end;
  3810. end;
  3811. end;
  3812. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  3813. x >= RetOffset) as it doesn't do anything (it writes either to a
  3814. parameter or to the temporary storage room for the function
  3815. result)
  3816. }
  3817. if IsExitCode(hp1) and
  3818. (taicpu(p).oper[1]^.typ = top_ref) and
  3819. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  3820. (
  3821. (
  3822. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  3823. not (
  3824. assigned(current_procinfo.procdef.funcretsym) and
  3825. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  3826. )
  3827. ) or
  3828. { Also discard writes to the stack that are below the base pointer,
  3829. as this is temporary storage rather than a function result on the
  3830. stack, say. }
  3831. (
  3832. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  3833. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  3834. )
  3835. ) then
  3836. begin
  3837. RemoveCurrentp(p, hp1);
  3838. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  3839. RemoveLastDeallocForFuncRes(p);
  3840. Result:=true;
  3841. exit;
  3842. end;
  3843. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  3844. begin
  3845. if MatchOpType(taicpu(p),top_reg,top_ref) and
  3846. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3847. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3848. begin
  3849. { change
  3850. mov reg1, mem1
  3851. test/cmp x, mem1
  3852. to
  3853. mov reg1, mem1
  3854. test/cmp x, reg1
  3855. }
  3856. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  3857. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  3858. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3859. Result := True;
  3860. Exit;
  3861. end;
  3862. if DoMovCmpMemOpt(p, hp1, True) then
  3863. begin
  3864. Result := True;
  3865. Exit;
  3866. end;
  3867. end;
  3868. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  3869. { If the flags register is in use, don't change the instruction to an
  3870. ADD otherwise this will scramble the flags. [Kit] }
  3871. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  3872. begin
  3873. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  3874. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3875. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3876. ) or
  3877. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3878. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3879. )
  3880. ) then
  3881. { mov reg1,ref
  3882. lea reg2,[reg1,reg2]
  3883. to
  3884. add reg2,ref}
  3885. begin
  3886. TransferUsedRegs(TmpUsedRegs);
  3887. { reg1 may not be used afterwards }
  3888. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3889. begin
  3890. Taicpu(hp1).opcode:=A_ADD;
  3891. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3892. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3893. RemoveCurrentp(p, hp1);
  3894. result:=true;
  3895. exit;
  3896. end;
  3897. end;
  3898. { If the LEA instruction can be converted into an arithmetic instruction,
  3899. it may be possible to then fold it in the next optimisation, otherwise
  3900. there's nothing more that can be optimised here. }
  3901. if not ConvertLEA(taicpu(hp1)) then
  3902. Exit;
  3903. end;
  3904. if (taicpu(p).oper[1]^.typ = top_reg) and
  3905. (hp1.typ = ait_instruction) and
  3906. GetNextInstruction(hp1, hp2) and
  3907. MatchInstruction(hp2,A_MOV,[]) and
  3908. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  3909. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  3910. (
  3911. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  3912. {$ifdef x86_64}
  3913. or
  3914. (
  3915. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  3916. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  3917. )
  3918. {$endif x86_64}
  3919. ) then
  3920. begin
  3921. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  3922. (taicpu(hp2).oper[0]^.typ=top_reg) then
  3923. { change movsX/movzX reg/ref, reg2
  3924. add/sub/or/... reg3/$const, reg2
  3925. mov reg2 reg/ref
  3926. dealloc reg2
  3927. to
  3928. add/sub/or/... reg3/$const, reg/ref }
  3929. begin
  3930. TransferUsedRegs(TmpUsedRegs);
  3931. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3932. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3933. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3934. begin
  3935. { by example:
  3936. movswl %si,%eax movswl %si,%eax p
  3937. decl %eax addl %edx,%eax hp1
  3938. movw %ax,%si movw %ax,%si hp2
  3939. ->
  3940. movswl %si,%eax movswl %si,%eax p
  3941. decw %eax addw %edx,%eax hp1
  3942. movw %ax,%si movw %ax,%si hp2
  3943. }
  3944. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  3945. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3946. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3947. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3948. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3949. {
  3950. ->
  3951. movswl %si,%eax movswl %si,%eax p
  3952. decw %si addw %dx,%si hp1
  3953. movw %ax,%si movw %ax,%si hp2
  3954. }
  3955. case taicpu(hp1).ops of
  3956. 1:
  3957. begin
  3958. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3959. if taicpu(hp1).oper[0]^.typ=top_reg then
  3960. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3961. end;
  3962. 2:
  3963. begin
  3964. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3965. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3966. (taicpu(hp1).opcode<>A_SHL) and
  3967. (taicpu(hp1).opcode<>A_SHR) and
  3968. (taicpu(hp1).opcode<>A_SAR) then
  3969. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3970. end;
  3971. else
  3972. internalerror(2008042701);
  3973. end;
  3974. {
  3975. ->
  3976. decw %si addw %dx,%si p
  3977. }
  3978. RemoveInstruction(hp2);
  3979. RemoveCurrentP(p, hp1);
  3980. Result:=True;
  3981. Exit;
  3982. end;
  3983. end;
  3984. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3985. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  3986. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  3987. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  3988. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  3989. )
  3990. {$ifdef i386}
  3991. { byte registers of esi, edi, ebp, esp are not available on i386 }
  3992. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3993. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3994. {$endif i386}
  3995. then
  3996. { change movsX/movzX reg/ref, reg2
  3997. add/sub/or/... regX/$const, reg2
  3998. mov reg2, reg3
  3999. dealloc reg2
  4000. to
  4001. movsX/movzX reg/ref, reg3
  4002. add/sub/or/... reg3/$const, reg3
  4003. }
  4004. begin
  4005. TransferUsedRegs(TmpUsedRegs);
  4006. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4007. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4008. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4009. begin
  4010. { by example:
  4011. movswl %si,%eax movswl %si,%eax p
  4012. decl %eax addl %edx,%eax hp1
  4013. movw %ax,%si movw %ax,%si hp2
  4014. ->
  4015. movswl %si,%eax movswl %si,%eax p
  4016. decw %eax addw %edx,%eax hp1
  4017. movw %ax,%si movw %ax,%si hp2
  4018. }
  4019. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4020. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4021. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4022. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4023. { limit size of constants as well to avoid assembler errors, but
  4024. check opsize to avoid overflow when left shifting the 1 }
  4025. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4026. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4027. {$ifdef x86_64}
  4028. { Be careful of, for example:
  4029. movl %reg1,%reg2
  4030. addl %reg3,%reg2
  4031. movq %reg2,%reg4
  4032. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4033. }
  4034. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4035. begin
  4036. taicpu(hp2).changeopsize(S_L);
  4037. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4038. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4039. end;
  4040. {$endif x86_64}
  4041. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4042. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4043. if taicpu(p).oper[0]^.typ=top_reg then
  4044. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4045. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4046. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4047. {
  4048. ->
  4049. movswl %si,%eax movswl %si,%eax p
  4050. decw %si addw %dx,%si hp1
  4051. movw %ax,%si movw %ax,%si hp2
  4052. }
  4053. case taicpu(hp1).ops of
  4054. 1:
  4055. begin
  4056. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4057. if taicpu(hp1).oper[0]^.typ=top_reg then
  4058. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4059. end;
  4060. 2:
  4061. begin
  4062. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4063. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4064. (taicpu(hp1).opcode<>A_SHL) and
  4065. (taicpu(hp1).opcode<>A_SHR) and
  4066. (taicpu(hp1).opcode<>A_SAR) then
  4067. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4068. end;
  4069. else
  4070. internalerror(2018111801);
  4071. end;
  4072. {
  4073. ->
  4074. decw %si addw %dx,%si p
  4075. }
  4076. RemoveInstruction(hp2);
  4077. end;
  4078. end;
  4079. end;
  4080. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4081. GetNextInstruction(hp1, hp2) and
  4082. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4083. MatchOperand(Taicpu(p).oper[0]^,0) and
  4084. (Taicpu(p).oper[1]^.typ = top_reg) and
  4085. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4086. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4087. { mov reg1,0
  4088. bts reg1,operand1 --> mov reg1,operand2
  4089. or reg1,operand2 bts reg1,operand1}
  4090. begin
  4091. Taicpu(hp2).opcode:=A_MOV;
  4092. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4093. asml.remove(hp1);
  4094. insertllitem(hp2,hp2.next,hp1);
  4095. RemoveCurrentp(p, hp1);
  4096. Result:=true;
  4097. exit;
  4098. end;
  4099. {
  4100. mov ref,reg0
  4101. <op> reg0,reg1
  4102. dealloc reg0
  4103. to
  4104. <op> ref,reg1
  4105. }
  4106. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4107. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4108. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4109. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4110. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4111. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4112. begin
  4113. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4114. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4115. RemoveCurrentp(p, hp1);
  4116. Result:=true;
  4117. exit;
  4118. end;
  4119. {$ifdef x86_64}
  4120. { Convert:
  4121. movq x(ref),%reg64
  4122. shrq y,%reg64
  4123. To:
  4124. movl x+4(ref),%reg32
  4125. shrl y-32,%reg32 (Remove if y = 32)
  4126. }
  4127. if (taicpu(p).opsize = S_Q) and
  4128. (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4129. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFB) and
  4130. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  4131. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4132. (taicpu(hp1).oper[0]^.val >= 32) and
  4133. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4134. begin
  4135. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4136. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4137. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4138. { Convert to 32-bit }
  4139. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4140. taicpu(p).opsize := S_L;
  4141. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4142. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4143. if (taicpu(hp1).oper[0]^.val = 32) then
  4144. begin
  4145. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4146. RemoveInstruction(hp1);
  4147. end
  4148. else
  4149. begin
  4150. { This will potentially open up more arithmetic operations since
  4151. the peephole optimizer now has a big hint that only the lower
  4152. 32 bits are currently in use (and opcodes are smaller in size) }
  4153. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4154. taicpu(hp1).opsize := S_L;
  4155. Dec(taicpu(hp1).oper[0]^.val, 32);
  4156. DebugMsg(SPeepholeOptimization + PreMessage +
  4157. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4158. end;
  4159. Result := True;
  4160. Exit;
  4161. end;
  4162. {$endif x86_64}
  4163. { Backward optimisation. If we have:
  4164. func. %reg1,%reg2
  4165. mov %reg2,%reg3
  4166. (dealloc %reg2)
  4167. Change to:
  4168. func. %reg1,%reg3 (see comment below for what a valid func. is)
  4169. }
  4170. if MatchOpType(taicpu(p), top_reg, top_reg) then
  4171. begin
  4172. p_SourceReg := taicpu(p).oper[0]^.reg;
  4173. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  4174. TransferUsedRegs(TmpUsedRegs);
  4175. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  4176. GetLastInstruction(p, hp2) and
  4177. (hp2.typ = ait_instruction) and
  4178. { Have to make sure it's an instruction that only reads from
  4179. operand 1 and only writes (not reads or modifies) from operand 2;
  4180. in essence, a one-operand pure function such as BSR or POPCNT }
  4181. (taicpu(hp2).ops = 2) and
  4182. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2]) and
  4183. (taicpu(hp2).oper[1]^.typ = top_reg) and
  4184. (taicpu(hp2).oper[1]^.reg = p_SourceReg) then
  4185. begin
  4186. case taicpu(hp2).opcode of
  4187. A_FSTSW, A_FNSTSW,
  4188. A_IN, A_INS, A_OUT, A_OUTS,
  4189. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  4190. { These routines have explicit operands, but they are restricted in
  4191. what they can be (e.g. IN and OUT can only read from AL, AX or
  4192. EAX. }
  4193. ;
  4194. else
  4195. begin
  4196. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  4197. taicpu(hp2).oper[1]^.reg := p_TargetReg;
  4198. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  4199. RemoveCurrentp(p, hp1);
  4200. Result := True;
  4201. Exit;
  4202. end;
  4203. end;
  4204. end;
  4205. end;
  4206. end;
  4207. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4208. var
  4209. hp1 : tai;
  4210. begin
  4211. Result:=false;
  4212. if taicpu(p).ops <> 2 then
  4213. exit;
  4214. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4215. GetNextInstruction(p,hp1) then
  4216. begin
  4217. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4218. (taicpu(hp1).ops = 2) then
  4219. begin
  4220. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4221. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4222. { movXX reg1, mem1 or movXX mem1, reg1
  4223. movXX mem2, reg2 movXX reg2, mem2}
  4224. begin
  4225. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4226. { movXX reg1, mem1 or movXX mem1, reg1
  4227. movXX mem2, reg1 movXX reg2, mem1}
  4228. begin
  4229. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4230. begin
  4231. { Removes the second statement from
  4232. movXX reg1, mem1/reg2
  4233. movXX mem1/reg2, reg1
  4234. }
  4235. if taicpu(p).oper[0]^.typ=top_reg then
  4236. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4237. { Removes the second statement from
  4238. movXX mem1/reg1, reg2
  4239. movXX reg2, mem1/reg1
  4240. }
  4241. if (taicpu(p).oper[1]^.typ=top_reg) and
  4242. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4243. begin
  4244. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4245. RemoveInstruction(hp1);
  4246. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4247. Result:=true;
  4248. exit;
  4249. end
  4250. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4251. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4252. begin
  4253. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4254. RemoveInstruction(hp1);
  4255. Result:=true;
  4256. exit;
  4257. end;
  4258. end
  4259. end;
  4260. end;
  4261. end;
  4262. end;
  4263. end;
  4264. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4265. var
  4266. hp1 : tai;
  4267. begin
  4268. result:=false;
  4269. { replace
  4270. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4271. MovX %mreg2,%mreg1
  4272. dealloc %mreg2
  4273. by
  4274. <Op>X %mreg2,%mreg1
  4275. ?
  4276. }
  4277. if GetNextInstruction(p,hp1) and
  4278. { we mix single and double opperations here because we assume that the compiler
  4279. generates vmovapd only after double operations and vmovaps only after single operations }
  4280. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4281. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4282. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4283. (taicpu(p).oper[0]^.typ=top_reg) then
  4284. begin
  4285. TransferUsedRegs(TmpUsedRegs);
  4286. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4287. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4288. begin
  4289. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4290. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4291. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4292. RemoveInstruction(hp1);
  4293. result:=true;
  4294. end;
  4295. end;
  4296. end;
  4297. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4298. var
  4299. hp1, p_label, p_dist, hp1_dist: tai;
  4300. JumpLabel, JumpLabel_dist: TAsmLabel;
  4301. FirstValue, SecondValue: TCGInt;
  4302. begin
  4303. Result := False;
  4304. if (taicpu(p).oper[0]^.typ = top_const) and
  4305. (taicpu(p).oper[0]^.val <> -1) then
  4306. begin
  4307. { Convert unsigned maximum constants to -1 to aid optimisation }
  4308. case taicpu(p).opsize of
  4309. S_B:
  4310. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4311. begin
  4312. taicpu(p).oper[0]^.val := -1;
  4313. Result := True;
  4314. Exit;
  4315. end;
  4316. S_W:
  4317. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4318. begin
  4319. taicpu(p).oper[0]^.val := -1;
  4320. Result := True;
  4321. Exit;
  4322. end;
  4323. S_L:
  4324. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4325. begin
  4326. taicpu(p).oper[0]^.val := -1;
  4327. Result := True;
  4328. Exit;
  4329. end;
  4330. {$ifdef x86_64}
  4331. S_Q:
  4332. { Storing anything greater than $7FFFFFFF is not possible so do
  4333. nothing };
  4334. {$endif x86_64}
  4335. else
  4336. InternalError(2021121001);
  4337. end;
  4338. end;
  4339. if GetNextInstruction(p, hp1) and
  4340. TrySwapMovCmp(p, hp1) then
  4341. begin
  4342. Result := True;
  4343. Exit;
  4344. end;
  4345. { Search for:
  4346. test $x,(reg/ref)
  4347. jne @lbl1
  4348. test $y,(reg/ref) (same register or reference)
  4349. jne @lbl1
  4350. Change to:
  4351. test $(x or y),(reg/ref)
  4352. jne @lbl1
  4353. (Note, this doesn't work with je instead of jne)
  4354. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4355. Also search for:
  4356. test $x,(reg/ref)
  4357. je @lbl1
  4358. test $y,(reg/ref)
  4359. je/jne @lbl2
  4360. If (x or y) = x, then the second jump is deterministic
  4361. }
  4362. if (
  4363. (
  4364. (taicpu(p).oper[0]^.typ = top_const) or
  4365. (
  4366. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4367. (taicpu(p).oper[0]^.typ = top_reg) and
  4368. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4369. )
  4370. ) and
  4371. MatchInstruction(hp1, A_JCC, [])
  4372. ) then
  4373. begin
  4374. if (taicpu(p).oper[0]^.typ = top_reg) and
  4375. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4376. FirstValue := -1
  4377. else
  4378. FirstValue := taicpu(p).oper[0]^.val;
  4379. { If we have several test/jne's in a row, it might be the case that
  4380. the second label doesn't go to the same location, but the one
  4381. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4382. so accommodate for this with a while loop.
  4383. }
  4384. hp1_dist := hp1;
  4385. if GetNextInstruction(hp1, p_dist) and
  4386. (p_dist.typ = ait_instruction) and
  4387. (
  4388. (
  4389. (taicpu(p_dist).opcode = A_TEST) and
  4390. (
  4391. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4392. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4393. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4394. )
  4395. ) or
  4396. (
  4397. { cmp 0,%reg = test %reg,%reg }
  4398. (taicpu(p_dist).opcode = A_CMP) and
  4399. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4400. )
  4401. ) and
  4402. { Make sure the destination operands are actually the same }
  4403. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4404. GetNextInstruction(p_dist, hp1_dist) and
  4405. MatchInstruction(hp1_dist, A_JCC, []) then
  4406. begin
  4407. if
  4408. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4409. (
  4410. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4411. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4412. ) then
  4413. SecondValue := -1
  4414. else
  4415. SecondValue := taicpu(p_dist).oper[0]^.val;
  4416. { If both of the TEST constants are identical, delete the second
  4417. TEST that is unnecessary. }
  4418. if (FirstValue = SecondValue) then
  4419. begin
  4420. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4421. RemoveInstruction(p_dist);
  4422. { Don't let the flags register become deallocated and reallocated between the jumps }
  4423. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4424. Result := True;
  4425. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4426. begin
  4427. { Since the second jump's condition is a subset of the first, we
  4428. know it will never branch because the first jump dominates it.
  4429. Get it out of the way now rather than wait for the jump
  4430. optimisations for a speed boost. }
  4431. if IsJumpToLabel(taicpu(hp1_dist)) then
  4432. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4433. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4434. RemoveInstruction(hp1_dist);
  4435. end
  4436. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4437. begin
  4438. { If the inverse of the first condition is a subset of the second,
  4439. the second one will definitely branch if the first one doesn't }
  4440. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4441. MakeUnconditional(taicpu(hp1_dist));
  4442. RemoveDeadCodeAfterJump(hp1_dist);
  4443. end;
  4444. Exit;
  4445. end;
  4446. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4447. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4448. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4449. then the second jump will never branch, so it can also be
  4450. removed regardless of where it goes }
  4451. (
  4452. (FirstValue = -1) or
  4453. (SecondValue = -1) or
  4454. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4455. ) then
  4456. begin
  4457. { Same jump location... can be a register since nothing's changed }
  4458. { If any of the entries are equivalent to test %reg,%reg, then the
  4459. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  4460. taicpu(p).loadconst(0, FirstValue or SecondValue);
  4461. if IsJumpToLabel(taicpu(hp1_dist)) then
  4462. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4463. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  4464. RemoveInstruction(hp1_dist);
  4465. { Only remove the second test if no jumps or other conditional instructions follow }
  4466. TransferUsedRegs(TmpUsedRegs);
  4467. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4468. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4469. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  4470. RemoveInstruction(p_dist);
  4471. Result := True;
  4472. Exit;
  4473. end;
  4474. end;
  4475. end;
  4476. { Search for:
  4477. test %reg,%reg
  4478. j(c1) @lbl1
  4479. ...
  4480. @lbl:
  4481. test %reg,%reg (same register)
  4482. j(c2) @lbl2
  4483. If c2 is a subset of c1, change to:
  4484. test %reg,%reg
  4485. j(c1) @lbl2
  4486. (@lbl1 may become a dead label as a result)
  4487. }
  4488. if (taicpu(p).oper[1]^.typ = top_reg) and
  4489. (taicpu(p).oper[0]^.typ = top_reg) and
  4490. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  4491. MatchInstruction(hp1, A_JCC, []) and
  4492. IsJumpToLabel(taicpu(hp1)) then
  4493. begin
  4494. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4495. p_label := nil;
  4496. if Assigned(JumpLabel) then
  4497. p_label := getlabelwithsym(JumpLabel);
  4498. if Assigned(p_label) and
  4499. GetNextInstruction(p_label, p_dist) and
  4500. MatchInstruction(p_dist, A_TEST, []) and
  4501. { It's fine if the second test uses smaller sub-registers }
  4502. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  4503. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  4504. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  4505. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  4506. GetNextInstruction(p_dist, hp1_dist) and
  4507. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4508. begin
  4509. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4510. if JumpLabel = JumpLabel_dist then
  4511. { This is an infinite loop }
  4512. Exit;
  4513. { Best optimisation when the first condition is a subset (or equal) of the second }
  4514. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  4515. begin
  4516. { Any registers used here will already be allocated }
  4517. if Assigned(JumpLabel_dist) then
  4518. JumpLabel_dist.IncRefs;
  4519. if Assigned(JumpLabel) then
  4520. JumpLabel.DecRefs;
  4521. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  4522. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  4523. Result := True;
  4524. Exit;
  4525. end;
  4526. end;
  4527. end;
  4528. end;
  4529. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  4530. var
  4531. hp1, hp2: tai;
  4532. ActiveReg: TRegister;
  4533. OldOffset: asizeint;
  4534. ThisConst: TCGInt;
  4535. function RegDeallocated: Boolean;
  4536. begin
  4537. TransferUsedRegs(TmpUsedRegs);
  4538. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4539. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4540. end;
  4541. begin
  4542. result:=false;
  4543. hp1 := nil;
  4544. { replace
  4545. addX const,%reg1
  4546. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4547. dealloc %reg1
  4548. by
  4549. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  4550. }
  4551. if MatchOpType(taicpu(p),top_const,top_reg) then
  4552. begin
  4553. ActiveReg := taicpu(p).oper[1]^.reg;
  4554. { Ensures the entire register was updated }
  4555. if (taicpu(p).opsize >= S_L) and
  4556. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  4557. MatchInstruction(hp1,A_LEA,[]) and
  4558. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  4559. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  4560. (
  4561. { Cover the case where the register in the reference is also the destination register }
  4562. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  4563. (
  4564. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  4565. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  4566. RegDeallocated
  4567. )
  4568. ) then
  4569. begin
  4570. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  4571. {$push}
  4572. {$R-}{$Q-}
  4573. { Explicitly disable overflow checking for these offset calculation
  4574. as those do not matter for the final result }
  4575. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  4576. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  4577. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  4578. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4579. {$pop}
  4580. {$ifdef x86_64}
  4581. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  4582. begin
  4583. { Overflow; abort }
  4584. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  4585. end
  4586. else
  4587. {$endif x86_64}
  4588. begin
  4589. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  4590. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  4591. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  4592. RemoveCurrentP(p, hp1)
  4593. else
  4594. RemoveCurrentP(p);
  4595. result:=true;
  4596. Exit;
  4597. end;
  4598. end;
  4599. if (
  4600. { Save calling GetNextInstructionUsingReg again }
  4601. Assigned(hp1) or
  4602. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  4603. ) and
  4604. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  4605. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  4606. begin
  4607. if taicpu(hp1).oper[0]^.typ = top_const then
  4608. begin
  4609. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  4610. if taicpu(hp1).opcode = A_ADD then
  4611. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  4612. else
  4613. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  4614. Result := True;
  4615. { Handle any overflows }
  4616. case taicpu(p).opsize of
  4617. S_B:
  4618. taicpu(p).oper[0]^.val := ThisConst and $FF;
  4619. S_W:
  4620. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  4621. S_L:
  4622. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  4623. {$ifdef x86_64}
  4624. S_Q:
  4625. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  4626. { Overflow; abort }
  4627. Result := False
  4628. else
  4629. taicpu(p).oper[0]^.val := ThisConst;
  4630. {$endif x86_64}
  4631. else
  4632. InternalError(2021102610);
  4633. end;
  4634. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  4635. if Result then
  4636. begin
  4637. if (taicpu(p).oper[0]^.val < 0) and
  4638. (
  4639. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  4640. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  4641. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  4642. ) then
  4643. begin
  4644. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  4645. taicpu(p).opcode := A_SUB;
  4646. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  4647. end
  4648. else
  4649. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  4650. RemoveInstruction(hp1);
  4651. end;
  4652. end
  4653. else
  4654. begin
  4655. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  4656. TransferUsedRegs(TmpUsedRegs);
  4657. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4658. hp2 := p;
  4659. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  4660. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  4661. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  4662. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  4663. begin
  4664. { Move the constant addition to after the reg/ref addition to improve optimisation }
  4665. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  4666. Asml.Remove(p);
  4667. Asml.InsertAfter(p, hp1);
  4668. p := hp1;
  4669. Result := True;
  4670. end;
  4671. end;
  4672. end;
  4673. end;
  4674. end;
  4675. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  4676. var
  4677. hp1: tai;
  4678. ref: Integer;
  4679. saveref: treference;
  4680. Multiple: TCGInt;
  4681. Adjacent: Boolean;
  4682. begin
  4683. Result:=false;
  4684. { play save and throw an error if LEA uses a seg register prefix,
  4685. this is most likely an error somewhere else }
  4686. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  4687. internalerror(2022022001);
  4688. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  4689. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4690. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  4691. (
  4692. { do not mess with leas accessing the stack pointer
  4693. unless it's a null operation }
  4694. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  4695. (
  4696. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  4697. (taicpu(p).oper[0]^.ref^.offset = 0)
  4698. )
  4699. ) and
  4700. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  4701. begin
  4702. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  4703. begin
  4704. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  4705. begin
  4706. hp1:=taicpu.op_reg_reg(A_MOV,taicpu(p).opsize,taicpu(p).oper[0]^.ref^.base,
  4707. taicpu(p).oper[1]^.reg);
  4708. InsertLLItem(p.previous,p.next, hp1);
  4709. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',hp1);
  4710. p.free;
  4711. p:=hp1;
  4712. end
  4713. else
  4714. begin
  4715. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  4716. RemoveCurrentP(p);
  4717. end;
  4718. Result:=true;
  4719. exit;
  4720. end
  4721. else if (
  4722. { continue to use lea to adjust the stack pointer,
  4723. it is the recommended way, but only if not optimizing for size }
  4724. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  4725. (cs_opt_size in current_settings.optimizerswitches)
  4726. ) and
  4727. { If the flags register is in use, don't change the instruction
  4728. to an ADD otherwise this will scramble the flags. [Kit] }
  4729. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  4730. ConvertLEA(taicpu(p)) then
  4731. begin
  4732. Result:=true;
  4733. exit;
  4734. end;
  4735. end;
  4736. { Don't optimise if the stack or frame pointer is the destination register }
  4737. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  4738. Exit;
  4739. if GetNextInstruction(p,hp1) and
  4740. (hp1.typ=ait_instruction) then
  4741. begin
  4742. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  4743. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4744. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  4745. begin
  4746. TransferUsedRegs(TmpUsedRegs);
  4747. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4748. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4749. begin
  4750. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4751. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  4752. RemoveInstruction(hp1);
  4753. result:=true;
  4754. exit;
  4755. end;
  4756. end;
  4757. { changes
  4758. lea <ref1>, reg1
  4759. <op> ...,<ref. with reg1>,...
  4760. to
  4761. <op> ...,<ref1>,... }
  4762. { find a reference which uses reg1 }
  4763. 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
  4764. ref:=0
  4765. 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
  4766. ref:=1
  4767. else
  4768. ref:=-1;
  4769. if (ref<>-1) and
  4770. { reg1 must be either the base or the index }
  4771. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  4772. begin
  4773. { reg1 can be removed from the reference }
  4774. saveref:=taicpu(hp1).oper[ref]^.ref^;
  4775. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  4776. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  4777. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  4778. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  4779. else
  4780. Internalerror(2019111201);
  4781. { check if the can insert all data of the lea into the second instruction }
  4782. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4783. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  4784. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  4785. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  4786. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  4787. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4788. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  4789. {$ifdef x86_64}
  4790. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  4791. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  4792. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  4793. )
  4794. {$endif x86_64}
  4795. then
  4796. begin
  4797. { reg1 might not used by the second instruction after it is remove from the reference }
  4798. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  4799. begin
  4800. TransferUsedRegs(TmpUsedRegs);
  4801. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4802. { reg1 is not updated so it might not be used afterwards }
  4803. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4804. begin
  4805. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  4806. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  4807. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4808. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4809. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4810. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  4811. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  4812. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  4813. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  4814. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  4815. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4816. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4817. RemoveCurrentP(p, hp1);
  4818. result:=true;
  4819. exit;
  4820. end
  4821. end;
  4822. end;
  4823. { recover }
  4824. taicpu(hp1).oper[ref]^.ref^:=saveref;
  4825. end;
  4826. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  4827. if Adjacent or
  4828. { Check further ahead (up to 2 instructions ahead for -O2) }
  4829. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  4830. begin
  4831. { Check common LEA/LEA conditions }
  4832. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  4833. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  4834. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  4835. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  4836. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  4837. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  4838. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  4839. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  4840. (
  4841. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  4842. calling it (since it calls GetNextInstruction) }
  4843. Adjacent or
  4844. (
  4845. (
  4846. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  4847. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  4848. ) and (
  4849. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  4850. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4851. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  4852. )
  4853. )
  4854. ) then
  4855. begin
  4856. { changes
  4857. lea (regX,scale), reg1
  4858. lea offset(reg1,reg1), reg1
  4859. to
  4860. lea offset(regX,scale*2), reg1
  4861. and
  4862. lea (regX,scale1), reg1
  4863. lea offset(reg1,scale2), reg1
  4864. to
  4865. lea offset(regX,scale1*scale2), reg1
  4866. ... so long as the final scale does not exceed 8
  4867. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  4868. }
  4869. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  4870. (taicpu(p).oper[0]^.ref^.offset = 0) and
  4871. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4872. (
  4873. (
  4874. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4875. ) or (
  4876. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4877. (
  4878. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  4879. (
  4880. { RegUsedBetween always returns False if p and hp1 are adjacent }
  4881. Adjacent or
  4882. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  4883. )
  4884. )
  4885. )
  4886. ) and (
  4887. (
  4888. { lea (reg1,scale2), reg1 variant }
  4889. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  4890. (
  4891. (
  4892. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  4893. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  4894. ) or (
  4895. { lea (regX,regX), reg1 variant }
  4896. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4897. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  4898. )
  4899. )
  4900. ) or (
  4901. { lea (reg1,reg1), reg1 variant }
  4902. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4903. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  4904. )
  4905. ) then
  4906. begin
  4907. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  4908. { Make everything homogeneous to make calculations easier }
  4909. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  4910. begin
  4911. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  4912. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  4913. taicpu(p).oper[0]^.ref^.scalefactor := 2
  4914. else
  4915. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  4916. taicpu(p).oper[0]^.ref^.base := NR_NO;
  4917. end;
  4918. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  4919. begin
  4920. { Just to prevent miscalculations }
  4921. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  4922. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  4923. else
  4924. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  4925. end
  4926. else
  4927. begin
  4928. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  4929. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  4930. end;
  4931. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  4932. RemoveCurrentP(p);
  4933. result:=true;
  4934. exit;
  4935. end
  4936. { changes
  4937. lea offset1(regX), reg1
  4938. lea offset2(reg1), reg1
  4939. to
  4940. lea offset1+offset2(regX), reg1 }
  4941. else if
  4942. (
  4943. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4944. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  4945. ) or (
  4946. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4947. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  4948. (
  4949. (
  4950. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4951. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4952. ) or (
  4953. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4954. (
  4955. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4956. (
  4957. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4958. (
  4959. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  4960. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  4961. )
  4962. )
  4963. )
  4964. )
  4965. )
  4966. ) then
  4967. begin
  4968. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  4969. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  4970. begin
  4971. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  4972. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4973. { if the register is used as index and base, we have to increase for base as well
  4974. and adapt base }
  4975. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  4976. begin
  4977. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4978. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4979. end;
  4980. end
  4981. else
  4982. begin
  4983. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4984. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4985. end;
  4986. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4987. begin
  4988. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  4989. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4990. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4991. end;
  4992. RemoveCurrentP(p);
  4993. result:=true;
  4994. exit;
  4995. end;
  4996. end;
  4997. { Change:
  4998. leal/q $x(%reg1),%reg2
  4999. ...
  5000. shll/q $y,%reg2
  5001. To:
  5002. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5003. }
  5004. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5005. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5006. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5007. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5008. (taicpu(hp1).oper[0]^.val <= 3) then
  5009. begin
  5010. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5011. TransferUsedRegs(TmpUsedRegs);
  5012. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5013. if
  5014. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5015. (this works even if scalefactor is zero) }
  5016. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5017. { Ensure offset doesn't go out of bounds }
  5018. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5019. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5020. (
  5021. (
  5022. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5023. (
  5024. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5025. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5026. (
  5027. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5028. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5029. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5030. )
  5031. )
  5032. ) or (
  5033. (
  5034. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5035. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5036. ) and
  5037. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5038. )
  5039. ) then
  5040. begin
  5041. repeat
  5042. with taicpu(p).oper[0]^.ref^ do
  5043. begin
  5044. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5045. if index = base then
  5046. begin
  5047. if Multiple > 4 then
  5048. { Optimisation will no longer work because resultant
  5049. scale factor will exceed 8 }
  5050. Break;
  5051. base := NR_NO;
  5052. scalefactor := 2;
  5053. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5054. end
  5055. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5056. begin
  5057. { Scale factor only works on the index register }
  5058. index := base;
  5059. base := NR_NO;
  5060. end;
  5061. { For safety }
  5062. if scalefactor <= 1 then
  5063. begin
  5064. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5065. scalefactor := Multiple;
  5066. end
  5067. else
  5068. begin
  5069. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5070. scalefactor := scalefactor * Multiple;
  5071. end;
  5072. offset := offset * Multiple;
  5073. end;
  5074. RemoveInstruction(hp1);
  5075. Result := True;
  5076. Exit;
  5077. { This repeat..until loop exists for the benefit of Break }
  5078. until True;
  5079. end;
  5080. end;
  5081. end;
  5082. end;
  5083. end;
  5084. function TX86AsmOptimizer.DoSubAddOpt(var p: tai): Boolean;
  5085. var
  5086. hp1 : tai;
  5087. begin
  5088. DoSubAddOpt := False;
  5089. if taicpu(p).oper[0]^.typ <> top_const then
  5090. { Should have been confirmed before calling }
  5091. InternalError(2021102601);
  5092. if GetLastInstruction(p, hp1) and
  5093. (hp1.typ = ait_instruction) and
  5094. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5095. case taicpu(hp1).opcode Of
  5096. A_DEC:
  5097. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5098. begin
  5099. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+1);
  5100. RemoveInstruction(hp1);
  5101. end;
  5102. A_SUB:
  5103. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5104. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5105. begin
  5106. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val);
  5107. RemoveInstruction(hp1);
  5108. end;
  5109. A_ADD:
  5110. begin
  5111. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5112. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5113. begin
  5114. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  5115. RemoveInstruction(hp1);
  5116. if (taicpu(p).oper[0]^.val = 0) then
  5117. begin
  5118. hp1 := tai(p.next);
  5119. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5120. if not GetLastInstruction(hp1, p) then
  5121. p := hp1;
  5122. DoSubAddOpt := True;
  5123. end
  5124. end;
  5125. end;
  5126. else
  5127. ;
  5128. end;
  5129. end;
  5130. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  5131. begin
  5132. Result := False;
  5133. if UpdateTmpUsedRegs then
  5134. TransferUsedRegs(TmpUsedRegs);
  5135. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5136. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5137. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5138. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5139. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5140. (
  5141. (
  5142. (taicpu(hp1).opcode = A_TEST)
  5143. ) or (
  5144. (taicpu(hp1).opcode = A_CMP) and
  5145. { A sanity check more than anything }
  5146. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5147. )
  5148. ) then
  5149. begin
  5150. { change
  5151. mov mem, %reg
  5152. cmp/test x, %reg / test %reg,%reg
  5153. (reg deallocated)
  5154. to
  5155. cmp/test x, mem / cmp 0, mem
  5156. }
  5157. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5158. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5159. begin
  5160. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5161. if (taicpu(hp1).opcode = A_TEST) and
  5162. (
  5163. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5164. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5165. ) then
  5166. begin
  5167. taicpu(hp1).opcode := A_CMP;
  5168. taicpu(hp1).loadconst(0, 0);
  5169. end;
  5170. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  5171. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  5172. RemoveCurrentP(p, hp1);
  5173. Result := True;
  5174. Exit;
  5175. end;
  5176. end;
  5177. end;
  5178. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  5179. var
  5180. hp2, hp3, hp4, hp5, hp6: tai;
  5181. ThisReg: TRegister;
  5182. JumpLoc: TAsmLabel;
  5183. begin
  5184. Result := False;
  5185. {
  5186. Convert:
  5187. j<c> .L1
  5188. .L2:
  5189. mov 1,reg
  5190. jmp .L3 (or ret, although it might not be a RET yet)
  5191. .L1:
  5192. mov 0,reg
  5193. jmp .L3 (or ret)
  5194. ( As long as .L3 <> .L1 or .L2)
  5195. To:
  5196. mov 0,reg
  5197. set<not(c)> reg
  5198. jmp .L3 (or ret)
  5199. .L2:
  5200. mov 1,reg
  5201. jmp .L3 (or ret)
  5202. .L1:
  5203. mov 0,reg
  5204. jmp .L3 (or ret)
  5205. }
  5206. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  5207. Exit;
  5208. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  5209. if GetNextInstruction(hp_label, hp2) and
  5210. MatchInstruction(hp2,A_MOV,[]) and
  5211. (taicpu(hp2).oper[0]^.typ = top_const) and
  5212. (
  5213. (
  5214. (taicpu(hp2).oper[1]^.typ = top_reg)
  5215. {$ifdef i386}
  5216. { Under i386, ESI, EDI, EBP and ESP
  5217. don't have an 8-bit representation }
  5218. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5219. {$endif i386}
  5220. ) or (
  5221. {$ifdef i386}
  5222. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  5223. {$endif i386}
  5224. (taicpu(hp2).opsize = S_B)
  5225. )
  5226. ) and
  5227. GetNextInstruction(hp2, hp3) and
  5228. MatchInstruction(hp3, A_JMP, A_RET, []) and
  5229. (
  5230. (taicpu(hp3).opcode=A_RET) or
  5231. (
  5232. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  5233. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  5234. )
  5235. ) and
  5236. GetNextInstruction(hp3, hp4) and
  5237. SkipAligns(hp4, hp4) and
  5238. (hp4.typ=ait_label) and
  5239. (tai_label(hp4).labsym=JumpLoc) and
  5240. (
  5241. not (cs_opt_size in current_settings.optimizerswitches) or
  5242. { If the initial jump is the label's only reference, then it will
  5243. become a dead label if the other conditions are met and hence
  5244. remove at least 2 instructions, including a jump }
  5245. (JumpLoc.getrefs = 1)
  5246. ) and
  5247. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  5248. that will be optimised out }
  5249. GetNextInstruction(hp4, hp5) and
  5250. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  5251. (taicpu(hp5).oper[0]^.typ = top_const) and
  5252. (
  5253. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  5254. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  5255. ) and
  5256. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  5257. GetNextInstruction(hp5,hp6) and
  5258. (
  5259. (hp6.typ<>ait_label) or
  5260. SkipLabels(hp6, hp6)
  5261. ) and
  5262. (hp6.typ=ait_instruction) then
  5263. begin
  5264. { First, let's look at the two jumps that are hp3 and hp6 }
  5265. if not
  5266. (
  5267. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5268. (
  5269. (taicpu(hp6).opcode=A_RET) or
  5270. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5271. )
  5272. ) then
  5273. { If condition is False, then the JMP/RET instructions matched conventionally }
  5274. begin
  5275. { See if one of the jumps can be instantly converted into a RET }
  5276. if (taicpu(hp3).opcode=A_JMP) then
  5277. begin
  5278. { Reuse hp5 }
  5279. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  5280. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  5281. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  5282. Exit;
  5283. if MatchInstruction(hp5, A_RET, []) then
  5284. begin
  5285. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  5286. ConvertJumpToRET(hp3, hp5);
  5287. Result := True;
  5288. end
  5289. else
  5290. Exit;
  5291. end;
  5292. if (taicpu(hp6).opcode=A_JMP) then
  5293. begin
  5294. { Reuse hp5 }
  5295. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  5296. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  5297. Exit;
  5298. if MatchInstruction(hp5, A_RET, []) then
  5299. begin
  5300. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  5301. ConvertJumpToRET(hp6, hp5);
  5302. Result := True;
  5303. end
  5304. else
  5305. Exit;
  5306. end;
  5307. if not
  5308. (
  5309. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5310. (
  5311. (taicpu(hp6).opcode=A_RET) or
  5312. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5313. )
  5314. ) then
  5315. { Still doesn't match }
  5316. Exit;
  5317. end;
  5318. if (taicpu(hp2).oper[0]^.val = 1) then
  5319. begin
  5320. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5321. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  5322. end
  5323. else
  5324. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  5325. if taicpu(hp2).opsize=S_B then
  5326. begin
  5327. if taicpu(hp2).oper[1]^.typ = top_reg then
  5328. hp4:=taicpu.op_reg(A_SETcc, S_B, taicpu(hp2).oper[1]^.reg)
  5329. else
  5330. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  5331. hp2 := p;
  5332. end
  5333. else
  5334. begin
  5335. { Will be a register because the size can't be S_B otherwise }
  5336. ThisReg:=newreg(R_INTREGISTER,getsupreg(taicpu(hp2).oper[1]^.reg), R_SUBL);
  5337. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  5338. hp2:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, taicpu(hp2).oper[1]^.reg);
  5339. { Inserting it right before p will guarantee that the flags are also tracked }
  5340. Asml.InsertBefore(hp2, p);
  5341. end;
  5342. taicpu(hp4).condition:=taicpu(p).condition;
  5343. asml.InsertBefore(hp4, hp2);
  5344. JumpLoc.decrefs;
  5345. if taicpu(hp3).opcode = A_JMP then
  5346. begin
  5347. MakeUnconditional(taicpu(p));
  5348. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  5349. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  5350. end
  5351. else
  5352. begin
  5353. taicpu(p).condition := C_None;
  5354. taicpu(p).opcode := A_RET;
  5355. taicpu(p).clearop(0);
  5356. taicpu(p).ops := 0;
  5357. end;
  5358. if (JumpLoc.getrefs = 0) then
  5359. RemoveDeadCodeAfterJump(hp3);
  5360. Result:=true;
  5361. exit;
  5362. end;
  5363. end;
  5364. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  5365. var
  5366. hp1, hp2: tai;
  5367. ActiveReg: TRegister;
  5368. OldOffset: asizeint;
  5369. ThisConst: TCGInt;
  5370. function RegDeallocated: Boolean;
  5371. begin
  5372. TransferUsedRegs(TmpUsedRegs);
  5373. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5374. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5375. end;
  5376. begin
  5377. Result:=false;
  5378. hp1 := nil;
  5379. { replace
  5380. subX const,%reg1
  5381. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5382. dealloc %reg1
  5383. by
  5384. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  5385. }
  5386. if MatchOpType(taicpu(p),top_const,top_reg) then
  5387. begin
  5388. ActiveReg := taicpu(p).oper[1]^.reg;
  5389. { Ensures the entire register was updated }
  5390. if (taicpu(p).opsize >= S_L) and
  5391. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5392. MatchInstruction(hp1,A_LEA,[]) and
  5393. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5394. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5395. (
  5396. { Cover the case where the register in the reference is also the destination register }
  5397. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5398. (
  5399. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5400. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5401. RegDeallocated
  5402. )
  5403. ) then
  5404. begin
  5405. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5406. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5407. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5408. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5409. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5410. {$ifdef x86_64}
  5411. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5412. begin
  5413. { Overflow; abort }
  5414. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5415. end
  5416. else
  5417. {$endif x86_64}
  5418. begin
  5419. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  5420. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5421. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5422. RemoveCurrentP(p, hp1)
  5423. else
  5424. RemoveCurrentP(p);
  5425. result:=true;
  5426. Exit;
  5427. end;
  5428. end;
  5429. if (
  5430. { Save calling GetNextInstructionUsingReg again }
  5431. Assigned(hp1) or
  5432. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5433. ) and
  5434. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  5435. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5436. begin
  5437. if taicpu(hp1).oper[0]^.typ = top_const then
  5438. begin
  5439. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  5440. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5441. Result := True;
  5442. { Handle any overflows }
  5443. case taicpu(p).opsize of
  5444. S_B:
  5445. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5446. S_W:
  5447. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5448. S_L:
  5449. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5450. {$ifdef x86_64}
  5451. S_Q:
  5452. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5453. { Overflow; abort }
  5454. Result := False
  5455. else
  5456. taicpu(p).oper[0]^.val := ThisConst;
  5457. {$endif x86_64}
  5458. else
  5459. InternalError(2021102610);
  5460. end;
  5461. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5462. if Result then
  5463. begin
  5464. if (taicpu(p).oper[0]^.val < 0) and
  5465. (
  5466. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5467. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5468. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5469. ) then
  5470. begin
  5471. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  5472. taicpu(p).opcode := A_SUB;
  5473. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5474. end
  5475. else
  5476. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  5477. RemoveInstruction(hp1);
  5478. end;
  5479. end
  5480. else
  5481. begin
  5482. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  5483. TransferUsedRegs(TmpUsedRegs);
  5484. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5485. hp2 := p;
  5486. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5487. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5488. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5489. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5490. begin
  5491. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  5492. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  5493. Asml.Remove(p);
  5494. Asml.InsertAfter(p, hp1);
  5495. p := hp1;
  5496. Result := True;
  5497. Exit;
  5498. end;
  5499. end;
  5500. end;
  5501. { * change "subl $2, %esp; pushw x" to "pushl x"}
  5502. { * change "sub/add const1, reg" or "dec reg" followed by
  5503. "sub const2, reg" to one "sub ..., reg" }
  5504. {$ifdef i386}
  5505. if (taicpu(p).oper[0]^.val = 2) and
  5506. (ActiveReg = NR_ESP) and
  5507. { Don't do the sub/push optimization if the sub }
  5508. { comes from setting up the stack frame (JM) }
  5509. (not(GetLastInstruction(p,hp1)) or
  5510. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  5511. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  5512. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  5513. begin
  5514. hp1 := tai(p.next);
  5515. while Assigned(hp1) and
  5516. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  5517. not RegReadByInstruction(NR_ESP,hp1) and
  5518. not RegModifiedByInstruction(NR_ESP,hp1) do
  5519. hp1 := tai(hp1.next);
  5520. if Assigned(hp1) and
  5521. MatchInstruction(hp1,A_PUSH,[S_W]) then
  5522. begin
  5523. taicpu(hp1).changeopsize(S_L);
  5524. if taicpu(hp1).oper[0]^.typ=top_reg then
  5525. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  5526. hp1 := tai(p.next);
  5527. RemoveCurrentp(p, hp1);
  5528. Result:=true;
  5529. exit;
  5530. end;
  5531. end;
  5532. {$endif i386}
  5533. if DoSubAddOpt(p) then
  5534. Result:=true;
  5535. end;
  5536. end;
  5537. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  5538. var
  5539. TmpBool1,TmpBool2 : Boolean;
  5540. tmpref : treference;
  5541. hp1,hp2: tai;
  5542. mask: tcgint;
  5543. begin
  5544. Result:=false;
  5545. { All these optimisations work on "shl/sal const,%reg" }
  5546. if not MatchOpType(taicpu(p),top_const,top_reg) then
  5547. Exit;
  5548. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  5549. (taicpu(p).oper[0]^.val <= 3) then
  5550. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  5551. begin
  5552. { should we check the next instruction? }
  5553. TmpBool1 := True;
  5554. { have we found an add/sub which could be
  5555. integrated in the lea? }
  5556. TmpBool2 := False;
  5557. reference_reset(tmpref,2,[]);
  5558. TmpRef.index := taicpu(p).oper[1]^.reg;
  5559. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5560. while TmpBool1 and
  5561. GetNextInstruction(p, hp1) and
  5562. (tai(hp1).typ = ait_instruction) and
  5563. ((((taicpu(hp1).opcode = A_ADD) or
  5564. (taicpu(hp1).opcode = A_SUB)) and
  5565. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  5566. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  5567. (((taicpu(hp1).opcode = A_INC) or
  5568. (taicpu(hp1).opcode = A_DEC)) and
  5569. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5570. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  5571. ((taicpu(hp1).opcode = A_LEA) and
  5572. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5573. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  5574. (not GetNextInstruction(hp1,hp2) or
  5575. not instrReadsFlags(hp2)) Do
  5576. begin
  5577. TmpBool1 := False;
  5578. if taicpu(hp1).opcode=A_LEA then
  5579. begin
  5580. if (TmpRef.base = NR_NO) and
  5581. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  5582. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  5583. { Segment register isn't a concern here }
  5584. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  5585. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  5586. begin
  5587. TmpBool1 := True;
  5588. TmpBool2 := True;
  5589. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  5590. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  5591. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  5592. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  5593. RemoveInstruction(hp1);
  5594. end
  5595. end
  5596. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  5597. begin
  5598. TmpBool1 := True;
  5599. TmpBool2 := True;
  5600. case taicpu(hp1).opcode of
  5601. A_ADD:
  5602. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5603. A_SUB:
  5604. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5605. else
  5606. internalerror(2019050536);
  5607. end;
  5608. RemoveInstruction(hp1);
  5609. end
  5610. else
  5611. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5612. (((taicpu(hp1).opcode = A_ADD) and
  5613. (TmpRef.base = NR_NO)) or
  5614. (taicpu(hp1).opcode = A_INC) or
  5615. (taicpu(hp1).opcode = A_DEC)) then
  5616. begin
  5617. TmpBool1 := True;
  5618. TmpBool2 := True;
  5619. case taicpu(hp1).opcode of
  5620. A_ADD:
  5621. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  5622. A_INC:
  5623. inc(TmpRef.offset);
  5624. A_DEC:
  5625. dec(TmpRef.offset);
  5626. else
  5627. internalerror(2019050535);
  5628. end;
  5629. RemoveInstruction(hp1);
  5630. end;
  5631. end;
  5632. if TmpBool2
  5633. {$ifndef x86_64}
  5634. or
  5635. ((current_settings.optimizecputype < cpu_Pentium2) and
  5636. (taicpu(p).oper[0]^.val <= 3) and
  5637. not(cs_opt_size in current_settings.optimizerswitches))
  5638. {$endif x86_64}
  5639. then
  5640. begin
  5641. if not(TmpBool2) and
  5642. (taicpu(p).oper[0]^.val=1) then
  5643. begin
  5644. hp1:=taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5645. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  5646. end
  5647. else
  5648. hp1:=taicpu.op_ref_reg(A_LEA, taicpu(p).opsize, TmpRef,
  5649. taicpu(p).oper[1]^.reg);
  5650. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  5651. InsertLLItem(p.previous, p.next, hp1);
  5652. p.free;
  5653. p := hp1;
  5654. end;
  5655. end
  5656. {$ifndef x86_64}
  5657. else if (current_settings.optimizecputype < cpu_Pentium2) then
  5658. begin
  5659. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  5660. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  5661. (unlike shl, which is only Tairable in the U pipe) }
  5662. if taicpu(p).oper[0]^.val=1 then
  5663. begin
  5664. hp1 := taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5665. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg);
  5666. InsertLLItem(p.previous, p.next, hp1);
  5667. p.free;
  5668. p := hp1;
  5669. end
  5670. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  5671. "shl $3, %reg" to "lea (,%reg,8), %reg }
  5672. else if (taicpu(p).opsize = S_L) and
  5673. (taicpu(p).oper[0]^.val<= 3) then
  5674. begin
  5675. reference_reset(tmpref,2,[]);
  5676. TmpRef.index := taicpu(p).oper[1]^.reg;
  5677. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5678. hp1 := taicpu.Op_ref_reg(A_LEA,S_L,TmpRef, taicpu(p).oper[1]^.reg);
  5679. InsertLLItem(p.previous, p.next, hp1);
  5680. p.free;
  5681. p := hp1;
  5682. end;
  5683. end
  5684. {$endif x86_64}
  5685. else if
  5686. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  5687. (
  5688. (
  5689. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  5690. SetAndTest(hp1, hp2)
  5691. {$ifdef x86_64}
  5692. ) or
  5693. (
  5694. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  5695. GetNextInstruction(hp1, hp2) and
  5696. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  5697. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  5698. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  5699. {$endif x86_64}
  5700. )
  5701. ) and
  5702. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  5703. begin
  5704. { Change:
  5705. shl x, %reg1
  5706. mov -(1<<x), %reg2
  5707. and %reg2, %reg1
  5708. Or:
  5709. shl x, %reg1
  5710. and -(1<<x), %reg1
  5711. To just:
  5712. shl x, %reg1
  5713. Since the and operation only zeroes bits that are already zero from the shl operation
  5714. }
  5715. case taicpu(p).oper[0]^.val of
  5716. 8:
  5717. mask:=$FFFFFFFFFFFFFF00;
  5718. 16:
  5719. mask:=$FFFFFFFFFFFF0000;
  5720. 32:
  5721. mask:=$FFFFFFFF00000000;
  5722. 63:
  5723. { Constant pre-calculated to prevent overflow errors with Int64 }
  5724. mask:=$8000000000000000;
  5725. else
  5726. begin
  5727. if taicpu(p).oper[0]^.val >= 64 then
  5728. { Shouldn't happen realistically, since the register
  5729. is guaranteed to be set to zero at this point }
  5730. mask := 0
  5731. else
  5732. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  5733. end;
  5734. end;
  5735. if taicpu(hp1).oper[0]^.val = mask then
  5736. begin
  5737. { Everything checks out, perform the optimisation, as long as
  5738. the FLAGS register isn't being used}
  5739. TransferUsedRegs(TmpUsedRegs);
  5740. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5741. {$ifdef x86_64}
  5742. if (hp1 <> hp2) then
  5743. begin
  5744. { "shl/mov/and" version }
  5745. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  5746. { Don't do the optimisation if the FLAGS register is in use }
  5747. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  5748. begin
  5749. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  5750. { Don't remove the 'mov' instruction if its register is used elsewhere }
  5751. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  5752. begin
  5753. RemoveInstruction(hp1);
  5754. Result := True;
  5755. end;
  5756. { Only set Result to True if the 'mov' instruction was removed }
  5757. RemoveInstruction(hp2);
  5758. end;
  5759. end
  5760. else
  5761. {$endif x86_64}
  5762. begin
  5763. { "shl/and" version }
  5764. { Don't do the optimisation if the FLAGS register is in use }
  5765. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  5766. begin
  5767. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  5768. RemoveInstruction(hp1);
  5769. Result := True;
  5770. end;
  5771. end;
  5772. Exit;
  5773. end
  5774. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  5775. begin
  5776. { Even if the mask doesn't allow for its removal, we might be
  5777. able to optimise the mask for the "shl/and" version, which
  5778. may permit other peephole optimisations }
  5779. {$ifdef DEBUG_AOPTCPU}
  5780. mask := taicpu(hp1).oper[0]^.val and mask;
  5781. if taicpu(hp1).oper[0]^.val <> mask then
  5782. begin
  5783. DebugMsg(
  5784. SPeepholeOptimization +
  5785. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  5786. ' to $' + debug_tostr(mask) +
  5787. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  5788. taicpu(hp1).oper[0]^.val := mask;
  5789. end;
  5790. {$else DEBUG_AOPTCPU}
  5791. { If debugging is off, just set the operand even if it's the same }
  5792. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  5793. {$endif DEBUG_AOPTCPU}
  5794. end;
  5795. end;
  5796. {
  5797. change
  5798. shl/sal const,reg
  5799. <op> ...(...,reg,1),...
  5800. into
  5801. <op> ...(...,reg,1 shl const),...
  5802. if const in 1..3
  5803. }
  5804. if MatchOpType(taicpu(p), top_const, top_reg) and
  5805. (taicpu(p).oper[0]^.val in [1..3]) and
  5806. GetNextInstruction(p, hp1) and
  5807. MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  5808. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  5809. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  5810. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  5811. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  5812. begin
  5813. TransferUsedRegs(TmpUsedRegs);
  5814. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5815. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  5816. begin
  5817. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  5818. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  5819. RemoveCurrentP(p);
  5820. Result:=true;
  5821. end;
  5822. end;
  5823. end;
  5824. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  5825. var
  5826. CurrentRef: TReference;
  5827. FullReg: TRegister;
  5828. hp1, hp2: tai;
  5829. begin
  5830. Result := False;
  5831. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  5832. Exit;
  5833. { We assume you've checked if the operand is actually a reference by
  5834. this point. If it isn't, you'll most likely get an access violation }
  5835. CurrentRef := first_mov.oper[1]^.ref^;
  5836. { Memory must be aligned }
  5837. if (CurrentRef.offset mod 4) <> 0 then
  5838. Exit;
  5839. Inc(CurrentRef.offset);
  5840. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5841. if MatchOperand(second_mov.oper[0]^, 0) and
  5842. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  5843. GetNextInstruction(second_mov, hp1) and
  5844. (hp1.typ = ait_instruction) and
  5845. (taicpu(hp1).opcode = A_MOV) and
  5846. MatchOpType(taicpu(hp1), top_const, top_ref) and
  5847. (taicpu(hp1).oper[0]^.val = 0) then
  5848. begin
  5849. Inc(CurrentRef.offset);
  5850. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  5851. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  5852. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  5853. begin
  5854. case taicpu(hp1).opsize of
  5855. S_B:
  5856. if GetNextInstruction(hp1, hp2) and
  5857. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  5858. MatchOpType(taicpu(hp2), top_const, top_ref) and
  5859. (taicpu(hp2).oper[0]^.val = 0) then
  5860. begin
  5861. Inc(CurrentRef.offset);
  5862. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5863. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  5864. (taicpu(hp2).opsize = S_B) then
  5865. begin
  5866. RemoveInstruction(hp1);
  5867. RemoveInstruction(hp2);
  5868. first_mov.opsize := S_L;
  5869. if first_mov.oper[0]^.typ = top_reg then
  5870. begin
  5871. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  5872. { Reuse second_mov as a MOVZX instruction }
  5873. second_mov.opcode := A_MOVZX;
  5874. second_mov.opsize := S_BL;
  5875. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5876. second_mov.loadreg(1, FullReg);
  5877. first_mov.oper[0]^.reg := FullReg;
  5878. asml.Remove(second_mov);
  5879. asml.InsertBefore(second_mov, first_mov);
  5880. end
  5881. else
  5882. { It's a value }
  5883. begin
  5884. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  5885. RemoveInstruction(second_mov);
  5886. end;
  5887. Result := True;
  5888. Exit;
  5889. end;
  5890. end;
  5891. S_W:
  5892. begin
  5893. RemoveInstruction(hp1);
  5894. first_mov.opsize := S_L;
  5895. if first_mov.oper[0]^.typ = top_reg then
  5896. begin
  5897. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  5898. { Reuse second_mov as a MOVZX instruction }
  5899. second_mov.opcode := A_MOVZX;
  5900. second_mov.opsize := S_BL;
  5901. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5902. second_mov.loadreg(1, FullReg);
  5903. first_mov.oper[0]^.reg := FullReg;
  5904. asml.Remove(second_mov);
  5905. asml.InsertBefore(second_mov, first_mov);
  5906. end
  5907. else
  5908. { It's a value }
  5909. begin
  5910. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  5911. RemoveInstruction(second_mov);
  5912. end;
  5913. Result := True;
  5914. Exit;
  5915. end;
  5916. else
  5917. ;
  5918. end;
  5919. end;
  5920. end;
  5921. end;
  5922. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  5923. { returns true if a "continue" should be done after this optimization }
  5924. var
  5925. hp1, hp2: tai;
  5926. begin
  5927. Result := false;
  5928. if MatchOpType(taicpu(p),top_ref) and
  5929. GetNextInstruction(p, hp1) and
  5930. (hp1.typ = ait_instruction) and
  5931. (((taicpu(hp1).opcode = A_FLD) and
  5932. (taicpu(p).opcode = A_FSTP)) or
  5933. ((taicpu(p).opcode = A_FISTP) and
  5934. (taicpu(hp1).opcode = A_FILD))) and
  5935. MatchOpType(taicpu(hp1),top_ref) and
  5936. (taicpu(hp1).opsize = taicpu(p).opsize) and
  5937. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  5938. begin
  5939. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  5940. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  5941. GetNextInstruction(hp1, hp2) and
  5942. (hp2.typ = ait_instruction) and
  5943. IsExitCode(hp2) and
  5944. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  5945. not(assigned(current_procinfo.procdef.funcretsym) and
  5946. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  5947. (taicpu(p).oper[0]^.ref^.index = NR_NO) then
  5948. begin
  5949. RemoveInstruction(hp1);
  5950. RemoveCurrentP(p, hp2);
  5951. RemoveLastDeallocForFuncRes(p);
  5952. Result := true;
  5953. end
  5954. else
  5955. { we can do this only in fast math mode as fstp is rounding ...
  5956. ... still disabled as it breaks the compiler and/or rtl }
  5957. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  5958. { ... or if another fstp equal to the first one follows }
  5959. (GetNextInstruction(hp1,hp2) and
  5960. (hp2.typ = ait_instruction) and
  5961. (taicpu(p).opcode=taicpu(hp2).opcode) and
  5962. (taicpu(p).opsize=taicpu(hp2).opsize))
  5963. ) and
  5964. { fst can't store an extended/comp value }
  5965. (taicpu(p).opsize <> S_FX) and
  5966. (taicpu(p).opsize <> S_IQ) then
  5967. begin
  5968. if (taicpu(p).opcode = A_FSTP) then
  5969. taicpu(p).opcode := A_FST
  5970. else
  5971. taicpu(p).opcode := A_FIST;
  5972. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  5973. RemoveInstruction(hp1);
  5974. end;
  5975. end;
  5976. end;
  5977. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  5978. var
  5979. hp1, hp2: tai;
  5980. begin
  5981. result:=false;
  5982. if MatchOpType(taicpu(p),top_reg) and
  5983. GetNextInstruction(p, hp1) and
  5984. (hp1.typ = Ait_Instruction) and
  5985. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5986. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  5987. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  5988. { change to
  5989. fld reg fxxx reg,st
  5990. fxxxp st, st1 (hp1)
  5991. Remark: non commutative operations must be reversed!
  5992. }
  5993. begin
  5994. case taicpu(hp1).opcode Of
  5995. A_FMULP,A_FADDP,
  5996. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  5997. begin
  5998. case taicpu(hp1).opcode Of
  5999. A_FADDP: taicpu(hp1).opcode := A_FADD;
  6000. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  6001. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  6002. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  6003. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  6004. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  6005. else
  6006. internalerror(2019050534);
  6007. end;
  6008. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  6009. taicpu(hp1).oper[1]^.reg := NR_ST;
  6010. RemoveCurrentP(p, hp1);
  6011. Result:=true;
  6012. exit;
  6013. end;
  6014. else
  6015. ;
  6016. end;
  6017. end
  6018. else
  6019. if MatchOpType(taicpu(p),top_ref) and
  6020. GetNextInstruction(p, hp2) and
  6021. (hp2.typ = Ait_Instruction) and
  6022. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  6023. (taicpu(p).opsize in [S_FS, S_FL]) and
  6024. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  6025. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  6026. if GetLastInstruction(p, hp1) and
  6027. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  6028. MatchOpType(taicpu(hp1),top_ref) and
  6029. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6030. if ((taicpu(hp2).opcode = A_FMULP) or
  6031. (taicpu(hp2).opcode = A_FADDP)) then
  6032. { change to
  6033. fld/fst mem1 (hp1) fld/fst mem1
  6034. fld mem1 (p) fadd/
  6035. faddp/ fmul st, st
  6036. fmulp st, st1 (hp2) }
  6037. begin
  6038. RemoveCurrentP(p, hp1);
  6039. if (taicpu(hp2).opcode = A_FADDP) then
  6040. taicpu(hp2).opcode := A_FADD
  6041. else
  6042. taicpu(hp2).opcode := A_FMUL;
  6043. taicpu(hp2).oper[1]^.reg := NR_ST;
  6044. end
  6045. else
  6046. { change to
  6047. fld/fst mem1 (hp1) fld/fst mem1
  6048. fld mem1 (p) fld st}
  6049. begin
  6050. taicpu(p).changeopsize(S_FL);
  6051. taicpu(p).loadreg(0,NR_ST);
  6052. end
  6053. else
  6054. begin
  6055. case taicpu(hp2).opcode Of
  6056. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6057. { change to
  6058. fld/fst mem1 (hp1) fld/fst mem1
  6059. fld mem2 (p) fxxx mem2
  6060. fxxxp st, st1 (hp2) }
  6061. begin
  6062. case taicpu(hp2).opcode Of
  6063. A_FADDP: taicpu(p).opcode := A_FADD;
  6064. A_FMULP: taicpu(p).opcode := A_FMUL;
  6065. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  6066. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  6067. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  6068. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  6069. else
  6070. internalerror(2019050533);
  6071. end;
  6072. RemoveInstruction(hp2);
  6073. end
  6074. else
  6075. ;
  6076. end
  6077. end
  6078. end;
  6079. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  6080. begin
  6081. Result := condition_in(cond1, cond2) or
  6082. { Not strictly subsets due to the actual flags checked, but because we're
  6083. comparing integers, E is a subset of AE and GE and their aliases }
  6084. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  6085. end;
  6086. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  6087. var
  6088. v: TCGInt;
  6089. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  6090. FirstMatch: Boolean;
  6091. NewReg: TRegister;
  6092. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  6093. begin
  6094. Result:=false;
  6095. { All these optimisations need a next instruction }
  6096. if not GetNextInstruction(p, hp1) then
  6097. Exit;
  6098. { Search for:
  6099. cmp ###,###
  6100. j(c1) @lbl1
  6101. ...
  6102. @lbl:
  6103. cmp ###.### (same comparison as above)
  6104. j(c2) @lbl2
  6105. If c1 is a subset of c2, change to:
  6106. cmp ###,###
  6107. j(c2) @lbl2
  6108. (@lbl1 may become a dead label as a result)
  6109. }
  6110. { Also handle cases where there are multiple jumps in a row }
  6111. p_jump := hp1;
  6112. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  6113. begin
  6114. if IsJumpToLabel(taicpu(p_jump)) then
  6115. begin
  6116. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  6117. p_label := nil;
  6118. if Assigned(JumpLabel) then
  6119. p_label := getlabelwithsym(JumpLabel);
  6120. if Assigned(p_label) and
  6121. GetNextInstruction(p_label, p_dist) and
  6122. MatchInstruction(p_dist, A_CMP, []) and
  6123. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  6124. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  6125. GetNextInstruction(p_dist, hp1_dist) and
  6126. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  6127. begin
  6128. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  6129. if JumpLabel = JumpLabel_dist then
  6130. { This is an infinite loop }
  6131. Exit;
  6132. { Best optimisation when the first condition is a subset (or equal) of the second }
  6133. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  6134. begin
  6135. { Any registers used here will already be allocated }
  6136. if Assigned(JumpLabel_dist) then
  6137. JumpLabel_dist.IncRefs;
  6138. if Assigned(JumpLabel) then
  6139. JumpLabel.DecRefs;
  6140. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  6141. taicpu(p_jump).condition := taicpu(hp1_dist).condition;
  6142. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  6143. Result := True;
  6144. { Don't exit yet. Since p and p_jump haven't actually been
  6145. removed, we can check for more on this iteration }
  6146. end
  6147. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  6148. GetNextInstruction(hp1_dist, hp1_label) and
  6149. SkipAligns(hp1_label, hp1_label) and
  6150. (hp1_label.typ = ait_label) then
  6151. begin
  6152. JumpLabel_far := tai_label(hp1_label).labsym;
  6153. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  6154. { This is an infinite loop }
  6155. Exit;
  6156. if Assigned(JumpLabel_far) then
  6157. begin
  6158. { In this situation, if the first jump branches, the second one will never,
  6159. branch so change the destination label to after the second jump }
  6160. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  6161. if Assigned(JumpLabel) then
  6162. JumpLabel.DecRefs;
  6163. JumpLabel_far.IncRefs;
  6164. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  6165. Result := True;
  6166. { Don't exit yet. Since p and p_jump haven't actually been
  6167. removed, we can check for more on this iteration }
  6168. Continue;
  6169. end;
  6170. end;
  6171. end;
  6172. end;
  6173. { Search for:
  6174. cmp ###,###
  6175. j(c1) @lbl1
  6176. cmp ###,### (same as first)
  6177. Remove second cmp
  6178. }
  6179. if GetNextInstruction(p_jump, hp2) and
  6180. (
  6181. (
  6182. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  6183. (
  6184. (
  6185. MatchOpType(taicpu(p), top_const, top_reg) and
  6186. MatchOpType(taicpu(hp2), top_const, top_reg) and
  6187. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  6188. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6189. ) or (
  6190. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  6191. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  6192. )
  6193. )
  6194. ) or (
  6195. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  6196. MatchOperand(taicpu(p).oper[0]^, 0) and
  6197. (taicpu(p).oper[1]^.typ = top_reg) and
  6198. MatchInstruction(hp2, A_TEST, []) and
  6199. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6200. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  6201. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6202. )
  6203. ) then
  6204. begin
  6205. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  6206. RemoveInstruction(hp2);
  6207. Result := True;
  6208. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  6209. end;
  6210. GetNextInstruction(p_jump, p_jump);
  6211. end;
  6212. {
  6213. Try to optimise the following:
  6214. cmp $x,### ($x and $y can be registers or constants)
  6215. je @lbl1 (only reference)
  6216. cmp $y,### (### are identical)
  6217. @Lbl:
  6218. sete %reg1
  6219. Change to:
  6220. cmp $x,###
  6221. sete %reg2 (allocate new %reg2)
  6222. cmp $y,###
  6223. sete %reg1
  6224. orb %reg2,%reg1
  6225. (dealloc %reg2)
  6226. This adds an instruction (so don't perform under -Os), but it removes
  6227. a conditional branch.
  6228. }
  6229. if not (cs_opt_size in current_settings.optimizerswitches) and
  6230. (
  6231. (hp1 = p_jump) or
  6232. GetNextInstruction(p, hp1)
  6233. ) and
  6234. MatchInstruction(hp1, A_Jcc, []) and
  6235. IsJumpToLabel(taicpu(hp1)) and
  6236. (taicpu(hp1).condition in [C_E, C_Z]) and
  6237. GetNextInstruction(hp1, hp2) and
  6238. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  6239. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  6240. { The first operand of CMP instructions can only be a register or
  6241. immediate anyway, so no need to check }
  6242. GetNextInstruction(hp2, p_label) and
  6243. (
  6244. (p_label.typ = ait_label) or
  6245. (
  6246. { Sometimes there's a zero-distance jump before the label, so deal with it here
  6247. to potentially cut down on the iterations of Pass 1 }
  6248. MatchInstruction(p_label, A_Jcc, []) and
  6249. IsJumpToLabel(taicpu(p_label)) and
  6250. { Use p_dist to hold the jump briefly }
  6251. SetAndTest(p_label, p_dist) and
  6252. GetNextInstruction(p_dist, p_label) and
  6253. (p_label.typ = ait_label) and
  6254. (tai_label(p_label).labsym.getrefs >= 2) and
  6255. (JumpTargetOp(taicpu(p_dist))^.ref^.symbol = tai_label(p_label).labsym) and
  6256. { We might as well collapse the jump now }
  6257. CollapseZeroDistJump(p_dist, tai_label(p_label).labsym)
  6258. )
  6259. ) and
  6260. (tai_label(p_label).labsym.getrefs = 1) and
  6261. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  6262. GetNextInstruction(p_label, p_dist) and
  6263. MatchInstruction(p_dist, A_SETcc, []) and
  6264. (taicpu(p_dist).condition in [C_E, C_Z]) and
  6265. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  6266. { Get the instruction after the SETcc instruction so we can
  6267. allocate a new register over the entire range }
  6268. GetNextInstruction(p_dist, hp1_dist) then
  6269. begin
  6270. TransferUsedRegs(TmpUsedRegs);
  6271. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6272. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6273. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  6274. // UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  6275. { RegUsedAfterInstruction modifies TmpUsedRegs }
  6276. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  6277. begin
  6278. { Register can appear in p if it's not used afterwards, so only
  6279. allocate between hp1 and hp1_dist }
  6280. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, p_dist);
  6281. if NewReg <> NR_NO then
  6282. begin
  6283. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  6284. { Change the jump instruction into a SETcc instruction }
  6285. taicpu(hp1).opcode := A_SETcc;
  6286. taicpu(hp1).opsize := S_B;
  6287. taicpu(hp1).loadreg(0, NewReg);
  6288. { This is now a dead label }
  6289. tai_label(p_label).labsym.decrefs;
  6290. { Prefer adding before the next instruction so the FLAGS
  6291. register is deallocated first }
  6292. hp2 := taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg);
  6293. AsmL.InsertBefore(
  6294. hp2,
  6295. hp1_dist
  6296. );
  6297. { Make sure the new register is in use over the new instruction
  6298. (long-winded, but things work best when the FLAGS register
  6299. is not allocated here) }
  6300. AllocRegBetween(NewReg, p_dist, hp2, TmpUsedRegs);
  6301. Result := True;
  6302. { Don't exit yet, as p wasn't changed and hp1, while
  6303. modified, is still intact and might be optimised by the
  6304. SETcc optimisation below }
  6305. end;
  6306. end;
  6307. end;
  6308. if taicpu(p).oper[0]^.typ = top_const then
  6309. begin
  6310. if (taicpu(p).oper[0]^.val = 0) and
  6311. (taicpu(p).oper[1]^.typ = top_reg) and
  6312. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  6313. begin
  6314. hp2 := p;
  6315. FirstMatch := True;
  6316. { When dealing with "cmp $0,%reg", only ZF and SF contain
  6317. anything meaningful once it's converted to "test %reg,%reg";
  6318. additionally, some jumps will always (or never) branch, so
  6319. evaluate every jump immediately following the
  6320. comparison, optimising the conditions if possible.
  6321. Similarly with SETcc... those that are always set to 0 or 1
  6322. are changed to MOV instructions }
  6323. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  6324. (
  6325. GetNextInstruction(hp2, hp1) and
  6326. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  6327. ) do
  6328. begin
  6329. FirstMatch := False;
  6330. case taicpu(hp1).condition of
  6331. C_B, C_C, C_NAE, C_O:
  6332. { For B/NAE:
  6333. Will never branch since an unsigned integer can never be below zero
  6334. For C/O:
  6335. Result cannot overflow because 0 is being subtracted
  6336. }
  6337. begin
  6338. if taicpu(hp1).opcode = A_Jcc then
  6339. begin
  6340. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  6341. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  6342. RemoveInstruction(hp1);
  6343. { Since hp1 was deleted, hp2 must not be updated }
  6344. Continue;
  6345. end
  6346. else
  6347. begin
  6348. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  6349. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  6350. taicpu(hp1).opcode := A_MOV;
  6351. taicpu(hp1).ops := 2;
  6352. taicpu(hp1).condition := C_None;
  6353. taicpu(hp1).opsize := S_B;
  6354. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6355. taicpu(hp1).loadconst(0, 0);
  6356. end;
  6357. end;
  6358. C_BE, C_NA:
  6359. begin
  6360. { Will only branch if equal to zero }
  6361. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  6362. taicpu(hp1).condition := C_E;
  6363. end;
  6364. C_A, C_NBE:
  6365. begin
  6366. { Will only branch if not equal to zero }
  6367. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  6368. taicpu(hp1).condition := C_NE;
  6369. end;
  6370. C_AE, C_NB, C_NC, C_NO:
  6371. begin
  6372. { Will always branch }
  6373. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  6374. if taicpu(hp1).opcode = A_Jcc then
  6375. begin
  6376. MakeUnconditional(taicpu(hp1));
  6377. { Any jumps/set that follow will now be dead code }
  6378. RemoveDeadCodeAfterJump(taicpu(hp1));
  6379. Break;
  6380. end
  6381. else
  6382. begin
  6383. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  6384. taicpu(hp1).opcode := A_MOV;
  6385. taicpu(hp1).ops := 2;
  6386. taicpu(hp1).condition := C_None;
  6387. taicpu(hp1).opsize := S_B;
  6388. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6389. taicpu(hp1).loadconst(0, 1);
  6390. end;
  6391. end;
  6392. C_None:
  6393. InternalError(2020012201);
  6394. C_P, C_PE, C_NP, C_PO:
  6395. { We can't handle parity checks and they should never be generated
  6396. after a general-purpose CMP (it's used in some floating-point
  6397. comparisons that don't use CMP) }
  6398. InternalError(2020012202);
  6399. else
  6400. { Zero/Equality, Sign, their complements and all of the
  6401. signed comparisons do not need to be converted };
  6402. end;
  6403. hp2 := hp1;
  6404. end;
  6405. { Convert the instruction to a TEST }
  6406. taicpu(p).opcode := A_TEST;
  6407. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6408. Result := True;
  6409. Exit;
  6410. end
  6411. else if (taicpu(p).oper[0]^.val = 1) and
  6412. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6413. (taicpu(hp1).condition in [C_L, C_NGE]) then
  6414. begin
  6415. { Convert; To:
  6416. cmp $1,r/m cmp $0,r/m
  6417. jl @lbl jle @lbl
  6418. }
  6419. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  6420. taicpu(p).oper[0]^.val := 0;
  6421. taicpu(hp1).condition := C_LE;
  6422. { If the instruction is now "cmp $0,%reg", convert it to a
  6423. TEST (and effectively do the work of the "cmp $0,%reg" in
  6424. the block above)
  6425. If it's a reference, we can get away with not setting
  6426. Result to True because he haven't evaluated the jump
  6427. in this pass yet.
  6428. }
  6429. if (taicpu(p).oper[1]^.typ = top_reg) then
  6430. begin
  6431. taicpu(p).opcode := A_TEST;
  6432. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6433. Result := True;
  6434. end;
  6435. Exit;
  6436. end
  6437. else if (taicpu(p).oper[1]^.typ = top_reg)
  6438. {$ifdef x86_64}
  6439. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  6440. {$endif x86_64}
  6441. then
  6442. begin
  6443. { cmp register,$8000 neg register
  6444. je target --> jo target
  6445. .... only if register is deallocated before jump.}
  6446. case Taicpu(p).opsize of
  6447. S_B: v:=$80;
  6448. S_W: v:=$8000;
  6449. S_L: v:=qword($80000000);
  6450. else
  6451. internalerror(2013112905);
  6452. end;
  6453. if (taicpu(p).oper[0]^.val=v) and
  6454. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6455. (Taicpu(hp1).condition in [C_E,C_NE]) then
  6456. begin
  6457. TransferUsedRegs(TmpUsedRegs);
  6458. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  6459. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  6460. begin
  6461. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  6462. Taicpu(p).opcode:=A_NEG;
  6463. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  6464. Taicpu(p).clearop(1);
  6465. Taicpu(p).ops:=1;
  6466. if Taicpu(hp1).condition=C_E then
  6467. Taicpu(hp1).condition:=C_O
  6468. else
  6469. Taicpu(hp1).condition:=C_NO;
  6470. Result:=true;
  6471. exit;
  6472. end;
  6473. end;
  6474. end;
  6475. end;
  6476. if TrySwapMovCmp(p, hp1) then
  6477. begin
  6478. Result := True;
  6479. Exit;
  6480. end;
  6481. end;
  6482. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  6483. var
  6484. hp1: tai;
  6485. begin
  6486. {
  6487. remove the second (v)pxor from
  6488. pxor reg,reg
  6489. ...
  6490. pxor reg,reg
  6491. }
  6492. Result:=false;
  6493. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6494. MatchOpType(taicpu(p),top_reg,top_reg) and
  6495. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6496. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6497. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6498. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  6499. begin
  6500. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  6501. RemoveInstruction(hp1);
  6502. Result:=true;
  6503. Exit;
  6504. end
  6505. {
  6506. replace
  6507. pxor reg1,reg1
  6508. movapd/s reg1,reg2
  6509. dealloc reg1
  6510. by
  6511. pxor reg2,reg2
  6512. }
  6513. else if GetNextInstruction(p,hp1) and
  6514. { we mix single and double opperations here because we assume that the compiler
  6515. generates vmovapd only after double operations and vmovaps only after single operations }
  6516. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  6517. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6518. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  6519. (taicpu(p).oper[0]^.typ=top_reg) then
  6520. begin
  6521. TransferUsedRegs(TmpUsedRegs);
  6522. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6523. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  6524. begin
  6525. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  6526. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  6527. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  6528. RemoveInstruction(hp1);
  6529. result:=true;
  6530. end;
  6531. end;
  6532. end;
  6533. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  6534. var
  6535. hp1: tai;
  6536. begin
  6537. {
  6538. remove the second (v)pxor from
  6539. (v)pxor reg,reg
  6540. ...
  6541. (v)pxor reg,reg
  6542. }
  6543. Result:=false;
  6544. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  6545. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  6546. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6547. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6548. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6549. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  6550. begin
  6551. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2PXor done',hp1);
  6552. RemoveInstruction(hp1);
  6553. Result:=true;
  6554. Exit;
  6555. end
  6556. else
  6557. Result:=OptPass1VOP(p);
  6558. end;
  6559. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  6560. var
  6561. hp1 : tai;
  6562. begin
  6563. result:=false;
  6564. { replace
  6565. IMul const,%mreg1,%mreg2
  6566. Mov %reg2,%mreg3
  6567. dealloc %mreg3
  6568. by
  6569. Imul const,%mreg1,%mreg23
  6570. }
  6571. if (taicpu(p).ops=3) and
  6572. GetNextInstruction(p,hp1) and
  6573. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6574. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6575. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6576. begin
  6577. TransferUsedRegs(TmpUsedRegs);
  6578. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6579. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6580. begin
  6581. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6582. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  6583. RemoveInstruction(hp1);
  6584. result:=true;
  6585. end;
  6586. end;
  6587. end;
  6588. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  6589. var
  6590. hp1 : tai;
  6591. begin
  6592. result:=false;
  6593. { replace
  6594. IMul %reg0,%reg1,%reg2
  6595. Mov %reg2,%reg3
  6596. dealloc %reg2
  6597. by
  6598. Imul %reg0,%reg1,%reg3
  6599. }
  6600. if GetNextInstruction(p,hp1) and
  6601. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6602. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6603. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6604. begin
  6605. TransferUsedRegs(TmpUsedRegs);
  6606. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6607. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6608. begin
  6609. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6610. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  6611. RemoveInstruction(hp1);
  6612. result:=true;
  6613. end;
  6614. end;
  6615. end;
  6616. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  6617. var
  6618. hp1: tai;
  6619. begin
  6620. Result:=false;
  6621. { get rid of
  6622. (v)cvtss2sd reg0,<reg1,>reg2
  6623. (v)cvtss2sd reg2,<reg2,>reg0
  6624. }
  6625. if GetNextInstruction(p,hp1) and
  6626. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  6627. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  6628. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  6629. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  6630. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  6631. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  6632. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  6633. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  6634. )
  6635. ) then
  6636. begin
  6637. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  6638. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  6639. begin
  6640. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  6641. RemoveCurrentP(p);
  6642. RemoveInstruction(hp1);
  6643. end
  6644. else
  6645. begin
  6646. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  6647. if taicpu(hp1).opcode=A_CVTSD2SS then
  6648. begin
  6649. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  6650. taicpu(p).opcode:=A_MOVAPS;
  6651. end
  6652. else
  6653. begin
  6654. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  6655. taicpu(p).opcode:=A_VMOVAPS;
  6656. end;
  6657. taicpu(p).ops:=2;
  6658. RemoveInstruction(hp1);
  6659. end;
  6660. Result:=true;
  6661. Exit;
  6662. end;
  6663. end;
  6664. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  6665. var
  6666. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  6667. ThisReg: TRegister;
  6668. begin
  6669. Result := False;
  6670. if not GetNextInstruction(p,hp1) then
  6671. Exit;
  6672. {
  6673. convert
  6674. j<c> .L1
  6675. mov 1,reg
  6676. jmp .L2
  6677. .L1
  6678. mov 0,reg
  6679. .L2
  6680. into
  6681. mov 0,reg
  6682. set<not(c)> reg
  6683. take care of alignment and that the mov 0,reg is not converted into a xor as this
  6684. would destroy the flag contents
  6685. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  6686. executed at the same time as a previous comparison.
  6687. set<not(c)> reg
  6688. movzx reg, reg
  6689. }
  6690. if MatchInstruction(hp1,A_MOV,[]) and
  6691. (taicpu(hp1).oper[0]^.typ = top_const) and
  6692. (
  6693. (
  6694. (taicpu(hp1).oper[1]^.typ = top_reg)
  6695. {$ifdef i386}
  6696. { Under i386, ESI, EDI, EBP and ESP
  6697. don't have an 8-bit representation }
  6698. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6699. {$endif i386}
  6700. ) or (
  6701. {$ifdef i386}
  6702. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  6703. {$endif i386}
  6704. (taicpu(hp1).opsize = S_B)
  6705. )
  6706. ) and
  6707. GetNextInstruction(hp1,hp2) and
  6708. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  6709. GetNextInstruction(hp2,hp3) and
  6710. SkipAligns(hp3, hp3) and
  6711. (hp3.typ=ait_label) and
  6712. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  6713. GetNextInstruction(hp3,hp4) and
  6714. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  6715. (taicpu(hp4).oper[0]^.typ = top_const) and
  6716. (
  6717. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  6718. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  6719. ) and
  6720. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  6721. GetNextInstruction(hp4,hp5) and
  6722. SkipAligns(hp5, hp5) and
  6723. (hp5.typ=ait_label) and
  6724. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  6725. begin
  6726. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6727. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6728. tai_label(hp3).labsym.DecRefs;
  6729. { If this isn't the only reference to the middle label, we can
  6730. still make a saving - only that the first jump and everything
  6731. that follows will remain. }
  6732. if (tai_label(hp3).labsym.getrefs = 0) then
  6733. begin
  6734. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6735. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  6736. else
  6737. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  6738. { remove jump, first label and second MOV (also catching any aligns) }
  6739. repeat
  6740. if not GetNextInstruction(hp2, hp3) then
  6741. InternalError(2021040810);
  6742. RemoveInstruction(hp2);
  6743. hp2 := hp3;
  6744. until hp2 = hp5;
  6745. { Don't decrement reference count before the removal loop
  6746. above, otherwise GetNextInstruction won't stop on the
  6747. the label }
  6748. tai_label(hp5).labsym.DecRefs;
  6749. end
  6750. else
  6751. begin
  6752. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6753. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  6754. else
  6755. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  6756. end;
  6757. taicpu(p).opcode:=A_SETcc;
  6758. taicpu(p).opsize:=S_B;
  6759. taicpu(p).is_jmp:=False;
  6760. if taicpu(hp1).opsize=S_B then
  6761. begin
  6762. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  6763. if taicpu(hp1).oper[1]^.typ = top_reg then
  6764. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  6765. RemoveInstruction(hp1);
  6766. end
  6767. else
  6768. begin
  6769. { Will be a register because the size can't be S_B otherwise }
  6770. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  6771. taicpu(p).loadreg(0, ThisReg);
  6772. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  6773. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  6774. begin
  6775. case taicpu(hp1).opsize of
  6776. S_W:
  6777. taicpu(hp1).opsize := S_BW;
  6778. S_L:
  6779. taicpu(hp1).opsize := S_BL;
  6780. {$ifdef x86_64}
  6781. S_Q:
  6782. begin
  6783. taicpu(hp1).opsize := S_BL;
  6784. { Change the destination register to 32-bit }
  6785. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  6786. end;
  6787. {$endif x86_64}
  6788. else
  6789. InternalError(2021040820);
  6790. end;
  6791. taicpu(hp1).opcode := A_MOVZX;
  6792. taicpu(hp1).loadreg(0, ThisReg);
  6793. end
  6794. else
  6795. begin
  6796. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  6797. { hp1 is already a MOV instruction with the correct register }
  6798. taicpu(hp1).loadconst(0, 0);
  6799. { Inserting it right before p will guarantee that the flags are also tracked }
  6800. asml.Remove(hp1);
  6801. asml.InsertBefore(hp1, p);
  6802. end;
  6803. end;
  6804. Result:=true;
  6805. exit;
  6806. end
  6807. else if (hp1.typ = ait_label) then
  6808. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  6809. end;
  6810. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  6811. var
  6812. hp1, hp2, hp3: tai;
  6813. SourceRef, TargetRef: TReference;
  6814. CurrentReg: TRegister;
  6815. begin
  6816. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  6817. if not UseAVX then
  6818. InternalError(2021100501);
  6819. Result := False;
  6820. { Look for the following to simplify:
  6821. vmovdqa/u x(mem1), %xmmreg
  6822. vmovdqa/u %xmmreg, y(mem2)
  6823. vmovdqa/u x+16(mem1), %xmmreg
  6824. vmovdqa/u %xmmreg, y+16(mem2)
  6825. Change to:
  6826. vmovdqa/u x(mem1), %ymmreg
  6827. vmovdqa/u %ymmreg, y(mem2)
  6828. vpxor %ymmreg, %ymmreg, %ymmreg
  6829. ( The VPXOR instruction is to zero the upper half, thus removing the
  6830. need to call the potentially expensive VZEROUPPER instruction. Other
  6831. peephole optimisations can remove VPXOR if it's unnecessary )
  6832. }
  6833. TransferUsedRegs(TmpUsedRegs);
  6834. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6835. { NOTE: In the optimisations below, if the references dictate that an
  6836. aligned move is possible (i.e. VMOVDQA), the existing instructions
  6837. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  6838. if (taicpu(p).opsize = S_XMM) and
  6839. MatchOpType(taicpu(p), top_ref, top_reg) and
  6840. GetNextInstruction(p, hp1) and
  6841. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6842. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  6843. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6844. begin
  6845. SourceRef := taicpu(p).oper[0]^.ref^;
  6846. TargetRef := taicpu(hp1).oper[1]^.ref^;
  6847. if GetNextInstruction(hp1, hp2) and
  6848. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6849. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  6850. begin
  6851. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  6852. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6853. Inc(SourceRef.offset, 16);
  6854. { Reuse the register in the first block move }
  6855. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  6856. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  6857. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  6858. begin
  6859. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6860. Inc(TargetRef.offset, 16);
  6861. if GetNextInstruction(hp2, hp3) and
  6862. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6863. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6864. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6865. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6866. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6867. begin
  6868. { Update the register tracking to the new size }
  6869. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  6870. { Remember that the offsets are 16 ahead }
  6871. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6872. if not (
  6873. ((SourceRef.offset mod 32) = 16) and
  6874. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6875. ) then
  6876. taicpu(p).opcode := A_VMOVDQU;
  6877. taicpu(p).opsize := S_YMM;
  6878. taicpu(p).oper[1]^.reg := CurrentReg;
  6879. if not (
  6880. ((TargetRef.offset mod 32) = 16) and
  6881. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6882. ) then
  6883. taicpu(hp1).opcode := A_VMOVDQU;
  6884. taicpu(hp1).opsize := S_YMM;
  6885. taicpu(hp1).oper[0]^.reg := CurrentReg;
  6886. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  6887. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6888. if (pi_uses_ymm in current_procinfo.flags) then
  6889. RemoveInstruction(hp2)
  6890. else
  6891. begin
  6892. taicpu(hp2).opcode := A_VPXOR;
  6893. taicpu(hp2).opsize := S_YMM;
  6894. taicpu(hp2).loadreg(0, CurrentReg);
  6895. taicpu(hp2).loadreg(1, CurrentReg);
  6896. taicpu(hp2).loadreg(2, CurrentReg);
  6897. taicpu(hp2).ops := 3;
  6898. end;
  6899. RemoveInstruction(hp3);
  6900. Result := True;
  6901. Exit;
  6902. end;
  6903. end
  6904. else
  6905. begin
  6906. { See if the next references are 16 less rather than 16 greater }
  6907. Dec(SourceRef.offset, 32); { -16 the other way }
  6908. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  6909. begin
  6910. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6911. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  6912. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  6913. GetNextInstruction(hp2, hp3) and
  6914. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  6915. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6916. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6917. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6918. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6919. begin
  6920. { Update the register tracking to the new size }
  6921. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  6922. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  6923. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6924. if not(
  6925. ((SourceRef.offset mod 32) = 0) and
  6926. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6927. ) then
  6928. taicpu(hp2).opcode := A_VMOVDQU;
  6929. taicpu(hp2).opsize := S_YMM;
  6930. taicpu(hp2).oper[1]^.reg := CurrentReg;
  6931. if not (
  6932. ((TargetRef.offset mod 32) = 0) and
  6933. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6934. ) then
  6935. taicpu(hp3).opcode := A_VMOVDQU;
  6936. taicpu(hp3).opsize := S_YMM;
  6937. taicpu(hp3).oper[0]^.reg := CurrentReg;
  6938. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  6939. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6940. if (pi_uses_ymm in current_procinfo.flags) then
  6941. RemoveInstruction(hp1)
  6942. else
  6943. begin
  6944. taicpu(hp1).opcode := A_VPXOR;
  6945. taicpu(hp1).opsize := S_YMM;
  6946. taicpu(hp1).loadreg(0, CurrentReg);
  6947. taicpu(hp1).loadreg(1, CurrentReg);
  6948. taicpu(hp1).loadreg(2, CurrentReg);
  6949. taicpu(hp1).ops := 3;
  6950. Asml.Remove(hp1);
  6951. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  6952. end;
  6953. RemoveCurrentP(p, hp2);
  6954. Result := True;
  6955. Exit;
  6956. end;
  6957. end;
  6958. end;
  6959. end;
  6960. end;
  6961. end;
  6962. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  6963. var
  6964. hp2, hp3, first_assignment: tai;
  6965. IncCount, OperIdx: Integer;
  6966. OrigLabel: TAsmLabel;
  6967. begin
  6968. Count := 0;
  6969. Result := False;
  6970. first_assignment := nil;
  6971. if (LoopCount >= 20) then
  6972. begin
  6973. { Guard against infinite loops }
  6974. Exit;
  6975. end;
  6976. if (taicpu(p).oper[0]^.typ <> top_ref) or
  6977. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  6978. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  6979. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  6980. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  6981. Exit;
  6982. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  6983. {
  6984. change
  6985. jmp .L1
  6986. ...
  6987. .L1:
  6988. mov ##, ## ( multiple movs possible )
  6989. jmp/ret
  6990. into
  6991. mov ##, ##
  6992. jmp/ret
  6993. }
  6994. if not Assigned(hp1) then
  6995. begin
  6996. hp1 := GetLabelWithSym(OrigLabel);
  6997. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  6998. Exit;
  6999. end;
  7000. hp2 := hp1;
  7001. while Assigned(hp2) do
  7002. begin
  7003. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  7004. SkipLabels(hp2,hp2);
  7005. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  7006. Break;
  7007. case taicpu(hp2).opcode of
  7008. A_MOVSS:
  7009. begin
  7010. if taicpu(hp2).ops = 0 then
  7011. { Wrong MOVSS }
  7012. Break;
  7013. Inc(Count);
  7014. if Count >= 5 then
  7015. { Too many to be worthwhile }
  7016. Break;
  7017. GetNextInstruction(hp2, hp2);
  7018. Continue;
  7019. end;
  7020. A_MOV,
  7021. A_MOVD,
  7022. A_MOVQ,
  7023. A_MOVSX,
  7024. {$ifdef x86_64}
  7025. A_MOVSXD,
  7026. {$endif x86_64}
  7027. A_MOVZX,
  7028. A_MOVAPS,
  7029. A_MOVUPS,
  7030. A_MOVSD,
  7031. A_MOVAPD,
  7032. A_MOVUPD,
  7033. A_MOVDQA,
  7034. A_MOVDQU,
  7035. A_VMOVSS,
  7036. A_VMOVAPS,
  7037. A_VMOVUPS,
  7038. A_VMOVSD,
  7039. A_VMOVAPD,
  7040. A_VMOVUPD,
  7041. A_VMOVDQA,
  7042. A_VMOVDQU:
  7043. begin
  7044. Inc(Count);
  7045. if Count >= 5 then
  7046. { Too many to be worthwhile }
  7047. Break;
  7048. GetNextInstruction(hp2, hp2);
  7049. Continue;
  7050. end;
  7051. A_JMP:
  7052. begin
  7053. { Guard against infinite loops }
  7054. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  7055. Exit;
  7056. { Analyse this jump first in case it also duplicates assignments }
  7057. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  7058. begin
  7059. { Something did change! }
  7060. Result := True;
  7061. Inc(Count, IncCount);
  7062. if Count >= 5 then
  7063. begin
  7064. { Too many to be worthwhile }
  7065. Exit;
  7066. end;
  7067. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  7068. Break;
  7069. end;
  7070. Result := True;
  7071. Break;
  7072. end;
  7073. A_RET:
  7074. begin
  7075. Result := True;
  7076. Break;
  7077. end;
  7078. else
  7079. Break;
  7080. end;
  7081. end;
  7082. if Result then
  7083. begin
  7084. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  7085. if Count = 0 then
  7086. begin
  7087. Result := False;
  7088. Exit;
  7089. end;
  7090. hp3 := p;
  7091. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  7092. while True do
  7093. begin
  7094. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  7095. SkipLabels(hp1,hp1);
  7096. if (hp1.typ <> ait_instruction) then
  7097. InternalError(2021040720);
  7098. case taicpu(hp1).opcode of
  7099. A_JMP:
  7100. begin
  7101. { Change the original jump to the new destination }
  7102. OrigLabel.decrefs;
  7103. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  7104. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  7105. { Set p to the first duplicated assignment so it can get optimised if needs be }
  7106. if not Assigned(first_assignment) then
  7107. InternalError(2021040810)
  7108. else
  7109. p := first_assignment;
  7110. Exit;
  7111. end;
  7112. A_RET:
  7113. begin
  7114. { Now change the jump into a RET instruction }
  7115. ConvertJumpToRET(p, hp1);
  7116. { Set p to the first duplicated assignment so it can get optimised if needs be }
  7117. if not Assigned(first_assignment) then
  7118. InternalError(2021040811)
  7119. else
  7120. p := first_assignment;
  7121. Exit;
  7122. end;
  7123. else
  7124. begin
  7125. { Duplicate the MOV instruction }
  7126. hp3:=tai(hp1.getcopy);
  7127. if first_assignment = nil then
  7128. first_assignment := hp3;
  7129. asml.InsertBefore(hp3, p);
  7130. { Make sure the compiler knows about any final registers written here }
  7131. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  7132. with taicpu(hp3).oper[OperIdx]^ do
  7133. begin
  7134. case typ of
  7135. top_ref:
  7136. begin
  7137. if (ref^.base <> NR_NO) and
  7138. (getsupreg(ref^.base) <> RS_ESP) and
  7139. (getsupreg(ref^.base) <> RS_EBP)
  7140. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  7141. then
  7142. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  7143. if (ref^.index <> NR_NO) and
  7144. (getsupreg(ref^.index) <> RS_ESP) and
  7145. (getsupreg(ref^.index) <> RS_EBP)
  7146. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  7147. (ref^.index <> ref^.base) then
  7148. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  7149. end;
  7150. top_reg:
  7151. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  7152. else
  7153. ;
  7154. end;
  7155. end;
  7156. end;
  7157. end;
  7158. if not GetNextInstruction(hp1, hp1) then
  7159. { Should have dropped out earlier }
  7160. InternalError(2021040710);
  7161. end;
  7162. end;
  7163. end;
  7164. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  7165. var
  7166. hp2: tai;
  7167. X: Integer;
  7168. const
  7169. WriteOp: array[0..3] of set of TInsChange = (
  7170. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  7171. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  7172. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  7173. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  7174. RegWriteFlags: array[0..7] of set of TInsChange = (
  7175. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  7176. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  7177. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  7178. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  7179. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  7180. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  7181. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  7182. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  7183. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  7184. begin
  7185. { If we have something like:
  7186. cmp ###,%reg1
  7187. mov 0,%reg2
  7188. And no modified registers are shared, move the instruction to before
  7189. the comparison as this means it can be optimised without worrying
  7190. about the FLAGS register. (CMP/MOV is generated by
  7191. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  7192. As long as the second instruction doesn't use the flags or one of the
  7193. registers used by CMP or TEST (also check any references that use the
  7194. registers), then it can be moved prior to the comparison.
  7195. }
  7196. Result := False;
  7197. if (hp1.typ <> ait_instruction) or
  7198. taicpu(hp1).is_jmp or
  7199. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  7200. Exit;
  7201. { NOP is a pipeline fence, likely marking the beginning of the function
  7202. epilogue, so drop out. Similarly, drop out if POP or RET are
  7203. encountered }
  7204. if MatchInstruction(hp1, A_NOP, A_POP, []) then
  7205. Exit;
  7206. if (taicpu(hp1).opcode = A_MOVSS) and
  7207. (taicpu(hp1).ops = 0) then
  7208. { Wrong MOVSS }
  7209. Exit;
  7210. { Check for writes to specific registers first }
  7211. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  7212. for X := 0 to 7 do
  7213. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  7214. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  7215. Exit;
  7216. for X := 0 to taicpu(hp1).ops - 1 do
  7217. begin
  7218. { Check to see if this operand writes to something }
  7219. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  7220. { And matches something in the CMP/TEST instruction }
  7221. (
  7222. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  7223. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  7224. (
  7225. { If it's a register, make sure the register written to doesn't
  7226. appear in the cmp instruction as part of a reference }
  7227. (taicpu(hp1).oper[X]^.typ = top_reg) and
  7228. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  7229. )
  7230. ) then
  7231. Exit;
  7232. end;
  7233. { The instruction can be safely moved }
  7234. asml.Remove(hp1);
  7235. { Try to insert before the FLAGS register is allocated, so "mov $0,%reg"
  7236. can be optimised into "xor %reg,%reg" later }
  7237. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  7238. asml.InsertBefore(hp1, hp2)
  7239. else
  7240. { Note, if p.Previous is nil (even if it should logically never be the
  7241. case), FindRegAllocBackward immediately exits with False and so we
  7242. safely land here (we can't just pass p because FindRegAllocBackward
  7243. immediately exits on an instruction). [Kit] }
  7244. asml.InsertBefore(hp1, p);
  7245. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  7246. for X := 0 to taicpu(hp1).ops - 1 do
  7247. case taicpu(hp1).oper[X]^.typ of
  7248. top_reg:
  7249. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  7250. top_ref:
  7251. begin
  7252. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  7253. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  7254. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  7255. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  7256. end;
  7257. else
  7258. ;
  7259. end;
  7260. if taicpu(hp1).opcode = A_LEA then
  7261. { The flags will be overwritten by the CMP/TEST instruction }
  7262. ConvertLEA(taicpu(hp1));
  7263. Result := True;
  7264. end;
  7265. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  7266. function IsXCHGAcceptable: Boolean; inline;
  7267. begin
  7268. { Always accept if optimising for size }
  7269. Result := (cs_opt_size in current_settings.optimizerswitches) or
  7270. (
  7271. {$ifdef x86_64}
  7272. { XCHG takes 3 cycles on AMD Athlon64 }
  7273. (current_settings.optimizecputype >= cpu_core_i)
  7274. {$else x86_64}
  7275. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  7276. than 3, so it becomes a saving compared to three MOVs with two of
  7277. them able to execute simultaneously. [Kit] }
  7278. (current_settings.optimizecputype >= cpu_PentiumM)
  7279. {$endif x86_64}
  7280. );
  7281. end;
  7282. var
  7283. NewRef: TReference;
  7284. hp1, hp2, hp3, hp4: Tai;
  7285. {$ifndef x86_64}
  7286. OperIdx: Integer;
  7287. {$endif x86_64}
  7288. NewInstr : Taicpu;
  7289. NewAligh : Tai_align;
  7290. DestLabel: TAsmLabel;
  7291. function TryMovArith2Lea(InputInstr: tai): Boolean;
  7292. var
  7293. NextInstr: tai;
  7294. begin
  7295. Result := False;
  7296. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  7297. if not GetNextInstruction(InputInstr, NextInstr) or
  7298. (
  7299. { The FLAGS register isn't always tracked properly, so do not
  7300. perform this optimisation if a conditional statement follows }
  7301. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  7302. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  7303. ) then
  7304. begin
  7305. reference_reset(NewRef, 1, []);
  7306. NewRef.base := taicpu(p).oper[0]^.reg;
  7307. NewRef.scalefactor := 1;
  7308. if taicpu(InputInstr).opcode = A_ADD then
  7309. begin
  7310. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  7311. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  7312. end
  7313. else
  7314. begin
  7315. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  7316. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  7317. end;
  7318. taicpu(p).opcode := A_LEA;
  7319. taicpu(p).loadref(0, NewRef);
  7320. RemoveInstruction(InputInstr);
  7321. Result := True;
  7322. end;
  7323. end;
  7324. begin
  7325. Result:=false;
  7326. { This optimisation adds an instruction, so only do it for speed }
  7327. if not (cs_opt_size in current_settings.optimizerswitches) and
  7328. MatchOpType(taicpu(p), top_const, top_reg) and
  7329. (taicpu(p).oper[0]^.val = 0) then
  7330. begin
  7331. { To avoid compiler warning }
  7332. DestLabel := nil;
  7333. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  7334. InternalError(2021040750);
  7335. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  7336. Exit;
  7337. case hp1.typ of
  7338. ait_label:
  7339. begin
  7340. { Change:
  7341. mov $0,%reg mov $0,%reg
  7342. @Lbl1: @Lbl1:
  7343. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  7344. je @Lbl2 jne @Lbl2
  7345. To: To:
  7346. mov $0,%reg mov $0,%reg
  7347. jmp @Lbl2 jmp @Lbl3
  7348. (align) (align)
  7349. @Lbl1: @Lbl1:
  7350. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  7351. je @Lbl2 je @Lbl2
  7352. @Lbl3: <-- Only if label exists
  7353. (Not if it's optimised for size)
  7354. }
  7355. if not GetNextInstruction(hp1, hp2) then
  7356. Exit;
  7357. if not (cs_opt_size in current_settings.optimizerswitches) and
  7358. (hp2.typ = ait_instruction) and
  7359. (
  7360. { Register sizes must exactly match }
  7361. (
  7362. (taicpu(hp2).opcode = A_CMP) and
  7363. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  7364. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7365. ) or (
  7366. (taicpu(hp2).opcode = A_TEST) and
  7367. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7368. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7369. )
  7370. ) and GetNextInstruction(hp2, hp3) and
  7371. (hp3.typ = ait_instruction) and
  7372. (taicpu(hp3).opcode = A_JCC) and
  7373. (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
  7374. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  7375. begin
  7376. { Check condition of jump }
  7377. { Always true? }
  7378. if condition_in(C_E, taicpu(hp3).condition) then
  7379. begin
  7380. { Copy label symbol and obtain matching label entry for the
  7381. conditional jump, as this will be our destination}
  7382. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  7383. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  7384. Result := True;
  7385. end
  7386. { Always false? }
  7387. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  7388. begin
  7389. { This is only worth it if there's a jump to take }
  7390. case hp2.typ of
  7391. ait_instruction:
  7392. begin
  7393. if taicpu(hp2).opcode = A_JMP then
  7394. begin
  7395. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7396. { An unconditional jump follows the conditional jump which will always be false,
  7397. so use this jump's destination for the new jump }
  7398. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  7399. Result := True;
  7400. end
  7401. else if taicpu(hp2).opcode = A_JCC then
  7402. begin
  7403. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7404. if condition_in(C_E, taicpu(hp2).condition) then
  7405. begin
  7406. { A second conditional jump follows the conditional jump which will always be false,
  7407. while the second jump is always True, so use this jump's destination for the new jump }
  7408. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  7409. Result := True;
  7410. end;
  7411. { Don't risk it if the jump isn't always true (Result remains False) }
  7412. end;
  7413. end;
  7414. else
  7415. { If anything else don't optimise };
  7416. end;
  7417. end;
  7418. if Result then
  7419. begin
  7420. { Just so we have something to insert as a paremeter}
  7421. reference_reset(NewRef, 1, []);
  7422. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  7423. { Now actually load the correct parameter }
  7424. NewInstr.loadsymbol(0, DestLabel, 0);
  7425. { Get instruction before original label (may not be p under -O3) }
  7426. if not GetLastInstruction(hp1, hp2) then
  7427. { Shouldn't fail here }
  7428. InternalError(2021040701);
  7429. DestLabel.increfs;
  7430. AsmL.InsertAfter(NewInstr, hp2);
  7431. { Add new alignment field }
  7432. (* AsmL.InsertAfter(
  7433. cai_align.create_max(
  7434. current_settings.alignment.jumpalign,
  7435. current_settings.alignment.jumpalignskipmax
  7436. ),
  7437. NewInstr
  7438. ); *)
  7439. end;
  7440. Exit;
  7441. end;
  7442. end;
  7443. else
  7444. ;
  7445. end;
  7446. end;
  7447. if not GetNextInstruction(p, hp1) then
  7448. Exit;
  7449. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  7450. and DoMovCmpMemOpt(p, hp1, True) then
  7451. begin
  7452. Result := True;
  7453. Exit;
  7454. end
  7455. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  7456. begin
  7457. { Sometimes the MOVs that OptPass2JMP produces can be improved
  7458. further, but we can't just put this jump optimisation in pass 1
  7459. because it tends to perform worse when conditional jumps are
  7460. nearby (e.g. when converting CMOV instructions). [Kit] }
  7461. if OptPass2JMP(hp1) then
  7462. { call OptPass1MOV once to potentially merge any MOVs that were created }
  7463. Result := OptPass1MOV(p)
  7464. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  7465. returned True and the instruction is still a MOV, thus checking
  7466. the optimisations below }
  7467. { If OptPass2JMP returned False, no optimisations were done to
  7468. the jump and there are no further optimisations that can be done
  7469. to the MOV instruction on this pass }
  7470. end
  7471. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7472. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  7473. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  7474. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7475. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7476. begin
  7477. { Change:
  7478. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  7479. addl/q $x,%reg2 subl/q $x,%reg2
  7480. To:
  7481. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  7482. }
  7483. if (taicpu(hp1).oper[0]^.typ = top_const) and
  7484. { be lazy, checking separately for sub would be slightly better }
  7485. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  7486. begin
  7487. TransferUsedRegs(TmpUsedRegs);
  7488. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7489. if TryMovArith2Lea(hp1) then
  7490. begin
  7491. Result := True;
  7492. Exit;
  7493. end
  7494. end
  7495. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  7496. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  7497. { Same as above, but also adds or subtracts to %reg2 in between.
  7498. It's still valid as long as the flags aren't in use }
  7499. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  7500. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7501. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  7502. { be lazy, checking separately for sub would be slightly better }
  7503. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  7504. begin
  7505. TransferUsedRegs(TmpUsedRegs);
  7506. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7507. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7508. if TryMovArith2Lea(hp2) then
  7509. begin
  7510. Result := True;
  7511. Exit;
  7512. end;
  7513. end;
  7514. end
  7515. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7516. {$ifdef x86_64}
  7517. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  7518. {$else x86_64}
  7519. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  7520. {$endif x86_64}
  7521. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7522. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  7523. { mov reg1, reg2 mov reg1, reg2
  7524. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  7525. begin
  7526. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7527. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  7528. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  7529. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  7530. TransferUsedRegs(TmpUsedRegs);
  7531. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7532. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  7533. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  7534. then
  7535. begin
  7536. RemoveCurrentP(p, hp1);
  7537. Result:=true;
  7538. end;
  7539. exit;
  7540. end
  7541. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7542. IsXCHGAcceptable and
  7543. { XCHG doesn't support 8-byte registers }
  7544. (taicpu(p).opsize <> S_B) and
  7545. MatchInstruction(hp1, A_MOV, []) and
  7546. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7547. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  7548. GetNextInstruction(hp1, hp2) and
  7549. MatchInstruction(hp2, A_MOV, []) and
  7550. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  7551. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7552. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  7553. begin
  7554. { mov %reg1,%reg2
  7555. mov %reg3,%reg1 -> xchg %reg3,%reg1
  7556. mov %reg2,%reg3
  7557. (%reg2 not used afterwards)
  7558. Note that xchg takes 3 cycles to execute, and generally mov's take
  7559. only one cycle apiece, but the first two mov's can be executed in
  7560. parallel, only taking 2 cycles overall. Older processors should
  7561. therefore only optimise for size. [Kit]
  7562. }
  7563. TransferUsedRegs(TmpUsedRegs);
  7564. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7565. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7566. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  7567. begin
  7568. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  7569. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  7570. taicpu(hp1).opcode := A_XCHG;
  7571. RemoveCurrentP(p, hp1);
  7572. RemoveInstruction(hp2);
  7573. Result := True;
  7574. Exit;
  7575. end;
  7576. end
  7577. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7578. MatchInstruction(hp1, A_SAR, []) then
  7579. begin
  7580. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  7581. begin
  7582. { the use of %edx also covers the opsize being S_L }
  7583. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  7584. begin
  7585. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  7586. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  7587. (taicpu(p).oper[1]^.reg = NR_EDX) then
  7588. begin
  7589. { Change:
  7590. movl %eax,%edx
  7591. sarl $31,%edx
  7592. To:
  7593. cltd
  7594. }
  7595. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  7596. RemoveInstruction(hp1);
  7597. taicpu(p).opcode := A_CDQ;
  7598. taicpu(p).opsize := S_NO;
  7599. taicpu(p).clearop(1);
  7600. taicpu(p).clearop(0);
  7601. taicpu(p).ops:=0;
  7602. Result := True;
  7603. end
  7604. else if (cs_opt_size in current_settings.optimizerswitches) and
  7605. (taicpu(p).oper[0]^.reg = NR_EDX) and
  7606. (taicpu(p).oper[1]^.reg = NR_EAX) then
  7607. begin
  7608. { Change:
  7609. movl %edx,%eax
  7610. sarl $31,%edx
  7611. To:
  7612. movl %edx,%eax
  7613. cltd
  7614. Note that this creates a dependency between the two instructions,
  7615. so only perform if optimising for size.
  7616. }
  7617. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  7618. taicpu(hp1).opcode := A_CDQ;
  7619. taicpu(hp1).opsize := S_NO;
  7620. taicpu(hp1).clearop(1);
  7621. taicpu(hp1).clearop(0);
  7622. taicpu(hp1).ops:=0;
  7623. end;
  7624. {$ifndef x86_64}
  7625. end
  7626. { Don't bother if CMOV is supported, because a more optimal
  7627. sequence would have been generated for the Abs() intrinsic }
  7628. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  7629. { the use of %eax also covers the opsize being S_L }
  7630. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  7631. (taicpu(p).oper[0]^.reg = NR_EAX) and
  7632. (taicpu(p).oper[1]^.reg = NR_EDX) and
  7633. GetNextInstruction(hp1, hp2) and
  7634. MatchInstruction(hp2, A_XOR, [S_L]) and
  7635. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  7636. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  7637. GetNextInstruction(hp2, hp3) and
  7638. MatchInstruction(hp3, A_SUB, [S_L]) and
  7639. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  7640. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  7641. begin
  7642. { Change:
  7643. movl %eax,%edx
  7644. sarl $31,%eax
  7645. xorl %eax,%edx
  7646. subl %eax,%edx
  7647. (Instruction that uses %edx)
  7648. (%eax deallocated)
  7649. (%edx deallocated)
  7650. To:
  7651. cltd
  7652. xorl %edx,%eax <-- Note the registers have swapped
  7653. subl %edx,%eax
  7654. (Instruction that uses %eax) <-- %eax rather than %edx
  7655. }
  7656. TransferUsedRegs(TmpUsedRegs);
  7657. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7658. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7659. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7660. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  7661. begin
  7662. if GetNextInstruction(hp3, hp4) and
  7663. not RegModifiedByInstruction(NR_EDX, hp4) and
  7664. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  7665. begin
  7666. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  7667. taicpu(p).opcode := A_CDQ;
  7668. taicpu(p).clearop(1);
  7669. taicpu(p).clearop(0);
  7670. taicpu(p).ops:=0;
  7671. RemoveInstruction(hp1);
  7672. taicpu(hp2).loadreg(0, NR_EDX);
  7673. taicpu(hp2).loadreg(1, NR_EAX);
  7674. taicpu(hp3).loadreg(0, NR_EDX);
  7675. taicpu(hp3).loadreg(1, NR_EAX);
  7676. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  7677. { Convert references in the following instruction (hp4) from %edx to %eax }
  7678. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  7679. with taicpu(hp4).oper[OperIdx]^ do
  7680. case typ of
  7681. top_reg:
  7682. if getsupreg(reg) = RS_EDX then
  7683. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7684. top_ref:
  7685. begin
  7686. if getsupreg(reg) = RS_EDX then
  7687. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7688. if getsupreg(reg) = RS_EDX then
  7689. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7690. end;
  7691. else
  7692. ;
  7693. end;
  7694. end;
  7695. end;
  7696. {$else x86_64}
  7697. end;
  7698. end
  7699. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  7700. { the use of %rdx also covers the opsize being S_Q }
  7701. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  7702. begin
  7703. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  7704. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  7705. (taicpu(p).oper[1]^.reg = NR_RDX) then
  7706. begin
  7707. { Change:
  7708. movq %rax,%rdx
  7709. sarq $63,%rdx
  7710. To:
  7711. cqto
  7712. }
  7713. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  7714. RemoveInstruction(hp1);
  7715. taicpu(p).opcode := A_CQO;
  7716. taicpu(p).opsize := S_NO;
  7717. taicpu(p).clearop(1);
  7718. taicpu(p).clearop(0);
  7719. taicpu(p).ops:=0;
  7720. Result := True;
  7721. end
  7722. else if (cs_opt_size in current_settings.optimizerswitches) and
  7723. (taicpu(p).oper[0]^.reg = NR_RDX) and
  7724. (taicpu(p).oper[1]^.reg = NR_RAX) then
  7725. begin
  7726. { Change:
  7727. movq %rdx,%rax
  7728. sarq $63,%rdx
  7729. To:
  7730. movq %rdx,%rax
  7731. cqto
  7732. Note that this creates a dependency between the two instructions,
  7733. so only perform if optimising for size.
  7734. }
  7735. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  7736. taicpu(hp1).opcode := A_CQO;
  7737. taicpu(hp1).opsize := S_NO;
  7738. taicpu(hp1).clearop(1);
  7739. taicpu(hp1).clearop(0);
  7740. taicpu(hp1).ops:=0;
  7741. {$endif x86_64}
  7742. end;
  7743. end;
  7744. end
  7745. else if MatchInstruction(hp1, A_MOV, []) and
  7746. (taicpu(hp1).oper[1]^.typ = top_reg) then
  7747. { Though "GetNextInstruction" could be factored out, along with
  7748. the instructions that depend on hp2, it is an expensive call that
  7749. should be delayed for as long as possible, hence we do cheaper
  7750. checks first that are likely to be False. [Kit] }
  7751. begin
  7752. if (
  7753. (
  7754. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  7755. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  7756. (
  7757. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7758. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  7759. )
  7760. ) or
  7761. (
  7762. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  7763. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  7764. (
  7765. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7766. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  7767. )
  7768. )
  7769. ) and
  7770. GetNextInstruction(hp1, hp2) and
  7771. MatchInstruction(hp2, A_SAR, []) and
  7772. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  7773. begin
  7774. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  7775. begin
  7776. { Change:
  7777. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  7778. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  7779. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  7780. To:
  7781. movl r/m,%eax <- Note the change in register
  7782. cltd
  7783. }
  7784. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  7785. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  7786. taicpu(p).loadreg(1, NR_EAX);
  7787. taicpu(hp1).opcode := A_CDQ;
  7788. taicpu(hp1).clearop(1);
  7789. taicpu(hp1).clearop(0);
  7790. taicpu(hp1).ops:=0;
  7791. RemoveInstruction(hp2);
  7792. (*
  7793. {$ifdef x86_64}
  7794. end
  7795. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  7796. { This code sequence does not get generated - however it might become useful
  7797. if and when 128-bit signed integer types make an appearance, so the code
  7798. is kept here for when it is eventually needed. [Kit] }
  7799. (
  7800. (
  7801. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  7802. (
  7803. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7804. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  7805. )
  7806. ) or
  7807. (
  7808. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  7809. (
  7810. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7811. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  7812. )
  7813. )
  7814. ) and
  7815. GetNextInstruction(hp1, hp2) and
  7816. MatchInstruction(hp2, A_SAR, [S_Q]) and
  7817. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  7818. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  7819. begin
  7820. { Change:
  7821. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  7822. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  7823. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  7824. To:
  7825. movq r/m,%rax <- Note the change in register
  7826. cqto
  7827. }
  7828. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  7829. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  7830. taicpu(p).loadreg(1, NR_RAX);
  7831. taicpu(hp1).opcode := A_CQO;
  7832. taicpu(hp1).clearop(1);
  7833. taicpu(hp1).clearop(0);
  7834. taicpu(hp1).ops:=0;
  7835. RemoveInstruction(hp2);
  7836. {$endif x86_64}
  7837. *)
  7838. end;
  7839. end;
  7840. {$ifdef x86_64}
  7841. end
  7842. else if (taicpu(p).opsize = S_L) and
  7843. (taicpu(p).oper[1]^.typ = top_reg) and
  7844. (
  7845. MatchInstruction(hp1, A_MOV,[]) and
  7846. (taicpu(hp1).opsize = S_L) and
  7847. (taicpu(hp1).oper[1]^.typ = top_reg)
  7848. ) and (
  7849. GetNextInstruction(hp1, hp2) and
  7850. (tai(hp2).typ=ait_instruction) and
  7851. (taicpu(hp2).opsize = S_Q) and
  7852. (
  7853. (
  7854. MatchInstruction(hp2, A_ADD,[]) and
  7855. (taicpu(hp2).opsize = S_Q) and
  7856. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7857. (
  7858. (
  7859. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7860. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7861. ) or (
  7862. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7863. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7864. )
  7865. )
  7866. ) or (
  7867. MatchInstruction(hp2, A_LEA,[]) and
  7868. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  7869. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  7870. (
  7871. (
  7872. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7873. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7874. ) or (
  7875. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7876. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  7877. )
  7878. ) and (
  7879. (
  7880. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7881. ) or (
  7882. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7883. )
  7884. )
  7885. )
  7886. )
  7887. ) and (
  7888. GetNextInstruction(hp2, hp3) and
  7889. MatchInstruction(hp3, A_SHR,[]) and
  7890. (taicpu(hp3).opsize = S_Q) and
  7891. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7892. (taicpu(hp3).oper[0]^.val = 1) and
  7893. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  7894. ) then
  7895. begin
  7896. { Change movl x, reg1d movl x, reg1d
  7897. movl y, reg2d movl y, reg2d
  7898. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  7899. shrq $1, reg1q shrq $1, reg1q
  7900. ( reg1d and reg2d can be switched around in the first two instructions )
  7901. To movl x, reg1d
  7902. addl y, reg1d
  7903. rcrl $1, reg1d
  7904. This corresponds to the common expression (x + y) shr 1, where
  7905. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  7906. smaller code, but won't account for x + y causing an overflow). [Kit]
  7907. }
  7908. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  7909. { Change first MOV command to have the same register as the final output }
  7910. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  7911. else
  7912. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  7913. { Change second MOV command to an ADD command. This is easier than
  7914. converting the existing command because it means we don't have to
  7915. touch 'y', which might be a complicated reference, and also the
  7916. fact that the third command might either be ADD or LEA. [Kit] }
  7917. taicpu(hp1).opcode := A_ADD;
  7918. { Delete old ADD/LEA instruction }
  7919. RemoveInstruction(hp2);
  7920. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  7921. taicpu(hp3).opcode := A_RCR;
  7922. taicpu(hp3).changeopsize(S_L);
  7923. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  7924. {$endif x86_64}
  7925. end;
  7926. end;
  7927. {$push}
  7928. {$q-}{$r-}
  7929. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  7930. var
  7931. ThisReg: TRegister;
  7932. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  7933. TargetSubReg: TSubRegister;
  7934. hp1, hp2: tai;
  7935. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  7936. { Store list of found instructions so we don't have to call
  7937. GetNextInstructionUsingReg multiple times }
  7938. InstrList: array of taicpu;
  7939. InstrMax, Index: Integer;
  7940. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  7941. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  7942. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  7943. WorkingValue: TCgInt;
  7944. PreMessage: string;
  7945. { Data flow analysis }
  7946. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  7947. BitwiseOnly, OrXorUsed,
  7948. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  7949. function CheckOverflowConditions: Boolean;
  7950. begin
  7951. Result := True;
  7952. if (TestValSignedMax > SignedUpperLimit) then
  7953. UpperSignedOverflow := True;
  7954. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  7955. LowerSignedOverflow := True;
  7956. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  7957. LowerUnsignedOverflow := True;
  7958. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  7959. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  7960. begin
  7961. { Absolute overflow }
  7962. Result := False;
  7963. Exit;
  7964. end;
  7965. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  7966. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  7967. ShiftDownOverflow := True;
  7968. if (TestValMin < 0) or (TestValMax < 0) then
  7969. begin
  7970. LowerUnsignedOverflow := True;
  7971. UpperUnsignedOverflow := True;
  7972. end;
  7973. end;
  7974. function AdjustInitialLoadAndSize: Boolean;
  7975. begin
  7976. Result := False;
  7977. if not p_removed then
  7978. begin
  7979. if TargetSize = MinSize then
  7980. begin
  7981. { Convert the input MOVZX to a MOV }
  7982. if (taicpu(p).oper[0]^.typ = top_reg) and
  7983. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  7984. begin
  7985. { Or remove it completely! }
  7986. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  7987. RemoveCurrentP(p);
  7988. p_removed := True;
  7989. end
  7990. else
  7991. begin
  7992. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  7993. taicpu(p).opcode := A_MOV;
  7994. taicpu(p).oper[1]^.reg := ThisReg;
  7995. taicpu(p).opsize := TargetSize;
  7996. end;
  7997. Result := True;
  7998. end
  7999. else if TargetSize <> MaxSize then
  8000. begin
  8001. case MaxSize of
  8002. S_L:
  8003. if TargetSize = S_W then
  8004. begin
  8005. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  8006. taicpu(p).opsize := S_BW;
  8007. taicpu(p).oper[1]^.reg := ThisReg;
  8008. Result := True;
  8009. end
  8010. else
  8011. InternalError(2020112341);
  8012. S_W:
  8013. if TargetSize = S_L then
  8014. begin
  8015. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  8016. taicpu(p).opsize := S_BL;
  8017. taicpu(p).oper[1]^.reg := ThisReg;
  8018. Result := True;
  8019. end
  8020. else
  8021. InternalError(2020112342);
  8022. else
  8023. ;
  8024. end;
  8025. end
  8026. else if not hp1_removed and not RegInUse then
  8027. begin
  8028. { If we have something like:
  8029. movzbl (oper),%regd
  8030. add x, %regd
  8031. movzbl %regb, %regd
  8032. We can reduce the register size to the input of the final
  8033. movzbl instruction. Overflows won't have any effect.
  8034. }
  8035. if (taicpu(p).opsize in [S_BW, S_BL]) and
  8036. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  8037. begin
  8038. TargetSize := S_B;
  8039. setsubreg(ThisReg, R_SUBL);
  8040. Result := True;
  8041. end
  8042. else if (taicpu(p).opsize = S_WL) and
  8043. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  8044. begin
  8045. TargetSize := S_W;
  8046. setsubreg(ThisReg, R_SUBW);
  8047. Result := True;
  8048. end;
  8049. if Result then
  8050. begin
  8051. { Convert the input MOVZX to a MOV }
  8052. if (taicpu(p).oper[0]^.typ = top_reg) and
  8053. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  8054. begin
  8055. { Or remove it completely! }
  8056. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  8057. RemoveCurrentP(p);
  8058. p_removed := True;
  8059. end
  8060. else
  8061. begin
  8062. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  8063. taicpu(p).opcode := A_MOV;
  8064. taicpu(p).oper[1]^.reg := ThisReg;
  8065. taicpu(p).opsize := TargetSize;
  8066. end;
  8067. end;
  8068. end;
  8069. end;
  8070. end;
  8071. procedure AdjustFinalLoad;
  8072. begin
  8073. if not LowerUnsignedOverflow then
  8074. begin
  8075. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  8076. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  8077. begin
  8078. { Convert the output MOVZX to a MOV }
  8079. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8080. begin
  8081. { Or remove it completely! }
  8082. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  8083. { Be careful; if p = hp1 and p was also removed, p
  8084. will become a dangling pointer }
  8085. if p = hp1 then
  8086. begin
  8087. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  8088. p_removed := True;
  8089. end
  8090. else
  8091. RemoveInstruction(hp1);
  8092. hp1_removed := True;
  8093. end
  8094. else
  8095. begin
  8096. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  8097. taicpu(hp1).opcode := A_MOV;
  8098. taicpu(hp1).oper[0]^.reg := ThisReg;
  8099. taicpu(hp1).opsize := TargetSize;
  8100. end;
  8101. end
  8102. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  8103. begin
  8104. { Need to change the size of the output }
  8105. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  8106. taicpu(hp1).oper[0]^.reg := ThisReg;
  8107. taicpu(hp1).opsize := S_BL;
  8108. end;
  8109. end;
  8110. end;
  8111. function CompressInstructions: Boolean;
  8112. var
  8113. LocalIndex: Integer;
  8114. begin
  8115. Result := False;
  8116. { The objective here is to try to find a combination that
  8117. removes one of the MOV/Z instructions. }
  8118. if (
  8119. (taicpu(p).oper[0]^.typ <> top_reg) or
  8120. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  8121. ) and
  8122. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8123. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8124. begin
  8125. { Make a preference to remove the second MOVZX instruction }
  8126. case taicpu(hp1).opsize of
  8127. S_BL, S_WL:
  8128. begin
  8129. TargetSize := S_L;
  8130. TargetSubReg := R_SUBD;
  8131. end;
  8132. S_BW:
  8133. begin
  8134. TargetSize := S_W;
  8135. TargetSubReg := R_SUBW;
  8136. end;
  8137. else
  8138. InternalError(2020112302);
  8139. end;
  8140. end
  8141. else
  8142. begin
  8143. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  8144. begin
  8145. { Exceeded lower bound but not upper bound }
  8146. TargetSize := MaxSize;
  8147. end
  8148. else if not LowerUnsignedOverflow then
  8149. begin
  8150. { Size didn't exceed lower bound }
  8151. TargetSize := MinSize;
  8152. end
  8153. else
  8154. Exit;
  8155. end;
  8156. case TargetSize of
  8157. S_B:
  8158. TargetSubReg := R_SUBL;
  8159. S_W:
  8160. TargetSubReg := R_SUBW;
  8161. S_L:
  8162. TargetSubReg := R_SUBD;
  8163. else
  8164. InternalError(2020112350);
  8165. end;
  8166. { Update the register to its new size }
  8167. setsubreg(ThisReg, TargetSubReg);
  8168. RegInUse := False;
  8169. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8170. begin
  8171. { Check to see if the active register is used afterwards;
  8172. if not, we can change it and make a saving. }
  8173. TransferUsedRegs(TmpUsedRegs);
  8174. { The target register may be marked as in use to cross
  8175. a jump to a distant label, so exclude it }
  8176. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  8177. hp2 := p;
  8178. repeat
  8179. { Explicitly check for the excluded register (don't include the first
  8180. instruction as it may be reading from here }
  8181. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  8182. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  8183. begin
  8184. RegInUse := True;
  8185. Break;
  8186. end;
  8187. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  8188. if not GetNextInstruction(hp2, hp2) then
  8189. InternalError(2020112340);
  8190. until (hp2 = hp1);
  8191. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  8192. { We might still be able to get away with this }
  8193. RegInUse := not
  8194. (
  8195. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  8196. (hp2.typ = ait_instruction) and
  8197. (
  8198. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8199. instruction that doesn't actually contain ThisReg }
  8200. (cs_opt_level3 in current_settings.optimizerswitches) or
  8201. RegInInstruction(ThisReg, hp2)
  8202. ) and
  8203. RegLoadedWithNewValue(ThisReg, hp2)
  8204. );
  8205. if not RegInUse then
  8206. begin
  8207. { Force the register size to the same as this instruction so it can be removed}
  8208. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  8209. begin
  8210. TargetSize := S_L;
  8211. TargetSubReg := R_SUBD;
  8212. end
  8213. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  8214. begin
  8215. TargetSize := S_W;
  8216. TargetSubReg := R_SUBW;
  8217. end;
  8218. ThisReg := taicpu(hp1).oper[1]^.reg;
  8219. setsubreg(ThisReg, TargetSubReg);
  8220. RegChanged := True;
  8221. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  8222. TransferUsedRegs(TmpUsedRegs);
  8223. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  8224. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  8225. if p = hp1 then
  8226. begin
  8227. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  8228. p_removed := True;
  8229. end
  8230. else
  8231. RemoveInstruction(hp1);
  8232. hp1_removed := True;
  8233. { Instruction will become "mov %reg,%reg" }
  8234. if not p_removed and (taicpu(p).opcode = A_MOV) and
  8235. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  8236. begin
  8237. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  8238. RemoveCurrentP(p);
  8239. p_removed := True;
  8240. end
  8241. else
  8242. taicpu(p).oper[1]^.reg := ThisReg;
  8243. Result := True;
  8244. end
  8245. else
  8246. begin
  8247. if TargetSize <> MaxSize then
  8248. begin
  8249. { Since the register is in use, we have to force it to
  8250. MaxSize otherwise part of it may become undefined later on }
  8251. TargetSize := MaxSize;
  8252. case TargetSize of
  8253. S_B:
  8254. TargetSubReg := R_SUBL;
  8255. S_W:
  8256. TargetSubReg := R_SUBW;
  8257. S_L:
  8258. TargetSubReg := R_SUBD;
  8259. else
  8260. InternalError(2020112351);
  8261. end;
  8262. setsubreg(ThisReg, TargetSubReg);
  8263. end;
  8264. AdjustFinalLoad;
  8265. end;
  8266. end
  8267. else
  8268. AdjustFinalLoad;
  8269. Result := AdjustInitialLoadAndSize or Result;
  8270. { Now go through every instruction we found and change the
  8271. size. If TargetSize = MaxSize, then almost no changes are
  8272. needed and Result can remain False if it hasn't been set
  8273. yet.
  8274. If RegChanged is True, then the register requires changing
  8275. and so the point about TargetSize = MaxSize doesn't apply. }
  8276. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  8277. begin
  8278. for LocalIndex := 0 to InstrMax do
  8279. begin
  8280. { If p_removed is true, then the original MOV/Z was removed
  8281. and removing the AND instruction may not be safe if it
  8282. appears first }
  8283. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  8284. InternalError(2020112310);
  8285. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  8286. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  8287. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  8288. InstrList[LocalIndex].opsize := TargetSize;
  8289. end;
  8290. Result := True;
  8291. end;
  8292. end;
  8293. begin
  8294. Result := False;
  8295. p_removed := False;
  8296. hp1_removed := False;
  8297. ThisReg := taicpu(p).oper[1]^.reg;
  8298. { Check for:
  8299. movs/z ###,%ecx (or %cx or %rcx)
  8300. ...
  8301. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8302. (dealloc %ecx)
  8303. Change to:
  8304. mov ###,%cl (if ### = %cl, then remove completely)
  8305. ...
  8306. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8307. }
  8308. if (getsupreg(ThisReg) = RS_ECX) and
  8309. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  8310. (hp1.typ = ait_instruction) and
  8311. (
  8312. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8313. instruction that doesn't actually contain ECX }
  8314. (cs_opt_level3 in current_settings.optimizerswitches) or
  8315. RegInInstruction(NR_ECX, hp1) or
  8316. (
  8317. { It's common for the shift/rotate's read/write register to be
  8318. initialised in between, so under -O2 and under, search ahead
  8319. one more instruction
  8320. }
  8321. GetNextInstruction(hp1, hp1) and
  8322. (hp1.typ = ait_instruction) and
  8323. RegInInstruction(NR_ECX, hp1)
  8324. )
  8325. ) and
  8326. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  8327. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  8328. begin
  8329. TransferUsedRegs(TmpUsedRegs);
  8330. hp2 := p;
  8331. repeat
  8332. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8333. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  8334. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  8335. begin
  8336. case taicpu(p).opsize of
  8337. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8338. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  8339. begin
  8340. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  8341. RemoveCurrentP(p);
  8342. end
  8343. else
  8344. begin
  8345. taicpu(p).opcode := A_MOV;
  8346. taicpu(p).opsize := S_B;
  8347. taicpu(p).oper[1]^.reg := NR_CL;
  8348. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  8349. end;
  8350. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8351. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  8352. begin
  8353. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  8354. RemoveCurrentP(p);
  8355. end
  8356. else
  8357. begin
  8358. taicpu(p).opcode := A_MOV;
  8359. taicpu(p).opsize := S_W;
  8360. taicpu(p).oper[1]^.reg := NR_CX;
  8361. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  8362. end;
  8363. {$ifdef x86_64}
  8364. S_LQ:
  8365. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  8366. begin
  8367. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  8368. RemoveCurrentP(p);
  8369. end
  8370. else
  8371. begin
  8372. taicpu(p).opcode := A_MOV;
  8373. taicpu(p).opsize := S_L;
  8374. taicpu(p).oper[1]^.reg := NR_ECX;
  8375. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  8376. end;
  8377. {$endif x86_64}
  8378. else
  8379. InternalError(2021120401);
  8380. end;
  8381. Result := True;
  8382. Exit;
  8383. end;
  8384. end;
  8385. { This is anything but quick! }
  8386. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  8387. Exit;
  8388. SetLength(InstrList, 0);
  8389. InstrMax := -1;
  8390. case taicpu(p).opsize of
  8391. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8392. begin
  8393. {$if defined(i386) or defined(i8086)}
  8394. { If the target size is 8-bit, make sure we can actually encode it }
  8395. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  8396. Exit;
  8397. {$endif i386 or i8086}
  8398. LowerLimit := $FF;
  8399. SignedLowerLimit := $7F;
  8400. SignedLowerLimitBottom := -128;
  8401. MinSize := S_B;
  8402. if taicpu(p).opsize = S_BW then
  8403. begin
  8404. MaxSize := S_W;
  8405. UpperLimit := $FFFF;
  8406. SignedUpperLimit := $7FFF;
  8407. SignedUpperLimitBottom := -32768;
  8408. end
  8409. else
  8410. begin
  8411. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  8412. MaxSize := S_L;
  8413. UpperLimit := $FFFFFFFF;
  8414. SignedUpperLimit := $7FFFFFFF;
  8415. SignedUpperLimitBottom := -2147483648;
  8416. end;
  8417. end;
  8418. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8419. begin
  8420. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  8421. LowerLimit := $FFFF;
  8422. SignedLowerLimit := $7FFF;
  8423. SignedLowerLimitBottom := -32768;
  8424. UpperLimit := $FFFFFFFF;
  8425. SignedUpperLimit := $7FFFFFFF;
  8426. SignedUpperLimitBottom := -2147483648;
  8427. MinSize := S_W;
  8428. MaxSize := S_L;
  8429. end;
  8430. {$ifdef x86_64}
  8431. S_LQ:
  8432. begin
  8433. { Both the lower and upper limits are set to 32-bit. If a limit
  8434. is breached, then optimisation is impossible }
  8435. LowerLimit := $FFFFFFFF;
  8436. SignedLowerLimit := $7FFFFFFF;
  8437. SignedLowerLimitBottom := -2147483648;
  8438. UpperLimit := $FFFFFFFF;
  8439. SignedUpperLimit := $7FFFFFFF;
  8440. SignedUpperLimitBottom := -2147483648;
  8441. MinSize := S_L;
  8442. MaxSize := S_L;
  8443. end;
  8444. {$endif x86_64}
  8445. else
  8446. InternalError(2020112301);
  8447. end;
  8448. TestValMin := 0;
  8449. TestValMax := LowerLimit;
  8450. TestValSignedMax := SignedLowerLimit;
  8451. TryShiftDownLimit := LowerLimit;
  8452. TryShiftDown := S_NO;
  8453. ShiftDownOverflow := False;
  8454. RegChanged := False;
  8455. BitwiseOnly := True;
  8456. OrXorUsed := False;
  8457. UpperSignedOverflow := False;
  8458. LowerSignedOverflow := False;
  8459. UpperUnsignedOverflow := False;
  8460. LowerUnsignedOverflow := False;
  8461. hp1 := p;
  8462. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  8463. (hp1.typ = ait_instruction) and
  8464. (
  8465. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8466. instruction that doesn't actually contain ThisReg }
  8467. (cs_opt_level3 in current_settings.optimizerswitches) or
  8468. { This allows this Movx optimisation to work through the SETcc instructions
  8469. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  8470. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  8471. skip over these SETcc instructions). }
  8472. (taicpu(hp1).opcode = A_SETcc) or
  8473. RegInInstruction(ThisReg, hp1)
  8474. ) do
  8475. begin
  8476. case taicpu(hp1).opcode of
  8477. A_INC,A_DEC:
  8478. begin
  8479. { Has to be an exact match on the register }
  8480. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  8481. Break;
  8482. if taicpu(hp1).opcode = A_INC then
  8483. begin
  8484. Inc(TestValMin);
  8485. Inc(TestValMax);
  8486. Inc(TestValSignedMax);
  8487. end
  8488. else
  8489. begin
  8490. Dec(TestValMin);
  8491. Dec(TestValMax);
  8492. Dec(TestValSignedMax);
  8493. end;
  8494. end;
  8495. A_TEST, A_CMP:
  8496. begin
  8497. if (
  8498. { Too high a risk of non-linear behaviour that breaks DFA
  8499. here, unless it's cmp $0,%reg, which is equivalent to
  8500. test %reg,%reg }
  8501. OrXorUsed and
  8502. (taicpu(hp1).opcode = A_CMP) and
  8503. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  8504. ) or
  8505. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  8506. { Has to be an exact match on the register }
  8507. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8508. (
  8509. { Permit "test %reg,%reg" }
  8510. (taicpu(hp1).opcode = A_TEST) and
  8511. (taicpu(hp1).oper[0]^.typ = top_reg) and
  8512. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  8513. ) or
  8514. (taicpu(hp1).oper[0]^.typ <> top_const) or
  8515. { Make sure the comparison value is not smaller than the
  8516. smallest allowed signed value for the minimum size (e.g.
  8517. -128 for 8-bit) }
  8518. not (
  8519. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  8520. { Is it in the negative range? }
  8521. (
  8522. (taicpu(hp1).oper[0]^.val < 0) and
  8523. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  8524. )
  8525. ) then
  8526. Break;
  8527. { Check to see if the active register is used afterwards }
  8528. TransferUsedRegs(TmpUsedRegs);
  8529. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  8530. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  8531. begin
  8532. { Make sure the comparison or any previous instructions
  8533. hasn't pushed the test values outside of the range of
  8534. MinSize }
  8535. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  8536. begin
  8537. { Exceeded lower bound but not upper bound }
  8538. Exit;
  8539. end
  8540. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  8541. begin
  8542. { Size didn't exceed lower bound }
  8543. TargetSize := MinSize;
  8544. end
  8545. else
  8546. Break;
  8547. case TargetSize of
  8548. S_B:
  8549. TargetSubReg := R_SUBL;
  8550. S_W:
  8551. TargetSubReg := R_SUBW;
  8552. S_L:
  8553. TargetSubReg := R_SUBD;
  8554. else
  8555. InternalError(2021051002);
  8556. end;
  8557. if TargetSize <> MaxSize then
  8558. begin
  8559. { Update the register to its new size }
  8560. setsubreg(ThisReg, TargetSubReg);
  8561. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  8562. taicpu(hp1).oper[1]^.reg := ThisReg;
  8563. taicpu(hp1).opsize := TargetSize;
  8564. { Convert the input MOVZX to a MOV if necessary }
  8565. AdjustInitialLoadAndSize;
  8566. if (InstrMax >= 0) then
  8567. begin
  8568. for Index := 0 to InstrMax do
  8569. begin
  8570. { If p_removed is true, then the original MOV/Z was removed
  8571. and removing the AND instruction may not be safe if it
  8572. appears first }
  8573. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  8574. InternalError(2020112311);
  8575. if InstrList[Index].oper[0]^.typ = top_reg then
  8576. InstrList[Index].oper[0]^.reg := ThisReg;
  8577. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  8578. InstrList[Index].opsize := MinSize;
  8579. end;
  8580. end;
  8581. Result := True;
  8582. end;
  8583. Exit;
  8584. end;
  8585. end;
  8586. A_SETcc:
  8587. begin
  8588. { This allows this Movx optimisation to work through the SETcc instructions
  8589. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  8590. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  8591. skip over these SETcc instructions). }
  8592. if (cs_opt_level3 in current_settings.optimizerswitches) or
  8593. { Of course, break out if the current register is used }
  8594. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  8595. Break
  8596. else
  8597. { We must use Continue so the instruction doesn't get added
  8598. to InstrList }
  8599. Continue;
  8600. end;
  8601. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  8602. begin
  8603. if
  8604. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  8605. { Has to be an exact match on the register }
  8606. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  8607. (
  8608. (
  8609. (taicpu(hp1).oper[0]^.typ = top_const) and
  8610. (
  8611. (
  8612. (taicpu(hp1).opcode = A_SHL) and
  8613. (
  8614. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  8615. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  8616. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  8617. )
  8618. ) or (
  8619. (taicpu(hp1).opcode <> A_SHL) and
  8620. (
  8621. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8622. { Is it in the negative range? }
  8623. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  8624. )
  8625. )
  8626. )
  8627. ) or (
  8628. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  8629. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  8630. )
  8631. ) then
  8632. Break;
  8633. { Only process OR and XOR if there are only bitwise operations,
  8634. since otherwise they can too easily fool the data flow
  8635. analysis (they can cause non-linear behaviour) }
  8636. case taicpu(hp1).opcode of
  8637. A_ADD:
  8638. begin
  8639. if OrXorUsed then
  8640. { Too high a risk of non-linear behaviour that breaks DFA here }
  8641. Break
  8642. else
  8643. BitwiseOnly := False;
  8644. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8645. begin
  8646. TestValMin := TestValMin * 2;
  8647. TestValMax := TestValMax * 2;
  8648. TestValSignedMax := TestValSignedMax * 2;
  8649. end
  8650. else
  8651. begin
  8652. WorkingValue := taicpu(hp1).oper[0]^.val;
  8653. TestValMin := TestValMin + WorkingValue;
  8654. TestValMax := TestValMax + WorkingValue;
  8655. TestValSignedMax := TestValSignedMax + WorkingValue;
  8656. end;
  8657. end;
  8658. A_SUB:
  8659. begin
  8660. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8661. begin
  8662. TestValMin := 0;
  8663. TestValMax := 0;
  8664. TestValSignedMax := 0;
  8665. end
  8666. else
  8667. begin
  8668. if OrXorUsed then
  8669. { Too high a risk of non-linear behaviour that breaks DFA here }
  8670. Break
  8671. else
  8672. BitwiseOnly := False;
  8673. WorkingValue := taicpu(hp1).oper[0]^.val;
  8674. TestValMin := TestValMin - WorkingValue;
  8675. TestValMax := TestValMax - WorkingValue;
  8676. TestValSignedMax := TestValSignedMax - WorkingValue;
  8677. end;
  8678. end;
  8679. A_AND:
  8680. if (taicpu(hp1).oper[0]^.typ = top_const) then
  8681. begin
  8682. { we might be able to go smaller if AND appears first }
  8683. if InstrMax = -1 then
  8684. case MinSize of
  8685. S_B:
  8686. ;
  8687. S_W:
  8688. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8689. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8690. begin
  8691. TryShiftDown := S_B;
  8692. TryShiftDownLimit := $FF;
  8693. end;
  8694. S_L:
  8695. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8696. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8697. begin
  8698. TryShiftDown := S_B;
  8699. TryShiftDownLimit := $FF;
  8700. end
  8701. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  8702. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  8703. begin
  8704. TryShiftDown := S_W;
  8705. TryShiftDownLimit := $FFFF;
  8706. end;
  8707. else
  8708. InternalError(2020112320);
  8709. end;
  8710. WorkingValue := taicpu(hp1).oper[0]^.val;
  8711. TestValMin := TestValMin and WorkingValue;
  8712. TestValMax := TestValMax and WorkingValue;
  8713. TestValSignedMax := TestValSignedMax and WorkingValue;
  8714. end;
  8715. A_OR:
  8716. begin
  8717. if not BitwiseOnly then
  8718. Break;
  8719. OrXorUsed := True;
  8720. WorkingValue := taicpu(hp1).oper[0]^.val;
  8721. TestValMin := TestValMin or WorkingValue;
  8722. TestValMax := TestValMax or WorkingValue;
  8723. TestValSignedMax := TestValSignedMax or WorkingValue;
  8724. end;
  8725. A_XOR:
  8726. begin
  8727. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8728. begin
  8729. TestValMin := 0;
  8730. TestValMax := 0;
  8731. TestValSignedMax := 0;
  8732. end
  8733. else
  8734. begin
  8735. if not BitwiseOnly then
  8736. Break;
  8737. OrXorUsed := True;
  8738. WorkingValue := taicpu(hp1).oper[0]^.val;
  8739. TestValMin := TestValMin xor WorkingValue;
  8740. TestValMax := TestValMax xor WorkingValue;
  8741. TestValSignedMax := TestValSignedMax xor WorkingValue;
  8742. end;
  8743. end;
  8744. A_SHL:
  8745. begin
  8746. BitwiseOnly := False;
  8747. WorkingValue := taicpu(hp1).oper[0]^.val;
  8748. TestValMin := TestValMin shl WorkingValue;
  8749. TestValMax := TestValMax shl WorkingValue;
  8750. TestValSignedMax := TestValSignedMax shl WorkingValue;
  8751. end;
  8752. A_SHR,
  8753. { The first instruction was MOVZX, so the value won't be negative }
  8754. A_SAR:
  8755. begin
  8756. if InstrMax <> -1 then
  8757. BitwiseOnly := False
  8758. else
  8759. { we might be able to go smaller if SHR appears first }
  8760. case MinSize of
  8761. S_B:
  8762. ;
  8763. S_W:
  8764. if (taicpu(hp1).oper[0]^.val >= 8) then
  8765. begin
  8766. TryShiftDown := S_B;
  8767. TryShiftDownLimit := $FF;
  8768. TryShiftDownSignedLimit := $7F;
  8769. TryShiftDownSignedLimitLower := -128;
  8770. end;
  8771. S_L:
  8772. if (taicpu(hp1).oper[0]^.val >= 24) then
  8773. begin
  8774. TryShiftDown := S_B;
  8775. TryShiftDownLimit := $FF;
  8776. TryShiftDownSignedLimit := $7F;
  8777. TryShiftDownSignedLimitLower := -128;
  8778. end
  8779. else if (taicpu(hp1).oper[0]^.val >= 16) then
  8780. begin
  8781. TryShiftDown := S_W;
  8782. TryShiftDownLimit := $FFFF;
  8783. TryShiftDownSignedLimit := $7FFF;
  8784. TryShiftDownSignedLimitLower := -32768;
  8785. end;
  8786. else
  8787. InternalError(2020112321);
  8788. end;
  8789. WorkingValue := taicpu(hp1).oper[0]^.val;
  8790. if taicpu(hp1).opcode = A_SAR then
  8791. begin
  8792. TestValMin := SarInt64(TestValMin, WorkingValue);
  8793. TestValMax := SarInt64(TestValMax, WorkingValue);
  8794. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  8795. end
  8796. else
  8797. begin
  8798. TestValMin := TestValMin shr WorkingValue;
  8799. TestValMax := TestValMax shr WorkingValue;
  8800. TestValSignedMax := TestValSignedMax shr WorkingValue;
  8801. end;
  8802. end;
  8803. else
  8804. InternalError(2020112303);
  8805. end;
  8806. end;
  8807. (*
  8808. A_IMUL:
  8809. case taicpu(hp1).ops of
  8810. 2:
  8811. begin
  8812. if not MatchOpType(hp1, top_reg, top_reg) or
  8813. { Has to be an exact match on the register }
  8814. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  8815. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  8816. Break;
  8817. TestValMin := TestValMin * TestValMin;
  8818. TestValMax := TestValMax * TestValMax;
  8819. TestValSignedMax := TestValSignedMax * TestValMax;
  8820. end;
  8821. 3:
  8822. begin
  8823. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8824. { Has to be an exact match on the register }
  8825. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8826. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8827. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8828. { Is it in the negative range? }
  8829. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8830. Break;
  8831. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  8832. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  8833. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  8834. end;
  8835. else
  8836. Break;
  8837. end;
  8838. A_IDIV:
  8839. case taicpu(hp1).ops of
  8840. 3:
  8841. begin
  8842. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8843. { Has to be an exact match on the register }
  8844. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8845. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8846. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8847. { Is it in the negative range? }
  8848. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8849. Break;
  8850. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  8851. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  8852. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  8853. end;
  8854. else
  8855. Break;
  8856. end;
  8857. *)
  8858. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  8859. begin
  8860. { If there are no instructions in between, then we might be able to make a saving }
  8861. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  8862. Break;
  8863. { We have something like:
  8864. movzbw %dl,%dx
  8865. ...
  8866. movswl %dx,%edx
  8867. Change the latter to a zero-extension then enter the
  8868. A_MOVZX case branch.
  8869. }
  8870. {$ifdef x86_64}
  8871. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8872. begin
  8873. { this becomes a zero extension from 32-bit to 64-bit, but
  8874. the upper 32 bits are already zero, so just delete the
  8875. instruction }
  8876. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  8877. RemoveInstruction(hp1);
  8878. Result := True;
  8879. Exit;
  8880. end
  8881. else
  8882. {$endif x86_64}
  8883. begin
  8884. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  8885. taicpu(hp1).opcode := A_MOVZX;
  8886. {$ifdef x86_64}
  8887. case taicpu(hp1).opsize of
  8888. S_BQ:
  8889. begin
  8890. taicpu(hp1).opsize := S_BL;
  8891. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8892. end;
  8893. S_WQ:
  8894. begin
  8895. taicpu(hp1).opsize := S_WL;
  8896. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8897. end;
  8898. S_LQ:
  8899. begin
  8900. taicpu(hp1).opcode := A_MOV;
  8901. taicpu(hp1).opsize := S_L;
  8902. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8903. { In this instance, we need to break out because the
  8904. instruction is no longer MOVZX or MOVSXD }
  8905. Result := True;
  8906. Exit;
  8907. end;
  8908. else
  8909. ;
  8910. end;
  8911. {$endif x86_64}
  8912. Result := CompressInstructions;
  8913. Exit;
  8914. end;
  8915. end;
  8916. A_MOVZX:
  8917. begin
  8918. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  8919. Break;
  8920. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  8921. begin
  8922. if (InstrMax = -1) and
  8923. { Will return false if the second parameter isn't ThisReg
  8924. (can happen on -O2 and under) }
  8925. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8926. begin
  8927. { The two MOVZX instructions are adjacent, so remove the first one }
  8928. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  8929. RemoveCurrentP(p);
  8930. Result := True;
  8931. Exit;
  8932. end;
  8933. Break;
  8934. end;
  8935. Result := CompressInstructions;
  8936. Exit;
  8937. end;
  8938. else
  8939. { This includes ADC, SBB and IDIV }
  8940. Break;
  8941. end;
  8942. if not CheckOverflowConditions then
  8943. Break;
  8944. { Contains highest index (so instruction count - 1) }
  8945. Inc(InstrMax);
  8946. if InstrMax > High(InstrList) then
  8947. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  8948. InstrList[InstrMax] := taicpu(hp1);
  8949. end;
  8950. end;
  8951. {$pop}
  8952. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  8953. var
  8954. hp1 : tai;
  8955. begin
  8956. Result:=false;
  8957. if (taicpu(p).ops >= 2) and
  8958. ((taicpu(p).oper[0]^.typ = top_const) or
  8959. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  8960. (taicpu(p).oper[1]^.typ = top_reg) and
  8961. ((taicpu(p).ops = 2) or
  8962. ((taicpu(p).oper[2]^.typ = top_reg) and
  8963. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  8964. GetLastInstruction(p,hp1) and
  8965. MatchInstruction(hp1,A_MOV,[]) and
  8966. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8967. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8968. begin
  8969. TransferUsedRegs(TmpUsedRegs);
  8970. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  8971. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  8972. { change
  8973. mov reg1,reg2
  8974. imul y,reg2 to imul y,reg1,reg2 }
  8975. begin
  8976. taicpu(p).ops := 3;
  8977. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  8978. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  8979. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  8980. RemoveInstruction(hp1);
  8981. result:=true;
  8982. end;
  8983. end;
  8984. end;
  8985. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  8986. var
  8987. ThisLabel: TAsmLabel;
  8988. begin
  8989. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  8990. ThisLabel.decrefs;
  8991. taicpu(p).opcode := A_RET;
  8992. taicpu(p).is_jmp := false;
  8993. taicpu(p).ops := taicpu(ret_p).ops;
  8994. case taicpu(ret_p).ops of
  8995. 0:
  8996. taicpu(p).clearop(0);
  8997. 1:
  8998. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  8999. else
  9000. internalerror(2016041301);
  9001. end;
  9002. { If the original label is now dead, it might turn out that the label
  9003. immediately follows p. As a result, everything beyond it, which will
  9004. be just some final register configuration and a RET instruction, is
  9005. now dead code. [Kit] }
  9006. { NOTE: This is much faster than introducing a OptPass2RET routine and
  9007. running RemoveDeadCodeAfterJump for each RET instruction, because
  9008. this optimisation rarely happens and most RETs appear at the end of
  9009. routines where there is nothing that can be stripped. [Kit] }
  9010. if not ThisLabel.is_used then
  9011. RemoveDeadCodeAfterJump(p);
  9012. end;
  9013. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  9014. var
  9015. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  9016. Unconditional, PotentialModified: Boolean;
  9017. OperPtr: POper;
  9018. NewRef: TReference;
  9019. InstrList: array of taicpu;
  9020. InstrMax, Index: Integer;
  9021. const
  9022. {$ifdef DEBUG_AOPTCPU}
  9023. SNoFlags: shortstring = ' so the flags aren''t modified';
  9024. {$else DEBUG_AOPTCPU}
  9025. SNoFlags = '';
  9026. {$endif DEBUG_AOPTCPU}
  9027. begin
  9028. Result:=false;
  9029. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  9030. begin
  9031. if MatchInstruction(hp1, A_TEST, [S_B]) and
  9032. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9033. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9034. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9035. GetNextInstruction(hp1, hp2) and
  9036. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  9037. { Change from: To:
  9038. set(C) %reg j(~C) label
  9039. test %reg,%reg/cmp $0,%reg
  9040. je label
  9041. set(C) %reg j(C) label
  9042. test %reg,%reg/cmp $0,%reg
  9043. jne label
  9044. (Also do something similar with sete/setne instead of je/jne)
  9045. }
  9046. begin
  9047. { Before we do anything else, we need to check the instructions
  9048. in between SETcc and TEST to make sure they don't modify the
  9049. FLAGS register - if -O2 or under, there won't be any
  9050. instructions between SET and TEST }
  9051. TransferUsedRegs(TmpUsedRegs);
  9052. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9053. if (cs_opt_level3 in current_settings.optimizerswitches) then
  9054. begin
  9055. next := p;
  9056. SetLength(InstrList, 0);
  9057. InstrMax := -1;
  9058. PotentialModified := False;
  9059. { Make a note of every instruction that modifies the FLAGS
  9060. register }
  9061. while GetNextInstruction(next, next) and (next <> hp1) do
  9062. begin
  9063. if next.typ <> ait_instruction then
  9064. { GetNextInstructionUsingReg should have returned False }
  9065. InternalError(2021051701);
  9066. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  9067. begin
  9068. case taicpu(next).opcode of
  9069. A_SETcc,
  9070. A_CMOVcc,
  9071. A_Jcc:
  9072. begin
  9073. if PotentialModified then
  9074. { Not safe because the flags were modified earlier }
  9075. Exit
  9076. else
  9077. { Condition is the same as the initial SETcc, so this is safe
  9078. (don't add to instruction list though) }
  9079. Continue;
  9080. end;
  9081. A_ADD:
  9082. begin
  9083. if (taicpu(next).opsize = S_B) or
  9084. { LEA doesn't support 8-bit operands }
  9085. (taicpu(next).oper[1]^.typ <> top_reg) or
  9086. { Must write to a register }
  9087. (taicpu(next).oper[0]^.typ = top_ref) then
  9088. { Require a constant or a register }
  9089. Exit;
  9090. PotentialModified := True;
  9091. end;
  9092. A_SUB:
  9093. begin
  9094. if (taicpu(next).opsize = S_B) or
  9095. { LEA doesn't support 8-bit operands }
  9096. (taicpu(next).oper[1]^.typ <> top_reg) or
  9097. { Must write to a register }
  9098. (taicpu(next).oper[0]^.typ <> top_const) or
  9099. (taicpu(next).oper[0]^.val = $80000000) then
  9100. { Can't subtract a register with LEA - also
  9101. check that the value isn't -2^31, as this
  9102. can't be negated }
  9103. Exit;
  9104. PotentialModified := True;
  9105. end;
  9106. A_SAL,
  9107. A_SHL:
  9108. begin
  9109. if (taicpu(next).opsize = S_B) or
  9110. { LEA doesn't support 8-bit operands }
  9111. (taicpu(next).oper[1]^.typ <> top_reg) or
  9112. { Must write to a register }
  9113. (taicpu(next).oper[0]^.typ <> top_const) or
  9114. (taicpu(next).oper[0]^.val < 0) or
  9115. (taicpu(next).oper[0]^.val > 3) then
  9116. Exit;
  9117. PotentialModified := True;
  9118. end;
  9119. A_IMUL:
  9120. begin
  9121. if (taicpu(next).ops <> 3) or
  9122. (taicpu(next).oper[1]^.typ <> top_reg) or
  9123. { Must write to a register }
  9124. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  9125. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  9126. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  9127. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  9128. Exit
  9129. else
  9130. PotentialModified := True;
  9131. end;
  9132. else
  9133. { Don't know how to change this, so abort }
  9134. Exit;
  9135. end;
  9136. { Contains highest index (so instruction count - 1) }
  9137. Inc(InstrMax);
  9138. if InstrMax > High(InstrList) then
  9139. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  9140. InstrList[InstrMax] := taicpu(next);
  9141. end;
  9142. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  9143. end;
  9144. if not Assigned(next) or (next <> hp1) then
  9145. { It should be equal to hp1 }
  9146. InternalError(2021051702);
  9147. { Cycle through each instruction and check to see if we can
  9148. change them to versions that don't modify the flags }
  9149. if (InstrMax >= 0) then
  9150. begin
  9151. for Index := 0 to InstrMax do
  9152. case InstrList[Index].opcode of
  9153. A_ADD:
  9154. begin
  9155. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  9156. InstrList[Index].opcode := A_LEA;
  9157. reference_reset(NewRef, 1, []);
  9158. NewRef.base := InstrList[Index].oper[1]^.reg;
  9159. if InstrList[Index].oper[0]^.typ = top_reg then
  9160. begin
  9161. NewRef.index := InstrList[Index].oper[0]^.reg;
  9162. NewRef.scalefactor := 1;
  9163. end
  9164. else
  9165. NewRef.offset := InstrList[Index].oper[0]^.val;
  9166. InstrList[Index].loadref(0, NewRef);
  9167. end;
  9168. A_SUB:
  9169. begin
  9170. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  9171. InstrList[Index].opcode := A_LEA;
  9172. reference_reset(NewRef, 1, []);
  9173. NewRef.base := InstrList[Index].oper[1]^.reg;
  9174. NewRef.offset := -InstrList[Index].oper[0]^.val;
  9175. InstrList[Index].loadref(0, NewRef);
  9176. end;
  9177. A_SHL,
  9178. A_SAL:
  9179. begin
  9180. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  9181. InstrList[Index].opcode := A_LEA;
  9182. reference_reset(NewRef, 1, []);
  9183. NewRef.index := InstrList[Index].oper[1]^.reg;
  9184. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  9185. InstrList[Index].loadref(0, NewRef);
  9186. end;
  9187. A_IMUL:
  9188. begin
  9189. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  9190. InstrList[Index].opcode := A_LEA;
  9191. reference_reset(NewRef, 1, []);
  9192. NewRef.index := InstrList[Index].oper[1]^.reg;
  9193. case InstrList[Index].oper[0]^.val of
  9194. 2, 4, 8:
  9195. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  9196. else {3, 5 and 9}
  9197. begin
  9198. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  9199. NewRef.base := InstrList[Index].oper[1]^.reg;
  9200. end;
  9201. end;
  9202. InstrList[Index].loadref(0, NewRef);
  9203. end;
  9204. else
  9205. InternalError(2021051710);
  9206. end;
  9207. end;
  9208. { Mark the FLAGS register as used across this whole block }
  9209. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  9210. end;
  9211. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  9212. JumpC := taicpu(hp2).condition;
  9213. Unconditional := False;
  9214. if conditions_equal(JumpC, C_E) then
  9215. SetC := inverse_cond(taicpu(p).condition)
  9216. else if conditions_equal(JumpC, C_NE) then
  9217. SetC := taicpu(p).condition
  9218. else
  9219. { We've got something weird here (and inefficent) }
  9220. begin
  9221. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  9222. SetC := C_NONE;
  9223. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  9224. if condition_in(C_AE, JumpC) then
  9225. Unconditional := True
  9226. else
  9227. { Not sure what to do with this jump - drop out }
  9228. Exit;
  9229. end;
  9230. RemoveInstruction(hp1);
  9231. if Unconditional then
  9232. MakeUnconditional(taicpu(hp2))
  9233. else
  9234. begin
  9235. if SetC = C_NONE then
  9236. InternalError(2018061402);
  9237. taicpu(hp2).SetCondition(SetC);
  9238. end;
  9239. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  9240. TmpUsedRegs }
  9241. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  9242. begin
  9243. RemoveCurrentp(p, hp2);
  9244. if taicpu(hp2).opcode = A_SETcc then
  9245. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  9246. else
  9247. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  9248. end
  9249. else
  9250. if taicpu(hp2).opcode = A_SETcc then
  9251. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  9252. else
  9253. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  9254. Result := True;
  9255. end
  9256. else if
  9257. { Make sure the instructions are adjacent }
  9258. (
  9259. not (cs_opt_level3 in current_settings.optimizerswitches) or
  9260. GetNextInstruction(p, hp1)
  9261. ) and
  9262. MatchInstruction(hp1, A_MOV, [S_B]) and
  9263. { Writing to memory is allowed }
  9264. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  9265. begin
  9266. {
  9267. Watch out for sequences such as:
  9268. set(c)b %regb
  9269. movb %regb,(ref)
  9270. movb $0,1(ref)
  9271. movb $0,2(ref)
  9272. movb $0,3(ref)
  9273. Much more efficient to turn it into:
  9274. movl $0,%regl
  9275. set(c)b %regb
  9276. movl %regl,(ref)
  9277. Or:
  9278. set(c)b %regb
  9279. movzbl %regb,%regl
  9280. movl %regl,(ref)
  9281. }
  9282. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  9283. GetNextInstruction(hp1, hp2) and
  9284. MatchInstruction(hp2, A_MOV, [S_B]) and
  9285. (taicpu(hp2).oper[1]^.typ = top_ref) and
  9286. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  9287. begin
  9288. { Don't do anything else except set Result to True }
  9289. end
  9290. else
  9291. begin
  9292. if taicpu(p).oper[0]^.typ = top_reg then
  9293. begin
  9294. TransferUsedRegs(TmpUsedRegs);
  9295. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9296. end;
  9297. { If it's not a register, it's a memory address }
  9298. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  9299. begin
  9300. { Even if the register is still in use, we can minimise the
  9301. pipeline stall by changing the MOV into another SETcc. }
  9302. taicpu(hp1).opcode := A_SETcc;
  9303. taicpu(hp1).condition := taicpu(p).condition;
  9304. if taicpu(hp1).oper[1]^.typ = top_ref then
  9305. begin
  9306. { Swapping the operand pointers like this is probably a
  9307. bit naughty, but it is far faster than using loadoper
  9308. to transfer the reference from oper[1] to oper[0] if
  9309. you take into account the extra procedure calls and
  9310. the memory allocation and deallocation required }
  9311. OperPtr := taicpu(hp1).oper[1];
  9312. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  9313. taicpu(hp1).oper[0] := OperPtr;
  9314. end
  9315. else
  9316. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  9317. taicpu(hp1).clearop(1);
  9318. taicpu(hp1).ops := 1;
  9319. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  9320. end
  9321. else
  9322. begin
  9323. if taicpu(hp1).oper[1]^.typ = top_reg then
  9324. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  9325. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  9326. RemoveInstruction(hp1);
  9327. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  9328. end
  9329. end;
  9330. Result := True;
  9331. end;
  9332. end;
  9333. end;
  9334. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  9335. var
  9336. hp1: tai;
  9337. Count: Integer;
  9338. OrigLabel: TAsmLabel;
  9339. begin
  9340. result := False;
  9341. { Sometimes, the optimisations below can permit this }
  9342. RemoveDeadCodeAfterJump(p);
  9343. 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
  9344. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  9345. begin
  9346. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9347. { Also a side-effect of optimisations }
  9348. if CollapseZeroDistJump(p, OrigLabel) then
  9349. begin
  9350. Result := True;
  9351. Exit;
  9352. end;
  9353. hp1 := GetLabelWithSym(OrigLabel);
  9354. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  9355. begin
  9356. case taicpu(hp1).opcode of
  9357. A_RET:
  9358. {
  9359. change
  9360. jmp .L1
  9361. ...
  9362. .L1:
  9363. ret
  9364. into
  9365. ret
  9366. }
  9367. begin
  9368. ConvertJumpToRET(p, hp1);
  9369. result:=true;
  9370. end;
  9371. { Check any kind of direct assignment instruction }
  9372. A_MOV,
  9373. A_MOVD,
  9374. A_MOVQ,
  9375. A_MOVSX,
  9376. {$ifdef x86_64}
  9377. A_MOVSXD,
  9378. {$endif x86_64}
  9379. A_MOVZX,
  9380. A_MOVAPS,
  9381. A_MOVUPS,
  9382. A_MOVSD,
  9383. A_MOVAPD,
  9384. A_MOVUPD,
  9385. A_MOVDQA,
  9386. A_MOVDQU,
  9387. A_VMOVSS,
  9388. A_VMOVAPS,
  9389. A_VMOVUPS,
  9390. A_VMOVSD,
  9391. A_VMOVAPD,
  9392. A_VMOVUPD,
  9393. A_VMOVDQA,
  9394. A_VMOVDQU:
  9395. if ((current_settings.optimizerswitches * [cs_opt_level3, cs_opt_size]) <> [cs_opt_size]) and
  9396. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  9397. begin
  9398. Result := True;
  9399. Exit;
  9400. end;
  9401. else
  9402. ;
  9403. end;
  9404. end;
  9405. end;
  9406. end;
  9407. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  9408. begin
  9409. CanBeCMOV:=assigned(p) and
  9410. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  9411. { we can't use cmov ref,reg because
  9412. ref could be nil and cmov still throws an exception
  9413. if ref=nil but the mov isn't done (FK)
  9414. or ((taicpu(p).oper[0]^.typ = top_ref) and
  9415. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  9416. }
  9417. (taicpu(p).oper[1]^.typ = top_reg) and
  9418. (
  9419. (taicpu(p).oper[0]^.typ = top_reg) or
  9420. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  9421. it is not expected that this can cause a seg. violation }
  9422. (
  9423. (taicpu(p).oper[0]^.typ = top_ref) and
  9424. IsRefSafe(taicpu(p).oper[0]^.ref)
  9425. )
  9426. );
  9427. end;
  9428. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  9429. var
  9430. hp1,hp2: tai;
  9431. {$ifndef i8086}
  9432. hp3,hp4,hpmov2, hp5: tai;
  9433. l : Longint;
  9434. condition : TAsmCond;
  9435. {$endif i8086}
  9436. carryadd_opcode : TAsmOp;
  9437. symbol: TAsmSymbol;
  9438. increg, tmpreg: TRegister;
  9439. begin
  9440. result:=false;
  9441. if GetNextInstruction(p,hp1) then
  9442. begin
  9443. if (hp1.typ=ait_label) then
  9444. begin
  9445. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  9446. Exit;
  9447. end
  9448. else if (hp1.typ<>ait_instruction) then
  9449. Exit;
  9450. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9451. if (
  9452. (
  9453. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  9454. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  9455. (Taicpu(hp1).oper[0]^.val=1)
  9456. ) or
  9457. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  9458. ) and
  9459. GetNextInstruction(hp1,hp2) and
  9460. SkipAligns(hp2, hp2) and
  9461. (hp2.typ = ait_label) and
  9462. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  9463. { jb @@1 cmc
  9464. inc/dec operand --> adc/sbb operand,0
  9465. @@1:
  9466. ... and ...
  9467. jnb @@1
  9468. inc/dec operand --> adc/sbb operand,0
  9469. @@1: }
  9470. begin
  9471. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  9472. begin
  9473. case taicpu(hp1).opcode of
  9474. A_INC,
  9475. A_ADD:
  9476. carryadd_opcode:=A_ADC;
  9477. A_DEC,
  9478. A_SUB:
  9479. carryadd_opcode:=A_SBB;
  9480. else
  9481. InternalError(2021011001);
  9482. end;
  9483. Taicpu(p).clearop(0);
  9484. Taicpu(p).ops:=0;
  9485. Taicpu(p).is_jmp:=false;
  9486. Taicpu(p).opcode:=A_CMC;
  9487. Taicpu(p).condition:=C_NONE;
  9488. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  9489. Taicpu(hp1).ops:=2;
  9490. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  9491. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  9492. else
  9493. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  9494. Taicpu(hp1).loadconst(0,0);
  9495. Taicpu(hp1).opcode:=carryadd_opcode;
  9496. result:=true;
  9497. exit;
  9498. end
  9499. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  9500. begin
  9501. case taicpu(hp1).opcode of
  9502. A_INC,
  9503. A_ADD:
  9504. carryadd_opcode:=A_ADC;
  9505. A_DEC,
  9506. A_SUB:
  9507. carryadd_opcode:=A_SBB;
  9508. else
  9509. InternalError(2021011002);
  9510. end;
  9511. Taicpu(hp1).ops:=2;
  9512. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  9513. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  9514. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  9515. else
  9516. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  9517. Taicpu(hp1).loadconst(0,0);
  9518. Taicpu(hp1).opcode:=carryadd_opcode;
  9519. RemoveCurrentP(p, hp1);
  9520. result:=true;
  9521. exit;
  9522. end
  9523. {
  9524. jcc @@1 setcc tmpreg
  9525. inc/dec/add/sub operand -> (movzx tmpreg)
  9526. @@1: add/sub tmpreg,operand
  9527. While this increases code size slightly, it makes the code much faster if the
  9528. jump is unpredictable
  9529. }
  9530. else if not(cs_opt_size in current_settings.optimizerswitches) then
  9531. begin
  9532. { search for an available register which is volatile }
  9533. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  9534. if increg <> NR_NO then
  9535. begin
  9536. { We don't need to check if tmpreg is in hp1 or not, because
  9537. it will be marked as in use at p (if not, this is
  9538. indictive of a compiler bug). }
  9539. TAsmLabel(symbol).decrefs;
  9540. Taicpu(p).clearop(0);
  9541. Taicpu(p).ops:=1;
  9542. Taicpu(p).is_jmp:=false;
  9543. Taicpu(p).opcode:=A_SETcc;
  9544. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  9545. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  9546. Taicpu(p).loadreg(0,increg);
  9547. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  9548. begin
  9549. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  9550. R_SUBW:
  9551. begin
  9552. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  9553. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  9554. end;
  9555. R_SUBD:
  9556. begin
  9557. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  9558. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  9559. end;
  9560. {$ifdef x86_64}
  9561. R_SUBQ:
  9562. begin
  9563. { MOVZX doesn't have a 64-bit variant, because
  9564. the 32-bit version implicitly zeroes the
  9565. upper 32-bits of the destination register }
  9566. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  9567. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  9568. setsubreg(tmpreg, R_SUBQ);
  9569. end;
  9570. {$endif x86_64}
  9571. else
  9572. Internalerror(2020030601);
  9573. end;
  9574. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  9575. asml.InsertAfter(hp2,p);
  9576. end
  9577. else
  9578. tmpreg := increg;
  9579. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  9580. begin
  9581. Taicpu(hp1).ops:=2;
  9582. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  9583. end;
  9584. Taicpu(hp1).loadreg(0,tmpreg);
  9585. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  9586. Result := True;
  9587. { p is no longer a Jcc instruction, so exit }
  9588. Exit;
  9589. end;
  9590. end;
  9591. end;
  9592. { Detect the following:
  9593. jmp<cond> @Lbl1
  9594. jmp @Lbl2
  9595. ...
  9596. @Lbl1:
  9597. ret
  9598. Change to:
  9599. jmp<inv_cond> @Lbl2
  9600. ret
  9601. }
  9602. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  9603. begin
  9604. hp2:=getlabelwithsym(TAsmLabel(symbol));
  9605. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  9606. MatchInstruction(hp2,A_RET,[S_NO]) then
  9607. begin
  9608. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  9609. { Change label address to that of the unconditional jump }
  9610. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  9611. TAsmLabel(symbol).DecRefs;
  9612. taicpu(hp1).opcode := A_RET;
  9613. taicpu(hp1).is_jmp := false;
  9614. taicpu(hp1).ops := taicpu(hp2).ops;
  9615. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  9616. case taicpu(hp2).ops of
  9617. 0:
  9618. taicpu(hp1).clearop(0);
  9619. 1:
  9620. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  9621. else
  9622. internalerror(2016041302);
  9623. end;
  9624. end;
  9625. {$ifndef i8086}
  9626. end
  9627. {
  9628. convert
  9629. j<c> .L1
  9630. mov 1,reg
  9631. jmp .L2
  9632. .L1
  9633. mov 0,reg
  9634. .L2
  9635. into
  9636. mov 0,reg
  9637. set<not(c)> reg
  9638. take care of alignment and that the mov 0,reg is not converted into a xor as this
  9639. would destroy the flag contents
  9640. }
  9641. else if MatchInstruction(hp1,A_MOV,[]) and
  9642. MatchOpType(taicpu(hp1),top_const,top_reg) and
  9643. {$ifdef i386}
  9644. (
  9645. { Under i386, ESI, EDI, EBP and ESP
  9646. don't have an 8-bit representation }
  9647. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  9648. ) and
  9649. {$endif i386}
  9650. (taicpu(hp1).oper[0]^.val=1) and
  9651. GetNextInstruction(hp1,hp2) and
  9652. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  9653. GetNextInstruction(hp2,hp3) and
  9654. { skip align }
  9655. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  9656. (hp3.typ=ait_label) and
  9657. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  9658. (tai_label(hp3).labsym.getrefs=1) and
  9659. GetNextInstruction(hp3,hp4) and
  9660. MatchInstruction(hp4,A_MOV,[]) and
  9661. MatchOpType(taicpu(hp4),top_const,top_reg) and
  9662. (taicpu(hp4).oper[0]^.val=0) and
  9663. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  9664. GetNextInstruction(hp4,hp5) and
  9665. (hp5.typ=ait_label) and
  9666. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  9667. (tai_label(hp5).labsym.getrefs=1) then
  9668. begin
  9669. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  9670. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  9671. { remove last label }
  9672. RemoveInstruction(hp5);
  9673. { remove second label }
  9674. RemoveInstruction(hp3);
  9675. { if align is present remove it }
  9676. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  9677. RemoveInstruction(hp3);
  9678. { remove jmp }
  9679. RemoveInstruction(hp2);
  9680. if taicpu(hp1).opsize=S_B then
  9681. RemoveInstruction(hp1)
  9682. else
  9683. taicpu(hp1).loadconst(0,0);
  9684. taicpu(hp4).opcode:=A_SETcc;
  9685. taicpu(hp4).opsize:=S_B;
  9686. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  9687. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  9688. taicpu(hp4).opercnt:=1;
  9689. taicpu(hp4).ops:=1;
  9690. taicpu(hp4).freeop(1);
  9691. RemoveCurrentP(p);
  9692. Result:=true;
  9693. exit;
  9694. end
  9695. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  9696. begin
  9697. { check for
  9698. jCC xxx
  9699. <several movs>
  9700. xxx:
  9701. Also spot:
  9702. Jcc xxx
  9703. <several movs>
  9704. jmp xxx
  9705. Change to:
  9706. <several cmovs with inverted condition>
  9707. jmp xxx
  9708. }
  9709. l:=0;
  9710. while assigned(hp1) and
  9711. CanBeCMOV(hp1) and
  9712. { stop on labels }
  9713. not(hp1.typ=ait_label) do
  9714. begin
  9715. inc(l);
  9716. hp5 := hp1;
  9717. GetNextInstruction(hp1,hp1);
  9718. end;
  9719. if assigned(hp1) then
  9720. begin
  9721. TransferUsedRegs(TmpUsedRegs);
  9722. if (
  9723. MatchInstruction(hp1, A_JMP, []) and
  9724. (JumpTargetOp(taicpu(hp1))^.typ=top_ref) and
  9725. (JumpTargetOp(taicpu(hp1))^.ref^.symbol=symbol)
  9726. ) or
  9727. FindLabel(tasmlabel(symbol),hp1) then
  9728. begin
  9729. if (l<=4) and (l>0) then
  9730. begin
  9731. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  9732. condition:=inverse_cond(taicpu(p).condition);
  9733. UpdateUsedRegs(tai(p.next));
  9734. GetNextInstruction(p,hp1);
  9735. repeat
  9736. if not Assigned(hp1) then
  9737. InternalError(2018062900);
  9738. taicpu(hp1).opcode:=A_CMOVcc;
  9739. taicpu(hp1).condition:=condition;
  9740. UpdateUsedRegs(tai(hp1.next));
  9741. GetNextInstruction(hp1,hp1);
  9742. until not(CanBeCMOV(hp1));
  9743. { Remember what hp1 is in case there's multiple aligns to get rid of }
  9744. hp2 := hp1;
  9745. repeat
  9746. if not Assigned(hp2) then
  9747. InternalError(2018062910);
  9748. case hp2.typ of
  9749. ait_label:
  9750. { What we expected - break out of the loop (it won't be a dead label at the top of
  9751. a cluster because that was optimised at an earlier stage) }
  9752. Break;
  9753. ait_align:
  9754. { Go to the next entry until a label is found (may be multiple aligns before it) }
  9755. begin
  9756. hp2 := tai(hp2.Next);
  9757. Continue;
  9758. end;
  9759. ait_instruction:
  9760. begin
  9761. if taicpu(hp2).opcode<>A_JMP then
  9762. InternalError(2018062912);
  9763. { This is the Jcc @Lbl; <several movs>; JMP @Lbl variant }
  9764. Break;
  9765. end
  9766. else
  9767. begin
  9768. { Might be a comment or temporary allocation entry }
  9769. if not (hp2.typ in SkipInstr) then
  9770. InternalError(2018062911);
  9771. hp2 := tai(hp2.Next);
  9772. Continue;
  9773. end;
  9774. end;
  9775. until False;
  9776. { Now we can safely decrement the reference count }
  9777. tasmlabel(symbol).decrefs;
  9778. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  9779. { Remove the original jump }
  9780. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  9781. if hp2.typ=ait_instruction then
  9782. begin
  9783. p:=hp2;
  9784. Result:=True;
  9785. end
  9786. else
  9787. begin
  9788. UpdateUsedRegs(tai(hp2.next));
  9789. Result:=GetNextInstruction(hp2, p); { Instruction after the label }
  9790. { Remove the label if this is its final reference }
  9791. if (tasmlabel(symbol).getrefs=0) then
  9792. StripLabelFast(hp1);
  9793. end;
  9794. exit;
  9795. end;
  9796. end
  9797. else
  9798. begin
  9799. { check further for
  9800. jCC xxx
  9801. <several movs 1>
  9802. jmp yyy
  9803. xxx:
  9804. <several movs 2>
  9805. yyy:
  9806. }
  9807. { hp2 points to jmp yyy }
  9808. hp2:=hp1;
  9809. { skip hp1 to xxx (or an align right before it) }
  9810. GetNextInstruction(hp1, hp1);
  9811. if assigned(hp2) and
  9812. assigned(hp1) and
  9813. (l<=3) and
  9814. (hp2.typ=ait_instruction) and
  9815. (taicpu(hp2).is_jmp) and
  9816. (taicpu(hp2).condition=C_None) and
  9817. { real label and jump, no further references to the
  9818. label are allowed }
  9819. (tasmlabel(symbol).getrefs=1) and
  9820. FindLabel(tasmlabel(symbol),hp1) then
  9821. begin
  9822. l:=0;
  9823. { skip hp1 to <several moves 2> }
  9824. if (hp1.typ = ait_align) then
  9825. GetNextInstruction(hp1, hp1);
  9826. GetNextInstruction(hp1, hpmov2);
  9827. hp1 := hpmov2;
  9828. while assigned(hp1) and
  9829. CanBeCMOV(hp1) do
  9830. begin
  9831. inc(l);
  9832. hp5 := hp1;
  9833. GetNextInstruction(hp1, hp1);
  9834. end;
  9835. { hp1 points to yyy (or an align right before it) }
  9836. hp3 := hp1;
  9837. if assigned(hp1) and
  9838. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  9839. begin
  9840. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  9841. condition:=inverse_cond(taicpu(p).condition);
  9842. UpdateUsedRegs(tai(p.next));
  9843. GetNextInstruction(p,hp1);
  9844. repeat
  9845. taicpu(hp1).opcode:=A_CMOVcc;
  9846. taicpu(hp1).condition:=condition;
  9847. UpdateUsedRegs(tai(hp1.next));
  9848. GetNextInstruction(hp1,hp1);
  9849. until not(assigned(hp1)) or
  9850. not(CanBeCMOV(hp1));
  9851. condition:=inverse_cond(condition);
  9852. if GetLastInstruction(hpmov2,hp1) then
  9853. UpdateUsedRegs(tai(hp1.next));
  9854. hp1 := hpmov2;
  9855. { hp1 is now at <several movs 2> }
  9856. while Assigned(hp1) and CanBeCMOV(hp1) do
  9857. begin
  9858. taicpu(hp1).opcode:=A_CMOVcc;
  9859. taicpu(hp1).condition:=condition;
  9860. UpdateUsedRegs(tai(hp1.next));
  9861. GetNextInstruction(hp1,hp1);
  9862. end;
  9863. hp1 := p;
  9864. { Get first instruction after label }
  9865. UpdateUsedRegs(tai(hp3.next));
  9866. GetNextInstruction(hp3, p);
  9867. if assigned(p) and (hp3.typ = ait_align) then
  9868. GetNextInstruction(p, p);
  9869. { Don't dereference yet, as doing so will cause
  9870. GetNextInstruction to skip the label and
  9871. optional align marker. [Kit] }
  9872. GetNextInstruction(hp2, hp4);
  9873. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  9874. { remove jCC }
  9875. RemoveInstruction(hp1);
  9876. { Now we can safely decrement it }
  9877. tasmlabel(symbol).decrefs;
  9878. { Remove label xxx (it will have a ref of zero due to the initial check }
  9879. StripLabelFast(hp4);
  9880. { remove jmp }
  9881. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  9882. RemoveInstruction(hp2);
  9883. { As before, now we can safely decrement it }
  9884. tasmlabel(symbol).decrefs;
  9885. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  9886. if tasmlabel(symbol).getrefs = 0 then
  9887. StripLabelFast(hp3);
  9888. if Assigned(p) then
  9889. result:=true;
  9890. exit;
  9891. end;
  9892. end;
  9893. end;
  9894. end;
  9895. {$endif i8086}
  9896. end;
  9897. end;
  9898. end;
  9899. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  9900. var
  9901. hp1,hp2,hp3: tai;
  9902. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  9903. NewSize: TOpSize;
  9904. NewRegSize: TSubRegister;
  9905. Limit: TCgInt;
  9906. SwapOper: POper;
  9907. begin
  9908. result:=false;
  9909. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  9910. GetNextInstruction(p,hp1) and
  9911. (hp1.typ = ait_instruction);
  9912. if reg_and_hp1_is_instr and
  9913. (
  9914. (taicpu(hp1).opcode <> A_LEA) or
  9915. { If the LEA instruction can be converted into an arithmetic instruction,
  9916. it may be possible to then fold it. }
  9917. (
  9918. { If the flags register is in use, don't change the instruction
  9919. to an ADD otherwise this will scramble the flags. [Kit] }
  9920. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  9921. ConvertLEA(taicpu(hp1))
  9922. )
  9923. ) and
  9924. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  9925. GetNextInstruction(hp1,hp2) and
  9926. MatchInstruction(hp2,A_MOV,[]) and
  9927. (taicpu(hp2).oper[0]^.typ = top_reg) and
  9928. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  9929. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  9930. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  9931. {$ifdef i386}
  9932. { not all registers have byte size sub registers on i386 }
  9933. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  9934. {$endif i386}
  9935. (((taicpu(hp1).ops=2) and
  9936. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  9937. ((taicpu(hp1).ops=1) and
  9938. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  9939. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  9940. begin
  9941. { change movsX/movzX reg/ref, reg2
  9942. add/sub/or/... reg3/$const, reg2
  9943. mov reg2 reg/ref
  9944. to add/sub/or/... reg3/$const, reg/ref }
  9945. { by example:
  9946. movswl %si,%eax movswl %si,%eax p
  9947. decl %eax addl %edx,%eax hp1
  9948. movw %ax,%si movw %ax,%si hp2
  9949. ->
  9950. movswl %si,%eax movswl %si,%eax p
  9951. decw %eax addw %edx,%eax hp1
  9952. movw %ax,%si movw %ax,%si hp2
  9953. }
  9954. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  9955. {
  9956. ->
  9957. movswl %si,%eax movswl %si,%eax p
  9958. decw %si addw %dx,%si hp1
  9959. movw %ax,%si movw %ax,%si hp2
  9960. }
  9961. case taicpu(hp1).ops of
  9962. 1:
  9963. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  9964. 2:
  9965. begin
  9966. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  9967. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9968. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  9969. end;
  9970. else
  9971. internalerror(2008042702);
  9972. end;
  9973. {
  9974. ->
  9975. decw %si addw %dx,%si p
  9976. }
  9977. DebugMsg(SPeepholeOptimization + 'var3',p);
  9978. RemoveCurrentP(p, hp1);
  9979. RemoveInstruction(hp2);
  9980. Result := True;
  9981. Exit;
  9982. end;
  9983. if reg_and_hp1_is_instr and
  9984. (taicpu(hp1).opcode = A_MOV) and
  9985. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9986. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  9987. {$ifdef x86_64}
  9988. { check for implicit extension to 64 bit }
  9989. or
  9990. ((taicpu(p).opsize in [S_BL,S_WL]) and
  9991. (taicpu(hp1).opsize=S_Q) and
  9992. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  9993. )
  9994. {$endif x86_64}
  9995. )
  9996. then
  9997. begin
  9998. { change
  9999. movx %reg1,%reg2
  10000. mov %reg2,%reg3
  10001. dealloc %reg2
  10002. into
  10003. movx %reg,%reg3
  10004. }
  10005. TransferUsedRegs(TmpUsedRegs);
  10006. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10007. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  10008. begin
  10009. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  10010. {$ifdef x86_64}
  10011. if (taicpu(p).opsize in [S_BL,S_WL]) and
  10012. (taicpu(hp1).opsize=S_Q) then
  10013. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  10014. else
  10015. {$endif x86_64}
  10016. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  10017. RemoveInstruction(hp1);
  10018. Result := True;
  10019. Exit;
  10020. end;
  10021. end;
  10022. if reg_and_hp1_is_instr and
  10023. ((taicpu(hp1).opcode=A_MOV) or
  10024. (taicpu(hp1).opcode=A_ADD) or
  10025. (taicpu(hp1).opcode=A_SUB) or
  10026. (taicpu(hp1).opcode=A_CMP) or
  10027. (taicpu(hp1).opcode=A_OR) or
  10028. (taicpu(hp1).opcode=A_XOR) or
  10029. (taicpu(hp1).opcode=A_AND)
  10030. ) and
  10031. (taicpu(hp1).oper[1]^.typ = top_reg) then
  10032. begin
  10033. AndTest := (taicpu(hp1).opcode=A_AND) and
  10034. GetNextInstruction(hp1, hp2) and
  10035. (hp2.typ = ait_instruction) and
  10036. (
  10037. (
  10038. (taicpu(hp2).opcode=A_TEST) and
  10039. (
  10040. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  10041. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  10042. (
  10043. { If the AND and TEST instructions share a constant, this is also valid }
  10044. (taicpu(hp1).oper[0]^.typ = top_const) and
  10045. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  10046. )
  10047. ) and
  10048. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  10049. ) or
  10050. (
  10051. (taicpu(hp2).opcode=A_CMP) and
  10052. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  10053. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  10054. )
  10055. );
  10056. { change
  10057. movx (oper),%reg2
  10058. and $x,%reg2
  10059. test %reg2,%reg2
  10060. dealloc %reg2
  10061. into
  10062. op %reg1,%reg3
  10063. if the second op accesses only the bits stored in reg1
  10064. }
  10065. if ((taicpu(p).oper[0]^.typ=top_reg) or
  10066. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  10067. (taicpu(hp1).oper[0]^.typ = top_const) and
  10068. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  10069. AndTest then
  10070. begin
  10071. { Check if the AND constant is in range }
  10072. case taicpu(p).opsize of
  10073. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10074. begin
  10075. NewSize := S_B;
  10076. Limit := $FF;
  10077. end;
  10078. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10079. begin
  10080. NewSize := S_W;
  10081. Limit := $FFFF;
  10082. end;
  10083. {$ifdef x86_64}
  10084. S_LQ:
  10085. begin
  10086. NewSize := S_L;
  10087. Limit := $FFFFFFFF;
  10088. end;
  10089. {$endif x86_64}
  10090. else
  10091. InternalError(2021120303);
  10092. end;
  10093. if (
  10094. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  10095. { Check for negative operands }
  10096. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  10097. ) and
  10098. GetNextInstruction(hp2,hp3) and
  10099. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  10100. (taicpu(hp3).condition in [C_E,C_NE]) then
  10101. begin
  10102. TransferUsedRegs(TmpUsedRegs);
  10103. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10104. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  10105. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  10106. begin
  10107. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  10108. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  10109. taicpu(hp1).opcode := A_TEST;
  10110. taicpu(hp1).opsize := NewSize;
  10111. RemoveInstruction(hp2);
  10112. RemoveCurrentP(p, hp1);
  10113. Result:=true;
  10114. exit;
  10115. end;
  10116. end;
  10117. end;
  10118. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  10119. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  10120. (taicpu(hp1).opsize=S_B)) or
  10121. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  10122. (taicpu(hp1).opsize=S_W))
  10123. {$ifdef x86_64}
  10124. or ((taicpu(p).opsize=S_LQ) and
  10125. (taicpu(hp1).opsize=S_L))
  10126. {$endif x86_64}
  10127. ) and
  10128. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  10129. begin
  10130. { change
  10131. movx %reg1,%reg2
  10132. op %reg2,%reg3
  10133. dealloc %reg2
  10134. into
  10135. op %reg1,%reg3
  10136. if the second op accesses only the bits stored in reg1
  10137. }
  10138. TransferUsedRegs(TmpUsedRegs);
  10139. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10140. if AndTest then
  10141. begin
  10142. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10143. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  10144. end
  10145. else
  10146. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  10147. if not RegUsed then
  10148. begin
  10149. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  10150. if taicpu(p).oper[0]^.typ=top_reg then
  10151. begin
  10152. case taicpu(hp1).opsize of
  10153. S_B:
  10154. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  10155. S_W:
  10156. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  10157. S_L:
  10158. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  10159. else
  10160. Internalerror(2020102301);
  10161. end;
  10162. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  10163. end
  10164. else
  10165. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  10166. RemoveCurrentP(p);
  10167. if AndTest then
  10168. RemoveInstruction(hp2);
  10169. result:=true;
  10170. exit;
  10171. end;
  10172. end
  10173. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  10174. (
  10175. { Bitwise operations only }
  10176. (taicpu(hp1).opcode=A_AND) or
  10177. (taicpu(hp1).opcode=A_TEST) or
  10178. (
  10179. (taicpu(hp1).oper[0]^.typ = top_const) and
  10180. (
  10181. (taicpu(hp1).opcode=A_OR) or
  10182. (taicpu(hp1).opcode=A_XOR)
  10183. )
  10184. )
  10185. ) and
  10186. (
  10187. (taicpu(hp1).oper[0]^.typ = top_const) or
  10188. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  10189. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  10190. ) then
  10191. begin
  10192. { change
  10193. movx %reg2,%reg2
  10194. op const,%reg2
  10195. into
  10196. op const,%reg2 (smaller version)
  10197. movx %reg2,%reg2
  10198. also change
  10199. movx %reg1,%reg2
  10200. and/test (oper),%reg2
  10201. dealloc %reg2
  10202. into
  10203. and/test (oper),%reg1
  10204. }
  10205. case taicpu(p).opsize of
  10206. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10207. begin
  10208. NewSize := S_B;
  10209. NewRegSize := R_SUBL;
  10210. Limit := $FF;
  10211. end;
  10212. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10213. begin
  10214. NewSize := S_W;
  10215. NewRegSize := R_SUBW;
  10216. Limit := $FFFF;
  10217. end;
  10218. {$ifdef x86_64}
  10219. S_LQ:
  10220. begin
  10221. NewSize := S_L;
  10222. NewRegSize := R_SUBD;
  10223. Limit := $FFFFFFFF;
  10224. end;
  10225. {$endif x86_64}
  10226. else
  10227. Internalerror(2021120302);
  10228. end;
  10229. TransferUsedRegs(TmpUsedRegs);
  10230. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10231. if AndTest then
  10232. begin
  10233. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10234. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  10235. end
  10236. else
  10237. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  10238. if
  10239. (
  10240. (taicpu(p).opcode = A_MOVZX) and
  10241. (
  10242. (taicpu(hp1).opcode=A_AND) or
  10243. (taicpu(hp1).opcode=A_TEST)
  10244. ) and
  10245. not (
  10246. { If both are references, then the final instruction will have
  10247. both operands as references, which is not allowed }
  10248. (taicpu(p).oper[0]^.typ = top_ref) and
  10249. (taicpu(hp1).oper[0]^.typ = top_ref)
  10250. ) and
  10251. not RegUsed
  10252. ) or
  10253. (
  10254. (
  10255. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  10256. not RegUsed
  10257. ) and
  10258. (taicpu(p).oper[0]^.typ = top_reg) and
  10259. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10260. (taicpu(hp1).oper[0]^.typ = top_const) and
  10261. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  10262. ) then
  10263. begin
  10264. {$if defined(i386) or defined(i8086)}
  10265. { If the target size is 8-bit, make sure we can actually encode it }
  10266. 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
  10267. Exit;
  10268. {$endif i386 or i8086}
  10269. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  10270. taicpu(hp1).opsize := NewSize;
  10271. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  10272. if AndTest then
  10273. begin
  10274. RemoveInstruction(hp2);
  10275. if not RegUsed then
  10276. begin
  10277. taicpu(hp1).opcode := A_TEST;
  10278. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  10279. begin
  10280. { Make sure the reference is the second operand }
  10281. SwapOper := taicpu(hp1).oper[0];
  10282. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  10283. taicpu(hp1).oper[1] := SwapOper;
  10284. end;
  10285. end;
  10286. end;
  10287. case taicpu(hp1).oper[0]^.typ of
  10288. top_reg:
  10289. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  10290. top_const:
  10291. { For the AND/TEST case }
  10292. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  10293. else
  10294. ;
  10295. end;
  10296. if RegUsed then
  10297. begin
  10298. AsmL.Remove(p);
  10299. AsmL.InsertAfter(p, hp1);
  10300. p := hp1;
  10301. end
  10302. else
  10303. RemoveCurrentP(p, hp1);
  10304. result:=true;
  10305. exit;
  10306. end;
  10307. end;
  10308. end;
  10309. if reg_and_hp1_is_instr and
  10310. (taicpu(p).oper[0]^.typ = top_reg) and
  10311. (
  10312. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  10313. ) and
  10314. (taicpu(hp1).oper[0]^.typ = top_const) and
  10315. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10316. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10317. { Minimum shift value allowed is the bit difference between the sizes }
  10318. (taicpu(hp1).oper[0]^.val >=
  10319. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10320. 8 * (
  10321. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  10322. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10323. )
  10324. ) then
  10325. begin
  10326. { For:
  10327. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  10328. shl/sal ##, %reg1
  10329. Remove the movsx/movzx instruction if the shift overwrites the
  10330. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  10331. }
  10332. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  10333. RemoveCurrentP(p, hp1);
  10334. Result := True;
  10335. Exit;
  10336. end
  10337. else if reg_and_hp1_is_instr and
  10338. (taicpu(p).oper[0]^.typ = top_reg) and
  10339. (
  10340. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  10341. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  10342. ) and
  10343. (taicpu(hp1).oper[0]^.typ = top_const) and
  10344. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10345. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10346. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  10347. (taicpu(hp1).oper[0]^.val <
  10348. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10349. 8 * (
  10350. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10351. )
  10352. ) then
  10353. begin
  10354. { For:
  10355. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  10356. sar ##, %reg1 shr ##, %reg1
  10357. Move the shift to before the movx instruction if the shift value
  10358. is not too large.
  10359. }
  10360. asml.Remove(hp1);
  10361. asml.InsertBefore(hp1, p);
  10362. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  10363. case taicpu(p).opsize of
  10364. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  10365. taicpu(hp1).opsize := S_B;
  10366. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  10367. taicpu(hp1).opsize := S_W;
  10368. {$ifdef x86_64}
  10369. S_LQ:
  10370. taicpu(hp1).opsize := S_L;
  10371. {$endif}
  10372. else
  10373. InternalError(2020112401);
  10374. end;
  10375. if (taicpu(hp1).opcode = A_SHR) then
  10376. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  10377. else
  10378. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  10379. Result := True;
  10380. end;
  10381. if reg_and_hp1_is_instr and
  10382. (taicpu(p).oper[0]^.typ = top_reg) and
  10383. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10384. (
  10385. (taicpu(hp1).opcode = taicpu(p).opcode)
  10386. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  10387. {$ifdef x86_64}
  10388. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  10389. {$endif x86_64}
  10390. ) then
  10391. begin
  10392. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  10393. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  10394. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10395. begin
  10396. {
  10397. For example:
  10398. movzbw %al,%ax
  10399. movzwl %ax,%eax
  10400. Compress into:
  10401. movzbl %al,%eax
  10402. }
  10403. RegUsed := False;
  10404. case taicpu(p).opsize of
  10405. S_BW:
  10406. case taicpu(hp1).opsize of
  10407. S_WL:
  10408. begin
  10409. taicpu(p).opsize := S_BL;
  10410. RegUsed := True;
  10411. end;
  10412. {$ifdef x86_64}
  10413. S_WQ:
  10414. begin
  10415. if taicpu(p).opcode = A_MOVZX then
  10416. begin
  10417. taicpu(p).opsize := S_BL;
  10418. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10419. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10420. end
  10421. else
  10422. taicpu(p).opsize := S_BQ;
  10423. RegUsed := True;
  10424. end;
  10425. {$endif x86_64}
  10426. else
  10427. ;
  10428. end;
  10429. {$ifdef x86_64}
  10430. S_BL:
  10431. case taicpu(hp1).opsize of
  10432. S_LQ:
  10433. begin
  10434. if taicpu(p).opcode = A_MOVZX then
  10435. begin
  10436. taicpu(p).opsize := S_BL;
  10437. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10438. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10439. end
  10440. else
  10441. taicpu(p).opsize := S_BQ;
  10442. RegUsed := True;
  10443. end;
  10444. else
  10445. ;
  10446. end;
  10447. S_WL:
  10448. case taicpu(hp1).opsize of
  10449. S_LQ:
  10450. begin
  10451. if taicpu(p).opcode = A_MOVZX then
  10452. begin
  10453. taicpu(p).opsize := S_WL;
  10454. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10455. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10456. end
  10457. else
  10458. taicpu(p).opsize := S_WQ;
  10459. RegUsed := True;
  10460. end;
  10461. else
  10462. ;
  10463. end;
  10464. {$endif x86_64}
  10465. else
  10466. ;
  10467. end;
  10468. if RegUsed then
  10469. begin
  10470. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  10471. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  10472. RemoveInstruction(hp1);
  10473. Result := True;
  10474. Exit;
  10475. end;
  10476. end;
  10477. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  10478. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  10479. GetNextInstruction(hp1, hp2) and
  10480. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  10481. (
  10482. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  10483. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  10484. {$ifdef x86_64}
  10485. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  10486. {$endif x86_64}
  10487. ) and
  10488. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  10489. (
  10490. (
  10491. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10492. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  10493. ) or
  10494. (
  10495. { Only allow the operands in reverse order for TEST instructions }
  10496. (taicpu(hp2).opcode = A_TEST) and
  10497. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  10498. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  10499. )
  10500. ) then
  10501. begin
  10502. {
  10503. For example:
  10504. movzbl %al,%eax
  10505. movzbl (ref),%edx
  10506. andl %edx,%eax
  10507. (%edx deallocated)
  10508. Change to:
  10509. andb (ref),%al
  10510. movzbl %al,%eax
  10511. Rules are:
  10512. - First two instructions have the same opcode and opsize
  10513. - First instruction's operands are the same super-register
  10514. - Second instruction operates on a different register
  10515. - Third instruction is AND, OR, XOR or TEST
  10516. - Third instruction's operands are the destination registers of the first two instructions
  10517. - Third instruction writes to the destination register of the first instruction (except with TEST)
  10518. - Second instruction's destination register is deallocated afterwards
  10519. }
  10520. TransferUsedRegs(TmpUsedRegs);
  10521. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10522. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  10523. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  10524. begin
  10525. case taicpu(p).opsize of
  10526. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10527. NewSize := S_B;
  10528. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10529. NewSize := S_W;
  10530. {$ifdef x86_64}
  10531. S_LQ:
  10532. NewSize := S_L;
  10533. {$endif x86_64}
  10534. else
  10535. InternalError(2021120301);
  10536. end;
  10537. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  10538. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  10539. taicpu(hp2).opsize := NewSize;
  10540. RemoveInstruction(hp1);
  10541. { With TEST, it's best to keep the MOVX instruction at the top }
  10542. if (taicpu(hp2).opcode <> A_TEST) then
  10543. begin
  10544. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  10545. asml.Remove(p);
  10546. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  10547. asml.InsertAfter(p, hp2);
  10548. p := hp2;
  10549. end
  10550. else
  10551. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  10552. Result := True;
  10553. Exit;
  10554. end;
  10555. end;
  10556. end;
  10557. if taicpu(p).opcode=A_MOVZX then
  10558. begin
  10559. { removes superfluous And's after movzx's }
  10560. if reg_and_hp1_is_instr and
  10561. (taicpu(hp1).opcode = A_AND) and
  10562. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10563. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  10564. {$ifdef x86_64}
  10565. { check for implicit extension to 64 bit }
  10566. or
  10567. ((taicpu(p).opsize in [S_BL,S_WL]) and
  10568. (taicpu(hp1).opsize=S_Q) and
  10569. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  10570. )
  10571. {$endif x86_64}
  10572. )
  10573. then
  10574. begin
  10575. case taicpu(p).opsize Of
  10576. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10577. if (taicpu(hp1).oper[0]^.val = $ff) then
  10578. begin
  10579. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  10580. RemoveInstruction(hp1);
  10581. Result:=true;
  10582. exit;
  10583. end;
  10584. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10585. if (taicpu(hp1).oper[0]^.val = $ffff) then
  10586. begin
  10587. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  10588. RemoveInstruction(hp1);
  10589. Result:=true;
  10590. exit;
  10591. end;
  10592. {$ifdef x86_64}
  10593. S_LQ:
  10594. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  10595. begin
  10596. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  10597. RemoveInstruction(hp1);
  10598. Result:=true;
  10599. exit;
  10600. end;
  10601. {$endif x86_64}
  10602. else
  10603. ;
  10604. end;
  10605. { we cannot get rid of the and, but can we get rid of the movz ?}
  10606. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  10607. begin
  10608. case taicpu(p).opsize Of
  10609. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10610. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  10611. begin
  10612. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  10613. RemoveCurrentP(p,hp1);
  10614. Result:=true;
  10615. exit;
  10616. end;
  10617. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10618. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  10619. begin
  10620. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  10621. RemoveCurrentP(p,hp1);
  10622. Result:=true;
  10623. exit;
  10624. end;
  10625. {$ifdef x86_64}
  10626. S_LQ:
  10627. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  10628. begin
  10629. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  10630. RemoveCurrentP(p,hp1);
  10631. Result:=true;
  10632. exit;
  10633. end;
  10634. {$endif x86_64}
  10635. else
  10636. ;
  10637. end;
  10638. end;
  10639. end;
  10640. { changes some movzx constructs to faster synonyms (all examples
  10641. are given with eax/ax, but are also valid for other registers)}
  10642. if MatchOpType(taicpu(p),top_reg,top_reg) then
  10643. begin
  10644. case taicpu(p).opsize of
  10645. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  10646. (the machine code is equivalent to movzbl %al,%eax), but the
  10647. code generator still generates that assembler instruction and
  10648. it is silently converted. This should probably be checked.
  10649. [Kit] }
  10650. S_BW:
  10651. begin
  10652. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10653. (
  10654. not IsMOVZXAcceptable
  10655. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  10656. or (
  10657. (cs_opt_size in current_settings.optimizerswitches) and
  10658. (taicpu(p).oper[1]^.reg = NR_AX)
  10659. )
  10660. ) then
  10661. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  10662. begin
  10663. DebugMsg(SPeepholeOptimization + 'var7',p);
  10664. taicpu(p).opcode := A_AND;
  10665. taicpu(p).changeopsize(S_W);
  10666. taicpu(p).loadConst(0,$ff);
  10667. Result := True;
  10668. end
  10669. else if not IsMOVZXAcceptable and
  10670. GetNextInstruction(p, hp1) and
  10671. (tai(hp1).typ = ait_instruction) and
  10672. (taicpu(hp1).opcode = A_AND) and
  10673. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10674. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10675. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  10676. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  10677. begin
  10678. DebugMsg(SPeepholeOptimization + 'var8',p);
  10679. taicpu(p).opcode := A_MOV;
  10680. taicpu(p).changeopsize(S_W);
  10681. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  10682. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10683. Result := True;
  10684. end;
  10685. end;
  10686. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  10687. S_BL:
  10688. begin
  10689. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10690. (
  10691. not IsMOVZXAcceptable
  10692. { and $0xff,%eax has a smaller encoding but risks a partial write penalty }
  10693. or (
  10694. (cs_opt_size in current_settings.optimizerswitches) and
  10695. (taicpu(p).oper[1]^.reg = NR_EAX)
  10696. )
  10697. ) then
  10698. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  10699. begin
  10700. DebugMsg(SPeepholeOptimization + 'var9',p);
  10701. taicpu(p).opcode := A_AND;
  10702. taicpu(p).changeopsize(S_L);
  10703. taicpu(p).loadConst(0,$ff);
  10704. Result := True;
  10705. end
  10706. else if not IsMOVZXAcceptable and
  10707. GetNextInstruction(p, hp1) and
  10708. (tai(hp1).typ = ait_instruction) and
  10709. (taicpu(hp1).opcode = A_AND) and
  10710. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10711. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10712. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  10713. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  10714. begin
  10715. DebugMsg(SPeepholeOptimization + 'var10',p);
  10716. taicpu(p).opcode := A_MOV;
  10717. taicpu(p).changeopsize(S_L);
  10718. { do not use R_SUBWHOLE
  10719. as movl %rdx,%eax
  10720. is invalid in assembler PM }
  10721. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10722. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10723. Result := True;
  10724. end;
  10725. end;
  10726. {$endif i8086}
  10727. S_WL:
  10728. if not IsMOVZXAcceptable then
  10729. begin
  10730. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  10731. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  10732. begin
  10733. DebugMsg(SPeepholeOptimization + 'var11',p);
  10734. taicpu(p).opcode := A_AND;
  10735. taicpu(p).changeopsize(S_L);
  10736. taicpu(p).loadConst(0,$ffff);
  10737. Result := True;
  10738. end
  10739. else if GetNextInstruction(p, hp1) and
  10740. (tai(hp1).typ = ait_instruction) and
  10741. (taicpu(hp1).opcode = A_AND) and
  10742. (taicpu(hp1).oper[0]^.typ = top_const) and
  10743. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10744. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10745. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  10746. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  10747. begin
  10748. DebugMsg(SPeepholeOptimization + 'var12',p);
  10749. taicpu(p).opcode := A_MOV;
  10750. taicpu(p).changeopsize(S_L);
  10751. { do not use R_SUBWHOLE
  10752. as movl %rdx,%eax
  10753. is invalid in assembler PM }
  10754. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10755. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10756. Result := True;
  10757. end;
  10758. end;
  10759. else
  10760. InternalError(2017050705);
  10761. end;
  10762. end
  10763. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  10764. begin
  10765. if GetNextInstruction(p, hp1) and
  10766. (tai(hp1).typ = ait_instruction) and
  10767. (taicpu(hp1).opcode = A_AND) and
  10768. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10769. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10770. begin
  10771. //taicpu(p).opcode := A_MOV;
  10772. case taicpu(p).opsize Of
  10773. S_BL:
  10774. begin
  10775. DebugMsg(SPeepholeOptimization + 'var13',p);
  10776. taicpu(hp1).changeopsize(S_L);
  10777. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10778. end;
  10779. S_WL:
  10780. begin
  10781. DebugMsg(SPeepholeOptimization + 'var14',p);
  10782. taicpu(hp1).changeopsize(S_L);
  10783. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10784. end;
  10785. S_BW:
  10786. begin
  10787. DebugMsg(SPeepholeOptimization + 'var15',p);
  10788. taicpu(hp1).changeopsize(S_W);
  10789. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10790. end;
  10791. else
  10792. Internalerror(2017050704)
  10793. end;
  10794. Result := True;
  10795. end;
  10796. end;
  10797. end;
  10798. end;
  10799. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  10800. var
  10801. hp1, hp2 : tai;
  10802. MaskLength : Cardinal;
  10803. MaskedBits : TCgInt;
  10804. ActiveReg : TRegister;
  10805. begin
  10806. Result:=false;
  10807. { There are no optimisations for reference targets }
  10808. if (taicpu(p).oper[1]^.typ <> top_reg) then
  10809. Exit;
  10810. while GetNextInstruction(p, hp1) and
  10811. (hp1.typ = ait_instruction) do
  10812. begin
  10813. if (taicpu(p).oper[0]^.typ = top_const) then
  10814. begin
  10815. case taicpu(hp1).opcode of
  10816. A_AND:
  10817. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10818. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10819. { the second register must contain the first one, so compare their subreg types }
  10820. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  10821. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  10822. { change
  10823. and const1, reg
  10824. and const2, reg
  10825. to
  10826. and (const1 and const2), reg
  10827. }
  10828. begin
  10829. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  10830. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  10831. RemoveCurrentP(p, hp1);
  10832. Result:=true;
  10833. exit;
  10834. end;
  10835. A_CMP:
  10836. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  10837. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  10838. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10839. { Just check that the condition on the next instruction is compatible }
  10840. GetNextInstruction(hp1, hp2) and
  10841. (hp2.typ = ait_instruction) and
  10842. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  10843. then
  10844. { change
  10845. and 2^n, reg
  10846. cmp 2^n, reg
  10847. j(c) / set(c) / cmov(c) (c is equal or not equal)
  10848. to
  10849. and 2^n, reg
  10850. test reg, reg
  10851. j(~c) / set(~c) / cmov(~c)
  10852. }
  10853. begin
  10854. { Keep TEST instruction in, rather than remove it, because
  10855. it may trigger other optimisations such as MovAndTest2Test }
  10856. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  10857. taicpu(hp1).opcode := A_TEST;
  10858. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  10859. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  10860. Result := True;
  10861. Exit;
  10862. end;
  10863. A_MOVZX:
  10864. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10865. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  10866. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10867. (
  10868. (
  10869. (taicpu(p).opsize=S_W) and
  10870. (taicpu(hp1).opsize=S_BW)
  10871. ) or
  10872. (
  10873. (taicpu(p).opsize=S_L) and
  10874. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  10875. )
  10876. {$ifdef x86_64}
  10877. or
  10878. (
  10879. (taicpu(p).opsize=S_Q) and
  10880. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  10881. )
  10882. {$endif x86_64}
  10883. ) then
  10884. begin
  10885. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10886. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  10887. ) or
  10888. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10889. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  10890. then
  10891. begin
  10892. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  10893. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  10894. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  10895. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  10896. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  10897. }
  10898. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  10899. RemoveInstruction(hp1);
  10900. { See if there are other optimisations possible }
  10901. Continue;
  10902. end;
  10903. end;
  10904. A_SHL:
  10905. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10906. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  10907. begin
  10908. {$ifopt R+}
  10909. {$define RANGE_WAS_ON}
  10910. {$R-}
  10911. {$endif}
  10912. { get length of potential and mask }
  10913. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  10914. { really a mask? }
  10915. {$ifdef RANGE_WAS_ON}
  10916. {$R+}
  10917. {$endif}
  10918. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  10919. { unmasked part shifted out? }
  10920. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  10921. begin
  10922. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  10923. RemoveCurrentP(p, hp1);
  10924. Result:=true;
  10925. exit;
  10926. end;
  10927. end;
  10928. A_SHR:
  10929. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10930. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  10931. (taicpu(hp1).oper[0]^.val <= 63) then
  10932. begin
  10933. { Does SHR combined with the AND cover all the bits?
  10934. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  10935. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  10936. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  10937. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  10938. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  10939. begin
  10940. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  10941. RemoveCurrentP(p, hp1);
  10942. Result := True;
  10943. Exit;
  10944. end;
  10945. end;
  10946. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10947. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  10948. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10949. begin
  10950. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  10951. (
  10952. (
  10953. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10954. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  10955. ) or (
  10956. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10957. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  10958. {$ifdef x86_64}
  10959. ) or (
  10960. (taicpu(hp1).opsize = S_LQ) and
  10961. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  10962. {$endif x86_64}
  10963. )
  10964. ) then
  10965. begin
  10966. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  10967. begin
  10968. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  10969. RemoveInstruction(hp1);
  10970. { See if there are other optimisations possible }
  10971. Continue;
  10972. end;
  10973. { The super-registers are the same though.
  10974. Note that this change by itself doesn't improve
  10975. code speed, but it opens up other optimisations. }
  10976. {$ifdef x86_64}
  10977. { Convert 64-bit register to 32-bit }
  10978. case taicpu(hp1).opsize of
  10979. S_BQ:
  10980. begin
  10981. taicpu(hp1).opsize := S_BL;
  10982. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  10983. end;
  10984. S_WQ:
  10985. begin
  10986. taicpu(hp1).opsize := S_WL;
  10987. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  10988. end
  10989. else
  10990. ;
  10991. end;
  10992. {$endif x86_64}
  10993. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  10994. taicpu(hp1).opcode := A_MOVZX;
  10995. { See if there are other optimisations possible }
  10996. Continue;
  10997. end;
  10998. end;
  10999. else
  11000. ;
  11001. end;
  11002. end
  11003. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  11004. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  11005. begin
  11006. {$ifdef x86_64}
  11007. if (taicpu(p).opsize = S_Q) then
  11008. begin
  11009. { Never necessary }
  11010. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  11011. RemoveCurrentP(p, hp1);
  11012. Result := True;
  11013. Exit;
  11014. end;
  11015. {$endif x86_64}
  11016. { Forward check to determine necessity of and %reg,%reg }
  11017. TransferUsedRegs(TmpUsedRegs);
  11018. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11019. { Saves on a bunch of dereferences }
  11020. ActiveReg := taicpu(p).oper[1]^.reg;
  11021. case taicpu(hp1).opcode of
  11022. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  11023. if (
  11024. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11025. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11026. ) and
  11027. (
  11028. (taicpu(hp1).opcode <> A_MOV) or
  11029. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  11030. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  11031. ) and
  11032. not (
  11033. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  11034. (taicpu(hp1).opcode = A_MOV) and
  11035. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  11036. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  11037. ) and
  11038. (
  11039. (
  11040. (taicpu(hp1).oper[0]^.typ = top_reg) and
  11041. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  11042. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  11043. ) or
  11044. (
  11045. {$ifdef x86_64}
  11046. (
  11047. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  11048. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  11049. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  11050. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  11051. ) and
  11052. {$endif x86_64}
  11053. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  11054. )
  11055. ) then
  11056. begin
  11057. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  11058. RemoveCurrentP(p, hp1);
  11059. Result := True;
  11060. Exit;
  11061. end;
  11062. A_ADD,
  11063. A_AND,
  11064. A_BSF,
  11065. A_BSR,
  11066. A_BTC,
  11067. A_BTR,
  11068. A_BTS,
  11069. A_OR,
  11070. A_SUB,
  11071. A_XOR:
  11072. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  11073. if (
  11074. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11075. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11076. ) and
  11077. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  11078. begin
  11079. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  11080. RemoveCurrentP(p, hp1);
  11081. Result := True;
  11082. Exit;
  11083. end;
  11084. A_CMP,
  11085. A_TEST:
  11086. if (
  11087. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11088. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11089. ) and
  11090. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  11091. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  11092. begin
  11093. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  11094. RemoveCurrentP(p, hp1);
  11095. Result := True;
  11096. Exit;
  11097. end;
  11098. A_BSWAP,
  11099. A_NEG,
  11100. A_NOT:
  11101. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  11102. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  11103. begin
  11104. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  11105. RemoveCurrentP(p, hp1);
  11106. Result := True;
  11107. Exit;
  11108. end;
  11109. else
  11110. ;
  11111. end;
  11112. end;
  11113. if (taicpu(hp1).is_jmp) and
  11114. (taicpu(hp1).opcode<>A_JMP) and
  11115. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  11116. begin
  11117. { change
  11118. and x, reg
  11119. jxx
  11120. to
  11121. test x, reg
  11122. jxx
  11123. if reg is deallocated before the
  11124. jump, but only if it's a conditional jump (PFV)
  11125. }
  11126. taicpu(p).opcode := A_TEST;
  11127. Exit;
  11128. end;
  11129. Break;
  11130. end;
  11131. { Lone AND tests }
  11132. if (taicpu(p).oper[0]^.typ = top_const) then
  11133. begin
  11134. {
  11135. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  11136. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  11137. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  11138. }
  11139. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  11140. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  11141. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  11142. begin
  11143. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  11144. if taicpu(p).opsize = S_L then
  11145. begin
  11146. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  11147. Result := True;
  11148. end;
  11149. end;
  11150. end;
  11151. { Backward check to determine necessity of and %reg,%reg }
  11152. if (taicpu(p).oper[0]^.typ = top_reg) and
  11153. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  11154. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11155. GetLastInstruction(p, hp2) and
  11156. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  11157. { Check size of adjacent instruction to determine if the AND is
  11158. effectively a null operation }
  11159. (
  11160. (taicpu(p).opsize = taicpu(hp2).opsize) or
  11161. { Note: Don't include S_Q }
  11162. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  11163. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  11164. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  11165. ) then
  11166. begin
  11167. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  11168. { If GetNextInstruction returned False, hp1 will be nil }
  11169. RemoveCurrentP(p, hp1);
  11170. Result := True;
  11171. Exit;
  11172. end;
  11173. end;
  11174. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  11175. var
  11176. hp1: tai; NewRef: TReference;
  11177. { This entire nested function is used in an if-statement below, but we
  11178. want to avoid all the used reg transfers and GetNextInstruction calls
  11179. until we really have to check }
  11180. function MemRegisterNotUsedLater: Boolean; inline;
  11181. var
  11182. hp2: tai;
  11183. begin
  11184. TransferUsedRegs(TmpUsedRegs);
  11185. hp2 := p;
  11186. repeat
  11187. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  11188. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  11189. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  11190. end;
  11191. begin
  11192. Result := False;
  11193. if not GetNextInstruction(p, hp1) or (hp1.typ <> ait_instruction) then
  11194. Exit;
  11195. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) then
  11196. begin
  11197. { Change:
  11198. add %reg2,%reg1
  11199. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  11200. To:
  11201. mov/s/z #(%reg1,%reg2),%reg1
  11202. }
  11203. if MatchOpType(taicpu(p), top_reg, top_reg) and
  11204. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  11205. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  11206. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  11207. (
  11208. (
  11209. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  11210. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  11211. { r/esp cannot be an index }
  11212. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  11213. ) or (
  11214. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  11215. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  11216. )
  11217. ) and (
  11218. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  11219. (
  11220. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  11221. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  11222. MemRegisterNotUsedLater
  11223. )
  11224. ) then
  11225. begin
  11226. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  11227. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  11228. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  11229. RemoveCurrentp(p, hp1);
  11230. Result := True;
  11231. Exit;
  11232. end;
  11233. { Change:
  11234. addl/q $x,%reg1
  11235. movl/q %reg1,%reg2
  11236. To:
  11237. leal/q $x(%reg1),%reg2
  11238. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  11239. Breaks the dependency chain.
  11240. }
  11241. if MatchOpType(taicpu(p),top_const,top_reg) and
  11242. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  11243. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11244. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  11245. (
  11246. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  11247. not (cs_opt_size in current_settings.optimizerswitches) or
  11248. (
  11249. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  11250. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  11251. )
  11252. ) then
  11253. begin
  11254. { Change the MOV instruction to a LEA instruction, and update the
  11255. first operand }
  11256. reference_reset(NewRef, 1, []);
  11257. NewRef.base := taicpu(p).oper[1]^.reg;
  11258. NewRef.scalefactor := 1;
  11259. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  11260. taicpu(hp1).opcode := A_LEA;
  11261. taicpu(hp1).loadref(0, NewRef);
  11262. TransferUsedRegs(TmpUsedRegs);
  11263. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11264. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  11265. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  11266. begin
  11267. { Move what is now the LEA instruction to before the SUB instruction }
  11268. Asml.Remove(hp1);
  11269. Asml.InsertBefore(hp1, p);
  11270. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  11271. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  11272. p := hp1;
  11273. end
  11274. else
  11275. begin
  11276. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  11277. RemoveCurrentP(p, hp1);
  11278. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', p);
  11279. end;
  11280. Result := True;
  11281. end;
  11282. end;
  11283. end;
  11284. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  11285. var
  11286. SubReg: TSubRegister;
  11287. begin
  11288. Result:=false;
  11289. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  11290. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11291. with taicpu(p).oper[0]^.ref^ do
  11292. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  11293. begin
  11294. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  11295. begin
  11296. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  11297. taicpu(p).opcode := A_ADD;
  11298. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  11299. Result := True;
  11300. end
  11301. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  11302. begin
  11303. if (base <> NR_NO) then
  11304. begin
  11305. if (scalefactor <= 1) then
  11306. begin
  11307. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  11308. taicpu(p).opcode := A_ADD;
  11309. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  11310. Result := True;
  11311. end;
  11312. end
  11313. else
  11314. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  11315. if (scalefactor in [2, 4, 8]) then
  11316. begin
  11317. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  11318. taicpu(p).loadconst(0, BsrByte(scalefactor));
  11319. taicpu(p).opcode := A_SHL;
  11320. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  11321. Result := True;
  11322. end;
  11323. end;
  11324. end;
  11325. end;
  11326. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  11327. var
  11328. hp1: tai; NewRef: TReference;
  11329. begin
  11330. { Change:
  11331. subl/q $x,%reg1
  11332. movl/q %reg1,%reg2
  11333. To:
  11334. leal/q $-x(%reg1),%reg2
  11335. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  11336. Breaks the dependency chain and potentially permits the removal of
  11337. a CMP instruction if one follows.
  11338. }
  11339. Result := False;
  11340. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  11341. MatchOpType(taicpu(p),top_const,top_reg) and
  11342. GetNextInstruction(p, hp1) and
  11343. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  11344. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11345. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  11346. (
  11347. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  11348. not (cs_opt_size in current_settings.optimizerswitches) or
  11349. (
  11350. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  11351. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  11352. )
  11353. ) then
  11354. begin
  11355. { Change the MOV instruction to a LEA instruction, and update the
  11356. first operand }
  11357. reference_reset(NewRef, 1, []);
  11358. NewRef.base := taicpu(p).oper[1]^.reg;
  11359. NewRef.scalefactor := 1;
  11360. NewRef.offset := -taicpu(p).oper[0]^.val;
  11361. taicpu(hp1).opcode := A_LEA;
  11362. taicpu(hp1).loadref(0, NewRef);
  11363. TransferUsedRegs(TmpUsedRegs);
  11364. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11365. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  11366. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  11367. begin
  11368. { Move what is now the LEA instruction to before the SUB instruction }
  11369. Asml.Remove(hp1);
  11370. Asml.InsertBefore(hp1, p);
  11371. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  11372. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  11373. p := hp1;
  11374. end
  11375. else
  11376. begin
  11377. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  11378. RemoveCurrentP(p, hp1);
  11379. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', p);
  11380. end;
  11381. Result := True;
  11382. end;
  11383. end;
  11384. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  11385. begin
  11386. { we can skip all instructions not messing with the stack pointer }
  11387. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  11388. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  11389. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  11390. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  11391. ({(taicpu(hp1).ops=0) or }
  11392. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  11393. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  11394. ) and }
  11395. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  11396. )
  11397. ) do
  11398. GetNextInstruction(hp1,hp1);
  11399. Result:=assigned(hp1);
  11400. end;
  11401. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  11402. var
  11403. hp1, hp2, hp3, hp4, hp5: tai;
  11404. begin
  11405. Result:=false;
  11406. hp5:=nil;
  11407. { replace
  11408. leal(q) x(<stackpointer>),<stackpointer>
  11409. call procname
  11410. leal(q) -x(<stackpointer>),<stackpointer>
  11411. ret
  11412. by
  11413. jmp procname
  11414. but do it only on level 4 because it destroys stack back traces
  11415. }
  11416. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11417. MatchOpType(taicpu(p),top_ref,top_reg) and
  11418. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  11419. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  11420. { the -8 or -24 are not required, but bail out early if possible,
  11421. higher values are unlikely }
  11422. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  11423. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  11424. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  11425. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  11426. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  11427. GetNextInstruction(p, hp1) and
  11428. { Take a copy of hp1 }
  11429. SetAndTest(hp1, hp4) and
  11430. { trick to skip label }
  11431. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  11432. SkipSimpleInstructions(hp1) and
  11433. MatchInstruction(hp1,A_CALL,[S_NO]) and
  11434. GetNextInstruction(hp1, hp2) and
  11435. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  11436. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  11437. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  11438. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  11439. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  11440. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  11441. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  11442. { Segment register will be NR_NO }
  11443. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  11444. GetNextInstruction(hp2, hp3) and
  11445. { trick to skip label }
  11446. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  11447. (MatchInstruction(hp3,A_RET,[S_NO]) or
  11448. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  11449. SetAndTest(hp3,hp5) and
  11450. GetNextInstruction(hp3,hp3) and
  11451. MatchInstruction(hp3,A_RET,[S_NO])
  11452. )
  11453. ) and
  11454. (taicpu(hp3).ops=0) then
  11455. begin
  11456. taicpu(hp1).opcode := A_JMP;
  11457. taicpu(hp1).is_jmp := true;
  11458. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  11459. RemoveCurrentP(p, hp4);
  11460. RemoveInstruction(hp2);
  11461. RemoveInstruction(hp3);
  11462. if Assigned(hp5) then
  11463. begin
  11464. AsmL.Remove(hp5);
  11465. ASmL.InsertBefore(hp5,hp1)
  11466. end;
  11467. Result:=true;
  11468. end;
  11469. end;
  11470. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  11471. {$ifdef x86_64}
  11472. var
  11473. hp1, hp2, hp3, hp4, hp5: tai;
  11474. {$endif x86_64}
  11475. begin
  11476. Result:=false;
  11477. {$ifdef x86_64}
  11478. hp5:=nil;
  11479. { replace
  11480. push %rax
  11481. call procname
  11482. pop %rcx
  11483. ret
  11484. by
  11485. jmp procname
  11486. but do it only on level 4 because it destroys stack back traces
  11487. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  11488. for all supported calling conventions
  11489. }
  11490. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11491. MatchOpType(taicpu(p),top_reg) and
  11492. (taicpu(p).oper[0]^.reg=NR_RAX) and
  11493. GetNextInstruction(p, hp1) and
  11494. { Take a copy of hp1 }
  11495. SetAndTest(hp1, hp4) and
  11496. { trick to skip label }
  11497. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  11498. SkipSimpleInstructions(hp1) and
  11499. MatchInstruction(hp1,A_CALL,[S_NO]) and
  11500. GetNextInstruction(hp1, hp2) and
  11501. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  11502. MatchOpType(taicpu(hp2),top_reg) and
  11503. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  11504. GetNextInstruction(hp2, hp3) and
  11505. { trick to skip label }
  11506. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  11507. (MatchInstruction(hp3,A_RET,[S_NO]) or
  11508. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  11509. SetAndTest(hp3,hp5) and
  11510. GetNextInstruction(hp3,hp3) and
  11511. MatchInstruction(hp3,A_RET,[S_NO])
  11512. )
  11513. ) and
  11514. (taicpu(hp3).ops=0) then
  11515. begin
  11516. taicpu(hp1).opcode := A_JMP;
  11517. taicpu(hp1).is_jmp := true;
  11518. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  11519. RemoveCurrentP(p, hp4);
  11520. RemoveInstruction(hp2);
  11521. RemoveInstruction(hp3);
  11522. if Assigned(hp5) then
  11523. begin
  11524. AsmL.Remove(hp5);
  11525. ASmL.InsertBefore(hp5,hp1)
  11526. end;
  11527. Result:=true;
  11528. end;
  11529. {$endif x86_64}
  11530. end;
  11531. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  11532. var
  11533. Value, RegName: string;
  11534. begin
  11535. Result:=false;
  11536. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  11537. begin
  11538. case taicpu(p).oper[0]^.val of
  11539. 0:
  11540. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  11541. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11542. begin
  11543. { change "mov $0,%reg" into "xor %reg,%reg" }
  11544. taicpu(p).opcode := A_XOR;
  11545. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  11546. Result := True;
  11547. {$ifdef x86_64}
  11548. end
  11549. else if (taicpu(p).opsize = S_Q) then
  11550. begin
  11551. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  11552. { The actual optimization }
  11553. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11554. taicpu(p).changeopsize(S_L);
  11555. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  11556. Result := True;
  11557. end;
  11558. $1..$FFFFFFFF:
  11559. begin
  11560. { Code size reduction by J. Gareth "Kit" Moreton }
  11561. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  11562. case taicpu(p).opsize of
  11563. S_Q:
  11564. begin
  11565. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  11566. Value := debug_tostr(taicpu(p).oper[0]^.val);
  11567. { The actual optimization }
  11568. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11569. taicpu(p).changeopsize(S_L);
  11570. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  11571. Result := True;
  11572. end;
  11573. else
  11574. { Do nothing };
  11575. end;
  11576. {$endif x86_64}
  11577. end;
  11578. -1:
  11579. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  11580. if (cs_opt_size in current_settings.optimizerswitches) and
  11581. (taicpu(p).opsize <> S_B) and
  11582. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11583. begin
  11584. { change "mov $-1,%reg" into "or $-1,%reg" }
  11585. { NOTES:
  11586. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  11587. - This operation creates a false dependency on the register, so only do it when optimising for size
  11588. - 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
  11589. }
  11590. taicpu(p).opcode := A_OR;
  11591. Result := True;
  11592. end;
  11593. else
  11594. { Do nothing };
  11595. end;
  11596. end;
  11597. end;
  11598. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  11599. var
  11600. hp1: tai;
  11601. begin
  11602. { Detect:
  11603. andw x, %ax (0 <= x < $8000)
  11604. ...
  11605. movzwl %ax,%eax
  11606. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  11607. }
  11608. Result := False; if MatchOpType(taicpu(p), top_const, top_reg) and
  11609. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  11610. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  11611. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11612. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11613. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11614. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11615. begin
  11616. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  11617. taicpu(hp1).opcode := A_CWDE;
  11618. taicpu(hp1).clearop(0);
  11619. taicpu(hp1).clearop(1);
  11620. taicpu(hp1).ops := 0;
  11621. { A change was made, but not with p, so move forward 1 }
  11622. p := tai(p.Next);
  11623. Result := True;
  11624. end;
  11625. end;
  11626. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  11627. begin
  11628. Result := False;
  11629. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  11630. Exit;
  11631. { Convert:
  11632. movswl %ax,%eax -> cwtl
  11633. movslq %eax,%rax -> cdqe
  11634. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  11635. refer to the same opcode and depends only on the assembler's
  11636. current operand-size attribute. [Kit]
  11637. }
  11638. with taicpu(p) do
  11639. case opsize of
  11640. S_WL:
  11641. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  11642. begin
  11643. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  11644. opcode := A_CWDE;
  11645. clearop(0);
  11646. clearop(1);
  11647. ops := 0;
  11648. Result := True;
  11649. end;
  11650. {$ifdef x86_64}
  11651. S_LQ:
  11652. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  11653. begin
  11654. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  11655. opcode := A_CDQE;
  11656. clearop(0);
  11657. clearop(1);
  11658. ops := 0;
  11659. Result := True;
  11660. end;
  11661. {$endif x86_64}
  11662. else
  11663. ;
  11664. end;
  11665. end;
  11666. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  11667. var
  11668. hp1: tai;
  11669. begin
  11670. { Detect:
  11671. shr x, %ax (x > 0)
  11672. ...
  11673. movzwl %ax,%eax
  11674. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  11675. }
  11676. Result := False;
  11677. if MatchOpType(taicpu(p), top_const, top_reg) and
  11678. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  11679. (taicpu(p).oper[0]^.val > 0) and
  11680. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11681. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11682. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11683. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11684. begin
  11685. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  11686. taicpu(hp1).opcode := A_CWDE;
  11687. taicpu(hp1).clearop(0);
  11688. taicpu(hp1).clearop(1);
  11689. taicpu(hp1).ops := 0;
  11690. { A change was made, but not with p, so move forward 1 }
  11691. p := tai(p.Next);
  11692. Result := True;
  11693. end;
  11694. end;
  11695. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  11696. var
  11697. hp1, hp2: tai;
  11698. Opposite, SecondOpposite: TAsmOp;
  11699. NewCond: TAsmCond;
  11700. begin
  11701. Result := False;
  11702. { Change:
  11703. add/sub 128,(dest)
  11704. To:
  11705. sub/add -128,(dest)
  11706. This generaally takes fewer bytes to encode because -128 can be stored
  11707. in a signed byte, whereas +128 cannot.
  11708. }
  11709. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  11710. begin
  11711. if taicpu(p).opcode = A_ADD then
  11712. Opposite := A_SUB
  11713. else
  11714. Opposite := A_ADD;
  11715. { Be careful if the flags are in use, because the CF flag inverts
  11716. when changing from ADD to SUB and vice versa }
  11717. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11718. GetNextInstruction(p, hp1) then
  11719. begin
  11720. TransferUsedRegs(TmpUsedRegs);
  11721. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  11722. hp2 := hp1;
  11723. { Scan ahead to check if everything's safe }
  11724. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  11725. begin
  11726. if (hp1.typ <> ait_instruction) then
  11727. { Probably unsafe since the flags are still in use }
  11728. Exit;
  11729. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  11730. { Stop searching at an unconditional jump }
  11731. Break;
  11732. if not
  11733. (
  11734. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  11735. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  11736. ) and
  11737. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  11738. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  11739. Exit;
  11740. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11741. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  11742. { Move to the next instruction }
  11743. GetNextInstruction(hp1, hp1);
  11744. end;
  11745. while Assigned(hp2) and (hp2 <> hp1) do
  11746. begin
  11747. NewCond := C_None;
  11748. case taicpu(hp2).condition of
  11749. C_A, C_NBE:
  11750. NewCond := C_BE;
  11751. C_B, C_C, C_NAE:
  11752. NewCond := C_AE;
  11753. C_AE, C_NB, C_NC:
  11754. NewCond := C_B;
  11755. C_BE, C_NA:
  11756. NewCond := C_A;
  11757. else
  11758. { No change needed };
  11759. end;
  11760. if NewCond <> C_None then
  11761. begin
  11762. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  11763. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  11764. taicpu(hp2).condition := NewCond;
  11765. end
  11766. else
  11767. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  11768. begin
  11769. { Because of the flipping of the carry bit, to ensure
  11770. the operation remains equivalent, ADC becomes SBB
  11771. and vice versa, and the constant is not-inverted.
  11772. If multiple ADCs or SBBs appear in a row, each one
  11773. changed causes the carry bit to invert, so they all
  11774. need to be flipped }
  11775. if taicpu(hp2).opcode = A_ADC then
  11776. SecondOpposite := A_SBB
  11777. else
  11778. SecondOpposite := A_ADC;
  11779. if taicpu(hp2).oper[0]^.typ <> top_const then
  11780. { Should have broken out of this optimisation already }
  11781. InternalError(2021112901);
  11782. 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]^) + ' -> ' +
  11783. 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);
  11784. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  11785. taicpu(hp2).opcode := SecondOpposite;
  11786. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  11787. end;
  11788. { Move to the next instruction }
  11789. GetNextInstruction(hp2, hp2);
  11790. end;
  11791. if (hp2 <> hp1) then
  11792. InternalError(2021111501);
  11793. end;
  11794. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  11795. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  11796. taicpu(p).opcode := Opposite;
  11797. taicpu(p).oper[0]^.val := -128;
  11798. { No further optimisations can be made on this instruction, so move
  11799. onto the next one to save time }
  11800. p := tai(p.Next);
  11801. UpdateUsedRegs(p);
  11802. Result := True;
  11803. Exit;
  11804. end;
  11805. { Detect:
  11806. add/sub %reg2,(dest)
  11807. add/sub x, (dest)
  11808. (dest can be a register or a reference)
  11809. Swap the instructions to minimise a pipeline stall. This reverses the
  11810. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  11811. optimisations could be made.
  11812. }
  11813. if (taicpu(p).oper[0]^.typ = top_reg) and
  11814. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  11815. (
  11816. (
  11817. (taicpu(p).oper[1]^.typ = top_reg) and
  11818. { We can try searching further ahead if we're writing to a register }
  11819. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  11820. ) or
  11821. (
  11822. (taicpu(p).oper[1]^.typ = top_ref) and
  11823. GetNextInstruction(p, hp1)
  11824. )
  11825. ) and
  11826. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  11827. (taicpu(hp1).oper[0]^.typ = top_const) and
  11828. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  11829. begin
  11830. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  11831. TransferUsedRegs(TmpUsedRegs);
  11832. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11833. hp2 := p;
  11834. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  11835. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  11836. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  11837. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  11838. begin
  11839. asml.remove(hp1);
  11840. asml.InsertBefore(hp1, p);
  11841. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  11842. Result := True;
  11843. end;
  11844. end;
  11845. end;
  11846. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  11847. begin
  11848. Result:=false;
  11849. { change "cmp $0, %reg" to "test %reg, %reg" }
  11850. if MatchOpType(taicpu(p),top_const,top_reg) and
  11851. (taicpu(p).oper[0]^.val = 0) then
  11852. begin
  11853. taicpu(p).opcode := A_TEST;
  11854. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  11855. Result:=true;
  11856. end;
  11857. end;
  11858. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  11859. var
  11860. IsTestConstX : Boolean;
  11861. hp1,hp2 : tai;
  11862. begin
  11863. Result:=false;
  11864. { removes the line marked with (x) from the sequence
  11865. and/or/xor/add/sub/... $x, %y
  11866. test/or %y, %y | test $-1, %y (x)
  11867. j(n)z _Label
  11868. as the first instruction already adjusts the ZF
  11869. %y operand may also be a reference }
  11870. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  11871. MatchOperand(taicpu(p).oper[0]^,-1);
  11872. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  11873. GetLastInstruction(p, hp1) and
  11874. (tai(hp1).typ = ait_instruction) and
  11875. GetNextInstruction(p,hp2) and
  11876. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  11877. case taicpu(hp1).opcode Of
  11878. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  11879. { These two instructions set the zero flag if the result is zero }
  11880. A_POPCNT, A_LZCNT:
  11881. begin
  11882. if (
  11883. { With POPCNT, an input of zero will set the zero flag
  11884. because the population count of zero is zero }
  11885. (taicpu(hp1).opcode = A_POPCNT) and
  11886. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  11887. (
  11888. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  11889. { Faster than going through the second half of the 'or'
  11890. condition below }
  11891. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  11892. )
  11893. ) or (
  11894. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  11895. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11896. { and in case of carry for A(E)/B(E)/C/NC }
  11897. (
  11898. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  11899. (
  11900. (taicpu(hp1).opcode <> A_ADD) and
  11901. (taicpu(hp1).opcode <> A_SUB) and
  11902. (taicpu(hp1).opcode <> A_LZCNT)
  11903. )
  11904. )
  11905. ) then
  11906. begin
  11907. RemoveCurrentP(p, hp2);
  11908. Result:=true;
  11909. Exit;
  11910. end;
  11911. end;
  11912. A_SHL, A_SAL, A_SHR, A_SAR:
  11913. begin
  11914. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  11915. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  11916. { therefore, it's only safe to do this optimization for }
  11917. { shifts by a (nonzero) constant }
  11918. (taicpu(hp1).oper[0]^.typ = top_const) and
  11919. (taicpu(hp1).oper[0]^.val <> 0) and
  11920. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11921. { and in case of carry for A(E)/B(E)/C/NC }
  11922. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11923. begin
  11924. RemoveCurrentP(p, hp2);
  11925. Result:=true;
  11926. Exit;
  11927. end;
  11928. end;
  11929. A_DEC, A_INC, A_NEG:
  11930. begin
  11931. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  11932. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11933. { and in case of carry for A(E)/B(E)/C/NC }
  11934. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11935. begin
  11936. RemoveCurrentP(p, hp2);
  11937. Result:=true;
  11938. Exit;
  11939. end;
  11940. end
  11941. else
  11942. ;
  11943. end; { case }
  11944. { change "test $-1,%reg" into "test %reg,%reg" }
  11945. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  11946. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  11947. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  11948. if MatchInstruction(p, A_OR, []) and
  11949. { Can only match if they're both registers }
  11950. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  11951. begin
  11952. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  11953. taicpu(p).opcode := A_TEST;
  11954. { No need to set Result to True, as we've done all the optimisations we can }
  11955. end;
  11956. end;
  11957. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  11958. var
  11959. hp1,hp3 : tai;
  11960. {$ifndef x86_64}
  11961. hp2 : taicpu;
  11962. {$endif x86_64}
  11963. begin
  11964. Result:=false;
  11965. hp3:=nil;
  11966. {$ifndef x86_64}
  11967. { don't do this on modern CPUs, this really hurts them due to
  11968. broken call/ret pairing }
  11969. if (current_settings.optimizecputype < cpu_Pentium2) and
  11970. not(cs_create_pic in current_settings.moduleswitches) and
  11971. GetNextInstruction(p, hp1) and
  11972. MatchInstruction(hp1,A_JMP,[S_NO]) and
  11973. MatchOpType(taicpu(hp1),top_ref) and
  11974. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  11975. begin
  11976. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  11977. InsertLLItem(p.previous, p, hp2);
  11978. taicpu(p).opcode := A_JMP;
  11979. taicpu(p).is_jmp := true;
  11980. RemoveInstruction(hp1);
  11981. Result:=true;
  11982. end
  11983. else
  11984. {$endif x86_64}
  11985. { replace
  11986. call procname
  11987. ret
  11988. by
  11989. jmp procname
  11990. but do it only on level 4 because it destroys stack back traces
  11991. else if the subroutine is marked as no return, remove the ret
  11992. }
  11993. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  11994. (po_noreturn in current_procinfo.procdef.procoptions)) and
  11995. GetNextInstruction(p, hp1) and
  11996. (MatchInstruction(hp1,A_RET,[S_NO]) or
  11997. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  11998. SetAndTest(hp1,hp3) and
  11999. GetNextInstruction(hp1,hp1) and
  12000. MatchInstruction(hp1,A_RET,[S_NO])
  12001. )
  12002. ) and
  12003. (taicpu(hp1).ops=0) then
  12004. begin
  12005. if (cs_opt_level4 in current_settings.optimizerswitches) and
  12006. { we might destroy stack alignment here if we do not do a call }
  12007. (target_info.stackalign<=sizeof(SizeUInt)) then
  12008. begin
  12009. taicpu(p).opcode := A_JMP;
  12010. taicpu(p).is_jmp := true;
  12011. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  12012. end
  12013. else
  12014. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  12015. RemoveInstruction(hp1);
  12016. if Assigned(hp3) then
  12017. begin
  12018. AsmL.Remove(hp3);
  12019. AsmL.InsertBefore(hp3,p)
  12020. end;
  12021. Result:=true;
  12022. end;
  12023. end;
  12024. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  12025. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  12026. begin
  12027. case OpSize of
  12028. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12029. Result := (Val <= $FF) and (Val >= -128);
  12030. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12031. Result := (Val <= $FFFF) and (Val >= -32768);
  12032. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  12033. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  12034. else
  12035. Result := True;
  12036. end;
  12037. end;
  12038. var
  12039. hp1, hp2 : tai;
  12040. SizeChange: Boolean;
  12041. PreMessage: string;
  12042. begin
  12043. Result := False;
  12044. if (taicpu(p).oper[0]^.typ = top_reg) and
  12045. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12046. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  12047. begin
  12048. { Change (using movzbl %al,%eax as an example):
  12049. movzbl %al, %eax movzbl %al, %eax
  12050. cmpl x, %eax testl %eax,%eax
  12051. To:
  12052. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  12053. movzbl %al, %eax movzbl %al, %eax
  12054. Smaller instruction and minimises pipeline stall as the CPU
  12055. doesn't have to wait for the register to get zero-extended. [Kit]
  12056. Also allow if the smaller of the two registers is being checked,
  12057. as this still removes the false dependency.
  12058. }
  12059. if
  12060. (
  12061. (
  12062. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  12063. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  12064. ) or (
  12065. { If MatchOperand returns True, they must both be registers }
  12066. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  12067. )
  12068. ) and
  12069. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  12070. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  12071. begin
  12072. 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);
  12073. asml.Remove(hp1);
  12074. asml.InsertBefore(hp1, p);
  12075. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  12076. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  12077. begin
  12078. taicpu(hp1).opcode := A_TEST;
  12079. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  12080. end;
  12081. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  12082. case taicpu(p).opsize of
  12083. S_BW, S_BL:
  12084. begin
  12085. SizeChange := taicpu(hp1).opsize <> S_B;
  12086. taicpu(hp1).changeopsize(S_B);
  12087. end;
  12088. S_WL:
  12089. begin
  12090. SizeChange := taicpu(hp1).opsize <> S_W;
  12091. taicpu(hp1).changeopsize(S_W);
  12092. end
  12093. else
  12094. InternalError(2020112701);
  12095. end;
  12096. UpdateUsedRegs(tai(p.Next));
  12097. { Check if the register is used aferwards - if not, we can
  12098. remove the movzx instruction completely }
  12099. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  12100. begin
  12101. { Hp1 is a better position than p for debugging purposes }
  12102. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  12103. RemoveCurrentp(p, hp1);
  12104. Result := True;
  12105. end;
  12106. if SizeChange then
  12107. DebugMsg(SPeepholeOptimization + PreMessage +
  12108. 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)
  12109. else
  12110. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  12111. Exit;
  12112. end;
  12113. { Change (using movzwl %ax,%eax as an example):
  12114. movzwl %ax, %eax
  12115. movb %al, (dest) (Register is smaller than read register in movz)
  12116. To:
  12117. movb %al, (dest) (Move one back to avoid a false dependency)
  12118. movzwl %ax, %eax
  12119. }
  12120. if (taicpu(hp1).opcode = A_MOV) and
  12121. (taicpu(hp1).oper[0]^.typ = top_reg) and
  12122. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  12123. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  12124. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  12125. begin
  12126. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  12127. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  12128. asml.Remove(hp1);
  12129. asml.InsertBefore(hp1, p);
  12130. if taicpu(hp1).oper[1]^.typ = top_reg then
  12131. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  12132. { Check if the register is used aferwards - if not, we can
  12133. remove the movzx instruction completely }
  12134. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  12135. begin
  12136. { Hp1 is a better position than p for debugging purposes }
  12137. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  12138. RemoveCurrentp(p, hp1);
  12139. Result := True;
  12140. end;
  12141. Exit;
  12142. end;
  12143. end;
  12144. end;
  12145. {$ifdef x86_64}
  12146. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  12147. var
  12148. PreMessage, RegName: string;
  12149. begin
  12150. { Code size reduction by J. Gareth "Kit" Moreton }
  12151. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  12152. as this removes the REX prefix }
  12153. Result := False;
  12154. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  12155. Exit;
  12156. if taicpu(p).oper[0]^.typ <> top_reg then
  12157. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  12158. InternalError(2018011500);
  12159. case taicpu(p).opsize of
  12160. S_Q:
  12161. begin
  12162. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  12163. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  12164. { The actual optimization }
  12165. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12166. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  12167. taicpu(p).changeopsize(S_L);
  12168. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  12169. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  12170. end;
  12171. else
  12172. ;
  12173. end;
  12174. end;
  12175. {$endif}
  12176. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  12177. var
  12178. XReg: TRegister;
  12179. begin
  12180. Result := False;
  12181. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  12182. Smaller encoding and slightly faster on some platforms (also works for
  12183. ZMM-sized registers) }
  12184. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  12185. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  12186. begin
  12187. XReg := taicpu(p).oper[0]^.reg;
  12188. if (taicpu(p).oper[1]^.reg = XReg) then
  12189. begin
  12190. taicpu(p).changeopsize(S_XMM);
  12191. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  12192. if (cs_opt_size in current_settings.optimizerswitches) then
  12193. begin
  12194. { Change input registers to %xmm0 to reduce size. Note that
  12195. there's a risk of a false dependency doing this, so only
  12196. optimise for size here }
  12197. XReg := NR_XMM0;
  12198. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  12199. end
  12200. else
  12201. begin
  12202. setsubreg(XReg, R_SUBMMX);
  12203. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  12204. end;
  12205. taicpu(p).oper[0]^.reg := XReg;
  12206. taicpu(p).oper[1]^.reg := XReg;
  12207. Result := True;
  12208. end;
  12209. end;
  12210. end;
  12211. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  12212. var
  12213. OperIdx: Integer;
  12214. begin
  12215. for OperIdx := 0 to p.ops - 1 do
  12216. if p.oper[OperIdx]^.typ = top_ref then
  12217. optimize_ref(p.oper[OperIdx]^.ref^, False);
  12218. end;
  12219. end.