aoptx86.pas 459 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697
  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. {$ifdef EXTDEBUG}
  20. {$define DEBUG_AOPTCPU}
  21. {$endif EXTDEBUG}
  22. interface
  23. uses
  24. globtype,
  25. cpubase,
  26. aasmtai,aasmcpu,
  27. cgbase,cgutils,
  28. aopt,aoptobj;
  29. type
  30. TOptsToCheck = (
  31. aoc_MovAnd2Mov_3
  32. );
  33. TX86AsmOptimizer = class(TAsmOptimizer)
  34. { some optimizations are very expensive to check, so the
  35. pre opt pass can be used to set some flags, depending on the found
  36. instructions if it is worth to check a certain optimization }
  37. OptsToCheck : set of TOptsToCheck;
  38. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  39. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  40. function RegReadByInstruction(reg : TRegister; hp : tai) : boolean;
  41. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  42. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  43. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  44. potentially allowing further optimisation (although it might need to know if
  45. it crossed a conditional jump. }
  46. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  47. {
  48. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  49. the use of a register by allocs/dealloc, so it can ignore calls.
  50. In the following example, GetNextInstructionUsingReg will return the second movq,
  51. GetNextInstructionUsingRegTrackingUse won't.
  52. movq %rdi,%rax
  53. # Register rdi released
  54. # Register rdi allocated
  55. movq %rax,%rdi
  56. While in this example:
  57. movq %rdi,%rax
  58. call proc
  59. movq %rdi,%rax
  60. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  61. won't.
  62. }
  63. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  64. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  65. private
  66. function SkipSimpleInstructions(var hp1: tai): Boolean;
  67. protected
  68. class function IsMOVZXAcceptable: Boolean; static; inline;
  69. { Attempts to allocate a volatile integer register for use between p and hp,
  70. using AUsedRegs for the current register usage information. Returns NR_NO
  71. if no free register could be found }
  72. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  73. { Attempts to allocate a volatile MM register for use between p and hp,
  74. using AUsedRegs for the current register usage information. Returns NR_NO
  75. if no free register could be found }
  76. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  77. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  78. function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  79. { checks whether reading the value in reg1 depends on the value of reg2. This
  80. is very similar to SuperRegisterEquals, except it takes into account that
  81. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  82. depend on the value in AH). }
  83. function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  84. { Replaces all references to AOldReg in a memory reference to ANewReg }
  85. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  86. { Replaces all references to AOldReg in an operand to ANewReg }
  87. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  88. { Replaces all references to AOldReg in an instruction to ANewReg,
  89. except where the register is being written }
  90. function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  91. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  92. or writes to a global symbol }
  93. class function IsRefSafe(const ref: PReference): Boolean; static;
  94. { Returns true if the given MOV instruction can be safely converted to CMOV }
  95. class function CanBeCMOV(p : tai) : boolean; static;
  96. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  97. conversion was successful }
  98. function ConvertLEA(const p : taicpu): Boolean;
  99. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  100. procedure DebugMsg(const s : string; p : tai);inline;
  101. class function IsExitCode(p : tai) : boolean; static;
  102. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  103. procedure RemoveLastDeallocForFuncRes(p : tai);
  104. function DoSubAddOpt(var p : tai) : Boolean;
  105. function PrePeepholeOptSxx(var p : tai) : boolean;
  106. function PrePeepholeOptIMUL(var p : tai) : boolean;
  107. function PrePeepholeOptAND(var p : tai) : boolean;
  108. function OptPass1Test(var p: tai): boolean;
  109. function OptPass1Add(var p: tai): boolean;
  110. function OptPass1AND(var p : tai) : boolean;
  111. function OptPass1_V_MOVAP(var p : tai) : boolean;
  112. function OptPass1VOP(var p : tai) : boolean;
  113. function OptPass1MOV(var p : tai) : boolean;
  114. function OptPass1Movx(var p : tai) : boolean;
  115. function OptPass1MOVXX(var p : tai) : boolean;
  116. function OptPass1OP(var p : tai) : boolean;
  117. function OptPass1LEA(var p : tai) : boolean;
  118. function OptPass1Sub(var p : tai) : boolean;
  119. function OptPass1SHLSAL(var p : tai) : boolean;
  120. function OptPass1FSTP(var p : tai) : boolean;
  121. function OptPass1FLD(var p : tai) : boolean;
  122. function OptPass1Cmp(var p : tai) : boolean;
  123. function OptPass1PXor(var p : tai) : boolean;
  124. function OptPass1VPXor(var p: tai): boolean;
  125. function OptPass1Imul(var p : tai) : boolean;
  126. function OptPass1Jcc(var p : tai) : boolean;
  127. function OptPass1SHXX(var p: tai): boolean;
  128. function OptPass1VMOVDQ(var p: tai): Boolean;
  129. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  130. function OptPass2Movx(var p : tai): Boolean;
  131. function OptPass2MOV(var p : tai) : boolean;
  132. function OptPass2Imul(var p : tai) : boolean;
  133. function OptPass2Jmp(var p : tai) : boolean;
  134. function OptPass2Jcc(var p : tai) : boolean;
  135. function OptPass2Lea(var p: tai): Boolean;
  136. function OptPass2SUB(var p: tai): Boolean;
  137. function OptPass2ADD(var p : tai): Boolean;
  138. function OptPass2SETcc(var p : tai) : boolean;
  139. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  140. function PostPeepholeOptMov(var p : tai) : Boolean;
  141. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  142. {$ifdef x86_64} { These post-peephole optimisations only affect 64-bit registers. [Kit] }
  143. function PostPeepholeOptXor(var p : tai) : Boolean;
  144. {$endif x86_64}
  145. function PostPeepholeOptAnd(var p : tai) : boolean;
  146. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  147. function PostPeepholeOptCmp(var p : tai) : Boolean;
  148. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  149. function PostPeepholeOptCall(var p : tai) : Boolean;
  150. function PostPeepholeOptLea(var p : tai) : Boolean;
  151. function PostPeepholeOptPush(var p: tai): Boolean;
  152. function PostPeepholeOptShr(var p : tai) : boolean;
  153. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  154. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  155. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  156. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  157. { Processor-dependent reference optimisation }
  158. class procedure OptimizeRefs(var p: taicpu); static;
  159. end;
  160. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  161. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  162. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  163. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  164. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  165. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  166. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  167. {$if max_operands>2}
  168. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  169. {$endif max_operands>2}
  170. function RefsEqual(const r1, r2: treference): boolean;
  171. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  172. { returns true, if ref is a reference using only the registers passed as base and index
  173. and having an offset }
  174. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  175. implementation
  176. uses
  177. cutils,verbose,
  178. systems,
  179. globals,
  180. cpuinfo,
  181. procinfo,
  182. paramgr,
  183. aasmbase,
  184. aoptbase,aoptutils,
  185. symconst,symsym,
  186. cgx86,
  187. itcpugas;
  188. {$ifdef DEBUG_AOPTCPU}
  189. const
  190. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  191. {$else DEBUG_AOPTCPU}
  192. { Empty strings help the optimizer to remove string concatenations that won't
  193. ever appear to the user on release builds. [Kit] }
  194. const
  195. SPeepholeOptimization = '';
  196. {$endif DEBUG_AOPTCPU}
  197. LIST_STEP_SIZE = 4;
  198. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  199. begin
  200. result :=
  201. (instr.typ = ait_instruction) and
  202. (taicpu(instr).opcode = op) and
  203. ((opsize = []) or (taicpu(instr).opsize in opsize));
  204. end;
  205. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  206. begin
  207. result :=
  208. (instr.typ = ait_instruction) and
  209. ((taicpu(instr).opcode = op1) or
  210. (taicpu(instr).opcode = op2)
  211. ) and
  212. ((opsize = []) or (taicpu(instr).opsize in opsize));
  213. end;
  214. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  215. begin
  216. result :=
  217. (instr.typ = ait_instruction) and
  218. ((taicpu(instr).opcode = op1) or
  219. (taicpu(instr).opcode = op2) or
  220. (taicpu(instr).opcode = op3)
  221. ) and
  222. ((opsize = []) or (taicpu(instr).opsize in opsize));
  223. end;
  224. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  225. const opsize : topsizes) : boolean;
  226. var
  227. op : TAsmOp;
  228. begin
  229. result:=false;
  230. if (instr.typ <> ait_instruction) or
  231. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  232. exit;
  233. for op in ops do
  234. begin
  235. if taicpu(instr).opcode = op then
  236. begin
  237. result:=true;
  238. exit;
  239. end;
  240. end;
  241. end;
  242. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  243. begin
  244. result := (oper.typ = top_reg) and (oper.reg = reg);
  245. end;
  246. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  247. begin
  248. result := (oper.typ = top_const) and (oper.val = a);
  249. end;
  250. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  251. begin
  252. result := oper1.typ = oper2.typ;
  253. if result then
  254. case oper1.typ of
  255. top_const:
  256. Result:=oper1.val = oper2.val;
  257. top_reg:
  258. Result:=oper1.reg = oper2.reg;
  259. top_ref:
  260. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  261. else
  262. internalerror(2013102801);
  263. end
  264. end;
  265. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  266. begin
  267. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  268. if result then
  269. case oper1.typ of
  270. top_const:
  271. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  272. top_reg:
  273. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  274. top_ref:
  275. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  276. else
  277. internalerror(2020052401);
  278. end
  279. end;
  280. function RefsEqual(const r1, r2: treference): boolean;
  281. begin
  282. RefsEqual :=
  283. (r1.offset = r2.offset) and
  284. (r1.segment = r2.segment) and (r1.base = r2.base) and
  285. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  286. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  287. (r1.relsymbol = r2.relsymbol) and
  288. (r1.volatility=[]) and
  289. (r2.volatility=[]);
  290. end;
  291. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  292. begin
  293. Result:=(ref.offset=0) and
  294. (ref.scalefactor in [0,1]) and
  295. (ref.segment=NR_NO) and
  296. (ref.symbol=nil) and
  297. (ref.relsymbol=nil) and
  298. ((base=NR_INVALID) or
  299. (ref.base=base)) and
  300. ((index=NR_INVALID) or
  301. (ref.index=index)) and
  302. (ref.volatility=[]);
  303. end;
  304. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  305. begin
  306. Result:=(ref.scalefactor in [0,1]) and
  307. (ref.segment=NR_NO) and
  308. (ref.symbol=nil) and
  309. (ref.relsymbol=nil) and
  310. ((base=NR_INVALID) or
  311. (ref.base=base)) and
  312. ((index=NR_INVALID) or
  313. (ref.index=index)) and
  314. (ref.volatility=[]);
  315. end;
  316. function InstrReadsFlags(p: tai): boolean;
  317. begin
  318. InstrReadsFlags := true;
  319. case p.typ of
  320. ait_instruction:
  321. if InsProp[taicpu(p).opcode].Ch*
  322. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  323. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  324. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  325. exit;
  326. ait_label:
  327. exit;
  328. else
  329. ;
  330. end;
  331. InstrReadsFlags := false;
  332. end;
  333. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  334. begin
  335. Next:=Current;
  336. repeat
  337. Result:=GetNextInstruction(Next,Next);
  338. until not (Result) or
  339. not(cs_opt_level3 in current_settings.optimizerswitches) or
  340. (Next.typ<>ait_instruction) or
  341. RegInInstruction(reg,Next) or
  342. is_calljmp(taicpu(Next).opcode);
  343. end;
  344. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  345. begin
  346. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  347. Next := Current;
  348. repeat
  349. Result := GetNextInstruction(Next,Next);
  350. if Result and (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  351. if is_calljmpuncondret(taicpu(Next).opcode) then
  352. begin
  353. Result := False;
  354. Exit;
  355. end
  356. else
  357. CrossJump := True;
  358. until not Result or
  359. not (cs_opt_level3 in current_settings.optimizerswitches) or
  360. (Next.typ <> ait_instruction) or
  361. RegInInstruction(reg,Next);
  362. end;
  363. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  364. begin
  365. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  366. begin
  367. Result:=GetNextInstruction(Current,Next);
  368. exit;
  369. end;
  370. Next:=tai(Current.Next);
  371. Result:=false;
  372. while assigned(Next) do
  373. begin
  374. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  375. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  376. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  377. exit
  378. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  379. begin
  380. Result:=true;
  381. exit;
  382. end;
  383. Next:=tai(Next.Next);
  384. end;
  385. end;
  386. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  387. begin
  388. Result:=RegReadByInstruction(reg,hp);
  389. end;
  390. function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  391. var
  392. p: taicpu;
  393. opcount: longint;
  394. begin
  395. RegReadByInstruction := false;
  396. if hp.typ <> ait_instruction then
  397. exit;
  398. p := taicpu(hp);
  399. case p.opcode of
  400. A_CALL:
  401. regreadbyinstruction := true;
  402. A_IMUL:
  403. case p.ops of
  404. 1:
  405. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  406. (
  407. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  408. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  409. );
  410. 2,3:
  411. regReadByInstruction :=
  412. reginop(reg,p.oper[0]^) or
  413. reginop(reg,p.oper[1]^);
  414. else
  415. InternalError(2019112801);
  416. end;
  417. A_MUL:
  418. begin
  419. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  420. (
  421. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  422. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  423. );
  424. end;
  425. A_IDIV,A_DIV:
  426. begin
  427. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  428. (
  429. (getregtype(reg)=R_INTREGISTER) and
  430. (
  431. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  432. )
  433. );
  434. end;
  435. else
  436. begin
  437. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  438. begin
  439. RegReadByInstruction := false;
  440. exit;
  441. end;
  442. for opcount := 0 to p.ops-1 do
  443. if (p.oper[opCount]^.typ = top_ref) and
  444. RegInRef(reg,p.oper[opcount]^.ref^) then
  445. begin
  446. RegReadByInstruction := true;
  447. exit
  448. end;
  449. { special handling for SSE MOVSD }
  450. if (p.opcode=A_MOVSD) and (p.ops>0) then
  451. begin
  452. if p.ops<>2 then
  453. internalerror(2017042702);
  454. regReadByInstruction := reginop(reg,p.oper[0]^) or
  455. (
  456. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  457. );
  458. exit;
  459. end;
  460. with insprop[p.opcode] do
  461. begin
  462. case getregtype(reg) of
  463. R_INTREGISTER:
  464. begin
  465. case getsupreg(reg) of
  466. RS_EAX:
  467. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  468. begin
  469. RegReadByInstruction := true;
  470. exit
  471. end;
  472. RS_ECX:
  473. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  474. begin
  475. RegReadByInstruction := true;
  476. exit
  477. end;
  478. RS_EDX:
  479. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  480. begin
  481. RegReadByInstruction := true;
  482. exit
  483. end;
  484. RS_EBX:
  485. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  486. begin
  487. RegReadByInstruction := true;
  488. exit
  489. end;
  490. RS_ESP:
  491. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  492. begin
  493. RegReadByInstruction := true;
  494. exit
  495. end;
  496. RS_EBP:
  497. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  498. begin
  499. RegReadByInstruction := true;
  500. exit
  501. end;
  502. RS_ESI:
  503. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  504. begin
  505. RegReadByInstruction := true;
  506. exit
  507. end;
  508. RS_EDI:
  509. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  510. begin
  511. RegReadByInstruction := true;
  512. exit
  513. end;
  514. end;
  515. end;
  516. R_MMREGISTER:
  517. begin
  518. case getsupreg(reg) of
  519. RS_XMM0:
  520. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  521. begin
  522. RegReadByInstruction := true;
  523. exit
  524. end;
  525. end;
  526. end;
  527. else
  528. ;
  529. end;
  530. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  531. begin
  532. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  533. begin
  534. case p.condition of
  535. C_A,C_NBE, { CF=0 and ZF=0 }
  536. C_BE,C_NA: { CF=1 or ZF=1 }
  537. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  538. C_AE,C_NB,C_NC, { CF=0 }
  539. C_B,C_NAE,C_C: { CF=1 }
  540. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  541. C_NE,C_NZ, { ZF=0 }
  542. C_E,C_Z: { ZF=1 }
  543. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  544. C_G,C_NLE, { ZF=0 and SF=OF }
  545. C_LE,C_NG: { ZF=1 or SF<>OF }
  546. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  547. C_GE,C_NL, { SF=OF }
  548. C_L,C_NGE: { SF<>OF }
  549. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  550. C_NO, { OF=0 }
  551. C_O: { OF=1 }
  552. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  553. C_NP,C_PO, { PF=0 }
  554. C_P,C_PE: { PF=1 }
  555. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  556. C_NS, { SF=0 }
  557. C_S: { SF=1 }
  558. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  559. else
  560. internalerror(2017042701);
  561. end;
  562. if RegReadByInstruction then
  563. exit;
  564. end;
  565. case getsubreg(reg) of
  566. R_SUBW,R_SUBD,R_SUBQ:
  567. RegReadByInstruction :=
  568. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  569. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  570. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  571. R_SUBFLAGCARRY:
  572. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  573. R_SUBFLAGPARITY:
  574. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  575. R_SUBFLAGAUXILIARY:
  576. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  577. R_SUBFLAGZERO:
  578. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  579. R_SUBFLAGSIGN:
  580. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  581. R_SUBFLAGOVERFLOW:
  582. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  583. R_SUBFLAGINTERRUPT:
  584. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  585. R_SUBFLAGDIRECTION:
  586. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  587. else
  588. internalerror(2017042601);
  589. end;
  590. exit;
  591. end;
  592. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  593. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  594. (p.oper[0]^.reg=p.oper[1]^.reg) then
  595. exit;
  596. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  597. begin
  598. RegReadByInstruction := true;
  599. exit
  600. end;
  601. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  602. begin
  603. RegReadByInstruction := true;
  604. exit
  605. end;
  606. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  607. begin
  608. RegReadByInstruction := true;
  609. exit
  610. end;
  611. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  612. begin
  613. RegReadByInstruction := true;
  614. exit
  615. end;
  616. end;
  617. end;
  618. end;
  619. end;
  620. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  621. begin
  622. result:=false;
  623. if p1.typ<>ait_instruction then
  624. exit;
  625. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  626. exit(true);
  627. if (getregtype(reg)=R_INTREGISTER) and
  628. { change information for xmm movsd are not correct }
  629. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  630. begin
  631. case getsupreg(reg) of
  632. { RS_EAX = RS_RAX on x86-64 }
  633. RS_EAX:
  634. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  635. RS_ECX:
  636. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  637. RS_EDX:
  638. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  639. RS_EBX:
  640. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  641. RS_ESP:
  642. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  643. RS_EBP:
  644. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  645. RS_ESI:
  646. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  647. RS_EDI:
  648. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  649. else
  650. ;
  651. end;
  652. if result then
  653. exit;
  654. end
  655. else if getregtype(reg)=R_MMREGISTER then
  656. begin
  657. case getsupreg(reg) of
  658. RS_XMM0:
  659. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  660. else
  661. ;
  662. end;
  663. if result then
  664. exit;
  665. end
  666. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  667. begin
  668. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  669. exit(true);
  670. case getsubreg(reg) of
  671. R_SUBFLAGCARRY:
  672. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  673. R_SUBFLAGPARITY:
  674. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  675. R_SUBFLAGAUXILIARY:
  676. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  677. R_SUBFLAGZERO:
  678. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  679. R_SUBFLAGSIGN:
  680. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  681. R_SUBFLAGOVERFLOW:
  682. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  683. R_SUBFLAGINTERRUPT:
  684. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  685. R_SUBFLAGDIRECTION:
  686. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  687. R_SUBW,R_SUBD,R_SUBQ:
  688. { Everything except the direction bits }
  689. Result:=
  690. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  691. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  692. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  693. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  694. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  695. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  696. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  697. else
  698. ;
  699. end;
  700. if result then
  701. exit;
  702. end
  703. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  704. exit(true);
  705. Result:=inherited RegInInstruction(Reg, p1);
  706. end;
  707. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  708. const
  709. WriteOps: array[0..3] of set of TInsChange =
  710. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  711. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  712. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  713. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  714. var
  715. OperIdx: Integer;
  716. begin
  717. Result := False;
  718. if p1.typ <> ait_instruction then
  719. exit;
  720. with insprop[taicpu(p1).opcode] do
  721. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  722. begin
  723. case getsubreg(reg) of
  724. R_SUBW,R_SUBD,R_SUBQ:
  725. Result :=
  726. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  727. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  728. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  729. R_SUBFLAGCARRY:
  730. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  731. R_SUBFLAGPARITY:
  732. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  733. R_SUBFLAGAUXILIARY:
  734. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  735. R_SUBFLAGZERO:
  736. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  737. R_SUBFLAGSIGN:
  738. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  739. R_SUBFLAGOVERFLOW:
  740. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  741. R_SUBFLAGINTERRUPT:
  742. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  743. R_SUBFLAGDIRECTION:
  744. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  745. else
  746. internalerror(2017042602);
  747. end;
  748. exit;
  749. end;
  750. case taicpu(p1).opcode of
  751. A_CALL:
  752. { We could potentially set Result to False if the register in
  753. question is non-volatile for the subroutine's calling convention,
  754. but this would require detecting the calling convention in use and
  755. also assuming that the routine doesn't contain malformed assembly
  756. language, for example... so it could only be done under -O4 as it
  757. would be considered a side-effect. [Kit] }
  758. Result := True;
  759. A_MOVSD:
  760. { special handling for SSE MOVSD }
  761. if (taicpu(p1).ops>0) then
  762. begin
  763. if taicpu(p1).ops<>2 then
  764. internalerror(2017042703);
  765. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  766. end;
  767. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  768. so fix it here (FK)
  769. }
  770. A_VMOVSS,
  771. A_VMOVSD:
  772. begin
  773. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  774. exit;
  775. end;
  776. A_IMUL:
  777. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  778. else
  779. ;
  780. end;
  781. if Result then
  782. exit;
  783. with insprop[taicpu(p1).opcode] do
  784. begin
  785. if getregtype(reg)=R_INTREGISTER then
  786. begin
  787. case getsupreg(reg) of
  788. RS_EAX:
  789. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  790. begin
  791. Result := True;
  792. exit
  793. end;
  794. RS_ECX:
  795. if [Ch_WECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  796. begin
  797. Result := True;
  798. exit
  799. end;
  800. RS_EDX:
  801. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  802. begin
  803. Result := True;
  804. exit
  805. end;
  806. RS_EBX:
  807. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  808. begin
  809. Result := True;
  810. exit
  811. end;
  812. RS_ESP:
  813. if [Ch_WESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  814. begin
  815. Result := True;
  816. exit
  817. end;
  818. RS_EBP:
  819. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  820. begin
  821. Result := True;
  822. exit
  823. end;
  824. RS_ESI:
  825. if [Ch_WESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  826. begin
  827. Result := True;
  828. exit
  829. end;
  830. RS_EDI:
  831. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  832. begin
  833. Result := True;
  834. exit
  835. end;
  836. end;
  837. end;
  838. for OperIdx := 0 to taicpu(p1).ops - 1 do
  839. if (WriteOps[OperIdx]*Ch<>[]) and
  840. { The register doesn't get modified inside a reference }
  841. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  842. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  843. begin
  844. Result := true;
  845. exit
  846. end;
  847. end;
  848. end;
  849. {$ifdef DEBUG_AOPTCPU}
  850. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  851. begin
  852. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  853. end;
  854. function debug_tostr(i: tcgint): string; inline;
  855. begin
  856. Result := tostr(i);
  857. end;
  858. function debug_regname(r: TRegister): string; inline;
  859. begin
  860. Result := '%' + std_regname(r);
  861. end;
  862. { Debug output function - creates a string representation of an operator }
  863. function debug_operstr(oper: TOper): string;
  864. begin
  865. case oper.typ of
  866. top_const:
  867. Result := '$' + debug_tostr(oper.val);
  868. top_reg:
  869. Result := debug_regname(oper.reg);
  870. top_ref:
  871. begin
  872. if oper.ref^.offset <> 0 then
  873. Result := debug_tostr(oper.ref^.offset) + '('
  874. else
  875. Result := '(';
  876. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  877. begin
  878. Result := Result + debug_regname(oper.ref^.base);
  879. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  880. Result := Result + ',' + debug_regname(oper.ref^.index);
  881. end
  882. else
  883. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  884. Result := Result + debug_regname(oper.ref^.index);
  885. if (oper.ref^.scalefactor > 1) then
  886. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  887. else
  888. Result := Result + ')';
  889. end;
  890. else
  891. Result := '[UNKNOWN]';
  892. end;
  893. end;
  894. function debug_op2str(opcode: tasmop): string; inline;
  895. begin
  896. Result := std_op2str[opcode];
  897. end;
  898. function debug_opsize2str(opsize: topsize): string; inline;
  899. begin
  900. Result := gas_opsize2str[opsize];
  901. end;
  902. {$else DEBUG_AOPTCPU}
  903. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  904. begin
  905. end;
  906. function debug_tostr(i: tcgint): string; inline;
  907. begin
  908. Result := '';
  909. end;
  910. function debug_regname(r: TRegister): string; inline;
  911. begin
  912. Result := '';
  913. end;
  914. function debug_operstr(oper: TOper): string; inline;
  915. begin
  916. Result := '';
  917. end;
  918. function debug_op2str(opcode: tasmop): string; inline;
  919. begin
  920. Result := '';
  921. end;
  922. function debug_opsize2str(opsize: topsize): string; inline;
  923. begin
  924. Result := '';
  925. end;
  926. {$endif DEBUG_AOPTCPU}
  927. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  928. begin
  929. {$ifdef x86_64}
  930. { Always fine on x86-64 }
  931. Result := True;
  932. {$else x86_64}
  933. Result :=
  934. {$ifdef i8086}
  935. (current_settings.cputype >= cpu_386) and
  936. {$endif i8086}
  937. (
  938. { Always accept if optimising for size }
  939. (cs_opt_size in current_settings.optimizerswitches) or
  940. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  941. (current_settings.optimizecputype >= cpu_Pentium2)
  942. );
  943. {$endif x86_64}
  944. end;
  945. { Attempts to allocate a volatile integer register for use between p and hp,
  946. using AUsedRegs for the current register usage information. Returns NR_NO
  947. if no free register could be found }
  948. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  949. var
  950. RegSet: TCPURegisterSet;
  951. CurrentSuperReg: Integer;
  952. CurrentReg: TRegister;
  953. Currentp: tai;
  954. Breakout: Boolean;
  955. begin
  956. { TODO: Currently, only the volatile registers are checked - can this be extended to use any register the procedure has preserved? }
  957. Result := NR_NO;
  958. RegSet := paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption);
  959. for CurrentSuperReg in RegSet do
  960. begin
  961. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  962. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg) then
  963. begin
  964. Currentp := p;
  965. Breakout := False;
  966. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  967. begin
  968. case Currentp.typ of
  969. ait_instruction:
  970. begin
  971. if RegInInstruction(CurrentReg, Currentp) then
  972. begin
  973. Breakout := True;
  974. Break;
  975. end;
  976. { Cannot allocate across an unconditional jump }
  977. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  978. Exit;
  979. end;
  980. ait_marker:
  981. { Don't try anything more if a marker is hit }
  982. Exit;
  983. ait_regalloc:
  984. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  985. begin
  986. Breakout := True;
  987. Break;
  988. end;
  989. else
  990. ;
  991. end;
  992. end;
  993. if Breakout then
  994. { Try the next register }
  995. Continue;
  996. { We have a free register available }
  997. Result := CurrentReg;
  998. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  999. Exit;
  1000. end;
  1001. end;
  1002. end;
  1003. { Attempts to allocate a volatile MM register for use between p and hp,
  1004. using AUsedRegs for the current register usage information. Returns NR_NO
  1005. if no free register could be found }
  1006. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1007. var
  1008. RegSet: TCPURegisterSet;
  1009. CurrentSuperReg: Integer;
  1010. CurrentReg: TRegister;
  1011. Currentp: tai;
  1012. Breakout: Boolean;
  1013. begin
  1014. { TODO: Currently, only the volatile registers are checked - can this be extended to use any register the procedure has preserved? }
  1015. Result := NR_NO;
  1016. RegSet := paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption);
  1017. for CurrentSuperReg in RegSet do
  1018. begin
  1019. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1020. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1021. begin
  1022. Currentp := p;
  1023. Breakout := False;
  1024. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1025. begin
  1026. case Currentp.typ of
  1027. ait_instruction:
  1028. begin
  1029. if RegInInstruction(CurrentReg, Currentp) then
  1030. begin
  1031. Breakout := True;
  1032. Break;
  1033. end;
  1034. { Cannot allocate across an unconditional jump }
  1035. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1036. Exit;
  1037. end;
  1038. ait_marker:
  1039. { Don't try anything more if a marker is hit }
  1040. Exit;
  1041. ait_regalloc:
  1042. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1043. begin
  1044. Breakout := True;
  1045. Break;
  1046. end;
  1047. else
  1048. ;
  1049. end;
  1050. end;
  1051. if Breakout then
  1052. { Try the next register }
  1053. Continue;
  1054. { We have a free register available }
  1055. Result := CurrentReg;
  1056. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1057. Exit;
  1058. end;
  1059. end;
  1060. end;
  1061. function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1062. begin
  1063. if not SuperRegistersEqual(reg1,reg2) then
  1064. exit(false);
  1065. if getregtype(reg1)<>R_INTREGISTER then
  1066. exit(true); {because SuperRegisterEqual is true}
  1067. case getsubreg(reg1) of
  1068. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1069. higher, it preserves the high bits, so the new value depends on
  1070. reg2's previous value. In other words, it is equivalent to doing:
  1071. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1072. R_SUBL:
  1073. exit(getsubreg(reg2)=R_SUBL);
  1074. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1075. higher, it actually does a:
  1076. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1077. R_SUBH:
  1078. exit(getsubreg(reg2)=R_SUBH);
  1079. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1080. bits of reg2:
  1081. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1082. R_SUBW:
  1083. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1084. { a write to R_SUBD always overwrites every other subregister,
  1085. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1086. R_SUBD,
  1087. R_SUBQ:
  1088. exit(true);
  1089. else
  1090. internalerror(2017042801);
  1091. end;
  1092. end;
  1093. function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1094. begin
  1095. if not SuperRegistersEqual(reg1,reg2) then
  1096. exit(false);
  1097. if getregtype(reg1)<>R_INTREGISTER then
  1098. exit(true); {because SuperRegisterEqual is true}
  1099. case getsubreg(reg1) of
  1100. R_SUBL:
  1101. exit(getsubreg(reg2)<>R_SUBH);
  1102. R_SUBH:
  1103. exit(getsubreg(reg2)<>R_SUBL);
  1104. R_SUBW,
  1105. R_SUBD,
  1106. R_SUBQ:
  1107. exit(true);
  1108. else
  1109. internalerror(2017042802);
  1110. end;
  1111. end;
  1112. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1113. var
  1114. hp1 : tai;
  1115. l : TCGInt;
  1116. begin
  1117. result:=false;
  1118. { changes the code sequence
  1119. shr/sar const1, x
  1120. shl const2, x
  1121. to
  1122. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1123. if GetNextInstruction(p, hp1) and
  1124. MatchInstruction(hp1,A_SHL,[]) and
  1125. (taicpu(p).oper[0]^.typ = top_const) and
  1126. (taicpu(hp1).oper[0]^.typ = top_const) and
  1127. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1128. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1129. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1130. begin
  1131. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1132. not(cs_opt_size in current_settings.optimizerswitches) then
  1133. begin
  1134. { shr/sar const1, %reg
  1135. shl const2, %reg
  1136. with const1 > const2 }
  1137. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1138. taicpu(hp1).opcode := A_AND;
  1139. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1140. case taicpu(p).opsize Of
  1141. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1142. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1143. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1144. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1145. else
  1146. Internalerror(2017050703)
  1147. end;
  1148. end
  1149. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1150. not(cs_opt_size in current_settings.optimizerswitches) then
  1151. begin
  1152. { shr/sar const1, %reg
  1153. shl const2, %reg
  1154. with const1 < const2 }
  1155. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1156. taicpu(p).opcode := A_AND;
  1157. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1158. case taicpu(p).opsize Of
  1159. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1160. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1161. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1162. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1163. else
  1164. Internalerror(2017050702)
  1165. end;
  1166. end
  1167. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1168. begin
  1169. { shr/sar const1, %reg
  1170. shl const2, %reg
  1171. with const1 = const2 }
  1172. taicpu(p).opcode := A_AND;
  1173. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1174. case taicpu(p).opsize Of
  1175. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1176. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1177. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1178. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1179. else
  1180. Internalerror(2017050701)
  1181. end;
  1182. RemoveInstruction(hp1);
  1183. end;
  1184. end;
  1185. end;
  1186. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1187. var
  1188. opsize : topsize;
  1189. hp1 : tai;
  1190. tmpref : treference;
  1191. ShiftValue : Cardinal;
  1192. BaseValue : TCGInt;
  1193. begin
  1194. result:=false;
  1195. opsize:=taicpu(p).opsize;
  1196. { changes certain "imul const, %reg"'s to lea sequences }
  1197. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1198. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1199. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1200. if (taicpu(p).oper[0]^.val = 1) then
  1201. if (taicpu(p).ops = 2) then
  1202. { remove "imul $1, reg" }
  1203. begin
  1204. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1205. Result := RemoveCurrentP(p);
  1206. end
  1207. else
  1208. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1209. begin
  1210. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1211. InsertLLItem(p.previous, p.next, hp1);
  1212. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1213. p.free;
  1214. p := hp1;
  1215. end
  1216. else if ((taicpu(p).ops <= 2) or
  1217. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1218. not(cs_opt_size in current_settings.optimizerswitches) and
  1219. (not(GetNextInstruction(p, hp1)) or
  1220. not((tai(hp1).typ = ait_instruction) and
  1221. ((taicpu(hp1).opcode=A_Jcc) and
  1222. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1223. begin
  1224. {
  1225. imul X, reg1, reg2 to
  1226. lea (reg1,reg1,Y), reg2
  1227. shl ZZ,reg2
  1228. imul XX, reg1 to
  1229. lea (reg1,reg1,YY), reg1
  1230. shl ZZ,reg2
  1231. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1232. it does not exist as a separate optimization target in FPC though.
  1233. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1234. at most two zeros
  1235. }
  1236. reference_reset(tmpref,1,[]);
  1237. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1238. begin
  1239. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1240. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1241. TmpRef.base := taicpu(p).oper[1]^.reg;
  1242. TmpRef.index := taicpu(p).oper[1]^.reg;
  1243. if not(BaseValue in [3,5,9]) then
  1244. Internalerror(2018110101);
  1245. TmpRef.ScaleFactor := BaseValue-1;
  1246. if (taicpu(p).ops = 2) then
  1247. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1248. else
  1249. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1250. AsmL.InsertAfter(hp1,p);
  1251. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1252. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1253. RemoveCurrentP(p, hp1);
  1254. if ShiftValue>0 then
  1255. AsmL.InsertAfter(taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg),hp1);
  1256. end;
  1257. end;
  1258. end;
  1259. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1260. begin
  1261. Result := False;
  1262. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1263. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1264. begin
  1265. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1266. taicpu(p).opcode := A_MOV;
  1267. Result := True;
  1268. end;
  1269. end;
  1270. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1271. var
  1272. p: taicpu absolute hp;
  1273. i: Integer;
  1274. begin
  1275. Result := False;
  1276. if not assigned(hp) or
  1277. (hp.typ <> ait_instruction) then
  1278. Exit;
  1279. // p := taicpu(hp);
  1280. Prefetch(insprop[p.opcode]);
  1281. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1282. with insprop[p.opcode] do
  1283. begin
  1284. case getsubreg(reg) of
  1285. R_SUBW,R_SUBD,R_SUBQ:
  1286. Result:=
  1287. RegLoadedWithNewValue(NR_CARRYFLAG,hp) and
  1288. RegLoadedWithNewValue(NR_PARITYFLAG,hp) and
  1289. RegLoadedWithNewValue(NR_AUXILIARYFLAG,hp) and
  1290. RegLoadedWithNewValue(NR_ZEROFLAG,hp) and
  1291. RegLoadedWithNewValue(NR_SIGNFLAG,hp) and
  1292. RegLoadedWithNewValue(NR_OVERFLOWFLAG,hp);
  1293. R_SUBFLAGCARRY:
  1294. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1295. R_SUBFLAGPARITY:
  1296. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1297. R_SUBFLAGAUXILIARY:
  1298. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1299. R_SUBFLAGZERO:
  1300. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1301. R_SUBFLAGSIGN:
  1302. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1303. R_SUBFLAGOVERFLOW:
  1304. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1305. R_SUBFLAGINTERRUPT:
  1306. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1307. R_SUBFLAGDIRECTION:
  1308. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1309. else
  1310. begin
  1311. writeln(getsubreg(reg));
  1312. internalerror(2017050501);
  1313. end;
  1314. end;
  1315. exit;
  1316. end;
  1317. { Handle special cases first }
  1318. case p.opcode of
  1319. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1320. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1321. begin
  1322. Result :=
  1323. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1324. (p.oper[1]^.typ = top_reg) and
  1325. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1326. (
  1327. (p.oper[0]^.typ = top_const) or
  1328. (
  1329. (p.oper[0]^.typ = top_reg) and
  1330. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1331. ) or (
  1332. (p.oper[0]^.typ = top_ref) and
  1333. not RegInRef(reg,p.oper[0]^.ref^)
  1334. )
  1335. );
  1336. end;
  1337. A_MUL, A_IMUL:
  1338. Result :=
  1339. (
  1340. (p.ops=3) and { IMUL only }
  1341. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1342. (
  1343. (
  1344. (p.oper[1]^.typ=top_reg) and
  1345. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1346. ) or (
  1347. (p.oper[1]^.typ=top_ref) and
  1348. not RegInRef(reg,p.oper[1]^.ref^)
  1349. )
  1350. )
  1351. ) or (
  1352. (
  1353. (p.ops=1) and
  1354. (
  1355. (
  1356. (
  1357. (p.oper[0]^.typ=top_reg) and
  1358. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1359. )
  1360. ) or (
  1361. (p.oper[0]^.typ=top_ref) and
  1362. not RegInRef(reg,p.oper[0]^.ref^)
  1363. )
  1364. ) and (
  1365. (
  1366. (p.opsize=S_B) and
  1367. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1368. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1369. ) or (
  1370. (p.opsize=S_W) and
  1371. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1372. ) or (
  1373. (p.opsize=S_L) and
  1374. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1375. {$ifdef x86_64}
  1376. ) or (
  1377. (p.opsize=S_Q) and
  1378. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1379. {$endif x86_64}
  1380. )
  1381. )
  1382. )
  1383. );
  1384. A_CBW:
  1385. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1386. {$ifndef x86_64}
  1387. A_LDS:
  1388. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1389. A_LES:
  1390. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1391. {$endif not x86_64}
  1392. A_LFS:
  1393. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1394. A_LGS:
  1395. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1396. A_LSS:
  1397. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1398. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1399. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1400. A_LODSB:
  1401. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1402. A_LODSW:
  1403. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1404. {$ifdef x86_64}
  1405. A_LODSQ:
  1406. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1407. {$endif x86_64}
  1408. A_LODSD:
  1409. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1410. A_FSTSW, A_FNSTSW:
  1411. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1412. else
  1413. begin
  1414. with insprop[p.opcode] do
  1415. begin
  1416. if (
  1417. { xor %reg,%reg etc. is classed as a new value }
  1418. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1419. MatchOpType(p, top_reg, top_reg) and
  1420. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1421. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1422. ) then
  1423. begin
  1424. Result := True;
  1425. Exit;
  1426. end;
  1427. { Make sure the entire register is overwritten }
  1428. if (getregtype(reg) = R_INTREGISTER) then
  1429. begin
  1430. if (p.ops > 0) then
  1431. begin
  1432. if RegInOp(reg, p.oper[0]^) then
  1433. begin
  1434. if (p.oper[0]^.typ = top_ref) then
  1435. begin
  1436. if RegInRef(reg, p.oper[0]^.ref^) then
  1437. begin
  1438. Result := False;
  1439. Exit;
  1440. end;
  1441. end
  1442. else if (p.oper[0]^.typ = top_reg) then
  1443. begin
  1444. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1445. begin
  1446. Result := False;
  1447. Exit;
  1448. end
  1449. else if ([Ch_WOp1]*Ch<>[]) then
  1450. begin
  1451. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1452. Result := True
  1453. else
  1454. begin
  1455. Result := False;
  1456. Exit;
  1457. end;
  1458. end;
  1459. end;
  1460. end;
  1461. if (p.ops > 1) then
  1462. begin
  1463. if RegInOp(reg, p.oper[1]^) then
  1464. begin
  1465. if (p.oper[1]^.typ = top_ref) then
  1466. begin
  1467. if RegInRef(reg, p.oper[1]^.ref^) then
  1468. begin
  1469. Result := False;
  1470. Exit;
  1471. end;
  1472. end
  1473. else if (p.oper[1]^.typ = top_reg) then
  1474. begin
  1475. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1476. begin
  1477. Result := False;
  1478. Exit;
  1479. end
  1480. else if ([Ch_WOp2]*Ch<>[]) then
  1481. begin
  1482. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1483. Result := True
  1484. else
  1485. begin
  1486. Result := False;
  1487. Exit;
  1488. end;
  1489. end;
  1490. end;
  1491. end;
  1492. if (p.ops > 2) then
  1493. begin
  1494. if RegInOp(reg, p.oper[2]^) then
  1495. begin
  1496. if (p.oper[2]^.typ = top_ref) then
  1497. begin
  1498. if RegInRef(reg, p.oper[2]^.ref^) then
  1499. begin
  1500. Result := False;
  1501. Exit;
  1502. end;
  1503. end
  1504. else if (p.oper[2]^.typ = top_reg) then
  1505. begin
  1506. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1507. begin
  1508. Result := False;
  1509. Exit;
  1510. end
  1511. else if ([Ch_WOp3]*Ch<>[]) then
  1512. begin
  1513. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1514. Result := True
  1515. else
  1516. begin
  1517. Result := False;
  1518. Exit;
  1519. end;
  1520. end;
  1521. end;
  1522. end;
  1523. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1524. begin
  1525. if (p.oper[3]^.typ = top_ref) then
  1526. begin
  1527. if RegInRef(reg, p.oper[3]^.ref^) then
  1528. begin
  1529. Result := False;
  1530. Exit;
  1531. end;
  1532. end
  1533. else if (p.oper[3]^.typ = top_reg) then
  1534. begin
  1535. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1536. begin
  1537. Result := False;
  1538. Exit;
  1539. end
  1540. else if ([Ch_WOp4]*Ch<>[]) then
  1541. begin
  1542. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1543. Result := True
  1544. else
  1545. begin
  1546. Result := False;
  1547. Exit;
  1548. end;
  1549. end;
  1550. end;
  1551. end;
  1552. end;
  1553. end;
  1554. end;
  1555. { Don't do these ones first in case an input operand is equal to an explicit output registers }
  1556. case getsupreg(reg) of
  1557. RS_EAX:
  1558. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1559. begin
  1560. Result := True;
  1561. Exit;
  1562. end;
  1563. RS_ECX:
  1564. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1565. begin
  1566. Result := True;
  1567. Exit;
  1568. end;
  1569. RS_EDX:
  1570. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1571. begin
  1572. Result := True;
  1573. Exit;
  1574. end;
  1575. RS_EBX:
  1576. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1577. begin
  1578. Result := True;
  1579. Exit;
  1580. end;
  1581. RS_ESP:
  1582. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1583. begin
  1584. Result := True;
  1585. Exit;
  1586. end;
  1587. RS_EBP:
  1588. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1589. begin
  1590. Result := True;
  1591. Exit;
  1592. end;
  1593. RS_ESI:
  1594. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1595. begin
  1596. Result := True;
  1597. Exit;
  1598. end;
  1599. RS_EDI:
  1600. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1601. begin
  1602. Result := True;
  1603. Exit;
  1604. end;
  1605. else
  1606. ;
  1607. end;
  1608. end;
  1609. end;
  1610. end;
  1611. end;
  1612. end;
  1613. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1614. var
  1615. hp2,hp3 : tai;
  1616. begin
  1617. { some x86-64 issue a NOP before the real exit code }
  1618. if MatchInstruction(p,A_NOP,[]) then
  1619. GetNextInstruction(p,p);
  1620. result:=assigned(p) and (p.typ=ait_instruction) and
  1621. ((taicpu(p).opcode = A_RET) or
  1622. ((taicpu(p).opcode=A_LEAVE) and
  1623. GetNextInstruction(p,hp2) and
  1624. MatchInstruction(hp2,A_RET,[S_NO])
  1625. ) or
  1626. (((taicpu(p).opcode=A_LEA) and
  1627. MatchOpType(taicpu(p),top_ref,top_reg) and
  1628. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1629. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1630. ) and
  1631. GetNextInstruction(p,hp2) and
  1632. MatchInstruction(hp2,A_RET,[S_NO])
  1633. ) or
  1634. ((((taicpu(p).opcode=A_MOV) and
  1635. MatchOpType(taicpu(p),top_reg,top_reg) and
  1636. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1637. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1638. ((taicpu(p).opcode=A_LEA) and
  1639. MatchOpType(taicpu(p),top_ref,top_reg) and
  1640. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1641. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1642. )
  1643. ) and
  1644. GetNextInstruction(p,hp2) and
  1645. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1646. MatchOpType(taicpu(hp2),top_reg) and
  1647. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1648. GetNextInstruction(hp2,hp3) and
  1649. MatchInstruction(hp3,A_RET,[S_NO])
  1650. )
  1651. );
  1652. end;
  1653. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1654. begin
  1655. isFoldableArithOp := False;
  1656. case hp1.opcode of
  1657. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1658. isFoldableArithOp :=
  1659. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1660. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1661. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1662. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1663. (taicpu(hp1).oper[1]^.reg = reg);
  1664. A_INC,A_DEC,A_NEG,A_NOT:
  1665. isFoldableArithOp :=
  1666. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1667. (taicpu(hp1).oper[0]^.reg = reg);
  1668. else
  1669. ;
  1670. end;
  1671. end;
  1672. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1673. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1674. var
  1675. hp2: tai;
  1676. begin
  1677. hp2 := p;
  1678. repeat
  1679. hp2 := tai(hp2.previous);
  1680. if assigned(hp2) and
  1681. (hp2.typ = ait_regalloc) and
  1682. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1683. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1684. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1685. begin
  1686. RemoveInstruction(hp2);
  1687. break;
  1688. end;
  1689. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1690. end;
  1691. begin
  1692. case current_procinfo.procdef.returndef.typ of
  1693. arraydef,recorddef,pointerdef,
  1694. stringdef,enumdef,procdef,objectdef,errordef,
  1695. filedef,setdef,procvardef,
  1696. classrefdef,forwarddef:
  1697. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1698. orddef:
  1699. if current_procinfo.procdef.returndef.size <> 0 then
  1700. begin
  1701. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1702. { for int64/qword }
  1703. if current_procinfo.procdef.returndef.size = 8 then
  1704. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1705. end;
  1706. else
  1707. ;
  1708. end;
  1709. end;
  1710. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1711. var
  1712. hp1,hp2 : tai;
  1713. begin
  1714. result:=false;
  1715. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1716. begin
  1717. { vmova* reg1,reg1
  1718. =>
  1719. <nop> }
  1720. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1721. begin
  1722. RemoveCurrentP(p);
  1723. result:=true;
  1724. exit;
  1725. end
  1726. else if GetNextInstruction(p,hp1) then
  1727. begin
  1728. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1729. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1730. begin
  1731. { vmova* reg1,reg2
  1732. vmova* reg2,reg3
  1733. dealloc reg2
  1734. =>
  1735. vmova* reg1,reg3 }
  1736. TransferUsedRegs(TmpUsedRegs);
  1737. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1738. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1739. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1740. begin
  1741. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1742. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1743. RemoveInstruction(hp1);
  1744. result:=true;
  1745. exit;
  1746. end
  1747. { special case:
  1748. vmova* reg1,<op>
  1749. vmova* <op>,reg1
  1750. =>
  1751. vmova* reg1,<op> }
  1752. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1753. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1754. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1755. ) then
  1756. begin
  1757. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1758. RemoveInstruction(hp1);
  1759. result:=true;
  1760. exit;
  1761. end
  1762. end
  1763. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  1764. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  1765. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  1766. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  1767. ) and
  1768. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1769. begin
  1770. { vmova* reg1,reg2
  1771. vmovs* reg2,<op>
  1772. dealloc reg2
  1773. =>
  1774. vmovs* reg1,reg3 }
  1775. TransferUsedRegs(TmpUsedRegs);
  1776. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1777. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1778. begin
  1779. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  1780. taicpu(p).opcode:=taicpu(hp1).opcode;
  1781. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1782. RemoveInstruction(hp1);
  1783. result:=true;
  1784. exit;
  1785. end
  1786. end;
  1787. end;
  1788. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  1789. begin
  1790. if MatchInstruction(hp1,[A_VFMADDPD,
  1791. A_VFMADD132PD,
  1792. A_VFMADD132PS,
  1793. A_VFMADD132SD,
  1794. A_VFMADD132SS,
  1795. A_VFMADD213PD,
  1796. A_VFMADD213PS,
  1797. A_VFMADD213SD,
  1798. A_VFMADD213SS,
  1799. A_VFMADD231PD,
  1800. A_VFMADD231PS,
  1801. A_VFMADD231SD,
  1802. A_VFMADD231SS,
  1803. A_VFMADDSUB132PD,
  1804. A_VFMADDSUB132PS,
  1805. A_VFMADDSUB213PD,
  1806. A_VFMADDSUB213PS,
  1807. A_VFMADDSUB231PD,
  1808. A_VFMADDSUB231PS,
  1809. A_VFMSUB132PD,
  1810. A_VFMSUB132PS,
  1811. A_VFMSUB132SD,
  1812. A_VFMSUB132SS,
  1813. A_VFMSUB213PD,
  1814. A_VFMSUB213PS,
  1815. A_VFMSUB213SD,
  1816. A_VFMSUB213SS,
  1817. A_VFMSUB231PD,
  1818. A_VFMSUB231PS,
  1819. A_VFMSUB231SD,
  1820. A_VFMSUB231SS,
  1821. A_VFMSUBADD132PD,
  1822. A_VFMSUBADD132PS,
  1823. A_VFMSUBADD213PD,
  1824. A_VFMSUBADD213PS,
  1825. A_VFMSUBADD231PD,
  1826. A_VFMSUBADD231PS,
  1827. A_VFNMADD132PD,
  1828. A_VFNMADD132PS,
  1829. A_VFNMADD132SD,
  1830. A_VFNMADD132SS,
  1831. A_VFNMADD213PD,
  1832. A_VFNMADD213PS,
  1833. A_VFNMADD213SD,
  1834. A_VFNMADD213SS,
  1835. A_VFNMADD231PD,
  1836. A_VFNMADD231PS,
  1837. A_VFNMADD231SD,
  1838. A_VFNMADD231SS,
  1839. A_VFNMSUB132PD,
  1840. A_VFNMSUB132PS,
  1841. A_VFNMSUB132SD,
  1842. A_VFNMSUB132SS,
  1843. A_VFNMSUB213PD,
  1844. A_VFNMSUB213PS,
  1845. A_VFNMSUB213SD,
  1846. A_VFNMSUB213SS,
  1847. A_VFNMSUB231PD,
  1848. A_VFNMSUB231PS,
  1849. A_VFNMSUB231SD,
  1850. A_VFNMSUB231SS],[S_NO]) and
  1851. { we mix single and double opperations here because we assume that the compiler
  1852. generates vmovapd only after double operations and vmovaps only after single operations }
  1853. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  1854. GetNextInstruction(hp1,hp2) and
  1855. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  1856. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  1857. begin
  1858. TransferUsedRegs(TmpUsedRegs);
  1859. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1860. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1861. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1862. begin
  1863. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  1864. RemoveCurrentP(p, hp1); // <-- Is this actually safe? hp1 is not necessarily the next instruction. [Kit]
  1865. RemoveInstruction(hp2);
  1866. end;
  1867. end
  1868. else if (hp1.typ = ait_instruction) and
  1869. GetNextInstruction(hp1, hp2) and
  1870. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  1871. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  1872. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  1873. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  1874. (((taicpu(p).opcode=A_MOVAPS) and
  1875. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  1876. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  1877. ((taicpu(p).opcode=A_MOVAPD) and
  1878. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  1879. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  1880. ) then
  1881. { change
  1882. movapX reg,reg2
  1883. addsX/subsX/... reg3, reg2
  1884. movapX reg2,reg
  1885. to
  1886. addsX/subsX/... reg3,reg
  1887. }
  1888. begin
  1889. TransferUsedRegs(TmpUsedRegs);
  1890. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1891. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1892. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1893. begin
  1894. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  1895. debug_op2str(taicpu(p).opcode)+' '+
  1896. debug_op2str(taicpu(hp1).opcode)+' '+
  1897. debug_op2str(taicpu(hp2).opcode)+') done',p);
  1898. { we cannot eliminate the first move if
  1899. the operations uses the same register for source and dest }
  1900. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  1901. RemoveCurrentP(p, nil);
  1902. p:=hp1;
  1903. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  1904. RemoveInstruction(hp2);
  1905. result:=true;
  1906. end;
  1907. end;
  1908. end;
  1909. end;
  1910. end;
  1911. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  1912. var
  1913. hp1 : tai;
  1914. begin
  1915. result:=false;
  1916. { replace
  1917. V<Op>X %mreg1,%mreg2,%mreg3
  1918. VMovX %mreg3,%mreg4
  1919. dealloc %mreg3
  1920. by
  1921. V<Op>X %mreg1,%mreg2,%mreg4
  1922. ?
  1923. }
  1924. if GetNextInstruction(p,hp1) and
  1925. { we mix single and double operations here because we assume that the compiler
  1926. generates vmovapd only after double operations and vmovaps only after single operations }
  1927. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  1928. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  1929. (taicpu(hp1).oper[1]^.typ=top_reg) then
  1930. begin
  1931. TransferUsedRegs(TmpUsedRegs);
  1932. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1933. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  1934. begin
  1935. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  1936. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  1937. RemoveInstruction(hp1);
  1938. result:=true;
  1939. end;
  1940. end;
  1941. end;
  1942. { Replaces all references to AOldReg in a memory reference to ANewReg }
  1943. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  1944. begin
  1945. Result := False;
  1946. { For safety reasons, only check for exact register matches }
  1947. { Check base register }
  1948. if (ref.base = AOldReg) then
  1949. begin
  1950. ref.base := ANewReg;
  1951. Result := True;
  1952. end;
  1953. { Check index register }
  1954. if (ref.index = AOldReg) then
  1955. begin
  1956. ref.index := ANewReg;
  1957. Result := True;
  1958. end;
  1959. end;
  1960. { Replaces all references to AOldReg in an operand to ANewReg }
  1961. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  1962. var
  1963. OldSupReg, NewSupReg: TSuperRegister;
  1964. OldSubReg, NewSubReg: TSubRegister;
  1965. OldRegType: TRegisterType;
  1966. ThisOper: POper;
  1967. begin
  1968. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  1969. Result := False;
  1970. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  1971. InternalError(2020011801);
  1972. OldSupReg := getsupreg(AOldReg);
  1973. OldSubReg := getsubreg(AOldReg);
  1974. OldRegType := getregtype(AOldReg);
  1975. NewSupReg := getsupreg(ANewReg);
  1976. NewSubReg := getsubreg(ANewReg);
  1977. if OldRegType <> getregtype(ANewReg) then
  1978. InternalError(2020011802);
  1979. if OldSubReg <> NewSubReg then
  1980. InternalError(2020011803);
  1981. case ThisOper^.typ of
  1982. top_reg:
  1983. if (
  1984. (ThisOper^.reg = AOldReg) or
  1985. (
  1986. (OldRegType = R_INTREGISTER) and
  1987. (getsupreg(ThisOper^.reg) = OldSupReg) and
  1988. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  1989. (
  1990. (getsubreg(ThisOper^.reg) <= OldSubReg)
  1991. {$ifndef x86_64}
  1992. and (
  1993. { Under i386 and i8086, ESI, EDI, EBP and ESP
  1994. don't have an 8-bit representation }
  1995. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  1996. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  1997. )
  1998. {$endif x86_64}
  1999. )
  2000. )
  2001. ) then
  2002. begin
  2003. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2004. Result := True;
  2005. end;
  2006. top_ref:
  2007. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2008. Result := True;
  2009. else
  2010. ;
  2011. end;
  2012. end;
  2013. { Replaces all references to AOldReg in an instruction to ANewReg }
  2014. function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2015. const
  2016. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2017. var
  2018. OperIdx: Integer;
  2019. begin
  2020. Result := False;
  2021. for OperIdx := 0 to p.ops - 1 do
  2022. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2023. begin
  2024. { The shift and rotate instructions can only use CL }
  2025. if not (
  2026. (OperIdx = 0) and
  2027. { This second condition just helps to avoid unnecessarily
  2028. calling MatchInstruction for 10 different opcodes }
  2029. (p.oper[0]^.reg = NR_CL) and
  2030. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2031. ) then
  2032. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2033. end
  2034. else if p.oper[OperIdx]^.typ = top_ref then
  2035. { It's okay to replace registers in references that get written to }
  2036. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2037. end;
  2038. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2039. begin
  2040. with ref^ do
  2041. Result :=
  2042. (index = NR_NO) and
  2043. (
  2044. {$ifdef x86_64}
  2045. (
  2046. (base = NR_RIP) and
  2047. (refaddr in [addr_pic, addr_pic_no_got])
  2048. ) or
  2049. {$endif x86_64}
  2050. (base = NR_STACK_POINTER_REG) or
  2051. (base = current_procinfo.framepointer)
  2052. );
  2053. end;
  2054. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2055. var
  2056. l: asizeint;
  2057. begin
  2058. Result := False;
  2059. { Should have been checked previously }
  2060. if p.opcode <> A_LEA then
  2061. InternalError(2020072501);
  2062. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2063. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2064. not(cs_opt_size in current_settings.optimizerswitches) then
  2065. exit;
  2066. with p.oper[0]^.ref^ do
  2067. begin
  2068. if (base <> p.oper[1]^.reg) or
  2069. (index <> NR_NO) or
  2070. assigned(symbol) then
  2071. exit;
  2072. l:=offset;
  2073. if (l=1) and UseIncDec then
  2074. begin
  2075. p.opcode:=A_INC;
  2076. p.loadreg(0,p.oper[1]^.reg);
  2077. p.ops:=1;
  2078. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2079. end
  2080. else if (l=-1) and UseIncDec then
  2081. begin
  2082. p.opcode:=A_DEC;
  2083. p.loadreg(0,p.oper[1]^.reg);
  2084. p.ops:=1;
  2085. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2086. end
  2087. else
  2088. begin
  2089. if (l<0) and (l<>-2147483648) then
  2090. begin
  2091. p.opcode:=A_SUB;
  2092. p.loadConst(0,-l);
  2093. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2094. end
  2095. else
  2096. begin
  2097. p.opcode:=A_ADD;
  2098. p.loadConst(0,l);
  2099. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2100. end;
  2101. end;
  2102. end;
  2103. Result := True;
  2104. end;
  2105. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2106. var
  2107. CurrentReg, ReplaceReg: TRegister;
  2108. begin
  2109. Result := False;
  2110. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2111. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2112. case hp.opcode of
  2113. A_FSTSW, A_FNSTSW,
  2114. A_IN, A_INS, A_OUT, A_OUTS,
  2115. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2116. { These routines have explicit operands, but they are restricted in
  2117. what they can be (e.g. IN and OUT can only read from AL, AX or
  2118. EAX. }
  2119. Exit;
  2120. A_IMUL:
  2121. begin
  2122. { The 1-operand version writes to implicit registers
  2123. The 2-operand version reads from the first operator, and reads
  2124. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2125. the 3-operand version reads from a register that it doesn't write to
  2126. }
  2127. case hp.ops of
  2128. 1:
  2129. if (
  2130. (
  2131. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2132. ) or
  2133. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2134. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2135. begin
  2136. Result := True;
  2137. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2138. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2139. end;
  2140. 2:
  2141. { Only modify the first parameter }
  2142. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2143. begin
  2144. Result := True;
  2145. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2146. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2147. end;
  2148. 3:
  2149. { Only modify the second parameter }
  2150. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2151. begin
  2152. Result := True;
  2153. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2154. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2155. end;
  2156. else
  2157. InternalError(2020012901);
  2158. end;
  2159. end;
  2160. else
  2161. if (hp.ops > 0) and
  2162. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2163. begin
  2164. Result := True;
  2165. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2166. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2167. end;
  2168. end;
  2169. end;
  2170. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2171. var
  2172. hp1, hp2, hp3: tai;
  2173. DoOptimisation, TempBool: Boolean;
  2174. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2175. begin
  2176. if taicpu(hp1).opcode = signed_movop then
  2177. begin
  2178. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2179. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2180. end
  2181. else
  2182. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2183. end;
  2184. var
  2185. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2186. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2187. NewSize: topsize;
  2188. CurrentReg, ActiveReg: TRegister;
  2189. SourceRef, TargetRef: TReference;
  2190. MovAligned, MovUnaligned: TAsmOp;
  2191. begin
  2192. Result:=false;
  2193. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2194. { remove mov reg1,reg1? }
  2195. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2196. then
  2197. begin
  2198. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2199. { take care of the register (de)allocs following p }
  2200. RemoveCurrentP(p, hp1);
  2201. Result:=true;
  2202. exit;
  2203. end;
  2204. { All the next optimisations require a next instruction }
  2205. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2206. Exit;
  2207. { Look for:
  2208. mov %reg1,%reg2
  2209. ??? %reg2,r/m
  2210. Change to:
  2211. mov %reg1,%reg2
  2212. ??? %reg1,r/m
  2213. }
  2214. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2215. begin
  2216. CurrentReg := taicpu(p).oper[1]^.reg;
  2217. if RegReadByInstruction(CurrentReg, hp1) and
  2218. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2219. begin
  2220. { A change has occurred, just not in p }
  2221. Result := True;
  2222. TransferUsedRegs(TmpUsedRegs);
  2223. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2224. if not RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs) and
  2225. { Just in case something didn't get modified (e.g. an
  2226. implicit register) }
  2227. not RegReadByInstruction(CurrentReg, hp1) then
  2228. begin
  2229. { We can remove the original MOV }
  2230. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2231. RemoveCurrentp(p, hp1);
  2232. { UsedRegs got updated by RemoveCurrentp }
  2233. Result := True;
  2234. Exit;
  2235. end;
  2236. { If we know a MOV instruction has become a null operation, we might as well
  2237. get rid of it now to save time. }
  2238. if (taicpu(hp1).opcode = A_MOV) and
  2239. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2240. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2241. { Just being a register is enough to confirm it's a null operation }
  2242. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2243. begin
  2244. Result := True;
  2245. { Speed-up to reduce a pipeline stall... if we had something like...
  2246. movl %eax,%edx
  2247. movw %dx,%ax
  2248. ... the second instruction would change to movw %ax,%ax, but
  2249. given that it is now %ax that's active rather than %eax,
  2250. penalties might occur due to a partial register write, so instead,
  2251. change it to a MOVZX instruction when optimising for speed.
  2252. }
  2253. if not (cs_opt_size in current_settings.optimizerswitches) and
  2254. IsMOVZXAcceptable and
  2255. (taicpu(hp1).opsize < taicpu(p).opsize)
  2256. {$ifdef x86_64}
  2257. { operations already implicitly set the upper 64 bits to zero }
  2258. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2259. {$endif x86_64}
  2260. then
  2261. begin
  2262. CurrentReg := taicpu(hp1).oper[1]^.reg;
  2263. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2264. case taicpu(p).opsize of
  2265. S_W:
  2266. if taicpu(hp1).opsize = S_B then
  2267. taicpu(hp1).opsize := S_BL
  2268. else
  2269. InternalError(2020012911);
  2270. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2271. case taicpu(hp1).opsize of
  2272. S_B:
  2273. taicpu(hp1).opsize := S_BL;
  2274. S_W:
  2275. taicpu(hp1).opsize := S_WL;
  2276. else
  2277. InternalError(2020012912);
  2278. end;
  2279. else
  2280. InternalError(2020012910);
  2281. end;
  2282. taicpu(hp1).opcode := A_MOVZX;
  2283. taicpu(hp1).oper[1]^.reg := newreg(getregtype(CurrentReg), getsupreg(CurrentReg), R_SUBD)
  2284. end
  2285. else
  2286. begin
  2287. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2288. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2289. RemoveInstruction(hp1);
  2290. { The instruction after what was hp1 is now the immediate next instruction,
  2291. so we can continue to make optimisations if it's present }
  2292. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2293. Exit;
  2294. hp1 := hp2;
  2295. end;
  2296. end;
  2297. end;
  2298. end;
  2299. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2300. overwrites the original destination register. e.g.
  2301. movl ###,%reg2d
  2302. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2303. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2304. }
  2305. if (taicpu(p).oper[1]^.typ = top_reg) and
  2306. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2307. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2308. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2309. begin
  2310. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2311. begin
  2312. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2313. case taicpu(p).oper[0]^.typ of
  2314. top_const:
  2315. { We have something like:
  2316. movb $x, %regb
  2317. movzbl %regb,%regd
  2318. Change to:
  2319. movl $x, %regd
  2320. }
  2321. begin
  2322. case taicpu(hp1).opsize of
  2323. S_BW:
  2324. begin
  2325. convert_mov_value(A_MOVSX, $FF);
  2326. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2327. taicpu(p).opsize := S_W;
  2328. end;
  2329. S_BL:
  2330. begin
  2331. convert_mov_value(A_MOVSX, $FF);
  2332. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2333. taicpu(p).opsize := S_L;
  2334. end;
  2335. S_WL:
  2336. begin
  2337. convert_mov_value(A_MOVSX, $FFFF);
  2338. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2339. taicpu(p).opsize := S_L;
  2340. end;
  2341. {$ifdef x86_64}
  2342. S_BQ:
  2343. begin
  2344. convert_mov_value(A_MOVSX, $FF);
  2345. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2346. taicpu(p).opsize := S_Q;
  2347. end;
  2348. S_WQ:
  2349. begin
  2350. convert_mov_value(A_MOVSX, $FFFF);
  2351. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2352. taicpu(p).opsize := S_Q;
  2353. end;
  2354. S_LQ:
  2355. begin
  2356. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2357. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2358. taicpu(p).opsize := S_Q;
  2359. end;
  2360. {$endif x86_64}
  2361. else
  2362. { If hp1 was a MOV instruction, it should have been
  2363. optimised already }
  2364. InternalError(2020021001);
  2365. end;
  2366. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2367. RemoveInstruction(hp1);
  2368. Result := True;
  2369. Exit;
  2370. end;
  2371. top_ref:
  2372. { We have something like:
  2373. movb mem, %regb
  2374. movzbl %regb,%regd
  2375. Change to:
  2376. movzbl mem, %regd
  2377. }
  2378. if (taicpu(p).oper[0]^.ref^.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2379. begin
  2380. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2381. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  2382. RemoveCurrentP(p, hp1);
  2383. Result:=True;
  2384. Exit;
  2385. end;
  2386. else
  2387. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2388. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2389. Exit;
  2390. end;
  2391. end
  2392. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2393. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2394. optimised }
  2395. else
  2396. begin
  2397. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2398. RemoveCurrentP(p, hp1);
  2399. Result := True;
  2400. Exit;
  2401. end;
  2402. end;
  2403. if (taicpu(hp1).opcode = A_AND) and
  2404. (taicpu(p).oper[1]^.typ = top_reg) and
  2405. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2406. begin
  2407. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2408. begin
  2409. case taicpu(p).opsize of
  2410. S_L:
  2411. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2412. begin
  2413. { Optimize out:
  2414. mov x, %reg
  2415. and ffffffffh, %reg
  2416. }
  2417. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2418. RemoveInstruction(hp1);
  2419. Result:=true;
  2420. exit;
  2421. end;
  2422. S_Q: { TODO: Confirm if this is even possible }
  2423. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2424. begin
  2425. { Optimize out:
  2426. mov x, %reg
  2427. and ffffffffffffffffh, %reg
  2428. }
  2429. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2430. RemoveInstruction(hp1);
  2431. Result:=true;
  2432. exit;
  2433. end;
  2434. else
  2435. ;
  2436. end;
  2437. if ((taicpu(p).oper[0]^.typ=top_reg) or
  2438. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  2439. GetNextInstruction(hp1,hp2) and
  2440. MatchInstruction(hp2,A_TEST,[taicpu(p).opsize]) and
  2441. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) and
  2442. (MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2443. MatchOperand(taicpu(hp2).oper[0]^,-1)) and
  2444. GetNextInstruction(hp2,hp3) and
  2445. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2446. (taicpu(hp3).condition in [C_E,C_NE]) then
  2447. begin
  2448. TransferUsedRegs(TmpUsedRegs);
  2449. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2450. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2451. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2452. begin
  2453. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2454. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2455. taicpu(hp1).opcode:=A_TEST;
  2456. RemoveInstruction(hp2);
  2457. RemoveCurrentP(p, hp1);
  2458. Result:=true;
  2459. exit;
  2460. end;
  2461. end;
  2462. end
  2463. else if IsMOVZXAcceptable and
  2464. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  2465. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  2466. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  2467. then
  2468. begin
  2469. InputVal := debug_operstr(taicpu(p).oper[0]^);
  2470. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  2471. case taicpu(p).opsize of
  2472. S_B:
  2473. if (taicpu(hp1).oper[0]^.val = $ff) then
  2474. begin
  2475. { Convert:
  2476. movb x, %regl movb x, %regl
  2477. andw ffh, %regw andl ffh, %regd
  2478. To:
  2479. movzbw x, %regd movzbl x, %regd
  2480. (Identical registers, just different sizes)
  2481. }
  2482. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  2483. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  2484. case taicpu(hp1).opsize of
  2485. S_W: NewSize := S_BW;
  2486. S_L: NewSize := S_BL;
  2487. {$ifdef x86_64}
  2488. S_Q: NewSize := S_BQ;
  2489. {$endif x86_64}
  2490. else
  2491. InternalError(2018011510);
  2492. end;
  2493. end
  2494. else
  2495. NewSize := S_NO;
  2496. S_W:
  2497. if (taicpu(hp1).oper[0]^.val = $ffff) then
  2498. begin
  2499. { Convert:
  2500. movw x, %regw
  2501. andl ffffh, %regd
  2502. To:
  2503. movzwl x, %regd
  2504. (Identical registers, just different sizes)
  2505. }
  2506. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  2507. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  2508. case taicpu(hp1).opsize of
  2509. S_L: NewSize := S_WL;
  2510. {$ifdef x86_64}
  2511. S_Q: NewSize := S_WQ;
  2512. {$endif x86_64}
  2513. else
  2514. InternalError(2018011511);
  2515. end;
  2516. end
  2517. else
  2518. NewSize := S_NO;
  2519. else
  2520. NewSize := S_NO;
  2521. end;
  2522. if NewSize <> S_NO then
  2523. begin
  2524. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  2525. { The actual optimization }
  2526. taicpu(p).opcode := A_MOVZX;
  2527. taicpu(p).changeopsize(NewSize);
  2528. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  2529. { Safeguard if "and" is followed by a conditional command }
  2530. TransferUsedRegs(TmpUsedRegs);
  2531. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  2532. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  2533. begin
  2534. { At this point, the "and" command is effectively equivalent to
  2535. "test %reg,%reg". This will be handled separately by the
  2536. Peephole Optimizer. [Kit] }
  2537. DebugMsg(SPeepholeOptimization + PreMessage +
  2538. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2539. end
  2540. else
  2541. begin
  2542. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  2543. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2544. RemoveInstruction(hp1);
  2545. end;
  2546. Result := True;
  2547. Exit;
  2548. end;
  2549. end;
  2550. end;
  2551. if (taicpu(hp1).opcode = A_OR) and
  2552. (taicpu(p).oper[1]^.typ = top_reg) and
  2553. MatchOperand(taicpu(p).oper[0]^, 0) and
  2554. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  2555. begin
  2556. { mov 0, %reg
  2557. or ###,%reg
  2558. Change to (only if the flags are not used):
  2559. mov ###,%reg
  2560. }
  2561. TransferUsedRegs(TmpUsedRegs);
  2562. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2563. DoOptimisation := True;
  2564. { Even if the flags are used, we might be able to do the optimisation
  2565. if the conditions are predictable }
  2566. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2567. begin
  2568. { Only perform if ### = %reg (the same register) or equal to 0,
  2569. so %reg is guaranteed to still have a value of zero }
  2570. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  2571. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  2572. begin
  2573. hp2 := hp1;
  2574. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2575. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  2576. GetNextInstruction(hp2, hp3) do
  2577. begin
  2578. { Don't continue modifying if the flags state is getting changed }
  2579. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  2580. Break;
  2581. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  2582. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  2583. begin
  2584. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  2585. begin
  2586. { Condition is always true }
  2587. case taicpu(hp3).opcode of
  2588. A_Jcc:
  2589. begin
  2590. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  2591. { Check for jump shortcuts before we destroy the condition }
  2592. DoJumpOptimizations(hp3, TempBool);
  2593. MakeUnconditional(taicpu(hp3));
  2594. Result := True;
  2595. end;
  2596. A_CMOVcc:
  2597. begin
  2598. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  2599. taicpu(hp3).opcode := A_MOV;
  2600. taicpu(hp3).condition := C_None;
  2601. Result := True;
  2602. end;
  2603. A_SETcc:
  2604. begin
  2605. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  2606. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  2607. taicpu(hp3).opcode := A_MOV;
  2608. taicpu(hp3).ops := 2;
  2609. taicpu(hp3).condition := C_None;
  2610. taicpu(hp3).opsize := S_B;
  2611. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2612. taicpu(hp3).loadconst(0, 1);
  2613. Result := True;
  2614. end;
  2615. else
  2616. InternalError(2021090701);
  2617. end;
  2618. end
  2619. 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
  2620. begin
  2621. { Condition is always false }
  2622. case taicpu(hp3).opcode of
  2623. A_Jcc:
  2624. begin
  2625. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  2626. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  2627. RemoveInstruction(hp3);
  2628. Result := True;
  2629. { Since hp3 was deleted, hp2 must not be updated }
  2630. Continue;
  2631. end;
  2632. A_CMOVcc:
  2633. begin
  2634. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  2635. RemoveInstruction(hp3);
  2636. Result := True;
  2637. { Since hp3 was deleted, hp2 must not be updated }
  2638. Continue;
  2639. end;
  2640. A_SETcc:
  2641. begin
  2642. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  2643. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  2644. taicpu(hp3).opcode := A_MOV;
  2645. taicpu(hp3).ops := 2;
  2646. taicpu(hp3).condition := C_None;
  2647. taicpu(hp3).opsize := S_B;
  2648. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2649. taicpu(hp3).loadconst(0, 0);
  2650. Result := True;
  2651. end;
  2652. else
  2653. InternalError(2021090702);
  2654. end;
  2655. end
  2656. else
  2657. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  2658. DoOptimisation := False;
  2659. end;
  2660. hp2 := hp3;
  2661. end;
  2662. { Flags are still in use - don't optimise }
  2663. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2664. DoOptimisation := False;
  2665. end
  2666. else
  2667. DoOptimisation := False;
  2668. end;
  2669. if DoOptimisation then
  2670. begin
  2671. {$ifdef x86_64}
  2672. { OR only supports 32-bit sign-extended constants for 64-bit
  2673. instructions, so compensate for this if the constant is
  2674. encoded as a value greater than or equal to 2^31 }
  2675. if (taicpu(hp1).opsize = S_Q) and
  2676. (taicpu(hp1).oper[0]^.typ = top_const) and
  2677. (taicpu(hp1).oper[0]^.val >= $80000000) then
  2678. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  2679. {$endif x86_64}
  2680. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  2681. taicpu(hp1).opcode := A_MOV;
  2682. RemoveCurrentP(p, hp1);
  2683. Result := True;
  2684. Exit;
  2685. end;
  2686. end;
  2687. { Next instruction is also a MOV ? }
  2688. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  2689. begin
  2690. if (taicpu(p).oper[1]^.typ = top_reg) and
  2691. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2692. begin
  2693. CurrentReg := taicpu(p).oper[1]^.reg;
  2694. TransferUsedRegs(TmpUsedRegs);
  2695. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2696. { we have
  2697. mov x, %treg
  2698. mov %treg, y
  2699. }
  2700. if not(RegInOp(CurrentReg, taicpu(hp1).oper[1]^)) then
  2701. if not(RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs)) then
  2702. { we've got
  2703. mov x, %treg
  2704. mov %treg, y
  2705. with %treg is not used after }
  2706. case taicpu(p).oper[0]^.typ Of
  2707. { top_reg is covered by DeepMOVOpt }
  2708. top_const:
  2709. begin
  2710. { change
  2711. mov const, %treg
  2712. mov %treg, y
  2713. to
  2714. mov const, y
  2715. }
  2716. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  2717. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  2718. begin
  2719. if taicpu(hp1).oper[1]^.typ=top_reg then
  2720. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2721. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  2722. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  2723. RemoveInstruction(hp1);
  2724. Result:=true;
  2725. Exit;
  2726. end;
  2727. end;
  2728. top_ref:
  2729. case taicpu(hp1).oper[1]^.typ of
  2730. top_reg:
  2731. begin
  2732. { change
  2733. mov mem, %treg
  2734. mov %treg, %reg
  2735. to
  2736. mov mem, %reg"
  2737. }
  2738. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2739. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  2740. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  2741. RemoveInstruction(hp1);
  2742. Result:=true;
  2743. Exit;
  2744. end;
  2745. top_ref:
  2746. begin
  2747. {$ifdef x86_64}
  2748. { Look for the following to simplify:
  2749. mov x(mem1), %reg
  2750. mov %reg, y(mem2)
  2751. mov x+8(mem1), %reg
  2752. mov %reg, y+8(mem2)
  2753. Change to:
  2754. movdqu x(mem1), %xmmreg
  2755. movdqu %xmmreg, y(mem2)
  2756. }
  2757. SourceRef := taicpu(p).oper[0]^.ref^;
  2758. TargetRef := taicpu(hp1).oper[1]^.ref^;
  2759. if (taicpu(p).opsize = S_Q) and
  2760. GetNextInstruction(hp1, hp2) and
  2761. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  2762. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  2763. begin
  2764. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  2765. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2766. Inc(SourceRef.offset, 8);
  2767. if UseAVX then
  2768. begin
  2769. MovAligned := A_VMOVDQA;
  2770. MovUnaligned := A_VMOVDQU;
  2771. end
  2772. else
  2773. begin
  2774. MovAligned := A_MOVDQA;
  2775. MovUnaligned := A_MOVDQU;
  2776. end;
  2777. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  2778. begin
  2779. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  2780. Inc(TargetRef.offset, 8);
  2781. if GetNextInstruction(hp2, hp3) and
  2782. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  2783. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  2784. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  2785. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  2786. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  2787. begin
  2788. CurrentReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  2789. if CurrentReg <> NR_NO then
  2790. begin
  2791. { Remember that the offsets are 8 ahead }
  2792. if ((SourceRef.offset mod 16) = 8) and
  2793. (
  2794. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2795. (SourceRef.base = current_procinfo.framepointer) or
  2796. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  2797. ) then
  2798. taicpu(p).opcode := MovAligned
  2799. else
  2800. taicpu(p).opcode := MovUnaligned;
  2801. taicpu(p).opsize := S_XMM;
  2802. taicpu(p).oper[1]^.reg := CurrentReg;
  2803. if ((TargetRef.offset mod 16) = 8) and
  2804. (
  2805. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2806. (TargetRef.base = current_procinfo.framepointer) or
  2807. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  2808. ) then
  2809. taicpu(hp1).opcode := MovAligned
  2810. else
  2811. taicpu(hp1).opcode := MovUnaligned;
  2812. taicpu(hp1).opsize := S_XMM;
  2813. taicpu(hp1).oper[0]^.reg := CurrentReg;
  2814. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  2815. RemoveInstruction(hp2);
  2816. RemoveInstruction(hp3);
  2817. Result := True;
  2818. Exit;
  2819. end;
  2820. end;
  2821. end
  2822. else
  2823. begin
  2824. { See if the next references are 8 less rather than 8 greater }
  2825. Dec(SourceRef.offset, 16); { -8 the other way }
  2826. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  2827. begin
  2828. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  2829. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  2830. if GetNextInstruction(hp2, hp3) and
  2831. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  2832. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  2833. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  2834. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  2835. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  2836. begin
  2837. CurrentReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  2838. if CurrentReg <> NR_NO then
  2839. begin
  2840. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  2841. if ((SourceRef.offset mod 16) = 0) and
  2842. (
  2843. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2844. (SourceRef.base = current_procinfo.framepointer) or
  2845. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  2846. ) then
  2847. taicpu(hp2).opcode := MovAligned
  2848. else
  2849. taicpu(hp2).opcode := MovUnaligned;
  2850. taicpu(hp2).opsize := S_XMM;
  2851. taicpu(hp2).oper[1]^.reg := CurrentReg;
  2852. if ((TargetRef.offset mod 16) = 0) and
  2853. (
  2854. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2855. (TargetRef.base = current_procinfo.framepointer) or
  2856. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  2857. ) then
  2858. taicpu(hp3).opcode := MovAligned
  2859. else
  2860. taicpu(hp3).opcode := MovUnaligned;
  2861. taicpu(hp3).opsize := S_XMM;
  2862. taicpu(hp3).oper[0]^.reg := CurrentReg;
  2863. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  2864. RemoveInstruction(hp1);
  2865. RemoveCurrentP(p, hp2);
  2866. Result := True;
  2867. Exit;
  2868. end;
  2869. end;
  2870. end;
  2871. end;
  2872. end;
  2873. {$endif x86_64}
  2874. end;
  2875. else
  2876. { The write target should be a reg or a ref }
  2877. InternalError(2021091601);
  2878. end;
  2879. else
  2880. ;
  2881. end
  2882. else
  2883. { %treg is used afterwards, but all eventualities
  2884. other than the first MOV instruction being a constant
  2885. are covered by DeepMOVOpt, so only check for that }
  2886. if (taicpu(p).oper[0]^.typ = top_const) and
  2887. (
  2888. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  2889. not (cs_opt_size in current_settings.optimizerswitches) or
  2890. (taicpu(hp1).opsize = S_B)
  2891. ) and
  2892. (
  2893. (taicpu(hp1).oper[1]^.typ = top_reg) or
  2894. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  2895. ) then
  2896. begin
  2897. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  2898. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  2899. end;
  2900. end;
  2901. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  2902. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  2903. { mov reg1, mem1 or mov mem1, reg1
  2904. mov mem2, reg2 mov reg2, mem2}
  2905. begin
  2906. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  2907. { mov reg1, mem1 or mov mem1, reg1
  2908. mov mem2, reg1 mov reg2, mem1}
  2909. begin
  2910. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  2911. { Removes the second statement from
  2912. mov reg1, mem1/reg2
  2913. mov mem1/reg2, reg1 }
  2914. begin
  2915. if taicpu(p).oper[0]^.typ=top_reg then
  2916. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  2917. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  2918. RemoveInstruction(hp1);
  2919. Result:=true;
  2920. exit;
  2921. end
  2922. else
  2923. begin
  2924. TransferUsedRegs(TmpUsedRegs);
  2925. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2926. if (taicpu(p).oper[1]^.typ = top_ref) and
  2927. { mov reg1, mem1
  2928. mov mem2, reg1 }
  2929. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  2930. GetNextInstruction(hp1, hp2) and
  2931. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  2932. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  2933. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  2934. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  2935. { change to
  2936. mov reg1, mem1 mov reg1, mem1
  2937. mov mem2, reg1 cmp reg1, mem2
  2938. cmp mem1, reg1
  2939. }
  2940. begin
  2941. RemoveInstruction(hp2);
  2942. taicpu(hp1).opcode := A_CMP;
  2943. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  2944. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  2945. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  2946. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  2947. end;
  2948. end;
  2949. end
  2950. else if (taicpu(p).oper[1]^.typ=top_ref) and
  2951. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  2952. begin
  2953. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  2954. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  2955. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  2956. end
  2957. else
  2958. begin
  2959. TransferUsedRegs(TmpUsedRegs);
  2960. if GetNextInstruction(hp1, hp2) and
  2961. MatchOpType(taicpu(p),top_ref,top_reg) and
  2962. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  2963. (taicpu(hp1).oper[1]^.typ = top_ref) and
  2964. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  2965. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  2966. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  2967. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  2968. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  2969. { mov mem1, %reg1
  2970. mov %reg1, mem2
  2971. mov mem2, reg2
  2972. to:
  2973. mov mem1, reg2
  2974. mov reg2, mem2}
  2975. begin
  2976. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  2977. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  2978. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  2979. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  2980. RemoveInstruction(hp2);
  2981. Result := True;
  2982. end
  2983. {$ifdef i386}
  2984. { this is enabled for i386 only, as the rules to create the reg sets below
  2985. are too complicated for x86-64, so this makes this code too error prone
  2986. on x86-64
  2987. }
  2988. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  2989. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  2990. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  2991. { mov mem1, reg1 mov mem1, reg1
  2992. mov reg1, mem2 mov reg1, mem2
  2993. mov mem2, reg2 mov mem2, reg1
  2994. to: to:
  2995. mov mem1, reg1 mov mem1, reg1
  2996. mov mem1, reg2 mov reg1, mem2
  2997. mov reg1, mem2
  2998. or (if mem1 depends on reg1
  2999. and/or if mem2 depends on reg2)
  3000. to:
  3001. mov mem1, reg1
  3002. mov reg1, mem2
  3003. mov reg1, reg2
  3004. }
  3005. begin
  3006. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3007. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3008. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3009. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3010. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3011. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3012. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3013. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3014. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3015. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3016. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3017. end
  3018. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3019. begin
  3020. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3021. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3022. end
  3023. else
  3024. begin
  3025. RemoveInstruction(hp2);
  3026. end
  3027. {$endif i386}
  3028. ;
  3029. end;
  3030. end
  3031. { movl [mem1],reg1
  3032. movl [mem1],reg2
  3033. to
  3034. movl [mem1],reg1
  3035. movl reg1,reg2
  3036. }
  3037. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3038. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3039. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3040. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3041. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3042. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3043. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3044. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3045. begin
  3046. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3047. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3048. end;
  3049. { movl const1,[mem1]
  3050. movl [mem1],reg1
  3051. to
  3052. movl const1,reg1
  3053. movl reg1,[mem1]
  3054. }
  3055. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3056. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3057. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3058. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3059. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3060. begin
  3061. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3062. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3063. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3064. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3065. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3066. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3067. Result:=true;
  3068. exit;
  3069. end;
  3070. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3071. end;
  3072. { search further than the next instruction for a mov (as long as it's not a jump) }
  3073. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3074. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3075. (taicpu(p).oper[1]^.typ = top_reg) and
  3076. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3077. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3078. begin
  3079. { we work with hp2 here, so hp1 can be still used later on when
  3080. checking for GetNextInstruction_p }
  3081. hp3 := hp1;
  3082. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3083. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3084. { Saves on a large number of dereferences }
  3085. ActiveReg := taicpu(p).oper[1]^.reg;
  3086. TransferUsedRegs(TmpUsedRegs);
  3087. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3088. while GetNextInstructionUsingRegCond(hp3,hp2,ActiveReg,CrossJump) and
  3089. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3090. (hp2.typ=ait_instruction) do
  3091. begin
  3092. case taicpu(hp2).opcode of
  3093. A_POP:
  3094. if MatchOperand(taicpu(hp2).oper[0]^,ActiveReg) then
  3095. begin
  3096. if not CrossJump and
  3097. not RegUsedBetween(ActiveReg, p, hp2) then
  3098. begin
  3099. { We can remove the original MOV since the register
  3100. wasn't used between it and its popping from the stack }
  3101. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3102. RemoveCurrentp(p, hp1);
  3103. Result := True;
  3104. Exit;
  3105. end;
  3106. { Can't go any further }
  3107. Break;
  3108. end;
  3109. A_MOV:
  3110. if MatchOperand(taicpu(hp2).oper[0]^,ActiveReg) and
  3111. ((taicpu(p).oper[0]^.typ=top_const) or
  3112. ((taicpu(p).oper[0]^.typ=top_reg) and
  3113. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3114. )
  3115. ) then
  3116. begin
  3117. { we have
  3118. mov x, %treg
  3119. mov %treg, y
  3120. }
  3121. { We don't need to call UpdateUsedRegs for every instruction between
  3122. p and hp2 because the register we're concerned about will not
  3123. become deallocated (otherwise GetNextInstructionUsingReg would
  3124. have stopped at an earlier instruction). [Kit] }
  3125. TempRegUsed :=
  3126. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3127. RegReadByInstruction(ActiveReg, hp3) or
  3128. RegUsedAfterInstruction(ActiveReg, hp2, TmpUsedRegs);
  3129. case taicpu(p).oper[0]^.typ Of
  3130. top_reg:
  3131. begin
  3132. { change
  3133. mov %reg, %treg
  3134. mov %treg, y
  3135. to
  3136. mov %reg, y
  3137. }
  3138. CurrentReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3139. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3140. if taicpu(hp2).oper[1]^.reg = CurrentReg then
  3141. begin
  3142. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3143. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3144. if TempRegUsed then
  3145. begin
  3146. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3147. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  3148. { Set the start of the next GetNextInstructionUsingRegCond search
  3149. to start at the entry right before hp2 (which is about to be removed) }
  3150. hp3 := tai(hp2.Previous);
  3151. RemoveInstruction(hp2);
  3152. { See if there's more we can optimise }
  3153. Continue;
  3154. end
  3155. else
  3156. begin
  3157. RemoveInstruction(hp2);
  3158. { We can remove the original MOV too }
  3159. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3160. RemoveCurrentP(p, hp1);
  3161. Result:=true;
  3162. Exit;
  3163. end;
  3164. end
  3165. else
  3166. begin
  3167. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  3168. taicpu(hp2).loadReg(0, CurrentReg);
  3169. if TempRegUsed then
  3170. begin
  3171. { Don't remove the first instruction if the temporary register is in use }
  3172. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(CurrentReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3173. { No need to set Result to True. If there's another instruction later on
  3174. that can be optimised, it will be detected when the main Pass 1 loop
  3175. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3176. end
  3177. else
  3178. begin
  3179. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3180. RemoveCurrentP(p, hp1);
  3181. Result:=true;
  3182. Exit;
  3183. end;
  3184. end;
  3185. end;
  3186. top_const:
  3187. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3188. begin
  3189. { change
  3190. mov const, %treg
  3191. mov %treg, y
  3192. to
  3193. mov const, y
  3194. }
  3195. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3196. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3197. begin
  3198. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3199. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3200. if TempRegUsed then
  3201. begin
  3202. { Don't remove the first instruction if the temporary register is in use }
  3203. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3204. { No need to set Result to True. If there's another instruction later on
  3205. that can be optimised, it will be detected when the main Pass 1 loop
  3206. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3207. end
  3208. else
  3209. begin
  3210. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3211. RemoveCurrentP(p, hp1);
  3212. Result:=true;
  3213. Exit;
  3214. end;
  3215. end;
  3216. end;
  3217. else
  3218. Internalerror(2019103001);
  3219. end;
  3220. end
  3221. else
  3222. if MatchOperand(taicpu(hp2).oper[1]^, ActiveReg) then
  3223. begin
  3224. if not CrossJump and
  3225. not RegUsedBetween(ActiveReg, p, hp2) and
  3226. not RegReadByInstruction(ActiveReg, hp2) then
  3227. begin
  3228. { Register is not used before it is overwritten }
  3229. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3230. RemoveCurrentp(p, hp1);
  3231. Result := True;
  3232. Exit;
  3233. end;
  3234. if (taicpu(p).oper[0]^.typ = top_const) and
  3235. (taicpu(hp2).oper[0]^.typ = top_const) then
  3236. begin
  3237. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3238. begin
  3239. { Same value - register hasn't changed }
  3240. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3241. RemoveInstruction(hp2);
  3242. Result := True;
  3243. { See if there's more we can optimise }
  3244. Continue;
  3245. end;
  3246. end;
  3247. end;
  3248. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  3249. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  3250. MatchOperand(taicpu(hp2).oper[0]^, ActiveReg) and
  3251. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, ActiveReg) then
  3252. begin
  3253. {
  3254. Change from:
  3255. mov ###, %reg
  3256. ...
  3257. movs/z %reg,%reg (Same register, just different sizes)
  3258. To:
  3259. movs/z ###, %reg (Longer version)
  3260. ...
  3261. (remove)
  3262. }
  3263. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  3264. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  3265. { Keep the first instruction as mov if ### is a constant }
  3266. if taicpu(p).oper[0]^.typ = top_const then
  3267. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  3268. else
  3269. begin
  3270. taicpu(p).opcode := taicpu(hp2).opcode;
  3271. taicpu(p).opsize := taicpu(hp2).opsize;
  3272. end;
  3273. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  3274. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  3275. RemoveInstruction(hp2);
  3276. Result := True;
  3277. Exit;
  3278. end;
  3279. else
  3280. { Move down to the MatchOpType if-block below };
  3281. end;
  3282. { Also catches MOV/S/Z instructions that aren't modified }
  3283. if taicpu(p).oper[0]^.typ = top_reg then
  3284. begin
  3285. CurrentReg := taicpu(p).oper[0]^.reg;
  3286. if
  3287. not RegModifiedByInstruction(CurrentReg, hp3) and
  3288. not RegModifiedBetween(CurrentReg, hp3, hp2) and
  3289. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  3290. begin
  3291. Result := True;
  3292. { Just in case something didn't get modified (e.g. an
  3293. implicit register). Also, if it does read from this
  3294. register, then there's no longer an advantage to
  3295. changing the register on subsequent instructions.}
  3296. if not RegReadByInstruction(ActiveReg, hp2) then
  3297. begin
  3298. { If a conditional jump was crossed, do not delete
  3299. the original MOV no matter what }
  3300. if not CrossJump and
  3301. { RegEndOfLife returns True if the register is
  3302. deallocated before the next instruction or has
  3303. been loaded with a new value }
  3304. RegEndOfLife(ActiveReg, taicpu(hp2)) then
  3305. begin
  3306. { We can remove the original MOV }
  3307. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  3308. RemoveCurrentp(p, hp1);
  3309. Exit;
  3310. end;
  3311. if not RegModifiedByInstruction(ActiveReg, hp2) then
  3312. begin
  3313. { See if there's more we can optimise }
  3314. hp3 := hp2;
  3315. Continue;
  3316. end;
  3317. end;
  3318. end;
  3319. end;
  3320. { Break out of the while loop under normal circumstances }
  3321. Break;
  3322. end;
  3323. end;
  3324. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  3325. (taicpu(p).oper[1]^.typ = top_reg) and
  3326. (taicpu(p).opsize = S_L) and
  3327. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  3328. (taicpu(hp2).opcode = A_AND) and
  3329. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  3330. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3331. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  3332. ) then
  3333. begin
  3334. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  3335. begin
  3336. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  3337. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  3338. begin
  3339. { Optimize out:
  3340. mov x, %reg
  3341. and ffffffffh, %reg
  3342. }
  3343. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  3344. RemoveInstruction(hp2);
  3345. Result:=true;
  3346. exit;
  3347. end;
  3348. end;
  3349. end;
  3350. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  3351. x >= RetOffset) as it doesn't do anything (it writes either to a
  3352. parameter or to the temporary storage room for the function
  3353. result)
  3354. }
  3355. if IsExitCode(hp1) and
  3356. (taicpu(p).oper[1]^.typ = top_ref) and
  3357. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  3358. (
  3359. (
  3360. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  3361. not (
  3362. assigned(current_procinfo.procdef.funcretsym) and
  3363. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  3364. )
  3365. ) or
  3366. { Also discard writes to the stack that are below the base pointer,
  3367. as this is temporary storage rather than a function result on the
  3368. stack, say. }
  3369. (
  3370. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  3371. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  3372. )
  3373. ) then
  3374. begin
  3375. RemoveCurrentp(p, hp1);
  3376. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  3377. RemoveLastDeallocForFuncRes(p);
  3378. Result:=true;
  3379. exit;
  3380. end;
  3381. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  3382. begin
  3383. if MatchOpType(taicpu(p),top_reg,top_ref) and
  3384. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3385. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3386. begin
  3387. { change
  3388. mov reg1, mem1
  3389. test/cmp x, mem1
  3390. to
  3391. mov reg1, mem1
  3392. test/cmp x, reg1
  3393. }
  3394. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  3395. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  3396. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3397. Result := True;
  3398. Exit;
  3399. end;
  3400. if MatchOpType(taicpu(p),top_ref,top_reg) and
  3401. { The x86 assemblers have difficulty comparing values against absolute addresses }
  3402. (taicpu(p).oper[0]^.ref^.refaddr in [addr_no, addr_pic, addr_pic_no_got]) and
  3403. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  3404. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  3405. (
  3406. (
  3407. (taicpu(hp1).opcode = A_TEST)
  3408. ) or (
  3409. (taicpu(hp1).opcode = A_CMP) and
  3410. { A sanity check more than anything }
  3411. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  3412. )
  3413. ) then
  3414. begin
  3415. { change
  3416. mov mem, %reg
  3417. cmp/test x, %reg / test %reg,%reg
  3418. (reg deallocated)
  3419. to
  3420. cmp/test x, mem / cmp 0, mem
  3421. }
  3422. TransferUsedRegs(TmpUsedRegs);
  3423. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3424. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  3425. begin
  3426. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  3427. if (taicpu(hp1).opcode = A_TEST) and
  3428. (
  3429. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  3430. MatchOperand(taicpu(hp1).oper[0]^, -1)
  3431. ) then
  3432. begin
  3433. taicpu(hp1).opcode := A_CMP;
  3434. taicpu(hp1).loadconst(0, 0);
  3435. end;
  3436. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  3437. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  3438. RemoveCurrentP(p, hp1);
  3439. Result := True;
  3440. Exit;
  3441. end;
  3442. end;
  3443. end;
  3444. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  3445. { If the flags register is in use, don't change the instruction to an
  3446. ADD otherwise this will scramble the flags. [Kit] }
  3447. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  3448. begin
  3449. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  3450. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3451. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3452. ) or
  3453. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3454. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3455. )
  3456. ) then
  3457. { mov reg1,ref
  3458. lea reg2,[reg1,reg2]
  3459. to
  3460. add reg2,ref}
  3461. begin
  3462. TransferUsedRegs(TmpUsedRegs);
  3463. { reg1 may not be used afterwards }
  3464. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3465. begin
  3466. Taicpu(hp1).opcode:=A_ADD;
  3467. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3468. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3469. RemoveCurrentp(p, hp1);
  3470. result:=true;
  3471. exit;
  3472. end;
  3473. end;
  3474. { If the LEA instruction can be converted into an arithmetic instruction,
  3475. it may be possible to then fold it in the next optimisation, otherwise
  3476. there's nothing more that can be optimised here. }
  3477. if not ConvertLEA(taicpu(hp1)) then
  3478. Exit;
  3479. end;
  3480. if (taicpu(p).oper[1]^.typ = top_reg) and
  3481. (hp1.typ = ait_instruction) and
  3482. GetNextInstruction(hp1, hp2) and
  3483. MatchInstruction(hp2,A_MOV,[]) and
  3484. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  3485. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  3486. (
  3487. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  3488. {$ifdef x86_64}
  3489. or
  3490. (
  3491. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  3492. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  3493. )
  3494. {$endif x86_64}
  3495. ) then
  3496. begin
  3497. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  3498. (taicpu(hp2).oper[0]^.typ=top_reg) then
  3499. { change movsX/movzX reg/ref, reg2
  3500. add/sub/or/... reg3/$const, reg2
  3501. mov reg2 reg/ref
  3502. dealloc reg2
  3503. to
  3504. add/sub/or/... reg3/$const, reg/ref }
  3505. begin
  3506. TransferUsedRegs(TmpUsedRegs);
  3507. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3508. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3509. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3510. begin
  3511. { by example:
  3512. movswl %si,%eax movswl %si,%eax p
  3513. decl %eax addl %edx,%eax hp1
  3514. movw %ax,%si movw %ax,%si hp2
  3515. ->
  3516. movswl %si,%eax movswl %si,%eax p
  3517. decw %eax addw %edx,%eax hp1
  3518. movw %ax,%si movw %ax,%si hp2
  3519. }
  3520. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  3521. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3522. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3523. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3524. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3525. {
  3526. ->
  3527. movswl %si,%eax movswl %si,%eax p
  3528. decw %si addw %dx,%si hp1
  3529. movw %ax,%si movw %ax,%si hp2
  3530. }
  3531. case taicpu(hp1).ops of
  3532. 1:
  3533. begin
  3534. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3535. if taicpu(hp1).oper[0]^.typ=top_reg then
  3536. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3537. end;
  3538. 2:
  3539. begin
  3540. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3541. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3542. (taicpu(hp1).opcode<>A_SHL) and
  3543. (taicpu(hp1).opcode<>A_SHR) and
  3544. (taicpu(hp1).opcode<>A_SAR) then
  3545. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3546. end;
  3547. else
  3548. internalerror(2008042701);
  3549. end;
  3550. {
  3551. ->
  3552. decw %si addw %dx,%si p
  3553. }
  3554. RemoveInstruction(hp2);
  3555. RemoveCurrentP(p, hp1);
  3556. Result:=True;
  3557. Exit;
  3558. end;
  3559. end;
  3560. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3561. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  3562. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  3563. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  3564. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  3565. )
  3566. {$ifdef i386}
  3567. { byte registers of esi, edi, ebp, esp are not available on i386 }
  3568. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3569. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3570. {$endif i386}
  3571. then
  3572. { change movsX/movzX reg/ref, reg2
  3573. add/sub/or/... regX/$const, reg2
  3574. mov reg2, reg3
  3575. dealloc reg2
  3576. to
  3577. movsX/movzX reg/ref, reg3
  3578. add/sub/or/... reg3/$const, reg3
  3579. }
  3580. begin
  3581. TransferUsedRegs(TmpUsedRegs);
  3582. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3583. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3584. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3585. begin
  3586. { by example:
  3587. movswl %si,%eax movswl %si,%eax p
  3588. decl %eax addl %edx,%eax hp1
  3589. movw %ax,%si movw %ax,%si hp2
  3590. ->
  3591. movswl %si,%eax movswl %si,%eax p
  3592. decw %eax addw %edx,%eax hp1
  3593. movw %ax,%si movw %ax,%si hp2
  3594. }
  3595. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  3596. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3597. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3598. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3599. { limit size of constants as well to avoid assembler errors, but
  3600. check opsize to avoid overflow when left shifting the 1 }
  3601. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  3602. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  3603. {$ifdef x86_64}
  3604. { Be careful of, for example:
  3605. movl %reg1,%reg2
  3606. addl %reg3,%reg2
  3607. movq %reg2,%reg4
  3608. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  3609. }
  3610. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  3611. begin
  3612. taicpu(hp2).changeopsize(S_L);
  3613. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  3614. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  3615. end;
  3616. {$endif x86_64}
  3617. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3618. taicpu(p).changeopsize(taicpu(hp2).opsize);
  3619. if taicpu(p).oper[0]^.typ=top_reg then
  3620. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3621. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  3622. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  3623. {
  3624. ->
  3625. movswl %si,%eax movswl %si,%eax p
  3626. decw %si addw %dx,%si hp1
  3627. movw %ax,%si movw %ax,%si hp2
  3628. }
  3629. case taicpu(hp1).ops of
  3630. 1:
  3631. begin
  3632. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3633. if taicpu(hp1).oper[0]^.typ=top_reg then
  3634. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3635. end;
  3636. 2:
  3637. begin
  3638. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3639. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3640. (taicpu(hp1).opcode<>A_SHL) and
  3641. (taicpu(hp1).opcode<>A_SHR) and
  3642. (taicpu(hp1).opcode<>A_SAR) then
  3643. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3644. end;
  3645. else
  3646. internalerror(2018111801);
  3647. end;
  3648. {
  3649. ->
  3650. decw %si addw %dx,%si p
  3651. }
  3652. RemoveInstruction(hp2);
  3653. end;
  3654. end;
  3655. end;
  3656. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  3657. GetNextInstruction(hp1, hp2) and
  3658. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  3659. MatchOperand(Taicpu(p).oper[0]^,0) and
  3660. (Taicpu(p).oper[1]^.typ = top_reg) and
  3661. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  3662. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  3663. { mov reg1,0
  3664. bts reg1,operand1 --> mov reg1,operand2
  3665. or reg1,operand2 bts reg1,operand1}
  3666. begin
  3667. Taicpu(hp2).opcode:=A_MOV;
  3668. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  3669. asml.remove(hp1);
  3670. insertllitem(hp2,hp2.next,hp1);
  3671. RemoveCurrentp(p, hp1);
  3672. Result:=true;
  3673. exit;
  3674. end;
  3675. {
  3676. mov ref,reg0
  3677. <op> reg0,reg1
  3678. dealloc reg0
  3679. to
  3680. <op> ref,reg1
  3681. }
  3682. if MatchOpType(taicpu(p),top_ref,top_reg) and
  3683. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  3684. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3685. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  3686. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  3687. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  3688. begin
  3689. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  3690. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  3691. RemoveCurrentp(p, hp1);
  3692. Result:=true;
  3693. exit;
  3694. end;
  3695. {$ifdef x86_64}
  3696. { Convert:
  3697. movq x(ref),%reg64
  3698. shrq y,%reg64
  3699. To:
  3700. movq x+4(ref),%reg32
  3701. shrq y-32,%reg32 (Remove if y = 32)
  3702. }
  3703. if (taicpu(p).opsize = S_Q) and
  3704. (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  3705. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFB) and
  3706. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  3707. MatchOpType(taicpu(hp1), top_const, top_reg) and
  3708. (taicpu(hp1).oper[0]^.val >= 32) and
  3709. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  3710. begin
  3711. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  3712. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  3713. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  3714. { Convert to 32-bit }
  3715. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3716. taicpu(p).opsize := S_L;
  3717. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  3718. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  3719. if (taicpu(hp1).oper[0]^.val = 32) then
  3720. begin
  3721. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  3722. RemoveInstruction(hp1);
  3723. end
  3724. else
  3725. begin
  3726. { This will potentially open up more arithmetic operations since
  3727. the peephole optimizer now has a big hint that only the lower
  3728. 32 bits are currently in use (and opcodes are smaller in size) }
  3729. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3730. taicpu(hp1).opsize := S_L;
  3731. Dec(taicpu(hp1).oper[0]^.val, 32);
  3732. DebugMsg(SPeepholeOptimization + PreMessage +
  3733. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  3734. end;
  3735. Result := True;
  3736. Exit;
  3737. end;
  3738. {$endif x86_64}
  3739. end;
  3740. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  3741. var
  3742. hp1 : tai;
  3743. begin
  3744. Result:=false;
  3745. if taicpu(p).ops <> 2 then
  3746. exit;
  3747. if GetNextInstruction(p,hp1) then
  3748. begin
  3749. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  3750. (taicpu(hp1).ops = 2) then
  3751. begin
  3752. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3753. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3754. { movXX reg1, mem1 or movXX mem1, reg1
  3755. movXX mem2, reg2 movXX reg2, mem2}
  3756. begin
  3757. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3758. { movXX reg1, mem1 or movXX mem1, reg1
  3759. movXX mem2, reg1 movXX reg2, mem1}
  3760. begin
  3761. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3762. begin
  3763. { Removes the second statement from
  3764. movXX reg1, mem1/reg2
  3765. movXX mem1/reg2, reg1
  3766. }
  3767. if taicpu(p).oper[0]^.typ=top_reg then
  3768. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3769. { Removes the second statement from
  3770. movXX mem1/reg1, reg2
  3771. movXX reg2, mem1/reg1
  3772. }
  3773. if (taicpu(p).oper[1]^.typ=top_reg) and
  3774. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  3775. begin
  3776. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  3777. RemoveInstruction(hp1);
  3778. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  3779. end
  3780. else
  3781. begin
  3782. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  3783. RemoveInstruction(hp1);
  3784. end;
  3785. Result:=true;
  3786. exit;
  3787. end
  3788. end;
  3789. end;
  3790. end;
  3791. end;
  3792. end;
  3793. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  3794. var
  3795. hp1 : tai;
  3796. begin
  3797. result:=false;
  3798. { replace
  3799. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  3800. MovX %mreg2,%mreg1
  3801. dealloc %mreg2
  3802. by
  3803. <Op>X %mreg2,%mreg1
  3804. ?
  3805. }
  3806. if GetNextInstruction(p,hp1) and
  3807. { we mix single and double opperations here because we assume that the compiler
  3808. generates vmovapd only after double operations and vmovaps only after single operations }
  3809. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  3810. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3811. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  3812. (taicpu(p).oper[0]^.typ=top_reg) then
  3813. begin
  3814. TransferUsedRegs(TmpUsedRegs);
  3815. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3816. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3817. begin
  3818. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  3819. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  3820. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  3821. RemoveInstruction(hp1);
  3822. result:=true;
  3823. end;
  3824. end;
  3825. end;
  3826. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  3827. var
  3828. hp1, p_label, p_dist, hp1_dist: tai;
  3829. JumpLabel, JumpLabel_dist: TAsmLabel;
  3830. begin
  3831. Result := False;
  3832. if GetNextInstruction(p, hp1) and
  3833. TrySwapMovCmp(p, hp1) then
  3834. begin
  3835. Result := True;
  3836. Exit;
  3837. end;
  3838. { Search for:
  3839. test %reg,%reg
  3840. j(c1) @lbl1
  3841. ...
  3842. @lbl:
  3843. test %reg,%reg (same register)
  3844. j(c2) @lbl2
  3845. If c2 is a subset of c1, change to:
  3846. test %reg,%reg
  3847. j(c1) @lbl2
  3848. (@lbl1 may become a dead label as a result)
  3849. }
  3850. if (taicpu(p).oper[1]^.typ = top_reg) and
  3851. (taicpu(p).oper[0]^.typ = top_reg) and
  3852. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  3853. MatchInstruction(hp1, A_JCC, []) and
  3854. IsJumpToLabel(taicpu(hp1)) then
  3855. begin
  3856. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  3857. p_label := nil;
  3858. if Assigned(JumpLabel) then
  3859. p_label := getlabelwithsym(JumpLabel);
  3860. if Assigned(p_label) and
  3861. GetNextInstruction(p_label, p_dist) and
  3862. MatchInstruction(p_dist, A_TEST, []) and
  3863. { It's fine if the second test uses smaller sub-registers }
  3864. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  3865. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  3866. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  3867. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  3868. GetNextInstruction(p_dist, hp1_dist) and
  3869. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  3870. begin
  3871. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  3872. if JumpLabel = JumpLabel_dist then
  3873. { This is an infinite loop }
  3874. Exit;
  3875. { Best optimisation when the first condition is a subset (or equal) of the second }
  3876. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  3877. begin
  3878. { Any registers used here will already be allocated }
  3879. if Assigned(JumpLabel_dist) then
  3880. JumpLabel_dist.IncRefs;
  3881. if Assigned(JumpLabel) then
  3882. JumpLabel.DecRefs;
  3883. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  3884. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  3885. Result := True;
  3886. Exit;
  3887. end;
  3888. end;
  3889. end;
  3890. end;
  3891. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  3892. var
  3893. hp1 : tai;
  3894. begin
  3895. result:=false;
  3896. { replace
  3897. addX const,%reg1
  3898. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  3899. dealloc %reg1
  3900. by
  3901. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  3902. }
  3903. if MatchOpType(taicpu(p),top_const,top_reg) and
  3904. GetNextInstruction(p,hp1) and
  3905. MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  3906. ((taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.base) or
  3907. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index)) then
  3908. begin
  3909. TransferUsedRegs(TmpUsedRegs);
  3910. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3911. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3912. begin
  3913. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  3914. if taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.base then
  3915. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  3916. if taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index then
  3917. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  3918. RemoveCurrentP(p);
  3919. result:=true;
  3920. end;
  3921. end;
  3922. end;
  3923. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  3924. var
  3925. hp1: tai;
  3926. ref: Integer;
  3927. saveref: treference;
  3928. TempReg: TRegister;
  3929. Multiple: TCGInt;
  3930. begin
  3931. Result:=false;
  3932. { removes seg register prefixes from LEA operations, as they
  3933. don't do anything}
  3934. taicpu(p).oper[0]^.ref^.Segment:=NR_NO;
  3935. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  3936. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3937. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  3938. (
  3939. { do not mess with leas accessing the stack pointer
  3940. unless it's a null operation }
  3941. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  3942. (
  3943. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  3944. (taicpu(p).oper[0]^.ref^.offset = 0)
  3945. )
  3946. ) and
  3947. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  3948. begin
  3949. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  3950. begin
  3951. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  3952. begin
  3953. hp1:=taicpu.op_reg_reg(A_MOV,taicpu(p).opsize,taicpu(p).oper[0]^.ref^.base,
  3954. taicpu(p).oper[1]^.reg);
  3955. InsertLLItem(p.previous,p.next, hp1);
  3956. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',hp1);
  3957. p.free;
  3958. p:=hp1;
  3959. end
  3960. else
  3961. begin
  3962. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  3963. RemoveCurrentP(p);
  3964. end;
  3965. Result:=true;
  3966. exit;
  3967. end
  3968. else if (
  3969. { continue to use lea to adjust the stack pointer,
  3970. it is the recommended way, but only if not optimizing for size }
  3971. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  3972. (cs_opt_size in current_settings.optimizerswitches)
  3973. ) and
  3974. { If the flags register is in use, don't change the instruction
  3975. to an ADD otherwise this will scramble the flags. [Kit] }
  3976. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  3977. ConvertLEA(taicpu(p)) then
  3978. begin
  3979. Result:=true;
  3980. exit;
  3981. end;
  3982. end;
  3983. if GetNextInstruction(p,hp1) and
  3984. (hp1.typ=ait_instruction) then
  3985. begin
  3986. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  3987. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3988. MatchOpType(Taicpu(hp1),top_reg,top_reg) and
  3989. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) then
  3990. begin
  3991. TransferUsedRegs(TmpUsedRegs);
  3992. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3993. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3994. begin
  3995. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  3996. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  3997. RemoveInstruction(hp1);
  3998. result:=true;
  3999. exit;
  4000. end;
  4001. end;
  4002. { changes
  4003. lea <ref1>, reg1
  4004. <op> ...,<ref. with reg1>,...
  4005. to
  4006. <op> ...,<ref1>,... }
  4007. if (taicpu(p).oper[1]^.reg<>current_procinfo.framepointer) and
  4008. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) and
  4009. not(MatchInstruction(hp1,A_LEA,[])) then
  4010. begin
  4011. { find a reference which uses reg1 }
  4012. 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
  4013. ref:=0
  4014. 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
  4015. ref:=1
  4016. else
  4017. ref:=-1;
  4018. if (ref<>-1) and
  4019. { reg1 must be either the base or the index }
  4020. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  4021. begin
  4022. { reg1 can be removed from the reference }
  4023. saveref:=taicpu(hp1).oper[ref]^.ref^;
  4024. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  4025. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  4026. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  4027. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  4028. else
  4029. Internalerror(2019111201);
  4030. { check if the can insert all data of the lea into the second instruction }
  4031. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4032. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  4033. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  4034. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  4035. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  4036. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4037. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  4038. {$ifdef x86_64}
  4039. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  4040. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  4041. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  4042. )
  4043. {$endif x86_64}
  4044. then
  4045. begin
  4046. { reg1 might not used by the second instruction after it is remove from the reference }
  4047. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  4048. begin
  4049. TransferUsedRegs(TmpUsedRegs);
  4050. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4051. { reg1 is not updated so it might not be used afterwards }
  4052. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4053. begin
  4054. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  4055. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  4056. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4057. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4058. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4059. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  4060. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  4061. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  4062. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  4063. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  4064. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4065. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4066. RemoveCurrentP(p, hp1);
  4067. result:=true;
  4068. exit;
  4069. end
  4070. end;
  4071. end;
  4072. { recover }
  4073. taicpu(hp1).oper[ref]^.ref^:=saveref;
  4074. end;
  4075. end;
  4076. end;
  4077. { for now, we do not mess with the stack pointer, thought it might be usefull to remove
  4078. unneeded lea sequences on the stack pointer, it needs to be tested in detail }
  4079. if (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) and
  4080. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  4081. begin
  4082. { Check common LEA/LEA conditions }
  4083. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  4084. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  4085. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  4086. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  4087. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  4088. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  4089. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  4090. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  4091. (
  4092. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  4093. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  4094. ) and (
  4095. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  4096. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4097. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  4098. ) then
  4099. begin
  4100. { changes
  4101. lea (regX,scale), reg1
  4102. lea offset(reg1,reg1), reg1
  4103. to
  4104. lea offset(regX,scale*2), reg1
  4105. and
  4106. lea (regX,scale1), reg1
  4107. lea offset(reg1,scale2), reg1
  4108. to
  4109. lea offset(regX,scale1*scale2), reg1
  4110. ... so long as the final scale does not exceed 8
  4111. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  4112. }
  4113. if (taicpu(p).oper[0]^.ref^.offset = 0) and
  4114. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4115. (
  4116. (
  4117. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4118. ) or (
  4119. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4120. (
  4121. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  4122. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  4123. )
  4124. )
  4125. ) and (
  4126. (
  4127. { lea (reg1,scale2), reg1 variant }
  4128. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  4129. (
  4130. (
  4131. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  4132. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  4133. ) or (
  4134. { lea (regX,regX), reg1 variant }
  4135. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4136. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  4137. )
  4138. )
  4139. ) or (
  4140. { lea (reg1,reg1), reg1 variant }
  4141. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4142. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  4143. )
  4144. ) then
  4145. begin
  4146. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  4147. { Make everything homogeneous to make calculations easier }
  4148. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  4149. begin
  4150. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  4151. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  4152. taicpu(p).oper[0]^.ref^.scalefactor := 2
  4153. else
  4154. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  4155. taicpu(p).oper[0]^.ref^.base := NR_NO;
  4156. end;
  4157. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  4158. begin
  4159. { Just to prevent miscalculations }
  4160. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  4161. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  4162. else
  4163. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  4164. end
  4165. else
  4166. begin
  4167. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  4168. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  4169. end;
  4170. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  4171. RemoveCurrentP(p);
  4172. result:=true;
  4173. exit;
  4174. end
  4175. { changes
  4176. lea offset1(regX), reg1
  4177. lea offset2(reg1), reg1
  4178. to
  4179. lea offset1+offset2(regX), reg1 }
  4180. else if
  4181. (
  4182. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4183. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  4184. ) or (
  4185. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4186. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  4187. (
  4188. (
  4189. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4190. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4191. ) or (
  4192. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4193. (
  4194. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4195. (
  4196. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4197. (
  4198. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  4199. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  4200. )
  4201. )
  4202. )
  4203. )
  4204. )
  4205. ) then
  4206. begin
  4207. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  4208. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  4209. begin
  4210. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  4211. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4212. { if the register is used as index and base, we have to increase for base as well
  4213. and adapt base }
  4214. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  4215. begin
  4216. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4217. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4218. end;
  4219. end
  4220. else
  4221. begin
  4222. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4223. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4224. end;
  4225. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4226. begin
  4227. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  4228. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4229. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4230. end;
  4231. RemoveCurrentP(p);
  4232. result:=true;
  4233. exit;
  4234. end;
  4235. end;
  4236. { Change:
  4237. leal/q $x(%reg1),%reg2
  4238. ...
  4239. shll/q $y,%reg2
  4240. To:
  4241. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  4242. }
  4243. if MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  4244. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4245. (taicpu(hp1).oper[0]^.val <= 3) then
  4246. begin
  4247. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  4248. TransferUsedRegs(TmpUsedRegs);
  4249. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4250. TempReg := taicpu(hp1).oper[1]^.reg; { Store locally to reduce the number of dereferences }
  4251. if
  4252. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  4253. (this works even if scalefactor is zero) }
  4254. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  4255. { Ensure offset doesn't go out of bounds }
  4256. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  4257. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  4258. MatchOperand(taicpu(p).oper[1]^, TempReg) and
  4259. (
  4260. (
  4261. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, TempReg) and
  4262. (
  4263. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4264. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  4265. (
  4266. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  4267. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4268. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  4269. )
  4270. )
  4271. ) or (
  4272. (
  4273. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  4274. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  4275. ) and
  4276. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, TempReg)
  4277. )
  4278. ) then
  4279. begin
  4280. repeat
  4281. with taicpu(p).oper[0]^.ref^ do
  4282. begin
  4283. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  4284. if index = base then
  4285. begin
  4286. if Multiple > 4 then
  4287. { Optimisation will no longer work because resultant
  4288. scale factor will exceed 8 }
  4289. Break;
  4290. base := NR_NO;
  4291. scalefactor := 2;
  4292. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  4293. end
  4294. else if (base <> NR_NO) and (base <> NR_INVALID) then
  4295. begin
  4296. { Scale factor only works on the index register }
  4297. index := base;
  4298. base := NR_NO;
  4299. end;
  4300. { For safety }
  4301. if scalefactor <= 1 then
  4302. begin
  4303. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  4304. scalefactor := Multiple;
  4305. end
  4306. else
  4307. begin
  4308. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  4309. scalefactor := scalefactor * Multiple;
  4310. end;
  4311. offset := offset * Multiple;
  4312. end;
  4313. RemoveInstruction(hp1);
  4314. Result := True;
  4315. Exit;
  4316. { This repeat..until loop exists for the benefit of Break }
  4317. until True;
  4318. end;
  4319. end;
  4320. end;
  4321. end;
  4322. function TX86AsmOptimizer.DoSubAddOpt(var p: tai): Boolean;
  4323. var
  4324. hp1 : tai;
  4325. begin
  4326. DoSubAddOpt := False;
  4327. if GetLastInstruction(p, hp1) and
  4328. (hp1.typ = ait_instruction) and
  4329. (taicpu(hp1).opsize = taicpu(p).opsize) then
  4330. case taicpu(hp1).opcode Of
  4331. A_DEC:
  4332. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  4333. MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4334. begin
  4335. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+1);
  4336. RemoveInstruction(hp1);
  4337. end;
  4338. A_SUB:
  4339. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  4340. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  4341. begin
  4342. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val);
  4343. RemoveInstruction(hp1);
  4344. end;
  4345. A_ADD:
  4346. begin
  4347. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  4348. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  4349. begin
  4350. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  4351. RemoveInstruction(hp1);
  4352. if (taicpu(p).oper[0]^.val = 0) then
  4353. begin
  4354. hp1 := tai(p.next);
  4355. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  4356. if not GetLastInstruction(hp1, p) then
  4357. p := hp1;
  4358. DoSubAddOpt := True;
  4359. end
  4360. end;
  4361. end;
  4362. else
  4363. ;
  4364. end;
  4365. end;
  4366. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  4367. {$ifdef i386}
  4368. var
  4369. hp1 : tai;
  4370. {$endif i386}
  4371. begin
  4372. Result:=false;
  4373. { * change "subl $2, %esp; pushw x" to "pushl x"}
  4374. { * change "sub/add const1, reg" or "dec reg" followed by
  4375. "sub const2, reg" to one "sub ..., reg" }
  4376. if MatchOpType(taicpu(p),top_const,top_reg) then
  4377. begin
  4378. {$ifdef i386}
  4379. if (taicpu(p).oper[0]^.val = 2) and
  4380. (taicpu(p).oper[1]^.reg = NR_ESP) and
  4381. { Don't do the sub/push optimization if the sub }
  4382. { comes from setting up the stack frame (JM) }
  4383. (not(GetLastInstruction(p,hp1)) or
  4384. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  4385. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  4386. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  4387. begin
  4388. hp1 := tai(p.next);
  4389. while Assigned(hp1) and
  4390. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  4391. not RegReadByInstruction(NR_ESP,hp1) and
  4392. not RegModifiedByInstruction(NR_ESP,hp1) do
  4393. hp1 := tai(hp1.next);
  4394. if Assigned(hp1) and
  4395. MatchInstruction(hp1,A_PUSH,[S_W]) then
  4396. begin
  4397. taicpu(hp1).changeopsize(S_L);
  4398. if taicpu(hp1).oper[0]^.typ=top_reg then
  4399. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  4400. hp1 := tai(p.next);
  4401. RemoveCurrentp(p, hp1);
  4402. Result:=true;
  4403. exit;
  4404. end;
  4405. end;
  4406. {$endif i386}
  4407. if DoSubAddOpt(p) then
  4408. Result:=true;
  4409. end;
  4410. end;
  4411. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  4412. var
  4413. TmpBool1,TmpBool2 : Boolean;
  4414. tmpref : treference;
  4415. hp1,hp2: tai;
  4416. mask: tcgint;
  4417. begin
  4418. Result:=false;
  4419. { All these optimisations work on "shl/sal const,%reg" }
  4420. if not MatchOpType(taicpu(p),top_const,top_reg) then
  4421. Exit;
  4422. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4423. (taicpu(p).oper[0]^.val <= 3) then
  4424. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  4425. begin
  4426. { should we check the next instruction? }
  4427. TmpBool1 := True;
  4428. { have we found an add/sub which could be
  4429. integrated in the lea? }
  4430. TmpBool2 := False;
  4431. reference_reset(tmpref,2,[]);
  4432. TmpRef.index := taicpu(p).oper[1]^.reg;
  4433. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  4434. while TmpBool1 and
  4435. GetNextInstruction(p, hp1) and
  4436. (tai(hp1).typ = ait_instruction) and
  4437. ((((taicpu(hp1).opcode = A_ADD) or
  4438. (taicpu(hp1).opcode = A_SUB)) and
  4439. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  4440. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  4441. (((taicpu(hp1).opcode = A_INC) or
  4442. (taicpu(hp1).opcode = A_DEC)) and
  4443. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  4444. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  4445. ((taicpu(hp1).opcode = A_LEA) and
  4446. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4447. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  4448. (not GetNextInstruction(hp1,hp2) or
  4449. not instrReadsFlags(hp2)) Do
  4450. begin
  4451. TmpBool1 := False;
  4452. if taicpu(hp1).opcode=A_LEA then
  4453. begin
  4454. if (TmpRef.base = NR_NO) and
  4455. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  4456. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  4457. (taicpu(hp1).oper[0]^.ref^.segment=NR_NO) and
  4458. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  4459. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  4460. begin
  4461. TmpBool1 := True;
  4462. TmpBool2 := True;
  4463. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  4464. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  4465. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  4466. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  4467. RemoveInstruction(hp1);
  4468. end
  4469. end
  4470. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  4471. begin
  4472. TmpBool1 := True;
  4473. TmpBool2 := True;
  4474. case taicpu(hp1).opcode of
  4475. A_ADD:
  4476. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  4477. A_SUB:
  4478. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  4479. else
  4480. internalerror(2019050536);
  4481. end;
  4482. RemoveInstruction(hp1);
  4483. end
  4484. else
  4485. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  4486. (((taicpu(hp1).opcode = A_ADD) and
  4487. (TmpRef.base = NR_NO)) or
  4488. (taicpu(hp1).opcode = A_INC) or
  4489. (taicpu(hp1).opcode = A_DEC)) then
  4490. begin
  4491. TmpBool1 := True;
  4492. TmpBool2 := True;
  4493. case taicpu(hp1).opcode of
  4494. A_ADD:
  4495. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  4496. A_INC:
  4497. inc(TmpRef.offset);
  4498. A_DEC:
  4499. dec(TmpRef.offset);
  4500. else
  4501. internalerror(2019050535);
  4502. end;
  4503. RemoveInstruction(hp1);
  4504. end;
  4505. end;
  4506. if TmpBool2
  4507. {$ifndef x86_64}
  4508. or
  4509. ((current_settings.optimizecputype < cpu_Pentium2) and
  4510. (taicpu(p).oper[0]^.val <= 3) and
  4511. not(cs_opt_size in current_settings.optimizerswitches))
  4512. {$endif x86_64}
  4513. then
  4514. begin
  4515. if not(TmpBool2) and
  4516. (taicpu(p).oper[0]^.val=1) then
  4517. begin
  4518. hp1:=taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  4519. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  4520. end
  4521. else
  4522. hp1:=taicpu.op_ref_reg(A_LEA, taicpu(p).opsize, TmpRef,
  4523. taicpu(p).oper[1]^.reg);
  4524. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  4525. InsertLLItem(p.previous, p.next, hp1);
  4526. p.free;
  4527. p := hp1;
  4528. end;
  4529. end
  4530. {$ifndef x86_64}
  4531. else if (current_settings.optimizecputype < cpu_Pentium2) then
  4532. begin
  4533. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  4534. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  4535. (unlike shl, which is only Tairable in the U pipe) }
  4536. if taicpu(p).oper[0]^.val=1 then
  4537. begin
  4538. hp1 := taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  4539. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg);
  4540. InsertLLItem(p.previous, p.next, hp1);
  4541. p.free;
  4542. p := hp1;
  4543. end
  4544. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  4545. "shl $3, %reg" to "lea (,%reg,8), %reg }
  4546. else if (taicpu(p).opsize = S_L) and
  4547. (taicpu(p).oper[0]^.val<= 3) then
  4548. begin
  4549. reference_reset(tmpref,2,[]);
  4550. TmpRef.index := taicpu(p).oper[1]^.reg;
  4551. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  4552. hp1 := taicpu.Op_ref_reg(A_LEA,S_L,TmpRef, taicpu(p).oper[1]^.reg);
  4553. InsertLLItem(p.previous, p.next, hp1);
  4554. p.free;
  4555. p := hp1;
  4556. end;
  4557. end
  4558. {$endif x86_64}
  4559. else if
  4560. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  4561. (
  4562. (
  4563. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  4564. SetAndTest(hp1, hp2)
  4565. {$ifdef x86_64}
  4566. ) or
  4567. (
  4568. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  4569. GetNextInstruction(hp1, hp2) and
  4570. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  4571. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4572. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  4573. {$endif x86_64}
  4574. )
  4575. ) and
  4576. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  4577. begin
  4578. { Change:
  4579. shl x, %reg1
  4580. mov -(1<<x), %reg2
  4581. and %reg2, %reg1
  4582. Or:
  4583. shl x, %reg1
  4584. and -(1<<x), %reg1
  4585. To just:
  4586. shl x, %reg1
  4587. Since the and operation only zeroes bits that are already zero from the shl operation
  4588. }
  4589. case taicpu(p).oper[0]^.val of
  4590. 8:
  4591. mask:=$FFFFFFFFFFFFFF00;
  4592. 16:
  4593. mask:=$FFFFFFFFFFFF0000;
  4594. 32:
  4595. mask:=$FFFFFFFF00000000;
  4596. 63:
  4597. { Constant pre-calculated to prevent overflow errors with Int64 }
  4598. mask:=$8000000000000000;
  4599. else
  4600. begin
  4601. if taicpu(p).oper[0]^.val >= 64 then
  4602. { Shouldn't happen realistically, since the register
  4603. is guaranteed to be set to zero at this point }
  4604. mask := 0
  4605. else
  4606. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  4607. end;
  4608. end;
  4609. if taicpu(hp1).oper[0]^.val = mask then
  4610. begin
  4611. { Everything checks out, perform the optimisation, as long as
  4612. the FLAGS register isn't being used}
  4613. TransferUsedRegs(TmpUsedRegs);
  4614. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4615. {$ifdef x86_64}
  4616. if (hp1 <> hp2) then
  4617. begin
  4618. { "shl/mov/and" version }
  4619. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4620. { Don't do the optimisation if the FLAGS register is in use }
  4621. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  4622. begin
  4623. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  4624. { Don't remove the 'mov' instruction if its register is used elsewhere }
  4625. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  4626. begin
  4627. RemoveInstruction(hp1);
  4628. Result := True;
  4629. end;
  4630. { Only set Result to True if the 'mov' instruction was removed }
  4631. RemoveInstruction(hp2);
  4632. end;
  4633. end
  4634. else
  4635. {$endif x86_64}
  4636. begin
  4637. { "shl/and" version }
  4638. { Don't do the optimisation if the FLAGS register is in use }
  4639. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  4640. begin
  4641. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  4642. RemoveInstruction(hp1);
  4643. Result := True;
  4644. end;
  4645. end;
  4646. Exit;
  4647. end
  4648. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  4649. begin
  4650. { Even if the mask doesn't allow for its removal, we might be
  4651. able to optimise the mask for the "shl/and" version, which
  4652. may permit other peephole optimisations }
  4653. {$ifdef DEBUG_AOPTCPU}
  4654. mask := taicpu(hp1).oper[0]^.val and mask;
  4655. if taicpu(hp1).oper[0]^.val <> mask then
  4656. begin
  4657. DebugMsg(
  4658. SPeepholeOptimization +
  4659. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  4660. ' to $' + debug_tostr(mask) +
  4661. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  4662. taicpu(hp1).oper[0]^.val := mask;
  4663. end;
  4664. {$else DEBUG_AOPTCPU}
  4665. { If debugging is off, just set the operand even if it's the same }
  4666. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  4667. {$endif DEBUG_AOPTCPU}
  4668. end;
  4669. end;
  4670. {
  4671. change
  4672. shl/sal const,reg
  4673. <op> ...(...,reg,1),...
  4674. into
  4675. <op> ...(...,reg,1 shl const),...
  4676. if const in 1..3
  4677. }
  4678. if MatchOpType(taicpu(p), top_const, top_reg) and
  4679. (taicpu(p).oper[0]^.val in [1..3]) and
  4680. GetNextInstruction(p, hp1) and
  4681. MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  4682. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  4683. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  4684. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  4685. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  4686. begin
  4687. TransferUsedRegs(TmpUsedRegs);
  4688. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4689. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4690. begin
  4691. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  4692. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  4693. RemoveCurrentP(p);
  4694. Result:=true;
  4695. end;
  4696. end;
  4697. end;
  4698. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  4699. var
  4700. CurrentRef: TReference;
  4701. FullReg: TRegister;
  4702. hp1, hp2: tai;
  4703. begin
  4704. Result := False;
  4705. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  4706. Exit;
  4707. { We assume you've checked if the operand is actually a reference by
  4708. this point. If it isn't, you'll most likely get an access violation }
  4709. CurrentRef := first_mov.oper[1]^.ref^;
  4710. { Memory must be aligned }
  4711. if (CurrentRef.offset mod 4) <> 0 then
  4712. Exit;
  4713. Inc(CurrentRef.offset);
  4714. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  4715. if MatchOperand(second_mov.oper[0]^, 0) and
  4716. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  4717. GetNextInstruction(second_mov, hp1) and
  4718. (hp1.typ = ait_instruction) and
  4719. (taicpu(hp1).opcode = A_MOV) and
  4720. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4721. (taicpu(hp1).oper[0]^.val = 0) then
  4722. begin
  4723. Inc(CurrentRef.offset);
  4724. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  4725. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  4726. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  4727. begin
  4728. case taicpu(hp1).opsize of
  4729. S_B:
  4730. if GetNextInstruction(hp1, hp2) and
  4731. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  4732. MatchOpType(taicpu(hp2), top_const, top_ref) and
  4733. (taicpu(hp2).oper[0]^.val = 0) then
  4734. begin
  4735. Inc(CurrentRef.offset);
  4736. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  4737. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  4738. (taicpu(hp2).opsize = S_B) then
  4739. begin
  4740. RemoveInstruction(hp1);
  4741. RemoveInstruction(hp2);
  4742. first_mov.opsize := S_L;
  4743. if first_mov.oper[0]^.typ = top_reg then
  4744. begin
  4745. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  4746. { Reuse second_mov as a MOVZX instruction }
  4747. second_mov.opcode := A_MOVZX;
  4748. second_mov.opsize := S_BL;
  4749. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  4750. second_mov.loadreg(1, FullReg);
  4751. first_mov.oper[0]^.reg := FullReg;
  4752. asml.Remove(second_mov);
  4753. asml.InsertBefore(second_mov, first_mov);
  4754. end
  4755. else
  4756. { It's a value }
  4757. begin
  4758. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  4759. RemoveInstruction(second_mov);
  4760. end;
  4761. Result := True;
  4762. Exit;
  4763. end;
  4764. end;
  4765. S_W:
  4766. begin
  4767. RemoveInstruction(hp1);
  4768. first_mov.opsize := S_L;
  4769. if first_mov.oper[0]^.typ = top_reg then
  4770. begin
  4771. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  4772. { Reuse second_mov as a MOVZX instruction }
  4773. second_mov.opcode := A_MOVZX;
  4774. second_mov.opsize := S_BL;
  4775. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  4776. second_mov.loadreg(1, FullReg);
  4777. first_mov.oper[0]^.reg := FullReg;
  4778. asml.Remove(second_mov);
  4779. asml.InsertBefore(second_mov, first_mov);
  4780. end
  4781. else
  4782. { It's a value }
  4783. begin
  4784. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  4785. RemoveInstruction(second_mov);
  4786. end;
  4787. Result := True;
  4788. Exit;
  4789. end;
  4790. else
  4791. ;
  4792. end;
  4793. end;
  4794. end;
  4795. end;
  4796. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  4797. { returns true if a "continue" should be done after this optimization }
  4798. var
  4799. hp1, hp2: tai;
  4800. begin
  4801. Result := false;
  4802. if MatchOpType(taicpu(p),top_ref) and
  4803. GetNextInstruction(p, hp1) and
  4804. (hp1.typ = ait_instruction) and
  4805. (((taicpu(hp1).opcode = A_FLD) and
  4806. (taicpu(p).opcode = A_FSTP)) or
  4807. ((taicpu(p).opcode = A_FISTP) and
  4808. (taicpu(hp1).opcode = A_FILD))) and
  4809. MatchOpType(taicpu(hp1),top_ref) and
  4810. (taicpu(hp1).opsize = taicpu(p).opsize) and
  4811. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  4812. begin
  4813. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  4814. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  4815. GetNextInstruction(hp1, hp2) and
  4816. (hp2.typ = ait_instruction) and
  4817. IsExitCode(hp2) and
  4818. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  4819. not(assigned(current_procinfo.procdef.funcretsym) and
  4820. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  4821. (taicpu(p).oper[0]^.ref^.index = NR_NO) then
  4822. begin
  4823. RemoveInstruction(hp1);
  4824. RemoveCurrentP(p, hp2);
  4825. RemoveLastDeallocForFuncRes(p);
  4826. Result := true;
  4827. end
  4828. else
  4829. { we can do this only in fast math mode as fstp is rounding ...
  4830. ... still disabled as it breaks the compiler and/or rtl }
  4831. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  4832. { ... or if another fstp equal to the first one follows }
  4833. (GetNextInstruction(hp1,hp2) and
  4834. (hp2.typ = ait_instruction) and
  4835. (taicpu(p).opcode=taicpu(hp2).opcode) and
  4836. (taicpu(p).opsize=taicpu(hp2).opsize))
  4837. ) and
  4838. { fst can't store an extended/comp value }
  4839. (taicpu(p).opsize <> S_FX) and
  4840. (taicpu(p).opsize <> S_IQ) then
  4841. begin
  4842. if (taicpu(p).opcode = A_FSTP) then
  4843. taicpu(p).opcode := A_FST
  4844. else
  4845. taicpu(p).opcode := A_FIST;
  4846. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  4847. RemoveInstruction(hp1);
  4848. end;
  4849. end;
  4850. end;
  4851. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  4852. var
  4853. hp1, hp2: tai;
  4854. begin
  4855. result:=false;
  4856. if MatchOpType(taicpu(p),top_reg) and
  4857. GetNextInstruction(p, hp1) and
  4858. (hp1.typ = Ait_Instruction) and
  4859. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4860. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  4861. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  4862. { change to
  4863. fld reg fxxx reg,st
  4864. fxxxp st, st1 (hp1)
  4865. Remark: non commutative operations must be reversed!
  4866. }
  4867. begin
  4868. case taicpu(hp1).opcode Of
  4869. A_FMULP,A_FADDP,
  4870. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  4871. begin
  4872. case taicpu(hp1).opcode Of
  4873. A_FADDP: taicpu(hp1).opcode := A_FADD;
  4874. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  4875. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  4876. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  4877. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  4878. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  4879. else
  4880. internalerror(2019050534);
  4881. end;
  4882. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  4883. taicpu(hp1).oper[1]^.reg := NR_ST;
  4884. RemoveCurrentP(p, hp1);
  4885. Result:=true;
  4886. exit;
  4887. end;
  4888. else
  4889. ;
  4890. end;
  4891. end
  4892. else
  4893. if MatchOpType(taicpu(p),top_ref) and
  4894. GetNextInstruction(p, hp2) and
  4895. (hp2.typ = Ait_Instruction) and
  4896. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4897. (taicpu(p).opsize in [S_FS, S_FL]) and
  4898. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  4899. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  4900. if GetLastInstruction(p, hp1) and
  4901. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  4902. MatchOpType(taicpu(hp1),top_ref) and
  4903. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  4904. if ((taicpu(hp2).opcode = A_FMULP) or
  4905. (taicpu(hp2).opcode = A_FADDP)) then
  4906. { change to
  4907. fld/fst mem1 (hp1) fld/fst mem1
  4908. fld mem1 (p) fadd/
  4909. faddp/ fmul st, st
  4910. fmulp st, st1 (hp2) }
  4911. begin
  4912. RemoveCurrentP(p, hp1);
  4913. if (taicpu(hp2).opcode = A_FADDP) then
  4914. taicpu(hp2).opcode := A_FADD
  4915. else
  4916. taicpu(hp2).opcode := A_FMUL;
  4917. taicpu(hp2).oper[1]^.reg := NR_ST;
  4918. end
  4919. else
  4920. { change to
  4921. fld/fst mem1 (hp1) fld/fst mem1
  4922. fld mem1 (p) fld st}
  4923. begin
  4924. taicpu(p).changeopsize(S_FL);
  4925. taicpu(p).loadreg(0,NR_ST);
  4926. end
  4927. else
  4928. begin
  4929. case taicpu(hp2).opcode Of
  4930. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  4931. { change to
  4932. fld/fst mem1 (hp1) fld/fst mem1
  4933. fld mem2 (p) fxxx mem2
  4934. fxxxp st, st1 (hp2) }
  4935. begin
  4936. case taicpu(hp2).opcode Of
  4937. A_FADDP: taicpu(p).opcode := A_FADD;
  4938. A_FMULP: taicpu(p).opcode := A_FMUL;
  4939. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  4940. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  4941. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  4942. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  4943. else
  4944. internalerror(2019050533);
  4945. end;
  4946. RemoveInstruction(hp2);
  4947. end
  4948. else
  4949. ;
  4950. end
  4951. end
  4952. end;
  4953. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  4954. begin
  4955. Result := condition_in(cond1, cond2) or
  4956. { Not strictly subsets due to the actual flags checked, but because we're
  4957. comparing integers, E is a subset of AE and GE and their aliases }
  4958. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  4959. end;
  4960. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  4961. var
  4962. v: TCGInt;
  4963. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  4964. FirstMatch: Boolean;
  4965. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  4966. begin
  4967. Result:=false;
  4968. { All these optimisations need a next instruction }
  4969. if not GetNextInstruction(p, hp1) then
  4970. Exit;
  4971. { Search for:
  4972. cmp ###,###
  4973. j(c1) @lbl1
  4974. ...
  4975. @lbl:
  4976. cmp ###.### (same comparison as above)
  4977. j(c2) @lbl2
  4978. If c1 is a subset of c2, change to:
  4979. cmp ###,###
  4980. j(c2) @lbl2
  4981. (@lbl1 may become a dead label as a result)
  4982. }
  4983. { Also handle cases where there are multiple jumps in a row }
  4984. p_jump := hp1;
  4985. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  4986. begin
  4987. if IsJumpToLabel(taicpu(p_jump)) then
  4988. begin
  4989. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  4990. p_label := nil;
  4991. if Assigned(JumpLabel) then
  4992. p_label := getlabelwithsym(JumpLabel);
  4993. if Assigned(p_label) and
  4994. GetNextInstruction(p_label, p_dist) and
  4995. MatchInstruction(p_dist, A_CMP, []) and
  4996. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  4997. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4998. GetNextInstruction(p_dist, hp1_dist) and
  4999. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5000. begin
  5001. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5002. if JumpLabel = JumpLabel_dist then
  5003. { This is an infinite loop }
  5004. Exit;
  5005. { Best optimisation when the first condition is a subset (or equal) of the second }
  5006. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  5007. begin
  5008. { Any registers used here will already be allocated }
  5009. if Assigned(JumpLabel_dist) then
  5010. JumpLabel_dist.IncRefs;
  5011. if Assigned(JumpLabel) then
  5012. JumpLabel.DecRefs;
  5013. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  5014. taicpu(p_jump).condition := taicpu(hp1_dist).condition;
  5015. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  5016. Result := True;
  5017. { Don't exit yet. Since p and p_jump haven't actually been
  5018. removed, we can check for more on this iteration }
  5019. end
  5020. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  5021. GetNextInstruction(hp1_dist, hp1_label) and
  5022. SkipAligns(hp1_label, hp1_label) and
  5023. (hp1_label.typ = ait_label) then
  5024. begin
  5025. JumpLabel_far := tai_label(hp1_label).labsym;
  5026. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  5027. { This is an infinite loop }
  5028. Exit;
  5029. if Assigned(JumpLabel_far) then
  5030. begin
  5031. { In this situation, if the first jump branches, the second one will never,
  5032. branch so change the destination label to after the second jump }
  5033. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  5034. if Assigned(JumpLabel) then
  5035. JumpLabel.DecRefs;
  5036. JumpLabel_far.IncRefs;
  5037. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  5038. Result := True;
  5039. { Don't exit yet. Since p and p_jump haven't actually been
  5040. removed, we can check for more on this iteration }
  5041. Continue;
  5042. end;
  5043. end;
  5044. end;
  5045. end;
  5046. { Search for:
  5047. cmp ###,###
  5048. j(c1) @lbl1
  5049. cmp ###,### (same as first)
  5050. Remove second cmp
  5051. }
  5052. if GetNextInstruction(p_jump, hp2) and
  5053. (
  5054. (
  5055. MatchInstruction(hp2, A_CMP, []) and
  5056. (
  5057. (
  5058. MatchOpType(taicpu(p), top_const, top_reg) and
  5059. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  5060. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[1]^.reg)
  5061. ) or (
  5062. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  5063. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  5064. )
  5065. )
  5066. ) or (
  5067. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  5068. MatchOperand(taicpu(p).oper[0]^, 0) and
  5069. (taicpu(p).oper[1]^.typ = top_reg) and
  5070. MatchInstruction(hp2, A_TEST, []) and
  5071. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  5072. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  5073. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[1]^.reg)
  5074. )
  5075. ) then
  5076. begin
  5077. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  5078. RemoveInstruction(hp2);
  5079. Result := True;
  5080. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  5081. end;
  5082. GetNextInstruction(p_jump, p_jump);
  5083. end;
  5084. if taicpu(p).oper[0]^.typ = top_const then
  5085. begin
  5086. if (taicpu(p).oper[0]^.val = 0) and
  5087. (taicpu(p).oper[1]^.typ = top_reg) and
  5088. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  5089. begin
  5090. hp2 := p;
  5091. FirstMatch := True;
  5092. { When dealing with "cmp $0,%reg", only ZF and SF contain
  5093. anything meaningful once it's converted to "test %reg,%reg";
  5094. additionally, some jumps will always (or never) branch, so
  5095. evaluate every jump immediately following the
  5096. comparison, optimising the conditions if possible.
  5097. Similarly with SETcc... those that are always set to 0 or 1
  5098. are changed to MOV instructions }
  5099. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  5100. (
  5101. GetNextInstruction(hp2, hp1) and
  5102. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  5103. ) do
  5104. begin
  5105. FirstMatch := False;
  5106. case taicpu(hp1).condition of
  5107. C_B, C_C, C_NAE, C_O:
  5108. { For B/NAE:
  5109. Will never branch since an unsigned integer can never be below zero
  5110. For C/O:
  5111. Result cannot overflow because 0 is being subtracted
  5112. }
  5113. begin
  5114. if taicpu(hp1).opcode = A_Jcc then
  5115. begin
  5116. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  5117. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  5118. RemoveInstruction(hp1);
  5119. { Since hp1 was deleted, hp2 must not be updated }
  5120. Continue;
  5121. end
  5122. else
  5123. begin
  5124. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  5125. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  5126. taicpu(hp1).opcode := A_MOV;
  5127. taicpu(hp1).ops := 2;
  5128. taicpu(hp1).condition := C_None;
  5129. taicpu(hp1).opsize := S_B;
  5130. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  5131. taicpu(hp1).loadconst(0, 0);
  5132. end;
  5133. end;
  5134. C_BE, C_NA:
  5135. begin
  5136. { Will only branch if equal to zero }
  5137. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  5138. taicpu(hp1).condition := C_E;
  5139. end;
  5140. C_A, C_NBE:
  5141. begin
  5142. { Will only branch if not equal to zero }
  5143. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  5144. taicpu(hp1).condition := C_NE;
  5145. end;
  5146. C_AE, C_NB, C_NC, C_NO:
  5147. begin
  5148. { Will always branch }
  5149. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  5150. if taicpu(hp1).opcode = A_Jcc then
  5151. begin
  5152. MakeUnconditional(taicpu(hp1));
  5153. { Any jumps/set that follow will now be dead code }
  5154. RemoveDeadCodeAfterJump(taicpu(hp1));
  5155. Break;
  5156. end
  5157. else
  5158. begin
  5159. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  5160. taicpu(hp1).opcode := A_MOV;
  5161. taicpu(hp1).ops := 2;
  5162. taicpu(hp1).condition := C_None;
  5163. taicpu(hp1).opsize := S_B;
  5164. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  5165. taicpu(hp1).loadconst(0, 1);
  5166. end;
  5167. end;
  5168. C_None:
  5169. InternalError(2020012201);
  5170. C_P, C_PE, C_NP, C_PO:
  5171. { We can't handle parity checks and they should never be generated
  5172. after a general-purpose CMP (it's used in some floating-point
  5173. comparisons that don't use CMP) }
  5174. InternalError(2020012202);
  5175. else
  5176. { Zero/Equality, Sign, their complements and all of the
  5177. signed comparisons do not need to be converted };
  5178. end;
  5179. hp2 := hp1;
  5180. end;
  5181. { Convert the instruction to a TEST }
  5182. taicpu(p).opcode := A_TEST;
  5183. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  5184. Result := True;
  5185. Exit;
  5186. end
  5187. else if (taicpu(p).oper[0]^.val = 1) and
  5188. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  5189. (taicpu(hp1).condition in [C_L, C_NGE]) then
  5190. begin
  5191. { Convert; To:
  5192. cmp $1,r/m cmp $0,r/m
  5193. jl @lbl jle @lbl
  5194. }
  5195. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  5196. taicpu(p).oper[0]^.val := 0;
  5197. taicpu(hp1).condition := C_LE;
  5198. { If the instruction is now "cmp $0,%reg", convert it to a
  5199. TEST (and effectively do the work of the "cmp $0,%reg" in
  5200. the block above)
  5201. If it's a reference, we can get away with not setting
  5202. Result to True because he haven't evaluated the jump
  5203. in this pass yet.
  5204. }
  5205. if (taicpu(p).oper[1]^.typ = top_reg) then
  5206. begin
  5207. taicpu(p).opcode := A_TEST;
  5208. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  5209. Result := True;
  5210. end;
  5211. Exit;
  5212. end
  5213. else if (taicpu(p).oper[1]^.typ = top_reg)
  5214. {$ifdef x86_64}
  5215. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  5216. {$endif x86_64}
  5217. then
  5218. begin
  5219. { cmp register,$8000 neg register
  5220. je target --> jo target
  5221. .... only if register is deallocated before jump.}
  5222. case Taicpu(p).opsize of
  5223. S_B: v:=$80;
  5224. S_W: v:=$8000;
  5225. S_L: v:=qword($80000000);
  5226. else
  5227. internalerror(2013112905);
  5228. end;
  5229. if (taicpu(p).oper[0]^.val=v) and
  5230. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  5231. (Taicpu(hp1).condition in [C_E,C_NE]) then
  5232. begin
  5233. TransferUsedRegs(TmpUsedRegs);
  5234. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  5235. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  5236. begin
  5237. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  5238. Taicpu(p).opcode:=A_NEG;
  5239. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  5240. Taicpu(p).clearop(1);
  5241. Taicpu(p).ops:=1;
  5242. if Taicpu(hp1).condition=C_E then
  5243. Taicpu(hp1).condition:=C_O
  5244. else
  5245. Taicpu(hp1).condition:=C_NO;
  5246. Result:=true;
  5247. exit;
  5248. end;
  5249. end;
  5250. end;
  5251. end;
  5252. if TrySwapMovCmp(p, hp1) then
  5253. begin
  5254. Result := True;
  5255. Exit;
  5256. end;
  5257. end;
  5258. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  5259. var
  5260. hp1: tai;
  5261. begin
  5262. {
  5263. remove the second (v)pxor from
  5264. pxor reg,reg
  5265. ...
  5266. pxor reg,reg
  5267. }
  5268. Result:=false;
  5269. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  5270. MatchOpType(taicpu(p),top_reg,top_reg) and
  5271. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  5272. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  5273. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  5274. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  5275. begin
  5276. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  5277. RemoveInstruction(hp1);
  5278. Result:=true;
  5279. Exit;
  5280. end
  5281. {
  5282. replace
  5283. pxor reg1,reg1
  5284. movapd/s reg1,reg2
  5285. dealloc reg1
  5286. by
  5287. pxor reg2,reg2
  5288. }
  5289. else if GetNextInstruction(p,hp1) and
  5290. { we mix single and double opperations here because we assume that the compiler
  5291. generates vmovapd only after double operations and vmovaps only after single operations }
  5292. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  5293. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  5294. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5295. (taicpu(p).oper[0]^.typ=top_reg) then
  5296. begin
  5297. TransferUsedRegs(TmpUsedRegs);
  5298. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5299. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5300. begin
  5301. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  5302. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5303. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  5304. RemoveInstruction(hp1);
  5305. result:=true;
  5306. end;
  5307. end;
  5308. end;
  5309. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  5310. var
  5311. hp1: tai;
  5312. begin
  5313. {
  5314. remove the second (v)pxor from
  5315. (v)pxor reg,reg
  5316. ...
  5317. (v)pxor reg,reg
  5318. }
  5319. Result:=false;
  5320. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  5321. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  5322. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  5323. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  5324. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  5325. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  5326. begin
  5327. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2PXor done',hp1);
  5328. RemoveInstruction(hp1);
  5329. Result:=true;
  5330. Exit;
  5331. end
  5332. else
  5333. Result:=OptPass1VOP(p);
  5334. end;
  5335. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  5336. var
  5337. hp1 : tai;
  5338. begin
  5339. result:=false;
  5340. { replace
  5341. IMul const,%mreg1,%mreg2
  5342. Mov %reg2,%mreg3
  5343. dealloc %mreg3
  5344. by
  5345. Imul const,%mreg1,%mreg23
  5346. }
  5347. if (taicpu(p).ops=3) and
  5348. GetNextInstruction(p,hp1) and
  5349. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5350. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  5351. (taicpu(hp1).oper[1]^.typ=top_reg) then
  5352. begin
  5353. TransferUsedRegs(TmpUsedRegs);
  5354. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5355. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  5356. begin
  5357. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  5358. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  5359. RemoveInstruction(hp1);
  5360. result:=true;
  5361. end;
  5362. end;
  5363. end;
  5364. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  5365. var
  5366. hp1 : tai;
  5367. begin
  5368. result:=false;
  5369. { replace
  5370. IMul %reg0,%reg1,%reg2
  5371. Mov %reg2,%reg3
  5372. dealloc %reg2
  5373. by
  5374. Imul %reg0,%reg1,%reg3
  5375. }
  5376. if GetNextInstruction(p,hp1) and
  5377. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5378. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  5379. (taicpu(hp1).oper[1]^.typ=top_reg) then
  5380. begin
  5381. TransferUsedRegs(TmpUsedRegs);
  5382. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5383. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  5384. begin
  5385. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  5386. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  5387. RemoveInstruction(hp1);
  5388. result:=true;
  5389. end;
  5390. end;
  5391. end;
  5392. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  5393. var
  5394. hp1: tai;
  5395. begin
  5396. Result:=false;
  5397. { get rid of
  5398. (v)cvtss2sd reg0,<reg1,>reg2
  5399. (v)cvtss2sd reg2,<reg2,>reg0
  5400. }
  5401. if GetNextInstruction(p,hp1) and
  5402. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  5403. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  5404. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  5405. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  5406. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  5407. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  5408. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  5409. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  5410. )
  5411. ) then
  5412. begin
  5413. if getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg) then
  5414. begin
  5415. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  5416. RemoveCurrentP(p);
  5417. RemoveInstruction(hp1);
  5418. end
  5419. else
  5420. begin
  5421. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  5422. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  5423. taicpu(p).ops:=2;
  5424. taicpu(p).opcode:=A_VMOVAPS;
  5425. RemoveInstruction(hp1);
  5426. end;
  5427. Result:=true;
  5428. Exit;
  5429. end;
  5430. end;
  5431. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  5432. var
  5433. hp1, hp2, hp3, hp4, hp5: tai;
  5434. ThisReg: TRegister;
  5435. begin
  5436. Result := False;
  5437. if not GetNextInstruction(p,hp1) or (hp1.typ <> ait_instruction) then
  5438. Exit;
  5439. {
  5440. convert
  5441. j<c> .L1
  5442. mov 1,reg
  5443. jmp .L2
  5444. .L1
  5445. mov 0,reg
  5446. .L2
  5447. into
  5448. mov 0,reg
  5449. set<not(c)> reg
  5450. take care of alignment and that the mov 0,reg is not converted into a xor as this
  5451. would destroy the flag contents
  5452. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  5453. executed at the same time as a previous comparison.
  5454. set<not(c)> reg
  5455. movzx reg, reg
  5456. }
  5457. if MatchInstruction(hp1,A_MOV,[]) and
  5458. (taicpu(hp1).oper[0]^.typ = top_const) and
  5459. (
  5460. (
  5461. (taicpu(hp1).oper[1]^.typ = top_reg)
  5462. {$ifdef i386}
  5463. { Under i386, ESI, EDI, EBP and ESP
  5464. don't have an 8-bit representation }
  5465. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5466. {$endif i386}
  5467. ) or (
  5468. {$ifdef i386}
  5469. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  5470. {$endif i386}
  5471. (taicpu(hp1).opsize = S_B)
  5472. )
  5473. ) and
  5474. GetNextInstruction(hp1,hp2) and
  5475. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  5476. GetNextInstruction(hp2,hp3) and
  5477. SkipAligns(hp3, hp3) and
  5478. (hp3.typ=ait_label) and
  5479. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  5480. GetNextInstruction(hp3,hp4) and
  5481. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  5482. (taicpu(hp4).oper[0]^.typ = top_const) and
  5483. (
  5484. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  5485. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  5486. ) and
  5487. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  5488. GetNextInstruction(hp4,hp5) and
  5489. SkipAligns(hp5, hp5) and
  5490. (hp5.typ=ait_label) and
  5491. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  5492. begin
  5493. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  5494. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5495. tai_label(hp3).labsym.DecRefs;
  5496. { If this isn't the only reference to the middle label, we can
  5497. still make a saving - only that the first jump and everything
  5498. that follows will remain. }
  5499. if (tai_label(hp3).labsym.getrefs = 0) then
  5500. begin
  5501. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  5502. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  5503. else
  5504. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  5505. { remove jump, first label and second MOV (also catching any aligns) }
  5506. repeat
  5507. if not GetNextInstruction(hp2, hp3) then
  5508. InternalError(2021040810);
  5509. RemoveInstruction(hp2);
  5510. hp2 := hp3;
  5511. until hp2 = hp5;
  5512. { Don't decrement reference count before the removal loop
  5513. above, otherwise GetNextInstruction won't stop on the
  5514. the label }
  5515. tai_label(hp5).labsym.DecRefs;
  5516. end
  5517. else
  5518. begin
  5519. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  5520. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  5521. else
  5522. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  5523. end;
  5524. taicpu(p).opcode:=A_SETcc;
  5525. taicpu(p).opsize:=S_B;
  5526. taicpu(p).is_jmp:=False;
  5527. if taicpu(hp1).opsize=S_B then
  5528. begin
  5529. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  5530. if taicpu(hp1).oper[1]^.typ = top_reg then
  5531. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  5532. RemoveInstruction(hp1);
  5533. end
  5534. else
  5535. begin
  5536. { Will be a register because the size can't be S_B otherwise }
  5537. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  5538. taicpu(p).loadreg(0, ThisReg);
  5539. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  5540. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  5541. begin
  5542. case taicpu(hp1).opsize of
  5543. S_W:
  5544. taicpu(hp1).opsize := S_BW;
  5545. S_L:
  5546. taicpu(hp1).opsize := S_BL;
  5547. {$ifdef x86_64}
  5548. S_Q:
  5549. begin
  5550. taicpu(hp1).opsize := S_BL;
  5551. { Change the destination register to 32-bit }
  5552. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  5553. end;
  5554. {$endif x86_64}
  5555. else
  5556. InternalError(2021040820);
  5557. end;
  5558. taicpu(hp1).opcode := A_MOVZX;
  5559. taicpu(hp1).loadreg(0, ThisReg);
  5560. end
  5561. else
  5562. begin
  5563. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  5564. { hp1 is already a MOV instruction with the correct register }
  5565. taicpu(hp1).loadconst(0, 0);
  5566. { Inserting it right before p will guarantee that the flags are also tracked }
  5567. asml.Remove(hp1);
  5568. asml.InsertBefore(hp1, p);
  5569. end;
  5570. end;
  5571. Result:=true;
  5572. exit;
  5573. end
  5574. end;
  5575. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  5576. var
  5577. hp1, hp2, hp3: tai;
  5578. SourceRef, TargetRef: TReference;
  5579. CurrentReg: TRegister;
  5580. begin
  5581. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  5582. if not UseAVX then
  5583. InternalError(2021100501);
  5584. Result := False;
  5585. { Look for the following to simplify:
  5586. vmovdqa/u x(mem1), %xmmreg
  5587. vmovdqa/u %xmmreg, y(mem2)
  5588. vmovdqa/u x+16(mem1), %xmmreg
  5589. vmovdqa/u %xmmreg, y+16(mem2)
  5590. Change to:
  5591. vmovdqa/u x(mem1), %ymmreg
  5592. vmovdqa/u %ymmreg, y(mem2)
  5593. vpxor %ymmreg, %ymmreg, %ymmreg
  5594. ( The VPXOR instruction is to zero the upper half, thus removing the
  5595. need to call the potentially expensive VZEROUPPER instruction. Other
  5596. peephole optimisations can remove VPXOR if it's unnecessary )
  5597. }
  5598. TransferUsedRegs(TmpUsedRegs);
  5599. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5600. { NOTE: In the optimisations below, if the references dictate that an
  5601. aligned move is possible (i.e. VMOVDQA), the existing instructions
  5602. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  5603. if (taicpu(p).opsize = S_XMM) and
  5604. MatchOpType(taicpu(p), top_ref, top_reg) and
  5605. GetNextInstruction(p, hp1) and
  5606. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  5607. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  5608. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5609. begin
  5610. SourceRef := taicpu(p).oper[0]^.ref^;
  5611. TargetRef := taicpu(hp1).oper[1]^.ref^;
  5612. if GetNextInstruction(hp1, hp2) and
  5613. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  5614. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  5615. begin
  5616. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  5617. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5618. Inc(SourceRef.offset, 16);
  5619. { Reuse the register in the first block move }
  5620. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  5621. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  5622. begin
  5623. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5624. Inc(TargetRef.offset, 16);
  5625. if GetNextInstruction(hp2, hp3) and
  5626. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  5627. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  5628. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  5629. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  5630. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  5631. begin
  5632. { Update the register tracking to the new size }
  5633. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  5634. { Remember that the offsets are 16 ahead }
  5635. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  5636. if not (
  5637. ((SourceRef.offset mod 32) = 16) and
  5638. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  5639. ) then
  5640. taicpu(p).opcode := A_VMOVDQU;
  5641. taicpu(p).opsize := S_YMM;
  5642. taicpu(p).oper[1]^.reg := CurrentReg;
  5643. if not (
  5644. ((TargetRef.offset mod 32) = 16) and
  5645. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  5646. ) then
  5647. taicpu(hp1).opcode := A_VMOVDQU;
  5648. taicpu(hp1).opsize := S_YMM;
  5649. taicpu(hp1).oper[0]^.reg := CurrentReg;
  5650. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  5651. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  5652. if (pi_uses_ymm in current_procinfo.flags) then
  5653. RemoveInstruction(hp2)
  5654. else
  5655. begin
  5656. taicpu(hp2).opcode := A_VPXOR;
  5657. taicpu(hp2).opsize := S_YMM;
  5658. taicpu(hp2).loadreg(0, CurrentReg);
  5659. taicpu(hp2).loadreg(1, CurrentReg);
  5660. taicpu(hp2).loadreg(2, CurrentReg);
  5661. taicpu(hp2).ops := 3;
  5662. end;
  5663. RemoveInstruction(hp3);
  5664. Result := True;
  5665. Exit;
  5666. end;
  5667. end
  5668. else
  5669. begin
  5670. { See if the next references are 16 less rather than 16 greater }
  5671. Dec(SourceRef.offset, 32); { -16 the other way }
  5672. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  5673. begin
  5674. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5675. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  5676. if GetNextInstruction(hp2, hp3) and
  5677. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  5678. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  5679. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  5680. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  5681. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  5682. begin
  5683. { Update the register tracking to the new size }
  5684. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  5685. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  5686. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  5687. if not(
  5688. ((SourceRef.offset mod 32) = 0) and
  5689. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  5690. ) then
  5691. taicpu(hp2).opcode := A_VMOVDQU;
  5692. taicpu(hp2).opsize := S_YMM;
  5693. taicpu(hp2).oper[1]^.reg := CurrentReg;
  5694. if not (
  5695. ((TargetRef.offset mod 32) = 0) and
  5696. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  5697. ) then
  5698. taicpu(hp3).opcode := A_VMOVDQU;
  5699. taicpu(hp3).opsize := S_YMM;
  5700. taicpu(hp3).oper[0]^.reg := CurrentReg;
  5701. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  5702. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  5703. if (pi_uses_ymm in current_procinfo.flags) then
  5704. RemoveInstruction(hp1)
  5705. else
  5706. begin
  5707. taicpu(hp1).opcode := A_VPXOR;
  5708. taicpu(hp1).opsize := S_YMM;
  5709. taicpu(hp1).loadreg(0, CurrentReg);
  5710. taicpu(hp1).loadreg(1, CurrentReg);
  5711. taicpu(hp1).loadreg(2, CurrentReg);
  5712. taicpu(hp1).ops := 3;
  5713. Asml.Remove(hp1);
  5714. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  5715. end;
  5716. RemoveCurrentP(p, hp2);
  5717. Result := True;
  5718. Exit;
  5719. end;
  5720. end;
  5721. end;
  5722. end;
  5723. end;
  5724. end;
  5725. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  5726. var
  5727. hp2, hp3, first_assignment: tai;
  5728. IncCount, OperIdx: Integer;
  5729. OrigLabel: TAsmLabel;
  5730. begin
  5731. Count := 0;
  5732. Result := False;
  5733. first_assignment := nil;
  5734. if (LoopCount >= 20) then
  5735. begin
  5736. { Guard against infinite loops }
  5737. Exit;
  5738. end;
  5739. if (taicpu(p).oper[0]^.typ <> top_ref) or
  5740. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  5741. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  5742. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  5743. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  5744. Exit;
  5745. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  5746. {
  5747. change
  5748. jmp .L1
  5749. ...
  5750. .L1:
  5751. mov ##, ## ( multiple movs possible )
  5752. jmp/ret
  5753. into
  5754. mov ##, ##
  5755. jmp/ret
  5756. }
  5757. if not Assigned(hp1) then
  5758. begin
  5759. hp1 := GetLabelWithSym(OrigLabel);
  5760. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  5761. Exit;
  5762. end;
  5763. hp2 := hp1;
  5764. while Assigned(hp2) do
  5765. begin
  5766. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  5767. SkipLabels(hp2,hp2);
  5768. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  5769. Break;
  5770. case taicpu(hp2).opcode of
  5771. A_MOVSS:
  5772. begin
  5773. if taicpu(hp2).ops = 0 then
  5774. { Wrong MOVSS }
  5775. Break;
  5776. Inc(Count);
  5777. if Count >= 5 then
  5778. { Too many to be worthwhile }
  5779. Break;
  5780. GetNextInstruction(hp2, hp2);
  5781. Continue;
  5782. end;
  5783. A_MOV,
  5784. A_MOVD,
  5785. A_MOVQ,
  5786. A_MOVSX,
  5787. {$ifdef x86_64}
  5788. A_MOVSXD,
  5789. {$endif x86_64}
  5790. A_MOVZX,
  5791. A_MOVAPS,
  5792. A_MOVUPS,
  5793. A_MOVSD,
  5794. A_MOVAPD,
  5795. A_MOVUPD,
  5796. A_MOVDQA,
  5797. A_MOVDQU,
  5798. A_VMOVSS,
  5799. A_VMOVAPS,
  5800. A_VMOVUPS,
  5801. A_VMOVSD,
  5802. A_VMOVAPD,
  5803. A_VMOVUPD,
  5804. A_VMOVDQA,
  5805. A_VMOVDQU:
  5806. begin
  5807. Inc(Count);
  5808. if Count >= 5 then
  5809. { Too many to be worthwhile }
  5810. Break;
  5811. GetNextInstruction(hp2, hp2);
  5812. Continue;
  5813. end;
  5814. A_JMP:
  5815. begin
  5816. { Guard against infinite loops }
  5817. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  5818. Exit;
  5819. { Analyse this jump first in case it also duplicates assignments }
  5820. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  5821. begin
  5822. { Something did change! }
  5823. Result := True;
  5824. Inc(Count, IncCount);
  5825. if Count >= 5 then
  5826. begin
  5827. { Too many to be worthwhile }
  5828. Exit;
  5829. end;
  5830. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  5831. Break;
  5832. end;
  5833. Result := True;
  5834. Break;
  5835. end;
  5836. A_RET:
  5837. begin
  5838. Result := True;
  5839. Break;
  5840. end;
  5841. else
  5842. Break;
  5843. end;
  5844. end;
  5845. if Result then
  5846. begin
  5847. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  5848. if Count = 0 then
  5849. begin
  5850. Result := False;
  5851. Exit;
  5852. end;
  5853. hp3 := p;
  5854. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  5855. while True do
  5856. begin
  5857. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  5858. SkipLabels(hp1,hp1);
  5859. if (hp1.typ <> ait_instruction) then
  5860. InternalError(2021040720);
  5861. case taicpu(hp1).opcode of
  5862. A_JMP:
  5863. begin
  5864. { Change the original jump to the new destination }
  5865. OrigLabel.decrefs;
  5866. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  5867. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  5868. { Set p to the first duplicated assignment so it can get optimised if needs be }
  5869. if not Assigned(first_assignment) then
  5870. InternalError(2021040810)
  5871. else
  5872. p := first_assignment;
  5873. Exit;
  5874. end;
  5875. A_RET:
  5876. begin
  5877. { Now change the jump into a RET instruction }
  5878. ConvertJumpToRET(p, hp1);
  5879. { Set p to the first duplicated assignment so it can get optimised if needs be }
  5880. if not Assigned(first_assignment) then
  5881. InternalError(2021040811)
  5882. else
  5883. p := first_assignment;
  5884. Exit;
  5885. end;
  5886. else
  5887. begin
  5888. { Duplicate the MOV instruction }
  5889. hp3:=tai(hp1.getcopy);
  5890. if first_assignment = nil then
  5891. first_assignment := hp3;
  5892. asml.InsertBefore(hp3, p);
  5893. { Make sure the compiler knows about any final registers written here }
  5894. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  5895. with taicpu(hp3).oper[OperIdx]^ do
  5896. begin
  5897. case typ of
  5898. top_ref:
  5899. begin
  5900. if (ref^.base <> NR_NO) and
  5901. (getsupreg(ref^.base) <> RS_ESP) and
  5902. (getsupreg(ref^.base) <> RS_EBP)
  5903. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  5904. then
  5905. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  5906. if (ref^.index <> NR_NO) and
  5907. (getsupreg(ref^.index) <> RS_ESP) and
  5908. (getsupreg(ref^.index) <> RS_EBP)
  5909. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  5910. (ref^.index <> ref^.base) then
  5911. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  5912. end;
  5913. top_reg:
  5914. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  5915. else
  5916. ;
  5917. end;
  5918. end;
  5919. end;
  5920. end;
  5921. if not GetNextInstruction(hp1, hp1) then
  5922. { Should have dropped out earlier }
  5923. InternalError(2021040710);
  5924. end;
  5925. end;
  5926. end;
  5927. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  5928. var
  5929. hp2: tai;
  5930. X: Integer;
  5931. const
  5932. WriteOp: array[0..3] of set of TInsChange = (
  5933. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  5934. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  5935. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  5936. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  5937. RegWriteFlags: array[0..7] of set of TInsChange = (
  5938. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  5939. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  5940. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  5941. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  5942. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  5943. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  5944. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  5945. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  5946. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  5947. begin
  5948. { If we have something like:
  5949. cmp ###,%reg1
  5950. mov 0,%reg2
  5951. And no modified registers are shared, move the instruction to before
  5952. the comparison as this means it can be optimised without worrying
  5953. about the FLAGS register. (CMP/MOV is generated by
  5954. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  5955. As long as the second instruction doesn't use the flags or one of the
  5956. registers used by CMP or TEST (also check any references that use the
  5957. registers), then it can be moved prior to the comparison.
  5958. }
  5959. Result := False;
  5960. if (hp1.typ <> ait_instruction) or
  5961. taicpu(hp1).is_jmp or
  5962. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  5963. Exit;
  5964. { NOP is a pipeline fence, likely marking the beginning of the function
  5965. epilogue, so drop out. Similarly, drop out if POP or RET are
  5966. encountered }
  5967. if MatchInstruction(hp1, A_NOP, A_POP, []) then
  5968. Exit;
  5969. if (taicpu(hp1).opcode = A_MOVSS) and
  5970. (taicpu(hp1).ops = 0) then
  5971. { Wrong MOVSS }
  5972. Exit;
  5973. { Check for writes to specific registers first }
  5974. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  5975. for X := 0 to 7 do
  5976. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  5977. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  5978. Exit;
  5979. for X := 0 to taicpu(hp1).ops - 1 do
  5980. begin
  5981. { Check to see if this operand writes to something }
  5982. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  5983. { And matches something in the CMP/TEST instruction }
  5984. (
  5985. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  5986. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  5987. (
  5988. { If it's a register, make sure the register written to doesn't
  5989. appear in the cmp instruction as part of a reference }
  5990. (taicpu(hp1).oper[X]^.typ = top_reg) and
  5991. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  5992. )
  5993. ) then
  5994. Exit;
  5995. end;
  5996. { The instruction can be safely moved }
  5997. asml.Remove(hp1);
  5998. { Try to insert after the last instructions where the FLAGS register is not yet in use }
  5999. if not GetLastInstruction(p, hp2) then
  6000. asml.InsertBefore(hp1, p)
  6001. else
  6002. asml.InsertAfter(hp1, hp2);
  6003. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  6004. for X := 0 to taicpu(hp1).ops - 1 do
  6005. case taicpu(hp1).oper[X]^.typ of
  6006. top_reg:
  6007. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  6008. top_ref:
  6009. begin
  6010. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  6011. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  6012. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  6013. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  6014. end;
  6015. else
  6016. ;
  6017. end;
  6018. if taicpu(hp1).opcode = A_LEA then
  6019. { The flags will be overwritten by the CMP/TEST instruction }
  6020. ConvertLEA(taicpu(hp1));
  6021. Result := True;
  6022. end;
  6023. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  6024. function IsXCHGAcceptable: Boolean; inline;
  6025. begin
  6026. { Always accept if optimising for size }
  6027. Result := (cs_opt_size in current_settings.optimizerswitches) or
  6028. (
  6029. {$ifdef x86_64}
  6030. { XCHG takes 3 cycles on AMD Athlon64 }
  6031. (current_settings.optimizecputype >= cpu_core_i)
  6032. {$else x86_64}
  6033. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  6034. than 3, so it becomes a saving compared to three MOVs with two of
  6035. them able to execute simultaneously. [Kit] }
  6036. (current_settings.optimizecputype >= cpu_PentiumM)
  6037. {$endif x86_64}
  6038. );
  6039. end;
  6040. var
  6041. NewRef: TReference;
  6042. hp1, hp2, hp3, hp4: Tai;
  6043. {$ifndef x86_64}
  6044. OperIdx: Integer;
  6045. {$endif x86_64}
  6046. NewInstr : Taicpu;
  6047. NewAligh : Tai_align;
  6048. DestLabel: TAsmLabel;
  6049. begin
  6050. Result:=false;
  6051. { This optimisation adds an instruction, so only do it for speed }
  6052. if not (cs_opt_size in current_settings.optimizerswitches) and
  6053. MatchOpType(taicpu(p), top_const, top_reg) and
  6054. (taicpu(p).oper[0]^.val = 0) then
  6055. begin
  6056. { To avoid compiler warning }
  6057. DestLabel := nil;
  6058. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  6059. InternalError(2021040750);
  6060. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  6061. Exit;
  6062. case hp1.typ of
  6063. ait_label:
  6064. begin
  6065. { Change:
  6066. mov $0,%reg mov $0,%reg
  6067. @Lbl1: @Lbl1:
  6068. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  6069. je @Lbl2 jne @Lbl2
  6070. To: To:
  6071. mov $0,%reg mov $0,%reg
  6072. jmp @Lbl2 jmp @Lbl3
  6073. (align) (align)
  6074. @Lbl1: @Lbl1:
  6075. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  6076. je @Lbl2 je @Lbl2
  6077. @Lbl3: <-- Only if label exists
  6078. (Not if it's optimised for size)
  6079. }
  6080. if not GetNextInstruction(hp1, hp2) then
  6081. Exit;
  6082. if not (cs_opt_size in current_settings.optimizerswitches) and
  6083. (hp2.typ = ait_instruction) and
  6084. (
  6085. { Register sizes must exactly match }
  6086. (
  6087. (taicpu(hp2).opcode = A_CMP) and
  6088. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  6089. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  6090. ) or (
  6091. (taicpu(hp2).opcode = A_TEST) and
  6092. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  6093. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  6094. )
  6095. ) and GetNextInstruction(hp2, hp3) and
  6096. (hp3.typ = ait_instruction) and
  6097. (taicpu(hp3).opcode = A_JCC) and
  6098. (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
  6099. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  6100. begin
  6101. { Check condition of jump }
  6102. { Always true? }
  6103. if condition_in(C_E, taicpu(hp3).condition) then
  6104. begin
  6105. { Copy label symbol and obtain matching label entry for the
  6106. conditional jump, as this will be our destination}
  6107. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  6108. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  6109. Result := True;
  6110. end
  6111. { Always false? }
  6112. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  6113. begin
  6114. { This is only worth it if there's a jump to take }
  6115. case hp2.typ of
  6116. ait_instruction:
  6117. begin
  6118. if taicpu(hp2).opcode = A_JMP then
  6119. begin
  6120. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  6121. { An unconditional jump follows the conditional jump which will always be false,
  6122. so use this jump's destination for the new jump }
  6123. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  6124. Result := True;
  6125. end
  6126. else if taicpu(hp2).opcode = A_JCC then
  6127. begin
  6128. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  6129. if condition_in(C_E, taicpu(hp2).condition) then
  6130. begin
  6131. { A second conditional jump follows the conditional jump which will always be false,
  6132. while the second jump is always True, so use this jump's destination for the new jump }
  6133. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  6134. Result := True;
  6135. end;
  6136. { Don't risk it if the jump isn't always true (Result remains False) }
  6137. end;
  6138. end;
  6139. else
  6140. { If anything else don't optimise };
  6141. end;
  6142. end;
  6143. if Result then
  6144. begin
  6145. { Just so we have something to insert as a paremeter}
  6146. reference_reset(NewRef, 1, []);
  6147. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  6148. { Now actually load the correct parameter }
  6149. NewInstr.loadsymbol(0, DestLabel, 0);
  6150. { Get instruction before original label (may not be p under -O3) }
  6151. if not GetLastInstruction(hp1, hp2) then
  6152. { Shouldn't fail here }
  6153. InternalError(2021040701);
  6154. DestLabel.increfs;
  6155. AsmL.InsertAfter(NewInstr, hp2);
  6156. { Add new alignment field }
  6157. (* AsmL.InsertAfter(
  6158. cai_align.create_max(
  6159. current_settings.alignment.jumpalign,
  6160. current_settings.alignment.jumpalignskipmax
  6161. ),
  6162. NewInstr
  6163. ); *)
  6164. end;
  6165. Exit;
  6166. end;
  6167. end;
  6168. else
  6169. ;
  6170. end;
  6171. end;
  6172. if not GetNextInstruction(p, hp1) then
  6173. Exit;
  6174. if MatchInstruction(hp1, A_JMP, [S_NO]) then
  6175. begin
  6176. { Sometimes the MOVs that OptPass2JMP produces can be improved
  6177. further, but we can't just put this jump optimisation in pass 1
  6178. because it tends to perform worse when conditional jumps are
  6179. nearby (e.g. when converting CMOV instructions). [Kit] }
  6180. if OptPass2JMP(hp1) then
  6181. { call OptPass1MOV once to potentially merge any MOVs that were created }
  6182. Result := OptPass1MOV(p)
  6183. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  6184. returned True and the instruction is still a MOV, thus checking
  6185. the optimisations below }
  6186. { If OptPass2JMP returned False, no optimisations were done to
  6187. the jump and there are no further optimisations that can be done
  6188. to the MOV instruction on this pass }
  6189. end
  6190. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  6191. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  6192. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  6193. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6194. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  6195. { be lazy, checking separately for sub would be slightly better }
  6196. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  6197. begin
  6198. { Change:
  6199. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  6200. addl/q $x,%reg2 subl/q $x,%reg2
  6201. To:
  6202. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  6203. }
  6204. TransferUsedRegs(TmpUsedRegs);
  6205. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6206. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6207. if not GetNextInstruction(hp1, hp2) or
  6208. (
  6209. { The FLAGS register isn't always tracked properly, so do not
  6210. perform this optimisation if a conditional statement follows }
  6211. not RegReadByInstruction(NR_DEFAULTFLAGS, hp2) and
  6212. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)
  6213. ) then
  6214. begin
  6215. reference_reset(NewRef, 1, []);
  6216. NewRef.base := taicpu(p).oper[0]^.reg;
  6217. NewRef.scalefactor := 1;
  6218. if taicpu(hp1).opcode = A_ADD then
  6219. begin
  6220. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  6221. NewRef.offset := taicpu(hp1).oper[0]^.val;
  6222. end
  6223. else
  6224. begin
  6225. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  6226. NewRef.offset := -taicpu(hp1).oper[0]^.val;
  6227. end;
  6228. taicpu(p).opcode := A_LEA;
  6229. taicpu(p).loadref(0, NewRef);
  6230. RemoveInstruction(hp1);
  6231. Result := True;
  6232. Exit;
  6233. end;
  6234. end
  6235. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  6236. {$ifdef x86_64}
  6237. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  6238. {$else x86_64}
  6239. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  6240. {$endif x86_64}
  6241. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6242. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  6243. { mov reg1, reg2 mov reg1, reg2
  6244. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  6245. begin
  6246. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  6247. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  6248. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  6249. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  6250. TransferUsedRegs(TmpUsedRegs);
  6251. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6252. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  6253. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  6254. then
  6255. begin
  6256. RemoveCurrentP(p, hp1);
  6257. Result:=true;
  6258. end;
  6259. exit;
  6260. end
  6261. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  6262. IsXCHGAcceptable and
  6263. { XCHG doesn't support 8-byte registers }
  6264. (taicpu(p).opsize <> S_B) and
  6265. MatchInstruction(hp1, A_MOV, []) and
  6266. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6267. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  6268. GetNextInstruction(hp1, hp2) and
  6269. MatchInstruction(hp2, A_MOV, []) and
  6270. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  6271. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  6272. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  6273. begin
  6274. { mov %reg1,%reg2
  6275. mov %reg3,%reg1 -> xchg %reg3,%reg1
  6276. mov %reg2,%reg3
  6277. (%reg2 not used afterwards)
  6278. Note that xchg takes 3 cycles to execute, and generally mov's take
  6279. only one cycle apiece, but the first two mov's can be executed in
  6280. parallel, only taking 2 cycles overall. Older processors should
  6281. therefore only optimise for size. [Kit]
  6282. }
  6283. TransferUsedRegs(TmpUsedRegs);
  6284. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6285. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6286. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  6287. begin
  6288. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  6289. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  6290. taicpu(hp1).opcode := A_XCHG;
  6291. RemoveCurrentP(p, hp1);
  6292. RemoveInstruction(hp2);
  6293. Result := True;
  6294. Exit;
  6295. end;
  6296. end
  6297. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  6298. MatchInstruction(hp1, A_SAR, []) then
  6299. begin
  6300. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  6301. begin
  6302. { the use of %edx also covers the opsize being S_L }
  6303. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  6304. begin
  6305. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  6306. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  6307. (taicpu(p).oper[1]^.reg = NR_EDX) then
  6308. begin
  6309. { Change:
  6310. movl %eax,%edx
  6311. sarl $31,%edx
  6312. To:
  6313. cltd
  6314. }
  6315. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  6316. RemoveInstruction(hp1);
  6317. taicpu(p).opcode := A_CDQ;
  6318. taicpu(p).opsize := S_NO;
  6319. taicpu(p).clearop(1);
  6320. taicpu(p).clearop(0);
  6321. taicpu(p).ops:=0;
  6322. Result := True;
  6323. end
  6324. else if (cs_opt_size in current_settings.optimizerswitches) and
  6325. (taicpu(p).oper[0]^.reg = NR_EDX) and
  6326. (taicpu(p).oper[1]^.reg = NR_EAX) then
  6327. begin
  6328. { Change:
  6329. movl %edx,%eax
  6330. sarl $31,%edx
  6331. To:
  6332. movl %edx,%eax
  6333. cltd
  6334. Note that this creates a dependency between the two instructions,
  6335. so only perform if optimising for size.
  6336. }
  6337. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  6338. taicpu(hp1).opcode := A_CDQ;
  6339. taicpu(hp1).opsize := S_NO;
  6340. taicpu(hp1).clearop(1);
  6341. taicpu(hp1).clearop(0);
  6342. taicpu(hp1).ops:=0;
  6343. end;
  6344. {$ifndef x86_64}
  6345. end
  6346. { Don't bother if CMOV is supported, because a more optimal
  6347. sequence would have been generated for the Abs() intrinsic }
  6348. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  6349. { the use of %eax also covers the opsize being S_L }
  6350. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  6351. (taicpu(p).oper[0]^.reg = NR_EAX) and
  6352. (taicpu(p).oper[1]^.reg = NR_EDX) and
  6353. GetNextInstruction(hp1, hp2) and
  6354. MatchInstruction(hp2, A_XOR, [S_L]) and
  6355. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  6356. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  6357. GetNextInstruction(hp2, hp3) and
  6358. MatchInstruction(hp3, A_SUB, [S_L]) and
  6359. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  6360. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  6361. begin
  6362. { Change:
  6363. movl %eax,%edx
  6364. sarl $31,%eax
  6365. xorl %eax,%edx
  6366. subl %eax,%edx
  6367. (Instruction that uses %edx)
  6368. (%eax deallocated)
  6369. (%edx deallocated)
  6370. To:
  6371. cltd
  6372. xorl %edx,%eax <-- Note the registers have swapped
  6373. subl %edx,%eax
  6374. (Instruction that uses %eax) <-- %eax rather than %edx
  6375. }
  6376. TransferUsedRegs(TmpUsedRegs);
  6377. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6378. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6379. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6380. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  6381. begin
  6382. if GetNextInstruction(hp3, hp4) and
  6383. not RegModifiedByInstruction(NR_EDX, hp4) and
  6384. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  6385. begin
  6386. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  6387. taicpu(p).opcode := A_CDQ;
  6388. taicpu(p).clearop(1);
  6389. taicpu(p).clearop(0);
  6390. taicpu(p).ops:=0;
  6391. RemoveInstruction(hp1);
  6392. taicpu(hp2).loadreg(0, NR_EDX);
  6393. taicpu(hp2).loadreg(1, NR_EAX);
  6394. taicpu(hp3).loadreg(0, NR_EDX);
  6395. taicpu(hp3).loadreg(1, NR_EAX);
  6396. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  6397. { Convert references in the following instruction (hp4) from %edx to %eax }
  6398. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  6399. with taicpu(hp4).oper[OperIdx]^ do
  6400. case typ of
  6401. top_reg:
  6402. if getsupreg(reg) = RS_EDX then
  6403. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  6404. top_ref:
  6405. begin
  6406. if getsupreg(reg) = RS_EDX then
  6407. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  6408. if getsupreg(reg) = RS_EDX then
  6409. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  6410. end;
  6411. else
  6412. ;
  6413. end;
  6414. end;
  6415. end;
  6416. {$else x86_64}
  6417. end;
  6418. end
  6419. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  6420. { the use of %rdx also covers the opsize being S_Q }
  6421. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  6422. begin
  6423. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  6424. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  6425. (taicpu(p).oper[1]^.reg = NR_RDX) then
  6426. begin
  6427. { Change:
  6428. movq %rax,%rdx
  6429. sarq $63,%rdx
  6430. To:
  6431. cqto
  6432. }
  6433. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  6434. RemoveInstruction(hp1);
  6435. taicpu(p).opcode := A_CQO;
  6436. taicpu(p).opsize := S_NO;
  6437. taicpu(p).clearop(1);
  6438. taicpu(p).clearop(0);
  6439. taicpu(p).ops:=0;
  6440. Result := True;
  6441. end
  6442. else if (cs_opt_size in current_settings.optimizerswitches) and
  6443. (taicpu(p).oper[0]^.reg = NR_RDX) and
  6444. (taicpu(p).oper[1]^.reg = NR_RAX) then
  6445. begin
  6446. { Change:
  6447. movq %rdx,%rax
  6448. sarq $63,%rdx
  6449. To:
  6450. movq %rdx,%rax
  6451. cqto
  6452. Note that this creates a dependency between the two instructions,
  6453. so only perform if optimising for size.
  6454. }
  6455. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  6456. taicpu(hp1).opcode := A_CQO;
  6457. taicpu(hp1).opsize := S_NO;
  6458. taicpu(hp1).clearop(1);
  6459. taicpu(hp1).clearop(0);
  6460. taicpu(hp1).ops:=0;
  6461. {$endif x86_64}
  6462. end;
  6463. end;
  6464. end
  6465. else if MatchInstruction(hp1, A_MOV, []) and
  6466. (taicpu(hp1).oper[1]^.typ = top_reg) then
  6467. { Though "GetNextInstruction" could be factored out, along with
  6468. the instructions that depend on hp2, it is an expensive call that
  6469. should be delayed for as long as possible, hence we do cheaper
  6470. checks first that are likely to be False. [Kit] }
  6471. begin
  6472. if (
  6473. (
  6474. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  6475. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  6476. (
  6477. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  6478. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  6479. )
  6480. ) or
  6481. (
  6482. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  6483. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  6484. (
  6485. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  6486. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  6487. )
  6488. )
  6489. ) and
  6490. GetNextInstruction(hp1, hp2) and
  6491. MatchInstruction(hp2, A_SAR, []) and
  6492. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  6493. begin
  6494. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  6495. begin
  6496. { Change:
  6497. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  6498. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  6499. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  6500. To:
  6501. movl r/m,%eax <- Note the change in register
  6502. cltd
  6503. }
  6504. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  6505. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  6506. taicpu(p).loadreg(1, NR_EAX);
  6507. taicpu(hp1).opcode := A_CDQ;
  6508. taicpu(hp1).clearop(1);
  6509. taicpu(hp1).clearop(0);
  6510. taicpu(hp1).ops:=0;
  6511. RemoveInstruction(hp2);
  6512. (*
  6513. {$ifdef x86_64}
  6514. end
  6515. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  6516. { This code sequence does not get generated - however it might become useful
  6517. if and when 128-bit signed integer types make an appearance, so the code
  6518. is kept here for when it is eventually needed. [Kit] }
  6519. (
  6520. (
  6521. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  6522. (
  6523. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  6524. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  6525. )
  6526. ) or
  6527. (
  6528. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  6529. (
  6530. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  6531. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  6532. )
  6533. )
  6534. ) and
  6535. GetNextInstruction(hp1, hp2) and
  6536. MatchInstruction(hp2, A_SAR, [S_Q]) and
  6537. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  6538. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  6539. begin
  6540. { Change:
  6541. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  6542. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  6543. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  6544. To:
  6545. movq r/m,%rax <- Note the change in register
  6546. cqto
  6547. }
  6548. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  6549. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  6550. taicpu(p).loadreg(1, NR_RAX);
  6551. taicpu(hp1).opcode := A_CQO;
  6552. taicpu(hp1).clearop(1);
  6553. taicpu(hp1).clearop(0);
  6554. taicpu(hp1).ops:=0;
  6555. RemoveInstruction(hp2);
  6556. {$endif x86_64}
  6557. *)
  6558. end;
  6559. end;
  6560. {$ifdef x86_64}
  6561. end
  6562. else if (taicpu(p).opsize = S_L) and
  6563. (taicpu(p).oper[1]^.typ = top_reg) and
  6564. (
  6565. MatchInstruction(hp1, A_MOV,[]) and
  6566. (taicpu(hp1).opsize = S_L) and
  6567. (taicpu(hp1).oper[1]^.typ = top_reg)
  6568. ) and (
  6569. GetNextInstruction(hp1, hp2) and
  6570. (tai(hp2).typ=ait_instruction) and
  6571. (taicpu(hp2).opsize = S_Q) and
  6572. (
  6573. (
  6574. MatchInstruction(hp2, A_ADD,[]) and
  6575. (taicpu(hp2).opsize = S_Q) and
  6576. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  6577. (
  6578. (
  6579. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  6580. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  6581. ) or (
  6582. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  6583. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  6584. )
  6585. )
  6586. ) or (
  6587. MatchInstruction(hp2, A_LEA,[]) and
  6588. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  6589. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  6590. (
  6591. (
  6592. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  6593. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  6594. ) or (
  6595. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  6596. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  6597. )
  6598. ) and (
  6599. (
  6600. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  6601. ) or (
  6602. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  6603. )
  6604. )
  6605. )
  6606. )
  6607. ) and (
  6608. GetNextInstruction(hp2, hp3) and
  6609. MatchInstruction(hp3, A_SHR,[]) and
  6610. (taicpu(hp3).opsize = S_Q) and
  6611. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  6612. (taicpu(hp3).oper[0]^.val = 1) and
  6613. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  6614. ) then
  6615. begin
  6616. { Change movl x, reg1d movl x, reg1d
  6617. movl y, reg2d movl y, reg2d
  6618. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  6619. shrq $1, reg1q shrq $1, reg1q
  6620. ( reg1d and reg2d can be switched around in the first two instructions )
  6621. To movl x, reg1d
  6622. addl y, reg1d
  6623. rcrl $1, reg1d
  6624. This corresponds to the common expression (x + y) shr 1, where
  6625. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  6626. smaller code, but won't account for x + y causing an overflow). [Kit]
  6627. }
  6628. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  6629. { Change first MOV command to have the same register as the final output }
  6630. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  6631. else
  6632. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  6633. { Change second MOV command to an ADD command. This is easier than
  6634. converting the existing command because it means we don't have to
  6635. touch 'y', which might be a complicated reference, and also the
  6636. fact that the third command might either be ADD or LEA. [Kit] }
  6637. taicpu(hp1).opcode := A_ADD;
  6638. { Delete old ADD/LEA instruction }
  6639. RemoveInstruction(hp2);
  6640. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  6641. taicpu(hp3).opcode := A_RCR;
  6642. taicpu(hp3).changeopsize(S_L);
  6643. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  6644. {$endif x86_64}
  6645. end;
  6646. end;
  6647. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  6648. var
  6649. ThisReg: TRegister;
  6650. MinSize, MaxSize, TrySmaller, TargetSize: TOpSize;
  6651. TargetSubReg: TSubRegister;
  6652. hp1, hp2: tai;
  6653. RegInUse, RegChanged, p_removed: Boolean;
  6654. { Store list of found instructions so we don't have to call
  6655. GetNextInstructionUsingReg multiple times }
  6656. InstrList: array of taicpu;
  6657. InstrMax, Index: Integer;
  6658. UpperLimit, TrySmallerLimit: TCgInt;
  6659. PreMessage: string;
  6660. { Data flow analysis }
  6661. TestValMin, TestValMax: TCgInt;
  6662. SmallerOverflow: Boolean;
  6663. begin
  6664. Result := False;
  6665. p_removed := False;
  6666. { This is anything but quick! }
  6667. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  6668. Exit;
  6669. SetLength(InstrList, 0);
  6670. InstrMax := -1;
  6671. ThisReg := taicpu(p).oper[1]^.reg;
  6672. case taicpu(p).opsize of
  6673. S_BW, S_BL:
  6674. begin
  6675. {$if defined(i386) or defined(i8086)}
  6676. { If the target size is 8-bit, make sure we can actually encode it }
  6677. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  6678. Exit;
  6679. {$endif i386 or i8086}
  6680. UpperLimit := $FF;
  6681. MinSize := S_B;
  6682. if taicpu(p).opsize = S_BW then
  6683. MaxSize := S_W
  6684. else
  6685. MaxSize := S_L;
  6686. end;
  6687. S_WL:
  6688. begin
  6689. UpperLimit := $FFFF;
  6690. MinSize := S_W;
  6691. MaxSize := S_L;
  6692. end
  6693. else
  6694. InternalError(2020112301);
  6695. end;
  6696. TestValMin := 0;
  6697. TestValMax := UpperLimit;
  6698. TrySmallerLimit := UpperLimit;
  6699. TrySmaller := S_NO;
  6700. SmallerOverflow := False;
  6701. RegChanged := False;
  6702. hp1 := p;
  6703. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  6704. (hp1.typ = ait_instruction) and
  6705. (
  6706. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  6707. instruction that doesn't actually contain ThisReg }
  6708. (cs_opt_level3 in current_settings.optimizerswitches) or
  6709. RegInInstruction(ThisReg, hp1)
  6710. ) do
  6711. begin
  6712. case taicpu(hp1).opcode of
  6713. A_INC,A_DEC:
  6714. begin
  6715. { Has to be an exact match on the register }
  6716. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  6717. Break;
  6718. if taicpu(hp1).opcode = A_INC then
  6719. begin
  6720. Inc(TestValMin);
  6721. Inc(TestValMax);
  6722. end
  6723. else
  6724. begin
  6725. Dec(TestValMin);
  6726. Dec(TestValMax);
  6727. end;
  6728. end;
  6729. A_CMP:
  6730. begin
  6731. if (taicpu(hp1).oper[1]^.typ <> top_reg) or
  6732. { Has to be an exact match on the register }
  6733. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  6734. (taicpu(hp1).oper[0]^.typ <> top_const) or
  6735. { Make sure the comparison value is not smaller than the
  6736. smallest allowed signed value for the minimum size (e.g.
  6737. -128 for 8-bit) }
  6738. not (
  6739. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  6740. { Is it in the negative range? }
  6741. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  6742. ) then
  6743. Break;
  6744. TestValMin := TestValMin - taicpu(hp1).oper[0]^.val;
  6745. TestValMax := TestValMax - taicpu(hp1).oper[0]^.val;
  6746. if (TestValMin < TrySmallerLimit) or (TestValMax < TrySmallerLimit) or
  6747. (TestValMin > UpperLimit) or (TestValMax > UpperLimit) then
  6748. { Overflow }
  6749. Break;
  6750. { Check to see if the active register is used afterwards }
  6751. TransferUsedRegs(TmpUsedRegs);
  6752. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  6753. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  6754. begin
  6755. case MinSize of
  6756. S_B:
  6757. TargetSubReg := R_SUBL;
  6758. S_W:
  6759. TargetSubReg := R_SUBW;
  6760. else
  6761. InternalError(2021051002);
  6762. end;
  6763. { Update the register to its new size }
  6764. setsubreg(ThisReg, TargetSubReg);
  6765. taicpu(hp1).oper[1]^.reg := ThisReg;
  6766. taicpu(hp1).opsize := MinSize;
  6767. { Convert the input MOVZX to a MOV }
  6768. if (taicpu(p).oper[0]^.typ = top_reg) and
  6769. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  6770. begin
  6771. { Or remove it completely! }
  6772. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  6773. RemoveCurrentP(p);
  6774. p_removed := True;
  6775. end
  6776. else
  6777. begin
  6778. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  6779. taicpu(p).opcode := A_MOV;
  6780. taicpu(p).oper[1]^.reg := ThisReg;
  6781. taicpu(p).opsize := MinSize;
  6782. end;
  6783. if (InstrMax >= 0) then
  6784. begin
  6785. for Index := 0 to InstrMax do
  6786. begin
  6787. { If p_removed is true, then the original MOV/Z was removed
  6788. and removing the AND instruction may not be safe if it
  6789. appears first }
  6790. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  6791. InternalError(2020112311);
  6792. if InstrList[Index].oper[0]^.typ = top_reg then
  6793. InstrList[Index].oper[0]^.reg := ThisReg;
  6794. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  6795. InstrList[Index].opsize := MinSize;
  6796. end;
  6797. end;
  6798. Result := True;
  6799. Exit;
  6800. end;
  6801. end;
  6802. { OR and XOR are not included because they can too easily fool
  6803. the data flow analysis (they can cause non-linear behaviour) }
  6804. A_ADD,A_SUB,A_AND,A_SHL,A_SHR:
  6805. begin
  6806. if
  6807. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  6808. { Has to be an exact match on the register }
  6809. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  6810. (
  6811. (
  6812. (taicpu(hp1).oper[0]^.typ = top_const) and
  6813. (
  6814. (
  6815. (taicpu(hp1).opcode = A_SHL) and
  6816. (
  6817. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  6818. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  6819. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  6820. )
  6821. ) or (
  6822. (taicpu(hp1).opcode <> A_SHL) and
  6823. (
  6824. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  6825. { Is it in the negative range? }
  6826. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  6827. )
  6828. )
  6829. )
  6830. ) or (
  6831. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  6832. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  6833. )
  6834. ) then
  6835. Break;
  6836. case taicpu(hp1).opcode of
  6837. A_ADD:
  6838. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  6839. begin
  6840. TestValMin := TestValMin * 2;
  6841. TestValMax := TestValMax * 2;
  6842. end
  6843. else
  6844. begin
  6845. TestValMin := TestValMin + taicpu(hp1).oper[0]^.val;
  6846. TestValMax := TestValMax + taicpu(hp1).oper[0]^.val;
  6847. end;
  6848. A_SUB:
  6849. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  6850. begin
  6851. TestValMin := 0;
  6852. TestValMax := 0;
  6853. end
  6854. else
  6855. begin
  6856. TestValMin := TestValMin - taicpu(hp1).oper[0]^.val;
  6857. TestValMax := TestValMax - taicpu(hp1).oper[0]^.val;
  6858. end;
  6859. A_AND:
  6860. if (taicpu(hp1).oper[0]^.typ = top_const) then
  6861. begin
  6862. { we might be able to go smaller if AND appears first }
  6863. if InstrMax = -1 then
  6864. case MinSize of
  6865. S_B:
  6866. ;
  6867. S_W:
  6868. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  6869. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  6870. begin
  6871. TrySmaller := S_B;
  6872. TrySmallerLimit := $FF;
  6873. end;
  6874. S_L:
  6875. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  6876. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  6877. begin
  6878. TrySmaller := S_B;
  6879. TrySmallerLimit := $FF;
  6880. end
  6881. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  6882. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  6883. begin
  6884. TrySmaller := S_W;
  6885. TrySmallerLimit := $FFFF;
  6886. end;
  6887. else
  6888. InternalError(2020112320);
  6889. end;
  6890. TestValMin := TestValMin and taicpu(hp1).oper[0]^.val;
  6891. TestValMax := TestValMax and taicpu(hp1).oper[0]^.val;
  6892. end;
  6893. A_SHL:
  6894. begin
  6895. TestValMin := TestValMin shl taicpu(hp1).oper[0]^.val;
  6896. TestValMax := TestValMax shl taicpu(hp1).oper[0]^.val;
  6897. end;
  6898. A_SHR:
  6899. begin
  6900. { we might be able to go smaller if SHR appears first }
  6901. if InstrMax = -1 then
  6902. case MinSize of
  6903. S_B:
  6904. ;
  6905. S_W:
  6906. if (taicpu(hp1).oper[0]^.val >= 8) then
  6907. begin
  6908. TrySmaller := S_B;
  6909. TrySmallerLimit := $FF;
  6910. end;
  6911. S_L:
  6912. if (taicpu(hp1).oper[0]^.val >= 24) then
  6913. begin
  6914. TrySmaller := S_B;
  6915. TrySmallerLimit := $FF;
  6916. end
  6917. else if (taicpu(hp1).oper[0]^.val >= 16) then
  6918. begin
  6919. TrySmaller := S_W;
  6920. TrySmallerLimit := $FFFF;
  6921. end;
  6922. else
  6923. InternalError(2020112321);
  6924. end;
  6925. TestValMin := TestValMin shr taicpu(hp1).oper[0]^.val;
  6926. TestValMax := TestValMax shr taicpu(hp1).oper[0]^.val;
  6927. end;
  6928. else
  6929. InternalError(2020112303);
  6930. end;
  6931. end;
  6932. (*
  6933. A_IMUL:
  6934. case taicpu(hp1).ops of
  6935. 2:
  6936. begin
  6937. if not MatchOpType(hp1, top_reg, top_reg) or
  6938. { Has to be an exact match on the register }
  6939. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  6940. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  6941. Break;
  6942. TestValMin := TestValMin * TestValMin;
  6943. TestValMax := TestValMax * TestValMax;
  6944. end;
  6945. 3:
  6946. begin
  6947. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  6948. { Has to be an exact match on the register }
  6949. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  6950. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  6951. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  6952. { Is it in the negative range? }
  6953. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  6954. Break;
  6955. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  6956. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  6957. end;
  6958. else
  6959. Break;
  6960. end;
  6961. A_IDIV:
  6962. case taicpu(hp1).ops of
  6963. 3:
  6964. begin
  6965. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  6966. { Has to be an exact match on the register }
  6967. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  6968. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  6969. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  6970. { Is it in the negative range? }
  6971. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  6972. Break;
  6973. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  6974. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  6975. end;
  6976. else
  6977. Break;
  6978. end;
  6979. *)
  6980. A_MOVZX:
  6981. begin
  6982. if not MatchOpType(taicpu(hp1), top_reg, top_reg) then
  6983. Break;
  6984. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  6985. begin
  6986. { Because hp1 was obtained via GetNextInstructionUsingReg
  6987. and ThisReg doesn't appear in the first operand, it
  6988. must appear in the second operand and hence gets
  6989. overwritten }
  6990. if (InstrMax = -1) and
  6991. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  6992. begin
  6993. { The two MOVZX instructions are adjacent, so remove the first one }
  6994. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  6995. RemoveCurrentP(p);
  6996. Result := True;
  6997. Exit;
  6998. end;
  6999. Break;
  7000. end;
  7001. { The objective here is to try to find a combination that
  7002. removes one of the MOV/Z instructions. }
  7003. case taicpu(hp1).opsize of
  7004. S_WL:
  7005. if (MinSize in [S_B, S_W]) then
  7006. begin
  7007. TargetSize := S_L;
  7008. TargetSubReg := R_SUBD;
  7009. end
  7010. else if ((TrySmaller in [S_B, S_W]) and not SmallerOverflow) then
  7011. begin
  7012. TargetSize := TrySmaller;
  7013. if TrySmaller = S_B then
  7014. TargetSubReg := R_SUBL
  7015. else
  7016. TargetSubReg := R_SUBW;
  7017. end
  7018. else
  7019. Break;
  7020. S_BW:
  7021. if (MinSize in [S_B, S_W]) then
  7022. begin
  7023. TargetSize := S_W;
  7024. TargetSubReg := R_SUBW;
  7025. end
  7026. else if ((TrySmaller = S_B) and not SmallerOverflow) then
  7027. begin
  7028. TargetSize := S_B;
  7029. TargetSubReg := R_SUBL;
  7030. end
  7031. else
  7032. Break;
  7033. S_BL:
  7034. if (MinSize in [S_B, S_W]) then
  7035. begin
  7036. TargetSize := S_L;
  7037. TargetSubReg := R_SUBD;
  7038. end
  7039. else if ((TrySmaller = S_B) and not SmallerOverflow) then
  7040. begin
  7041. TargetSize := S_B;
  7042. TargetSubReg := R_SUBL;
  7043. end
  7044. else
  7045. Break;
  7046. else
  7047. InternalError(2020112302);
  7048. end;
  7049. { Update the register to its new size }
  7050. setsubreg(ThisReg, TargetSubReg);
  7051. if TargetSize = MinSize then
  7052. begin
  7053. { Convert the input MOVZX to a MOV }
  7054. if (taicpu(p).oper[0]^.typ = top_reg) and
  7055. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  7056. begin
  7057. { Or remove it completely! }
  7058. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  7059. RemoveCurrentP(p);
  7060. p_removed := True;
  7061. end
  7062. else
  7063. begin
  7064. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  7065. taicpu(p).opcode := A_MOV;
  7066. taicpu(p).oper[1]^.reg := ThisReg;
  7067. taicpu(p).opsize := TargetSize;
  7068. end;
  7069. Result := True;
  7070. end
  7071. else if TargetSize <> MaxSize then
  7072. begin
  7073. case MaxSize of
  7074. S_L:
  7075. if TargetSize = S_W then
  7076. begin
  7077. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  7078. taicpu(p).opsize := S_BW;
  7079. taicpu(p).oper[1]^.reg := ThisReg;
  7080. Result := True;
  7081. end
  7082. else
  7083. InternalError(2020112341);
  7084. S_W:
  7085. if TargetSize = S_L then
  7086. begin
  7087. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  7088. taicpu(p).opsize := S_BL;
  7089. taicpu(p).oper[1]^.reg := ThisReg;
  7090. Result := True;
  7091. end
  7092. else
  7093. InternalError(2020112342);
  7094. else
  7095. ;
  7096. end;
  7097. end;
  7098. if (MaxSize = TargetSize) or
  7099. ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  7100. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  7101. begin
  7102. { Convert the output MOVZX to a MOV }
  7103. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7104. begin
  7105. { Or remove it completely! }
  7106. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  7107. { Be careful; if p = hp1 and p was also removed, p
  7108. will become a dangling pointer }
  7109. if p = hp1 then
  7110. RemoveCurrentp(p) { p = hp1 and will then become the next instruction }
  7111. else
  7112. RemoveInstruction(hp1);
  7113. end
  7114. else
  7115. begin
  7116. taicpu(hp1).opcode := A_MOV;
  7117. taicpu(hp1).oper[0]^.reg := ThisReg;
  7118. taicpu(hp1).opsize := TargetSize;
  7119. { Check to see if the active register is used afterwards;
  7120. if not, we can change it and make a saving. }
  7121. RegInUse := False;
  7122. TransferUsedRegs(TmpUsedRegs);
  7123. { The target register may be marked as in use to cross
  7124. a jump to a distant label, so exclude it }
  7125. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  7126. hp2 := p;
  7127. repeat
  7128. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  7129. { Explicitly check for the excluded register (don't include the first
  7130. instruction as it may be reading from here }
  7131. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  7132. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  7133. begin
  7134. RegInUse := True;
  7135. Break;
  7136. end;
  7137. if not GetNextInstruction(hp2, hp2) then
  7138. InternalError(2020112340);
  7139. until (hp2 = hp1);
  7140. if not RegInUse and not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  7141. begin
  7142. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  7143. ThisReg := taicpu(hp1).oper[1]^.reg;
  7144. RegChanged := True;
  7145. TransferUsedRegs(TmpUsedRegs);
  7146. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  7147. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  7148. if p = hp1 then
  7149. RemoveCurrentp(p) { p = hp1 and will then become the next instruction }
  7150. else
  7151. RemoveInstruction(hp1);
  7152. { Instruction will become "mov %reg,%reg" }
  7153. if not p_removed and (taicpu(p).opcode = A_MOV) and
  7154. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  7155. begin
  7156. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  7157. RemoveCurrentP(p);
  7158. p_removed := True;
  7159. end
  7160. else
  7161. taicpu(p).oper[1]^.reg := ThisReg;
  7162. Result := True;
  7163. end
  7164. else
  7165. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  7166. end;
  7167. end
  7168. else
  7169. InternalError(2020112330);
  7170. { Now go through every instruction we found and change the
  7171. size. If TargetSize = MaxSize, then almost no changes are
  7172. needed and Result can remain False if it hasn't been set
  7173. yet.
  7174. If RegChanged is True, then the register requires changing
  7175. and so the point about TargetSize = MaxSize doesn't apply. }
  7176. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  7177. begin
  7178. for Index := 0 to InstrMax do
  7179. begin
  7180. { If p_removed is true, then the original MOV/Z was removed
  7181. and removing the AND instruction may not be safe if it
  7182. appears first }
  7183. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  7184. InternalError(2020112310);
  7185. if InstrList[Index].oper[0]^.typ = top_reg then
  7186. InstrList[Index].oper[0]^.reg := ThisReg;
  7187. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  7188. InstrList[Index].opsize := TargetSize;
  7189. end;
  7190. Result := True;
  7191. end;
  7192. Exit;
  7193. end;
  7194. else
  7195. { This includes ADC, SBB, IDIV and SAR }
  7196. Break;
  7197. end;
  7198. if (TestValMin < 0) or (TestValMax < 0) or
  7199. (TestValMin > UpperLimit) or (TestValMax > UpperLimit) then
  7200. { Overflow }
  7201. Break
  7202. else if not SmallerOverflow and (TrySmaller <> S_NO) and
  7203. ((TestValMin > TrySmallerLimit) or (TestValMax > TrySmallerLimit)) then
  7204. SmallerOverflow := True;
  7205. { Contains highest index (so instruction count - 1) }
  7206. Inc(InstrMax);
  7207. if InstrMax > High(InstrList) then
  7208. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  7209. InstrList[InstrMax] := taicpu(hp1);
  7210. end;
  7211. end;
  7212. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  7213. var
  7214. hp1 : tai;
  7215. begin
  7216. Result:=false;
  7217. if (taicpu(p).ops >= 2) and
  7218. ((taicpu(p).oper[0]^.typ = top_const) or
  7219. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  7220. (taicpu(p).oper[1]^.typ = top_reg) and
  7221. ((taicpu(p).ops = 2) or
  7222. ((taicpu(p).oper[2]^.typ = top_reg) and
  7223. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  7224. GetLastInstruction(p,hp1) and
  7225. MatchInstruction(hp1,A_MOV,[]) and
  7226. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7227. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7228. begin
  7229. TransferUsedRegs(TmpUsedRegs);
  7230. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  7231. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  7232. { change
  7233. mov reg1,reg2
  7234. imul y,reg2 to imul y,reg1,reg2 }
  7235. begin
  7236. taicpu(p).ops := 3;
  7237. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  7238. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7239. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  7240. RemoveInstruction(hp1);
  7241. result:=true;
  7242. end;
  7243. end;
  7244. end;
  7245. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  7246. var
  7247. ThisLabel: TAsmLabel;
  7248. begin
  7249. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  7250. ThisLabel.decrefs;
  7251. taicpu(p).opcode := A_RET;
  7252. taicpu(p).is_jmp := false;
  7253. taicpu(p).ops := taicpu(ret_p).ops;
  7254. case taicpu(ret_p).ops of
  7255. 0:
  7256. taicpu(p).clearop(0);
  7257. 1:
  7258. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  7259. else
  7260. internalerror(2016041301);
  7261. end;
  7262. { If the original label is now dead, it might turn out that the label
  7263. immediately follows p. As a result, everything beyond it, which will
  7264. be just some final register configuration and a RET instruction, is
  7265. now dead code. [Kit] }
  7266. { NOTE: This is much faster than introducing a OptPass2RET routine and
  7267. running RemoveDeadCodeAfterJump for each RET instruction, because
  7268. this optimisation rarely happens and most RETs appear at the end of
  7269. routines where there is nothing that can be stripped. [Kit] }
  7270. if not ThisLabel.is_used then
  7271. RemoveDeadCodeAfterJump(p);
  7272. end;
  7273. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  7274. var
  7275. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  7276. Unconditional, PotentialModified: Boolean;
  7277. OperPtr: POper;
  7278. NewRef: TReference;
  7279. InstrList: array of taicpu;
  7280. InstrMax, Index: Integer;
  7281. const
  7282. {$ifdef DEBUG_AOPTCPU}
  7283. SNoFlags: shortstring = ' so the flags aren''t modified';
  7284. {$else DEBUG_AOPTCPU}
  7285. SNoFlags = '';
  7286. {$endif DEBUG_AOPTCPU}
  7287. begin
  7288. Result:=false;
  7289. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  7290. begin
  7291. if MatchInstruction(hp1, A_TEST, [S_B]) and
  7292. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7293. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  7294. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  7295. GetNextInstruction(hp1, hp2) and
  7296. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  7297. { Change from: To:
  7298. set(C) %reg j(~C) label
  7299. test %reg,%reg/cmp $0,%reg
  7300. je label
  7301. set(C) %reg j(C) label
  7302. test %reg,%reg/cmp $0,%reg
  7303. jne label
  7304. (Also do something similar with sete/setne instead of je/jne)
  7305. }
  7306. begin
  7307. { Before we do anything else, we need to check the instructions
  7308. in between SETcc and TEST to make sure they don't modify the
  7309. FLAGS register - if -O2 or under, there won't be any
  7310. instructions between SET and TEST }
  7311. TransferUsedRegs(TmpUsedRegs);
  7312. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7313. if (cs_opt_level3 in current_settings.optimizerswitches) then
  7314. begin
  7315. next := p;
  7316. SetLength(InstrList, 0);
  7317. InstrMax := -1;
  7318. PotentialModified := False;
  7319. { Make a note of every instruction that modifies the FLAGS
  7320. register }
  7321. while GetNextInstruction(next, next) and (next <> hp1) do
  7322. begin
  7323. if next.typ <> ait_instruction then
  7324. { GetNextInstructionUsingReg should have returned False }
  7325. InternalError(2021051701);
  7326. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  7327. begin
  7328. case taicpu(next).opcode of
  7329. A_SETcc,
  7330. A_CMOVcc,
  7331. A_Jcc:
  7332. begin
  7333. if PotentialModified then
  7334. { Not safe because the flags were modified earlier }
  7335. Exit
  7336. else
  7337. { Condition is the same as the initial SETcc, so this is safe
  7338. (don't add to instruction list though) }
  7339. Continue;
  7340. end;
  7341. A_ADD:
  7342. begin
  7343. if (taicpu(next).opsize = S_B) or
  7344. { LEA doesn't support 8-bit operands }
  7345. (taicpu(next).oper[1]^.typ <> top_reg) or
  7346. { Must write to a register }
  7347. (taicpu(next).oper[0]^.typ = top_ref) then
  7348. { Require a constant or a register }
  7349. Exit;
  7350. PotentialModified := True;
  7351. end;
  7352. A_SUB:
  7353. begin
  7354. if (taicpu(next).opsize = S_B) or
  7355. { LEA doesn't support 8-bit operands }
  7356. (taicpu(next).oper[1]^.typ <> top_reg) or
  7357. { Must write to a register }
  7358. (taicpu(next).oper[0]^.typ <> top_const) or
  7359. (taicpu(next).oper[0]^.val = $80000000) then
  7360. { Can't subtract a register with LEA - also
  7361. check that the value isn't -2^31, as this
  7362. can't be negated }
  7363. Exit;
  7364. PotentialModified := True;
  7365. end;
  7366. A_SAL,
  7367. A_SHL:
  7368. begin
  7369. if (taicpu(next).opsize = S_B) or
  7370. { LEA doesn't support 8-bit operands }
  7371. (taicpu(next).oper[1]^.typ <> top_reg) or
  7372. { Must write to a register }
  7373. (taicpu(next).oper[0]^.typ <> top_const) or
  7374. (taicpu(next).oper[0]^.val < 0) or
  7375. (taicpu(next).oper[0]^.val > 3) then
  7376. Exit;
  7377. PotentialModified := True;
  7378. end;
  7379. A_IMUL:
  7380. begin
  7381. if (taicpu(next).ops <> 3) or
  7382. (taicpu(next).oper[1]^.typ <> top_reg) or
  7383. { Must write to a register }
  7384. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  7385. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  7386. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  7387. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  7388. Exit
  7389. else
  7390. PotentialModified := True;
  7391. end;
  7392. else
  7393. { Don't know how to change this, so abort }
  7394. Exit;
  7395. end;
  7396. { Contains highest index (so instruction count - 1) }
  7397. Inc(InstrMax);
  7398. if InstrMax > High(InstrList) then
  7399. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  7400. InstrList[InstrMax] := taicpu(next);
  7401. end;
  7402. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  7403. end;
  7404. if not Assigned(next) or (next <> hp1) then
  7405. { It should be equal to hp1 }
  7406. InternalError(2021051702);
  7407. { Cycle through each instruction and check to see if we can
  7408. change them to versions that don't modify the flags }
  7409. if (InstrMax >= 0) then
  7410. begin
  7411. for Index := 0 to InstrMax do
  7412. case InstrList[Index].opcode of
  7413. A_ADD:
  7414. begin
  7415. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  7416. InstrList[Index].opcode := A_LEA;
  7417. reference_reset(NewRef, 1, []);
  7418. NewRef.base := InstrList[Index].oper[1]^.reg;
  7419. if InstrList[Index].oper[0]^.typ = top_reg then
  7420. begin
  7421. NewRef.index := InstrList[Index].oper[0]^.reg;
  7422. NewRef.scalefactor := 1;
  7423. end
  7424. else
  7425. NewRef.offset := InstrList[Index].oper[0]^.val;
  7426. InstrList[Index].loadref(0, NewRef);
  7427. end;
  7428. A_SUB:
  7429. begin
  7430. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  7431. InstrList[Index].opcode := A_LEA;
  7432. reference_reset(NewRef, 1, []);
  7433. NewRef.base := InstrList[Index].oper[1]^.reg;
  7434. NewRef.offset := -InstrList[Index].oper[0]^.val;
  7435. InstrList[Index].loadref(0, NewRef);
  7436. end;
  7437. A_SHL,
  7438. A_SAL:
  7439. begin
  7440. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  7441. InstrList[Index].opcode := A_LEA;
  7442. reference_reset(NewRef, 1, []);
  7443. NewRef.index := InstrList[Index].oper[1]^.reg;
  7444. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  7445. InstrList[Index].loadref(0, NewRef);
  7446. end;
  7447. A_IMUL:
  7448. begin
  7449. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  7450. InstrList[Index].opcode := A_LEA;
  7451. reference_reset(NewRef, 1, []);
  7452. NewRef.index := InstrList[Index].oper[1]^.reg;
  7453. case InstrList[Index].oper[0]^.val of
  7454. 2, 4, 8:
  7455. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  7456. else {3, 5 and 9}
  7457. begin
  7458. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  7459. NewRef.base := InstrList[Index].oper[1]^.reg;
  7460. end;
  7461. end;
  7462. InstrList[Index].loadref(0, NewRef);
  7463. end;
  7464. else
  7465. InternalError(2021051710);
  7466. end;
  7467. end;
  7468. { Mark the FLAGS register as used across this whole block }
  7469. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  7470. end;
  7471. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  7472. JumpC := taicpu(hp2).condition;
  7473. Unconditional := False;
  7474. if conditions_equal(JumpC, C_E) then
  7475. SetC := inverse_cond(taicpu(p).condition)
  7476. else if conditions_equal(JumpC, C_NE) then
  7477. SetC := taicpu(p).condition
  7478. else
  7479. { We've got something weird here (and inefficent) }
  7480. begin
  7481. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  7482. SetC := C_NONE;
  7483. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  7484. if condition_in(C_AE, JumpC) then
  7485. Unconditional := True
  7486. else
  7487. { Not sure what to do with this jump - drop out }
  7488. Exit;
  7489. end;
  7490. RemoveInstruction(hp1);
  7491. if Unconditional then
  7492. MakeUnconditional(taicpu(hp2))
  7493. else
  7494. begin
  7495. if SetC = C_NONE then
  7496. InternalError(2018061402);
  7497. taicpu(hp2).SetCondition(SetC);
  7498. end;
  7499. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  7500. TmpUsedRegs }
  7501. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  7502. begin
  7503. RemoveCurrentp(p, hp2);
  7504. if taicpu(hp2).opcode = A_SETcc then
  7505. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  7506. else
  7507. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  7508. end
  7509. else
  7510. if taicpu(hp2).opcode = A_SETcc then
  7511. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  7512. else
  7513. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  7514. Result := True;
  7515. end
  7516. else if
  7517. { Make sure the instructions are adjacent }
  7518. (
  7519. not (cs_opt_level3 in current_settings.optimizerswitches) or
  7520. GetNextInstruction(p, hp1)
  7521. ) and
  7522. MatchInstruction(hp1, A_MOV, [S_B]) and
  7523. { Writing to memory is allowed }
  7524. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  7525. begin
  7526. {
  7527. Watch out for sequences such as:
  7528. set(c)b %regb
  7529. movb %regb,(ref)
  7530. movb $0,1(ref)
  7531. movb $0,2(ref)
  7532. movb $0,3(ref)
  7533. Much more efficient to turn it into:
  7534. movl $0,%regl
  7535. set(c)b %regb
  7536. movl %regl,(ref)
  7537. Or:
  7538. set(c)b %regb
  7539. movzbl %regb,%regl
  7540. movl %regl,(ref)
  7541. }
  7542. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  7543. GetNextInstruction(hp1, hp2) and
  7544. MatchInstruction(hp2, A_MOV, [S_B]) and
  7545. (taicpu(hp2).oper[1]^.typ = top_ref) and
  7546. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  7547. begin
  7548. { Don't do anything else except set Result to True }
  7549. end
  7550. else
  7551. begin
  7552. if taicpu(p).oper[0]^.typ = top_reg then
  7553. begin
  7554. TransferUsedRegs(TmpUsedRegs);
  7555. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7556. end;
  7557. { If it's not a register, it's a memory address }
  7558. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  7559. begin
  7560. { Even if the register is still in use, we can minimise the
  7561. pipeline stall by changing the MOV into another SETcc. }
  7562. taicpu(hp1).opcode := A_SETcc;
  7563. taicpu(hp1).condition := taicpu(p).condition;
  7564. if taicpu(hp1).oper[1]^.typ = top_ref then
  7565. begin
  7566. { Swapping the operand pointers like this is probably a
  7567. bit naughty, but it is far faster than using loadoper
  7568. to transfer the reference from oper[1] to oper[0] if
  7569. you take into account the extra procedure calls and
  7570. the memory allocation and deallocation required }
  7571. OperPtr := taicpu(hp1).oper[1];
  7572. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  7573. taicpu(hp1).oper[0] := OperPtr;
  7574. end
  7575. else
  7576. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  7577. taicpu(hp1).clearop(1);
  7578. taicpu(hp1).ops := 1;
  7579. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  7580. end
  7581. else
  7582. begin
  7583. if taicpu(hp1).oper[1]^.typ = top_reg then
  7584. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  7585. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  7586. RemoveInstruction(hp1);
  7587. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  7588. end
  7589. end;
  7590. Result := True;
  7591. end;
  7592. end;
  7593. end;
  7594. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  7595. var
  7596. hp1: tai;
  7597. Count: Integer;
  7598. OrigLabel: TAsmLabel;
  7599. begin
  7600. result := False;
  7601. { Sometimes, the optimisations below can permit this }
  7602. RemoveDeadCodeAfterJump(p);
  7603. 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
  7604. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  7605. begin
  7606. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  7607. { Also a side-effect of optimisations }
  7608. if CollapseZeroDistJump(p, OrigLabel) then
  7609. begin
  7610. Result := True;
  7611. Exit;
  7612. end;
  7613. hp1 := GetLabelWithSym(OrigLabel);
  7614. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  7615. begin
  7616. case taicpu(hp1).opcode of
  7617. A_RET:
  7618. {
  7619. change
  7620. jmp .L1
  7621. ...
  7622. .L1:
  7623. ret
  7624. into
  7625. ret
  7626. }
  7627. begin
  7628. ConvertJumpToRET(p, hp1);
  7629. result:=true;
  7630. end;
  7631. { Check any kind of direct assignment instruction }
  7632. A_MOV,
  7633. A_MOVD,
  7634. A_MOVQ,
  7635. A_MOVSX,
  7636. {$ifdef x86_64}
  7637. A_MOVSXD,
  7638. {$endif x86_64}
  7639. A_MOVZX,
  7640. A_MOVAPS,
  7641. A_MOVUPS,
  7642. A_MOVSD,
  7643. A_MOVAPD,
  7644. A_MOVUPD,
  7645. A_MOVDQA,
  7646. A_MOVDQU,
  7647. A_VMOVSS,
  7648. A_VMOVAPS,
  7649. A_VMOVUPS,
  7650. A_VMOVSD,
  7651. A_VMOVAPD,
  7652. A_VMOVUPD,
  7653. A_VMOVDQA,
  7654. A_VMOVDQU:
  7655. if ((current_settings.optimizerswitches * [cs_opt_level3, cs_opt_size]) <> [cs_opt_size]) and
  7656. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  7657. begin
  7658. Result := True;
  7659. Exit;
  7660. end;
  7661. else
  7662. ;
  7663. end;
  7664. end;
  7665. end;
  7666. end;
  7667. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  7668. begin
  7669. CanBeCMOV:=assigned(p) and
  7670. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  7671. { we can't use cmov ref,reg because
  7672. ref could be nil and cmov still throws an exception
  7673. if ref=nil but the mov isn't done (FK)
  7674. or ((taicpu(p).oper[0]^.typ = top_ref) and
  7675. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  7676. }
  7677. (taicpu(p).oper[1]^.typ = top_reg) and
  7678. (
  7679. (taicpu(p).oper[0]^.typ = top_reg) or
  7680. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  7681. it is not expected that this can cause a seg. violation }
  7682. (
  7683. (taicpu(p).oper[0]^.typ = top_ref) and
  7684. IsRefSafe(taicpu(p).oper[0]^.ref)
  7685. )
  7686. );
  7687. end;
  7688. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  7689. var
  7690. hp1,hp2: tai;
  7691. {$ifndef i8086}
  7692. hp3,hp4,hpmov2, hp5: tai;
  7693. l : Longint;
  7694. condition : TAsmCond;
  7695. {$endif i8086}
  7696. carryadd_opcode : TAsmOp;
  7697. symbol: TAsmSymbol;
  7698. reg: tsuperregister;
  7699. increg, tmpreg: TRegister;
  7700. begin
  7701. result:=false;
  7702. if GetNextInstruction(p,hp1) and (hp1.typ=ait_instruction) then
  7703. begin
  7704. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  7705. if (
  7706. (
  7707. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  7708. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  7709. (Taicpu(hp1).oper[0]^.val=1)
  7710. ) or
  7711. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  7712. ) and
  7713. GetNextInstruction(hp1,hp2) and
  7714. SkipAligns(hp2, hp2) and
  7715. (hp2.typ = ait_label) and
  7716. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  7717. { jb @@1 cmc
  7718. inc/dec operand --> adc/sbb operand,0
  7719. @@1:
  7720. ... and ...
  7721. jnb @@1
  7722. inc/dec operand --> adc/sbb operand,0
  7723. @@1: }
  7724. begin
  7725. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  7726. begin
  7727. case taicpu(hp1).opcode of
  7728. A_INC,
  7729. A_ADD:
  7730. carryadd_opcode:=A_ADC;
  7731. A_DEC,
  7732. A_SUB:
  7733. carryadd_opcode:=A_SBB;
  7734. else
  7735. InternalError(2021011001);
  7736. end;
  7737. Taicpu(p).clearop(0);
  7738. Taicpu(p).ops:=0;
  7739. Taicpu(p).is_jmp:=false;
  7740. Taicpu(p).opcode:=A_CMC;
  7741. Taicpu(p).condition:=C_NONE;
  7742. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  7743. Taicpu(hp1).ops:=2;
  7744. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  7745. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  7746. else
  7747. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  7748. Taicpu(hp1).loadconst(0,0);
  7749. Taicpu(hp1).opcode:=carryadd_opcode;
  7750. result:=true;
  7751. exit;
  7752. end
  7753. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  7754. begin
  7755. case taicpu(hp1).opcode of
  7756. A_INC,
  7757. A_ADD:
  7758. carryadd_opcode:=A_ADC;
  7759. A_DEC,
  7760. A_SUB:
  7761. carryadd_opcode:=A_SBB;
  7762. else
  7763. InternalError(2021011002);
  7764. end;
  7765. Taicpu(hp1).ops:=2;
  7766. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  7767. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  7768. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  7769. else
  7770. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  7771. Taicpu(hp1).loadconst(0,0);
  7772. Taicpu(hp1).opcode:=carryadd_opcode;
  7773. RemoveCurrentP(p, hp1);
  7774. result:=true;
  7775. exit;
  7776. end
  7777. {
  7778. jcc @@1 setcc tmpreg
  7779. inc/dec/add/sub operand -> (movzx tmpreg)
  7780. @@1: add/sub tmpreg,operand
  7781. While this increases code size slightly, it makes the code much faster if the
  7782. jump is unpredictable
  7783. }
  7784. else if not(cs_opt_size in current_settings.optimizerswitches) then
  7785. begin
  7786. { search for an available register which is volatile }
  7787. for reg in tcpuregisterset do
  7788. begin
  7789. if
  7790. {$if defined(i386) or defined(i8086)}
  7791. { Only use registers whose lowest 8-bits can Be accessed }
  7792. (reg in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) and
  7793. {$endif i386 or i8086}
  7794. (reg in paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption)) and
  7795. not(reg in UsedRegs[R_INTREGISTER].GetUsedRegs)
  7796. { We don't need to check if tmpreg is in hp1 or not, because
  7797. it will be marked as in use at p (if not, this is
  7798. indictive of a compiler bug). }
  7799. then
  7800. begin
  7801. TAsmLabel(symbol).decrefs;
  7802. increg := newreg(R_INTREGISTER,reg,R_SUBL);
  7803. Taicpu(p).clearop(0);
  7804. Taicpu(p).ops:=1;
  7805. Taicpu(p).is_jmp:=false;
  7806. Taicpu(p).opcode:=A_SETcc;
  7807. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  7808. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  7809. Taicpu(p).loadreg(0,increg);
  7810. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  7811. begin
  7812. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  7813. R_SUBW:
  7814. begin
  7815. tmpreg := newreg(R_INTREGISTER,reg,R_SUBW);
  7816. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  7817. end;
  7818. R_SUBD:
  7819. begin
  7820. tmpreg := newreg(R_INTREGISTER,reg,R_SUBD);
  7821. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  7822. end;
  7823. {$ifdef x86_64}
  7824. R_SUBQ:
  7825. begin
  7826. { MOVZX doesn't have a 64-bit variant, because
  7827. the 32-bit version implicitly zeroes the
  7828. upper 32-bits of the destination register }
  7829. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,
  7830. newreg(R_INTREGISTER,reg,R_SUBD));
  7831. tmpreg := newreg(R_INTREGISTER,reg,R_SUBQ);
  7832. end;
  7833. {$endif x86_64}
  7834. else
  7835. Internalerror(2020030601);
  7836. end;
  7837. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  7838. asml.InsertAfter(hp2,p);
  7839. end
  7840. else
  7841. tmpreg := increg;
  7842. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  7843. begin
  7844. Taicpu(hp1).ops:=2;
  7845. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  7846. end;
  7847. Taicpu(hp1).loadreg(0,tmpreg);
  7848. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  7849. Result := True;
  7850. { p is no longer a Jcc instruction, so exit }
  7851. Exit;
  7852. end;
  7853. end;
  7854. end;
  7855. end;
  7856. { Detect the following:
  7857. jmp<cond> @Lbl1
  7858. jmp @Lbl2
  7859. ...
  7860. @Lbl1:
  7861. ret
  7862. Change to:
  7863. jmp<inv_cond> @Lbl2
  7864. ret
  7865. }
  7866. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  7867. begin
  7868. hp2:=getlabelwithsym(TAsmLabel(symbol));
  7869. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  7870. MatchInstruction(hp2,A_RET,[S_NO]) then
  7871. begin
  7872. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7873. { Change label address to that of the unconditional jump }
  7874. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  7875. TAsmLabel(symbol).DecRefs;
  7876. taicpu(hp1).opcode := A_RET;
  7877. taicpu(hp1).is_jmp := false;
  7878. taicpu(hp1).ops := taicpu(hp2).ops;
  7879. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  7880. case taicpu(hp2).ops of
  7881. 0:
  7882. taicpu(hp1).clearop(0);
  7883. 1:
  7884. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  7885. else
  7886. internalerror(2016041302);
  7887. end;
  7888. end;
  7889. {$ifndef i8086}
  7890. end
  7891. {
  7892. convert
  7893. j<c> .L1
  7894. mov 1,reg
  7895. jmp .L2
  7896. .L1
  7897. mov 0,reg
  7898. .L2
  7899. into
  7900. mov 0,reg
  7901. set<not(c)> reg
  7902. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7903. would destroy the flag contents
  7904. }
  7905. else if MatchInstruction(hp1,A_MOV,[]) and
  7906. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7907. {$ifdef i386}
  7908. (
  7909. { Under i386, ESI, EDI, EBP and ESP
  7910. don't have an 8-bit representation }
  7911. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7912. ) and
  7913. {$endif i386}
  7914. (taicpu(hp1).oper[0]^.val=1) and
  7915. GetNextInstruction(hp1,hp2) and
  7916. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7917. GetNextInstruction(hp2,hp3) and
  7918. { skip align }
  7919. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  7920. (hp3.typ=ait_label) and
  7921. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7922. (tai_label(hp3).labsym.getrefs=1) and
  7923. GetNextInstruction(hp3,hp4) and
  7924. MatchInstruction(hp4,A_MOV,[]) and
  7925. MatchOpType(taicpu(hp4),top_const,top_reg) and
  7926. (taicpu(hp4).oper[0]^.val=0) and
  7927. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7928. GetNextInstruction(hp4,hp5) and
  7929. (hp5.typ=ait_label) and
  7930. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  7931. (tai_label(hp5).labsym.getrefs=1) then
  7932. begin
  7933. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  7934. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  7935. { remove last label }
  7936. RemoveInstruction(hp5);
  7937. { remove second label }
  7938. RemoveInstruction(hp3);
  7939. { if align is present remove it }
  7940. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  7941. RemoveInstruction(hp3);
  7942. { remove jmp }
  7943. RemoveInstruction(hp2);
  7944. if taicpu(hp1).opsize=S_B then
  7945. RemoveInstruction(hp1)
  7946. else
  7947. taicpu(hp1).loadconst(0,0);
  7948. taicpu(hp4).opcode:=A_SETcc;
  7949. taicpu(hp4).opsize:=S_B;
  7950. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  7951. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  7952. taicpu(hp4).opercnt:=1;
  7953. taicpu(hp4).ops:=1;
  7954. taicpu(hp4).freeop(1);
  7955. RemoveCurrentP(p);
  7956. Result:=true;
  7957. exit;
  7958. end
  7959. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  7960. begin
  7961. { check for
  7962. jCC xxx
  7963. <several movs>
  7964. xxx:
  7965. }
  7966. l:=0;
  7967. while assigned(hp1) and
  7968. CanBeCMOV(hp1) and
  7969. { stop on labels }
  7970. not(hp1.typ=ait_label) do
  7971. begin
  7972. inc(l);
  7973. GetNextInstruction(hp1,hp1);
  7974. end;
  7975. if assigned(hp1) then
  7976. begin
  7977. if FindLabel(tasmlabel(symbol),hp1) then
  7978. begin
  7979. if (l<=4) and (l>0) then
  7980. begin
  7981. condition:=inverse_cond(taicpu(p).condition);
  7982. GetNextInstruction(p,hp1);
  7983. repeat
  7984. if not Assigned(hp1) then
  7985. InternalError(2018062900);
  7986. taicpu(hp1).opcode:=A_CMOVcc;
  7987. taicpu(hp1).condition:=condition;
  7988. UpdateUsedRegs(hp1);
  7989. GetNextInstruction(hp1,hp1);
  7990. until not(CanBeCMOV(hp1));
  7991. { Remember what hp1 is in case there's multiple aligns to get rid of }
  7992. hp2 := hp1;
  7993. repeat
  7994. if not Assigned(hp2) then
  7995. InternalError(2018062910);
  7996. case hp2.typ of
  7997. ait_label:
  7998. { What we expected - break out of the loop (it won't be a dead label at the top of
  7999. a cluster because that was optimised at an earlier stage) }
  8000. Break;
  8001. ait_align:
  8002. { Go to the next entry until a label is found (may be multiple aligns before it) }
  8003. begin
  8004. hp2 := tai(hp2.Next);
  8005. Continue;
  8006. end;
  8007. else
  8008. begin
  8009. { Might be a comment or temporary allocation entry }
  8010. if not (hp2.typ in SkipInstr) then
  8011. InternalError(2018062911);
  8012. hp2 := tai(hp2.Next);
  8013. Continue;
  8014. end;
  8015. end;
  8016. until False;
  8017. { Now we can safely decrement the reference count }
  8018. tasmlabel(symbol).decrefs;
  8019. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  8020. { Remove the original jump }
  8021. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  8022. GetNextInstruction(hp2, p); { Instruction after the label }
  8023. { Remove the label if this is its final reference }
  8024. if (tasmlabel(symbol).getrefs=0) then
  8025. StripLabelFast(hp1);
  8026. if Assigned(p) then
  8027. begin
  8028. UpdateUsedRegs(p);
  8029. result:=true;
  8030. end;
  8031. exit;
  8032. end;
  8033. end
  8034. else
  8035. begin
  8036. { check further for
  8037. jCC xxx
  8038. <several movs 1>
  8039. jmp yyy
  8040. xxx:
  8041. <several movs 2>
  8042. yyy:
  8043. }
  8044. { hp2 points to jmp yyy }
  8045. hp2:=hp1;
  8046. { skip hp1 to xxx (or an align right before it) }
  8047. GetNextInstruction(hp1, hp1);
  8048. if assigned(hp2) and
  8049. assigned(hp1) and
  8050. (l<=3) and
  8051. (hp2.typ=ait_instruction) and
  8052. (taicpu(hp2).is_jmp) and
  8053. (taicpu(hp2).condition=C_None) and
  8054. { real label and jump, no further references to the
  8055. label are allowed }
  8056. (tasmlabel(symbol).getrefs=1) and
  8057. FindLabel(tasmlabel(symbol),hp1) then
  8058. begin
  8059. l:=0;
  8060. { skip hp1 to <several moves 2> }
  8061. if (hp1.typ = ait_align) then
  8062. GetNextInstruction(hp1, hp1);
  8063. GetNextInstruction(hp1, hpmov2);
  8064. hp1 := hpmov2;
  8065. while assigned(hp1) and
  8066. CanBeCMOV(hp1) do
  8067. begin
  8068. inc(l);
  8069. GetNextInstruction(hp1, hp1);
  8070. end;
  8071. { hp1 points to yyy (or an align right before it) }
  8072. hp3 := hp1;
  8073. if assigned(hp1) and
  8074. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  8075. begin
  8076. condition:=inverse_cond(taicpu(p).condition);
  8077. GetNextInstruction(p,hp1);
  8078. repeat
  8079. taicpu(hp1).opcode:=A_CMOVcc;
  8080. taicpu(hp1).condition:=condition;
  8081. UpdateUsedRegs(hp1);
  8082. GetNextInstruction(hp1,hp1);
  8083. until not(assigned(hp1)) or
  8084. not(CanBeCMOV(hp1));
  8085. condition:=inverse_cond(condition);
  8086. hp1 := hpmov2;
  8087. { hp1 is now at <several movs 2> }
  8088. while Assigned(hp1) and CanBeCMOV(hp1) do
  8089. begin
  8090. taicpu(hp1).opcode:=A_CMOVcc;
  8091. taicpu(hp1).condition:=condition;
  8092. UpdateUsedRegs(hp1);
  8093. GetNextInstruction(hp1,hp1);
  8094. end;
  8095. hp1 := p;
  8096. { Get first instruction after label }
  8097. GetNextInstruction(hp3, p);
  8098. if assigned(p) and (hp3.typ = ait_align) then
  8099. GetNextInstruction(p, p);
  8100. { Don't dereference yet, as doing so will cause
  8101. GetNextInstruction to skip the label and
  8102. optional align marker. [Kit] }
  8103. GetNextInstruction(hp2, hp4);
  8104. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  8105. { remove jCC }
  8106. RemoveInstruction(hp1);
  8107. { Now we can safely decrement it }
  8108. tasmlabel(symbol).decrefs;
  8109. { Remove label xxx (it will have a ref of zero due to the initial check }
  8110. StripLabelFast(hp4);
  8111. { remove jmp }
  8112. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  8113. RemoveInstruction(hp2);
  8114. { As before, now we can safely decrement it }
  8115. tasmlabel(symbol).decrefs;
  8116. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  8117. if tasmlabel(symbol).getrefs = 0 then
  8118. StripLabelFast(hp3);
  8119. if Assigned(p) then
  8120. begin
  8121. UpdateUsedRegs(p);
  8122. result:=true;
  8123. end;
  8124. exit;
  8125. end;
  8126. end;
  8127. end;
  8128. end;
  8129. {$endif i8086}
  8130. end;
  8131. end;
  8132. end;
  8133. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  8134. var
  8135. hp1,hp2: tai;
  8136. reg_and_hp1_is_instr: Boolean;
  8137. begin
  8138. result:=false;
  8139. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  8140. GetNextInstruction(p,hp1) and
  8141. (hp1.typ = ait_instruction);
  8142. if reg_and_hp1_is_instr and
  8143. (
  8144. (taicpu(hp1).opcode <> A_LEA) or
  8145. { If the LEA instruction can be converted into an arithmetic instruction,
  8146. it may be possible to then fold it. }
  8147. (
  8148. { If the flags register is in use, don't change the instruction
  8149. to an ADD otherwise this will scramble the flags. [Kit] }
  8150. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  8151. ConvertLEA(taicpu(hp1))
  8152. )
  8153. ) and
  8154. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  8155. GetNextInstruction(hp1,hp2) and
  8156. MatchInstruction(hp2,A_MOV,[]) and
  8157. (taicpu(hp2).oper[0]^.typ = top_reg) and
  8158. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  8159. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  8160. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  8161. {$ifdef i386}
  8162. { not all registers have byte size sub registers on i386 }
  8163. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  8164. {$endif i386}
  8165. (((taicpu(hp1).ops=2) and
  8166. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  8167. ((taicpu(hp1).ops=1) and
  8168. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  8169. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  8170. begin
  8171. { change movsX/movzX reg/ref, reg2
  8172. add/sub/or/... reg3/$const, reg2
  8173. mov reg2 reg/ref
  8174. to add/sub/or/... reg3/$const, reg/ref }
  8175. { by example:
  8176. movswl %si,%eax movswl %si,%eax p
  8177. decl %eax addl %edx,%eax hp1
  8178. movw %ax,%si movw %ax,%si hp2
  8179. ->
  8180. movswl %si,%eax movswl %si,%eax p
  8181. decw %eax addw %edx,%eax hp1
  8182. movw %ax,%si movw %ax,%si hp2
  8183. }
  8184. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  8185. {
  8186. ->
  8187. movswl %si,%eax movswl %si,%eax p
  8188. decw %si addw %dx,%si hp1
  8189. movw %ax,%si movw %ax,%si hp2
  8190. }
  8191. case taicpu(hp1).ops of
  8192. 1:
  8193. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  8194. 2:
  8195. begin
  8196. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  8197. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8198. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  8199. end;
  8200. else
  8201. internalerror(2008042702);
  8202. end;
  8203. {
  8204. ->
  8205. decw %si addw %dx,%si p
  8206. }
  8207. DebugMsg(SPeepholeOptimization + 'var3',p);
  8208. RemoveCurrentP(p, hp1);
  8209. RemoveInstruction(hp2);
  8210. end
  8211. else if reg_and_hp1_is_instr and
  8212. (taicpu(hp1).opcode = A_MOV) and
  8213. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8214. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  8215. {$ifdef x86_64}
  8216. { check for implicit extension to 64 bit }
  8217. or
  8218. ((taicpu(p).opsize in [S_BL,S_WL]) and
  8219. (taicpu(hp1).opsize=S_Q) and
  8220. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  8221. )
  8222. {$endif x86_64}
  8223. )
  8224. then
  8225. begin
  8226. { change
  8227. movx %reg1,%reg2
  8228. mov %reg2,%reg3
  8229. dealloc %reg2
  8230. into
  8231. movx %reg,%reg3
  8232. }
  8233. TransferUsedRegs(TmpUsedRegs);
  8234. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8235. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  8236. begin
  8237. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  8238. {$ifdef x86_64}
  8239. if (taicpu(p).opsize in [S_BL,S_WL]) and
  8240. (taicpu(hp1).opsize=S_Q) then
  8241. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  8242. else
  8243. {$endif x86_64}
  8244. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  8245. RemoveInstruction(hp1);
  8246. end;
  8247. end
  8248. else if reg_and_hp1_is_instr and
  8249. ((taicpu(hp1).opcode=A_MOV) or
  8250. (taicpu(hp1).opcode=A_ADD) or
  8251. (taicpu(hp1).opcode=A_SUB) or
  8252. (taicpu(hp1).opcode=A_CMP) or
  8253. (taicpu(hp1).opcode=A_OR) or
  8254. (taicpu(hp1).opcode=A_XOR) or
  8255. (taicpu(hp1).opcode=A_AND)
  8256. ) and
  8257. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8258. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  8259. (taicpu(hp1).opsize=S_B)) or
  8260. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  8261. (taicpu(hp1).opsize=S_W))
  8262. {$ifdef x86_64}
  8263. or ((taicpu(p).opsize=S_LQ) and
  8264. (taicpu(hp1).opsize=S_L))
  8265. {$endif x86_64}
  8266. ) and
  8267. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  8268. begin
  8269. { change
  8270. movx %reg1,%reg2
  8271. mov %reg2,%reg3
  8272. dealloc %reg2
  8273. into
  8274. mov %reg1,%reg3
  8275. if the second mov accesses only the bits stored in reg1
  8276. }
  8277. TransferUsedRegs(TmpUsedRegs);
  8278. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8279. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  8280. begin
  8281. DebugMsg(SPeepholeOptimization + 'MovxOp2Op',p);
  8282. if taicpu(p).oper[0]^.typ=top_reg then
  8283. begin
  8284. case taicpu(hp1).opsize of
  8285. S_B:
  8286. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  8287. S_W:
  8288. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  8289. S_L:
  8290. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  8291. else
  8292. Internalerror(2020102301);
  8293. end;
  8294. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  8295. end
  8296. else
  8297. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  8298. RemoveCurrentP(p);
  8299. result:=true;
  8300. exit;
  8301. end;
  8302. end
  8303. else if reg_and_hp1_is_instr and
  8304. (taicpu(p).oper[0]^.typ = top_reg) and
  8305. (
  8306. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  8307. ) and
  8308. (taicpu(hp1).oper[0]^.typ = top_const) and
  8309. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  8310. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  8311. { Minimum shift value allowed is the bit difference between the sizes }
  8312. (taicpu(hp1).oper[0]^.val >=
  8313. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  8314. 8 * (
  8315. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  8316. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  8317. )
  8318. ) then
  8319. begin
  8320. { For:
  8321. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  8322. shl/sal ##, %reg1
  8323. Remove the movsx/movzx instruction if the shift overwrites the
  8324. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  8325. }
  8326. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  8327. RemoveCurrentP(p, hp1);
  8328. Result := True;
  8329. Exit;
  8330. end
  8331. else if reg_and_hp1_is_instr and
  8332. (taicpu(p).oper[0]^.typ = top_reg) and
  8333. (
  8334. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  8335. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  8336. ) and
  8337. (taicpu(hp1).oper[0]^.typ = top_const) and
  8338. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  8339. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  8340. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  8341. (taicpu(hp1).oper[0]^.val <
  8342. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  8343. 8 * (
  8344. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  8345. )
  8346. ) then
  8347. begin
  8348. { For:
  8349. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  8350. sar ##, %reg1 shr ##, %reg1
  8351. Move the shift to before the movx instruction if the shift value
  8352. is not too large.
  8353. }
  8354. asml.Remove(hp1);
  8355. asml.InsertBefore(hp1, p);
  8356. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  8357. case taicpu(p).opsize of
  8358. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  8359. taicpu(hp1).opsize := S_B;
  8360. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  8361. taicpu(hp1).opsize := S_W;
  8362. {$ifdef x86_64}
  8363. S_LQ:
  8364. taicpu(hp1).opsize := S_L;
  8365. {$endif}
  8366. else
  8367. InternalError(2020112401);
  8368. end;
  8369. if (taicpu(hp1).opcode = A_SHR) then
  8370. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  8371. else
  8372. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  8373. Result := True;
  8374. end
  8375. else if taicpu(p).opcode=A_MOVZX then
  8376. begin
  8377. { removes superfluous And's after movzx's }
  8378. if reg_and_hp1_is_instr and
  8379. (taicpu(hp1).opcode = A_AND) and
  8380. MatchOpType(taicpu(hp1),top_const,top_reg) and
  8381. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  8382. {$ifdef x86_64}
  8383. { check for implicit extension to 64 bit }
  8384. or
  8385. ((taicpu(p).opsize in [S_BL,S_WL]) and
  8386. (taicpu(hp1).opsize=S_Q) and
  8387. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  8388. )
  8389. {$endif x86_64}
  8390. )
  8391. then
  8392. begin
  8393. case taicpu(p).opsize Of
  8394. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8395. if (taicpu(hp1).oper[0]^.val = $ff) then
  8396. begin
  8397. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  8398. RemoveInstruction(hp1);
  8399. Result:=true;
  8400. exit;
  8401. end;
  8402. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8403. if (taicpu(hp1).oper[0]^.val = $ffff) then
  8404. begin
  8405. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  8406. RemoveInstruction(hp1);
  8407. Result:=true;
  8408. exit;
  8409. end;
  8410. {$ifdef x86_64}
  8411. S_LQ:
  8412. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  8413. begin
  8414. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  8415. RemoveInstruction(hp1);
  8416. Result:=true;
  8417. exit;
  8418. end;
  8419. {$endif x86_64}
  8420. else
  8421. ;
  8422. end;
  8423. { we cannot get rid of the and, but can we get rid of the movz ?}
  8424. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  8425. begin
  8426. case taicpu(p).opsize Of
  8427. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8428. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  8429. begin
  8430. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  8431. RemoveCurrentP(p,hp1);
  8432. Result:=true;
  8433. exit;
  8434. end;
  8435. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8436. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  8437. begin
  8438. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  8439. RemoveCurrentP(p,hp1);
  8440. Result:=true;
  8441. exit;
  8442. end;
  8443. {$ifdef x86_64}
  8444. S_LQ:
  8445. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  8446. begin
  8447. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  8448. RemoveCurrentP(p,hp1);
  8449. Result:=true;
  8450. exit;
  8451. end;
  8452. {$endif x86_64}
  8453. else
  8454. ;
  8455. end;
  8456. end;
  8457. end;
  8458. { changes some movzx constructs to faster synonyms (all examples
  8459. are given with eax/ax, but are also valid for other registers)}
  8460. if MatchOpType(taicpu(p),top_reg,top_reg) then
  8461. begin
  8462. case taicpu(p).opsize of
  8463. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  8464. (the machine code is equivalent to movzbl %al,%eax), but the
  8465. code generator still generates that assembler instruction and
  8466. it is silently converted. This should probably be checked.
  8467. [Kit] }
  8468. S_BW:
  8469. begin
  8470. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  8471. (
  8472. not IsMOVZXAcceptable
  8473. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  8474. or (
  8475. (cs_opt_size in current_settings.optimizerswitches) and
  8476. (taicpu(p).oper[1]^.reg = NR_AX)
  8477. )
  8478. ) then
  8479. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  8480. begin
  8481. DebugMsg(SPeepholeOptimization + 'var7',p);
  8482. taicpu(p).opcode := A_AND;
  8483. taicpu(p).changeopsize(S_W);
  8484. taicpu(p).loadConst(0,$ff);
  8485. Result := True;
  8486. end
  8487. else if not IsMOVZXAcceptable and
  8488. GetNextInstruction(p, hp1) and
  8489. (tai(hp1).typ = ait_instruction) and
  8490. (taicpu(hp1).opcode = A_AND) and
  8491. MatchOpType(taicpu(hp1),top_const,top_reg) and
  8492. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8493. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  8494. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  8495. begin
  8496. DebugMsg(SPeepholeOptimization + 'var8',p);
  8497. taicpu(p).opcode := A_MOV;
  8498. taicpu(p).changeopsize(S_W);
  8499. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  8500. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  8501. Result := True;
  8502. end;
  8503. end;
  8504. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  8505. S_BL:
  8506. begin
  8507. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  8508. (
  8509. not IsMOVZXAcceptable
  8510. { and $0xff,%eax has a smaller encoding but risks a partial write penalty }
  8511. or (
  8512. (cs_opt_size in current_settings.optimizerswitches) and
  8513. (taicpu(p).oper[1]^.reg = NR_EAX)
  8514. )
  8515. ) then
  8516. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  8517. begin
  8518. DebugMsg(SPeepholeOptimization + 'var9',p);
  8519. taicpu(p).opcode := A_AND;
  8520. taicpu(p).changeopsize(S_L);
  8521. taicpu(p).loadConst(0,$ff);
  8522. Result := True;
  8523. end
  8524. else if not IsMOVZXAcceptable and
  8525. GetNextInstruction(p, hp1) and
  8526. (tai(hp1).typ = ait_instruction) and
  8527. (taicpu(hp1).opcode = A_AND) and
  8528. MatchOpType(taicpu(hp1),top_const,top_reg) and
  8529. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8530. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  8531. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  8532. begin
  8533. DebugMsg(SPeepholeOptimization + 'var10',p);
  8534. taicpu(p).opcode := A_MOV;
  8535. taicpu(p).changeopsize(S_L);
  8536. { do not use R_SUBWHOLE
  8537. as movl %rdx,%eax
  8538. is invalid in assembler PM }
  8539. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  8540. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  8541. Result := True;
  8542. end;
  8543. end;
  8544. {$endif i8086}
  8545. S_WL:
  8546. if not IsMOVZXAcceptable then
  8547. begin
  8548. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  8549. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  8550. begin
  8551. DebugMsg(SPeepholeOptimization + 'var11',p);
  8552. taicpu(p).opcode := A_AND;
  8553. taicpu(p).changeopsize(S_L);
  8554. taicpu(p).loadConst(0,$ffff);
  8555. Result := True;
  8556. end
  8557. else if GetNextInstruction(p, hp1) and
  8558. (tai(hp1).typ = ait_instruction) and
  8559. (taicpu(hp1).opcode = A_AND) and
  8560. (taicpu(hp1).oper[0]^.typ = top_const) and
  8561. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8562. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8563. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  8564. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  8565. begin
  8566. DebugMsg(SPeepholeOptimization + 'var12',p);
  8567. taicpu(p).opcode := A_MOV;
  8568. taicpu(p).changeopsize(S_L);
  8569. { do not use R_SUBWHOLE
  8570. as movl %rdx,%eax
  8571. is invalid in assembler PM }
  8572. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  8573. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  8574. Result := True;
  8575. end;
  8576. end;
  8577. else
  8578. InternalError(2017050705);
  8579. end;
  8580. end
  8581. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  8582. begin
  8583. if GetNextInstruction(p, hp1) and
  8584. (tai(hp1).typ = ait_instruction) and
  8585. (taicpu(hp1).opcode = A_AND) and
  8586. MatchOpType(taicpu(hp1),top_const,top_reg) and
  8587. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8588. begin
  8589. //taicpu(p).opcode := A_MOV;
  8590. case taicpu(p).opsize Of
  8591. S_BL:
  8592. begin
  8593. DebugMsg(SPeepholeOptimization + 'var13',p);
  8594. taicpu(hp1).changeopsize(S_L);
  8595. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  8596. end;
  8597. S_WL:
  8598. begin
  8599. DebugMsg(SPeepholeOptimization + 'var14',p);
  8600. taicpu(hp1).changeopsize(S_L);
  8601. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  8602. end;
  8603. S_BW:
  8604. begin
  8605. DebugMsg(SPeepholeOptimization + 'var15',p);
  8606. taicpu(hp1).changeopsize(S_W);
  8607. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  8608. end;
  8609. else
  8610. Internalerror(2017050704)
  8611. end;
  8612. Result := True;
  8613. end;
  8614. end;
  8615. end;
  8616. end;
  8617. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  8618. var
  8619. hp1, hp2 : tai;
  8620. MaskLength : Cardinal;
  8621. MaskedBits : TCgInt;
  8622. begin
  8623. Result:=false;
  8624. { There are no optimisations for reference targets }
  8625. if (taicpu(p).oper[1]^.typ <> top_reg) then
  8626. Exit;
  8627. while GetNextInstruction(p, hp1) and
  8628. (hp1.typ = ait_instruction) do
  8629. begin
  8630. if (taicpu(p).oper[0]^.typ = top_const) then
  8631. begin
  8632. case taicpu(hp1).opcode of
  8633. A_AND:
  8634. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  8635. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8636. { the second register must contain the first one, so compare their subreg types }
  8637. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  8638. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  8639. { change
  8640. and const1, reg
  8641. and const2, reg
  8642. to
  8643. and (const1 and const2), reg
  8644. }
  8645. begin
  8646. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  8647. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  8648. RemoveCurrentP(p, hp1);
  8649. Result:=true;
  8650. exit;
  8651. end;
  8652. A_CMP:
  8653. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  8654. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  8655. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  8656. { Just check that the condition on the next instruction is compatible }
  8657. GetNextInstruction(hp1, hp2) and
  8658. (hp2.typ = ait_instruction) and
  8659. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  8660. then
  8661. { change
  8662. and 2^n, reg
  8663. cmp 2^n, reg
  8664. j(c) / set(c) / cmov(c) (c is equal or not equal)
  8665. to
  8666. and 2^n, reg
  8667. test reg, reg
  8668. j(~c) / set(~c) / cmov(~c)
  8669. }
  8670. begin
  8671. { Keep TEST instruction in, rather than remove it, because
  8672. it may trigger other optimisations such as MovAndTest2Test }
  8673. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  8674. taicpu(hp1).opcode := A_TEST;
  8675. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  8676. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  8677. Result := True;
  8678. Exit;
  8679. end;
  8680. A_MOVZX:
  8681. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8682. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  8683. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8684. (
  8685. (
  8686. (taicpu(p).opsize=S_W) and
  8687. (taicpu(hp1).opsize=S_BW)
  8688. ) or
  8689. (
  8690. (taicpu(p).opsize=S_L) and
  8691. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  8692. )
  8693. {$ifdef x86_64}
  8694. or
  8695. (
  8696. (taicpu(p).opsize=S_Q) and
  8697. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  8698. )
  8699. {$endif x86_64}
  8700. ) then
  8701. begin
  8702. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  8703. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  8704. ) or
  8705. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  8706. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  8707. then
  8708. begin
  8709. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  8710. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  8711. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  8712. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  8713. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  8714. }
  8715. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  8716. RemoveInstruction(hp1);
  8717. { See if there are other optimisations possible }
  8718. Continue;
  8719. end;
  8720. end;
  8721. A_SHL:
  8722. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  8723. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  8724. begin
  8725. {$ifopt R+}
  8726. {$define RANGE_WAS_ON}
  8727. {$R-}
  8728. {$endif}
  8729. { get length of potential and mask }
  8730. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  8731. { really a mask? }
  8732. {$ifdef RANGE_WAS_ON}
  8733. {$R+}
  8734. {$endif}
  8735. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  8736. { unmasked part shifted out? }
  8737. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  8738. begin
  8739. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  8740. RemoveCurrentP(p, hp1);
  8741. Result:=true;
  8742. exit;
  8743. end;
  8744. end;
  8745. A_SHR:
  8746. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  8747. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  8748. (taicpu(hp1).oper[0]^.val <= 63) then
  8749. begin
  8750. { Does SHR combined with the AND cover all the bits?
  8751. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  8752. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  8753. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  8754. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  8755. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  8756. begin
  8757. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  8758. RemoveCurrentP(p, hp1);
  8759. Result := True;
  8760. Exit;
  8761. end;
  8762. end;
  8763. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  8764. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  8765. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  8766. begin
  8767. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  8768. (
  8769. (
  8770. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  8771. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  8772. ) or (
  8773. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  8774. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  8775. {$ifdef x86_64}
  8776. ) or (
  8777. (taicpu(hp1).opsize = S_LQ) and
  8778. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  8779. {$endif x86_64}
  8780. )
  8781. ) then
  8782. begin
  8783. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  8784. begin
  8785. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  8786. RemoveInstruction(hp1);
  8787. { See if there are other optimisations possible }
  8788. Continue;
  8789. end;
  8790. { The super-registers are the same though.
  8791. Note that this change by itself doesn't improve
  8792. code speed, but it opens up other optimisations. }
  8793. {$ifdef x86_64}
  8794. { Convert 64-bit register to 32-bit }
  8795. case taicpu(hp1).opsize of
  8796. S_BQ:
  8797. begin
  8798. taicpu(hp1).opsize := S_BL;
  8799. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  8800. end;
  8801. S_WQ:
  8802. begin
  8803. taicpu(hp1).opsize := S_WL;
  8804. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  8805. end
  8806. else
  8807. ;
  8808. end;
  8809. {$endif x86_64}
  8810. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  8811. taicpu(hp1).opcode := A_MOVZX;
  8812. { See if there are other optimisations possible }
  8813. Continue;
  8814. end;
  8815. end;
  8816. else
  8817. ;
  8818. end;
  8819. end;
  8820. if (taicpu(hp1).is_jmp) and
  8821. (taicpu(hp1).opcode<>A_JMP) and
  8822. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  8823. begin
  8824. { change
  8825. and x, reg
  8826. jxx
  8827. to
  8828. test x, reg
  8829. jxx
  8830. if reg is deallocated before the
  8831. jump, but only if it's a conditional jump (PFV)
  8832. }
  8833. taicpu(p).opcode := A_TEST;
  8834. Exit;
  8835. end;
  8836. Break;
  8837. end;
  8838. { Lone AND tests }
  8839. if (taicpu(p).oper[0]^.typ = top_const) then
  8840. begin
  8841. {
  8842. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  8843. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  8844. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  8845. }
  8846. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  8847. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  8848. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  8849. begin
  8850. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  8851. if taicpu(p).opsize = S_L then
  8852. begin
  8853. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  8854. Result := True;
  8855. end;
  8856. end;
  8857. end;
  8858. { Backward check to determine necessity of and %reg,%reg }
  8859. if (taicpu(p).oper[0]^.typ = top_reg) and
  8860. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  8861. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  8862. GetLastInstruction(p, hp2) and
  8863. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  8864. { Check size of adjacent instruction to determine if the AND is
  8865. effectively a null operation }
  8866. (
  8867. (taicpu(p).opsize = taicpu(hp2).opsize) or
  8868. { Note: Don't include S_Q }
  8869. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  8870. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  8871. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  8872. ) then
  8873. begin
  8874. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  8875. { If GetNextInstruction returned False, hp1 will be nil }
  8876. RemoveCurrentP(p, hp1);
  8877. Result := True;
  8878. Exit;
  8879. end;
  8880. end;
  8881. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  8882. var
  8883. hp1: tai; NewRef: TReference;
  8884. { This entire nested function is used in an if-statement below, but we
  8885. want to avoid all the used reg transfers and GetNextInstruction calls
  8886. until we really have to check }
  8887. function MemRegisterNotUsedLater: Boolean; inline;
  8888. var
  8889. hp2: tai;
  8890. begin
  8891. TransferUsedRegs(TmpUsedRegs);
  8892. hp2 := p;
  8893. repeat
  8894. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8895. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  8896. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  8897. end;
  8898. begin
  8899. Result := False;
  8900. if not GetNextInstruction(p, hp1) or (hp1.typ <> ait_instruction) then
  8901. Exit;
  8902. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) then
  8903. begin
  8904. { Change:
  8905. add %reg2,%reg1
  8906. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  8907. To:
  8908. mov/s/z #(%reg1,%reg2),%reg1
  8909. }
  8910. if MatchOpType(taicpu(p), top_reg, top_reg) and
  8911. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  8912. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  8913. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  8914. (
  8915. (
  8916. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  8917. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  8918. { r/esp cannot be an index }
  8919. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  8920. ) or (
  8921. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  8922. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  8923. )
  8924. ) and (
  8925. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  8926. (
  8927. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  8928. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  8929. MemRegisterNotUsedLater
  8930. )
  8931. ) then
  8932. begin
  8933. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  8934. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  8935. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  8936. RemoveCurrentp(p, hp1);
  8937. Result := True;
  8938. Exit;
  8939. end;
  8940. { Change:
  8941. addl/q $x,%reg1
  8942. movl/q %reg1,%reg2
  8943. To:
  8944. leal/q $x(%reg1),%reg2
  8945. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  8946. Breaks the dependency chain.
  8947. }
  8948. if MatchOpType(taicpu(p),top_const,top_reg) and
  8949. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  8950. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8951. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  8952. (
  8953. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  8954. not (cs_opt_size in current_settings.optimizerswitches) or
  8955. (
  8956. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  8957. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  8958. )
  8959. ) then
  8960. begin
  8961. { Change the MOV instruction to a LEA instruction, and update the
  8962. first operand }
  8963. reference_reset(NewRef, 1, []);
  8964. NewRef.base := taicpu(p).oper[1]^.reg;
  8965. NewRef.scalefactor := 1;
  8966. NewRef.offset := taicpu(p).oper[0]^.val;
  8967. taicpu(hp1).opcode := A_LEA;
  8968. taicpu(hp1).loadref(0, NewRef);
  8969. TransferUsedRegs(TmpUsedRegs);
  8970. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8971. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  8972. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  8973. begin
  8974. { Move what is now the LEA instruction to before the SUB instruction }
  8975. Asml.Remove(hp1);
  8976. Asml.InsertBefore(hp1, p);
  8977. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  8978. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  8979. p := hp1;
  8980. end
  8981. else
  8982. begin
  8983. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  8984. RemoveCurrentP(p, hp1);
  8985. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', p);
  8986. end;
  8987. Result := True;
  8988. end;
  8989. end;
  8990. end;
  8991. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  8992. begin
  8993. Result:=false;
  8994. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  8995. begin
  8996. if MatchReference(taicpu(p).oper[0]^.ref^,taicpu(p).oper[1]^.reg,NR_INVALID) and
  8997. (taicpu(p).oper[0]^.ref^.index<>NR_NO) then
  8998. begin
  8999. taicpu(p).loadreg(1,taicpu(p).oper[0]^.ref^.base);
  9000. taicpu(p).loadreg(0,taicpu(p).oper[0]^.ref^.index);
  9001. taicpu(p).opcode:=A_ADD;
  9002. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  9003. result:=true;
  9004. end
  9005. else if MatchReference(taicpu(p).oper[0]^.ref^,NR_INVALID,taicpu(p).oper[1]^.reg) and
  9006. (taicpu(p).oper[0]^.ref^.base<>NR_NO) then
  9007. begin
  9008. taicpu(p).loadreg(1,taicpu(p).oper[0]^.ref^.index);
  9009. taicpu(p).loadreg(0,taicpu(p).oper[0]^.ref^.base);
  9010. taicpu(p).opcode:=A_ADD;
  9011. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  9012. result:=true;
  9013. end;
  9014. end;
  9015. end;
  9016. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  9017. var
  9018. hp1: tai; NewRef: TReference;
  9019. begin
  9020. { Change:
  9021. subl/q $x,%reg1
  9022. movl/q %reg1,%reg2
  9023. To:
  9024. leal/q $-x(%reg1),%reg2
  9025. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  9026. Breaks the dependency chain and potentially permits the removal of
  9027. a CMP instruction if one follows.
  9028. }
  9029. Result := False;
  9030. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  9031. MatchOpType(taicpu(p),top_const,top_reg) and
  9032. GetNextInstruction(p, hp1) and
  9033. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  9034. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9035. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  9036. (
  9037. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  9038. not (cs_opt_size in current_settings.optimizerswitches) or
  9039. (
  9040. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  9041. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  9042. )
  9043. ) then
  9044. begin
  9045. { Change the MOV instruction to a LEA instruction, and update the
  9046. first operand }
  9047. reference_reset(NewRef, 1, []);
  9048. NewRef.base := taicpu(p).oper[1]^.reg;
  9049. NewRef.scalefactor := 1;
  9050. NewRef.offset := -taicpu(p).oper[0]^.val;
  9051. taicpu(hp1).opcode := A_LEA;
  9052. taicpu(hp1).loadref(0, NewRef);
  9053. TransferUsedRegs(TmpUsedRegs);
  9054. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9055. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  9056. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  9057. begin
  9058. { Move what is now the LEA instruction to before the SUB instruction }
  9059. Asml.Remove(hp1);
  9060. Asml.InsertBefore(hp1, p);
  9061. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  9062. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  9063. p := hp1;
  9064. end
  9065. else
  9066. begin
  9067. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  9068. RemoveCurrentP(p, hp1);
  9069. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', p);
  9070. end;
  9071. Result := True;
  9072. end;
  9073. end;
  9074. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  9075. begin
  9076. { we can skip all instructions not messing with the stack pointer }
  9077. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  9078. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  9079. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  9080. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  9081. ({(taicpu(hp1).ops=0) or }
  9082. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  9083. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  9084. ) and }
  9085. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  9086. )
  9087. ) do
  9088. GetNextInstruction(hp1,hp1);
  9089. Result:=assigned(hp1);
  9090. end;
  9091. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  9092. var
  9093. hp1, hp2, hp3, hp4, hp5: tai;
  9094. begin
  9095. Result:=false;
  9096. hp5:=nil;
  9097. { replace
  9098. leal(q) x(<stackpointer>),<stackpointer>
  9099. call procname
  9100. leal(q) -x(<stackpointer>),<stackpointer>
  9101. ret
  9102. by
  9103. jmp procname
  9104. but do it only on level 4 because it destroys stack back traces
  9105. }
  9106. if (cs_opt_level4 in current_settings.optimizerswitches) and
  9107. MatchOpType(taicpu(p),top_ref,top_reg) and
  9108. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  9109. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  9110. { the -8 or -24 are not required, but bail out early if possible,
  9111. higher values are unlikely }
  9112. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  9113. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  9114. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  9115. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  9116. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and
  9117. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  9118. GetNextInstruction(p, hp1) and
  9119. { Take a copy of hp1 }
  9120. SetAndTest(hp1, hp4) and
  9121. { trick to skip label }
  9122. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  9123. SkipSimpleInstructions(hp1) and
  9124. MatchInstruction(hp1,A_CALL,[S_NO]) and
  9125. GetNextInstruction(hp1, hp2) and
  9126. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  9127. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  9128. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  9129. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  9130. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  9131. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  9132. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  9133. (taicpu(hp2).oper[0]^.ref^.segment=NR_NO) and
  9134. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  9135. GetNextInstruction(hp2, hp3) and
  9136. { trick to skip label }
  9137. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  9138. (MatchInstruction(hp3,A_RET,[S_NO]) or
  9139. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  9140. SetAndTest(hp3,hp5) and
  9141. GetNextInstruction(hp3,hp3) and
  9142. MatchInstruction(hp3,A_RET,[S_NO])
  9143. )
  9144. ) and
  9145. (taicpu(hp3).ops=0) then
  9146. begin
  9147. taicpu(hp1).opcode := A_JMP;
  9148. taicpu(hp1).is_jmp := true;
  9149. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  9150. RemoveCurrentP(p, hp4);
  9151. RemoveInstruction(hp2);
  9152. RemoveInstruction(hp3);
  9153. if Assigned(hp5) then
  9154. begin
  9155. AsmL.Remove(hp5);
  9156. ASmL.InsertBefore(hp5,hp1)
  9157. end;
  9158. Result:=true;
  9159. end;
  9160. end;
  9161. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  9162. {$ifdef x86_64}
  9163. var
  9164. hp1, hp2, hp3, hp4, hp5: tai;
  9165. {$endif x86_64}
  9166. begin
  9167. Result:=false;
  9168. {$ifdef x86_64}
  9169. hp5:=nil;
  9170. { replace
  9171. push %rax
  9172. call procname
  9173. pop %rcx
  9174. ret
  9175. by
  9176. jmp procname
  9177. but do it only on level 4 because it destroys stack back traces
  9178. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  9179. for all supported calling conventions
  9180. }
  9181. if (cs_opt_level4 in current_settings.optimizerswitches) and
  9182. MatchOpType(taicpu(p),top_reg) and
  9183. (taicpu(p).oper[0]^.reg=NR_RAX) and
  9184. GetNextInstruction(p, hp1) and
  9185. { Take a copy of hp1 }
  9186. SetAndTest(hp1, hp4) and
  9187. { trick to skip label }
  9188. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  9189. SkipSimpleInstructions(hp1) and
  9190. MatchInstruction(hp1,A_CALL,[S_NO]) and
  9191. GetNextInstruction(hp1, hp2) and
  9192. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  9193. MatchOpType(taicpu(hp2),top_reg) and
  9194. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  9195. GetNextInstruction(hp2, hp3) and
  9196. { trick to skip label }
  9197. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  9198. (MatchInstruction(hp3,A_RET,[S_NO]) or
  9199. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  9200. SetAndTest(hp3,hp5) and
  9201. GetNextInstruction(hp3,hp3) and
  9202. MatchInstruction(hp3,A_RET,[S_NO])
  9203. )
  9204. ) and
  9205. (taicpu(hp3).ops=0) then
  9206. begin
  9207. taicpu(hp1).opcode := A_JMP;
  9208. taicpu(hp1).is_jmp := true;
  9209. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  9210. RemoveCurrentP(p, hp4);
  9211. RemoveInstruction(hp2);
  9212. RemoveInstruction(hp3);
  9213. if Assigned(hp5) then
  9214. begin
  9215. AsmL.Remove(hp5);
  9216. ASmL.InsertBefore(hp5,hp1)
  9217. end;
  9218. Result:=true;
  9219. end;
  9220. {$endif x86_64}
  9221. end;
  9222. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  9223. var
  9224. Value, RegName: string;
  9225. begin
  9226. Result:=false;
  9227. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  9228. begin
  9229. case taicpu(p).oper[0]^.val of
  9230. 0:
  9231. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  9232. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  9233. begin
  9234. { change "mov $0,%reg" into "xor %reg,%reg" }
  9235. taicpu(p).opcode := A_XOR;
  9236. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  9237. Result := True;
  9238. {$ifdef x86_64}
  9239. end
  9240. else if (taicpu(p).opsize = S_Q) then
  9241. begin
  9242. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  9243. { The actual optimization }
  9244. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  9245. taicpu(p).changeopsize(S_L);
  9246. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  9247. Result := True;
  9248. end;
  9249. $1..$FFFFFFFF:
  9250. begin
  9251. { Code size reduction by J. Gareth "Kit" Moreton }
  9252. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  9253. case taicpu(p).opsize of
  9254. S_Q:
  9255. begin
  9256. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  9257. Value := debug_tostr(taicpu(p).oper[0]^.val);
  9258. { The actual optimization }
  9259. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  9260. taicpu(p).changeopsize(S_L);
  9261. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  9262. Result := True;
  9263. end;
  9264. else
  9265. { Do nothing };
  9266. end;
  9267. {$endif x86_64}
  9268. end;
  9269. -1:
  9270. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  9271. if (cs_opt_size in current_settings.optimizerswitches) and
  9272. (taicpu(p).opsize <> S_B) and
  9273. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  9274. begin
  9275. { change "mov $-1,%reg" into "or $-1,%reg" }
  9276. { NOTES:
  9277. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  9278. - This operation creates a false dependency on the register, so only do it when optimising for size
  9279. - 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
  9280. }
  9281. taicpu(p).opcode := A_OR;
  9282. Result := True;
  9283. end;
  9284. else
  9285. { Do nothing };
  9286. end;
  9287. end;
  9288. end;
  9289. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  9290. var
  9291. hp1: tai;
  9292. begin
  9293. { Detect:
  9294. andw x, %ax (0 <= x < $8000)
  9295. ...
  9296. movzwl %ax,%eax
  9297. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  9298. }
  9299. Result := False; if MatchOpType(taicpu(p), top_const, top_reg) and
  9300. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  9301. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  9302. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  9303. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  9304. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  9305. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  9306. begin
  9307. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  9308. taicpu(hp1).opcode := A_CWDE;
  9309. taicpu(hp1).clearop(0);
  9310. taicpu(hp1).clearop(1);
  9311. taicpu(hp1).ops := 0;
  9312. { A change was made, but not with p, so move forward 1 }
  9313. p := tai(p.Next);
  9314. Result := True;
  9315. end;
  9316. end;
  9317. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  9318. begin
  9319. Result := False;
  9320. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  9321. Exit;
  9322. { Convert:
  9323. movswl %ax,%eax -> cwtl
  9324. movslq %eax,%rax -> cdqe
  9325. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  9326. refer to the same opcode and depends only on the assembler's
  9327. current operand-size attribute. [Kit]
  9328. }
  9329. with taicpu(p) do
  9330. case opsize of
  9331. S_WL:
  9332. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  9333. begin
  9334. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  9335. opcode := A_CWDE;
  9336. clearop(0);
  9337. clearop(1);
  9338. ops := 0;
  9339. Result := True;
  9340. end;
  9341. {$ifdef x86_64}
  9342. S_LQ:
  9343. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  9344. begin
  9345. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  9346. opcode := A_CDQE;
  9347. clearop(0);
  9348. clearop(1);
  9349. ops := 0;
  9350. Result := True;
  9351. end;
  9352. {$endif x86_64}
  9353. else
  9354. ;
  9355. end;
  9356. end;
  9357. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  9358. var
  9359. hp1: tai;
  9360. begin
  9361. { Detect:
  9362. shr x, %ax (x > 0)
  9363. ...
  9364. movzwl %ax,%eax
  9365. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  9366. }
  9367. Result := False;
  9368. if MatchOpType(taicpu(p), top_const, top_reg) and
  9369. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  9370. (taicpu(p).oper[0]^.val > 0) and
  9371. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  9372. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  9373. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  9374. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  9375. begin
  9376. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  9377. taicpu(hp1).opcode := A_CWDE;
  9378. taicpu(hp1).clearop(0);
  9379. taicpu(hp1).clearop(1);
  9380. taicpu(hp1).ops := 0;
  9381. { A change was made, but not with p, so move forward 1 }
  9382. p := tai(p.Next);
  9383. Result := True;
  9384. end;
  9385. end;
  9386. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  9387. begin
  9388. Result:=false;
  9389. { change "cmp $0, %reg" to "test %reg, %reg" }
  9390. if MatchOpType(taicpu(p),top_const,top_reg) and
  9391. (taicpu(p).oper[0]^.val = 0) then
  9392. begin
  9393. taicpu(p).opcode := A_TEST;
  9394. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  9395. Result:=true;
  9396. end;
  9397. end;
  9398. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  9399. var
  9400. IsTestConstX : Boolean;
  9401. hp1,hp2 : tai;
  9402. begin
  9403. Result:=false;
  9404. { removes the line marked with (x) from the sequence
  9405. and/or/xor/add/sub/... $x, %y
  9406. test/or %y, %y | test $-1, %y (x)
  9407. j(n)z _Label
  9408. as the first instruction already adjusts the ZF
  9409. %y operand may also be a reference }
  9410. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  9411. MatchOperand(taicpu(p).oper[0]^,-1);
  9412. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  9413. GetLastInstruction(p, hp1) and
  9414. (tai(hp1).typ = ait_instruction) and
  9415. GetNextInstruction(p,hp2) and
  9416. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  9417. case taicpu(hp1).opcode Of
  9418. A_ADD, A_SUB, A_OR, A_XOR, A_AND:
  9419. begin
  9420. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  9421. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  9422. { and in case of carry for A(E)/B(E)/C/NC }
  9423. ((taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  9424. ((taicpu(hp1).opcode <> A_ADD) and
  9425. (taicpu(hp1).opcode <> A_SUB))) then
  9426. begin
  9427. RemoveCurrentP(p, hp2);
  9428. Result:=true;
  9429. Exit;
  9430. end;
  9431. end;
  9432. A_SHL, A_SAL, A_SHR, A_SAR:
  9433. begin
  9434. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  9435. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  9436. { therefore, it's only safe to do this optimization for }
  9437. { shifts by a (nonzero) constant }
  9438. (taicpu(hp1).oper[0]^.typ = top_const) and
  9439. (taicpu(hp1).oper[0]^.val <> 0) and
  9440. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  9441. { and in case of carry for A(E)/B(E)/C/NC }
  9442. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  9443. begin
  9444. RemoveCurrentP(p, hp2);
  9445. Result:=true;
  9446. Exit;
  9447. end;
  9448. end;
  9449. A_DEC, A_INC, A_NEG:
  9450. begin
  9451. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  9452. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  9453. { and in case of carry for A(E)/B(E)/C/NC }
  9454. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  9455. begin
  9456. RemoveCurrentP(p, hp2);
  9457. Result:=true;
  9458. Exit;
  9459. end;
  9460. end
  9461. else
  9462. ;
  9463. end; { case }
  9464. { change "test $-1,%reg" into "test %reg,%reg" }
  9465. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  9466. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  9467. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  9468. if MatchInstruction(p, A_OR, []) and
  9469. { Can only match if they're both registers }
  9470. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  9471. begin
  9472. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  9473. taicpu(p).opcode := A_TEST;
  9474. { No need to set Result to True, as we've done all the optimisations we can }
  9475. end;
  9476. end;
  9477. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  9478. var
  9479. hp1,hp3 : tai;
  9480. {$ifndef x86_64}
  9481. hp2 : taicpu;
  9482. {$endif x86_64}
  9483. begin
  9484. Result:=false;
  9485. hp3:=nil;
  9486. {$ifndef x86_64}
  9487. { don't do this on modern CPUs, this really hurts them due to
  9488. broken call/ret pairing }
  9489. if (current_settings.optimizecputype < cpu_Pentium2) and
  9490. not(cs_create_pic in current_settings.moduleswitches) and
  9491. GetNextInstruction(p, hp1) and
  9492. MatchInstruction(hp1,A_JMP,[S_NO]) and
  9493. MatchOpType(taicpu(hp1),top_ref) and
  9494. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  9495. begin
  9496. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  9497. InsertLLItem(p.previous, p, hp2);
  9498. taicpu(p).opcode := A_JMP;
  9499. taicpu(p).is_jmp := true;
  9500. RemoveInstruction(hp1);
  9501. Result:=true;
  9502. end
  9503. else
  9504. {$endif x86_64}
  9505. { replace
  9506. call procname
  9507. ret
  9508. by
  9509. jmp procname
  9510. but do it only on level 4 because it destroys stack back traces
  9511. else if the subroutine is marked as no return, remove the ret
  9512. }
  9513. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  9514. (po_noreturn in current_procinfo.procdef.procoptions)) and
  9515. GetNextInstruction(p, hp1) and
  9516. (MatchInstruction(hp1,A_RET,[S_NO]) or
  9517. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  9518. SetAndTest(hp1,hp3) and
  9519. GetNextInstruction(hp1,hp1) and
  9520. MatchInstruction(hp1,A_RET,[S_NO])
  9521. )
  9522. ) and
  9523. (taicpu(hp1).ops=0) then
  9524. begin
  9525. if (cs_opt_level4 in current_settings.optimizerswitches) and
  9526. { we might destroy stack alignment here if we do not do a call }
  9527. (target_info.stackalign<=sizeof(SizeUInt)) then
  9528. begin
  9529. taicpu(p).opcode := A_JMP;
  9530. taicpu(p).is_jmp := true;
  9531. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  9532. end
  9533. else
  9534. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  9535. RemoveInstruction(hp1);
  9536. if Assigned(hp3) then
  9537. begin
  9538. AsmL.Remove(hp3);
  9539. AsmL.InsertBefore(hp3,p)
  9540. end;
  9541. Result:=true;
  9542. end;
  9543. end;
  9544. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  9545. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  9546. begin
  9547. case OpSize of
  9548. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9549. Result := (Val <= $FF) and (Val >= -128);
  9550. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9551. Result := (Val <= $FFFF) and (Val >= -32768);
  9552. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  9553. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  9554. else
  9555. Result := True;
  9556. end;
  9557. end;
  9558. var
  9559. hp1, hp2 : tai;
  9560. SizeChange: Boolean;
  9561. PreMessage: string;
  9562. begin
  9563. Result := False;
  9564. if (taicpu(p).oper[0]^.typ = top_reg) and
  9565. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  9566. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  9567. begin
  9568. { Change (using movzbl %al,%eax as an example):
  9569. movzbl %al, %eax movzbl %al, %eax
  9570. cmpl x, %eax testl %eax,%eax
  9571. To:
  9572. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  9573. movzbl %al, %eax movzbl %al, %eax
  9574. Smaller instruction and minimises pipeline stall as the CPU
  9575. doesn't have to wait for the register to get zero-extended. [Kit]
  9576. Also allow if the smaller of the two registers is being checked,
  9577. as this still removes the false dependency.
  9578. }
  9579. if
  9580. (
  9581. (
  9582. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  9583. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  9584. ) or (
  9585. { If MatchOperand returns True, they must both be registers }
  9586. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  9587. )
  9588. ) and
  9589. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  9590. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  9591. begin
  9592. 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);
  9593. asml.Remove(hp1);
  9594. asml.InsertBefore(hp1, p);
  9595. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  9596. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  9597. begin
  9598. taicpu(hp1).opcode := A_TEST;
  9599. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  9600. end;
  9601. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  9602. case taicpu(p).opsize of
  9603. S_BW, S_BL:
  9604. begin
  9605. SizeChange := taicpu(hp1).opsize <> S_B;
  9606. taicpu(hp1).changeopsize(S_B);
  9607. end;
  9608. S_WL:
  9609. begin
  9610. SizeChange := taicpu(hp1).opsize <> S_W;
  9611. taicpu(hp1).changeopsize(S_W);
  9612. end
  9613. else
  9614. InternalError(2020112701);
  9615. end;
  9616. UpdateUsedRegs(tai(p.Next));
  9617. { Check if the register is used aferwards - if not, we can
  9618. remove the movzx instruction completely }
  9619. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  9620. begin
  9621. { Hp1 is a better position than p for debugging purposes }
  9622. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  9623. RemoveCurrentp(p, hp1);
  9624. Result := True;
  9625. end;
  9626. if SizeChange then
  9627. DebugMsg(SPeepholeOptimization + PreMessage +
  9628. 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)
  9629. else
  9630. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  9631. Exit;
  9632. end;
  9633. { Change (using movzwl %ax,%eax as an example):
  9634. movzwl %ax, %eax
  9635. movb %al, (dest) (Register is smaller than read register in movz)
  9636. To:
  9637. movb %al, (dest) (Move one back to avoid a false dependency)
  9638. movzwl %ax, %eax
  9639. }
  9640. if (taicpu(hp1).opcode = A_MOV) and
  9641. (taicpu(hp1).oper[0]^.typ = top_reg) and
  9642. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  9643. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  9644. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  9645. begin
  9646. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  9647. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  9648. asml.Remove(hp1);
  9649. asml.InsertBefore(hp1, p);
  9650. if taicpu(hp1).oper[1]^.typ = top_reg then
  9651. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  9652. { Check if the register is used aferwards - if not, we can
  9653. remove the movzx instruction completely }
  9654. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  9655. begin
  9656. { Hp1 is a better position than p for debugging purposes }
  9657. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  9658. RemoveCurrentp(p, hp1);
  9659. Result := True;
  9660. end;
  9661. Exit;
  9662. end;
  9663. end;
  9664. end;
  9665. {$ifdef x86_64}
  9666. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  9667. var
  9668. PreMessage, RegName: string;
  9669. begin
  9670. { Code size reduction by J. Gareth "Kit" Moreton }
  9671. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  9672. as this removes the REX prefix }
  9673. Result := False;
  9674. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  9675. Exit;
  9676. if taicpu(p).oper[0]^.typ <> top_reg then
  9677. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  9678. InternalError(2018011500);
  9679. case taicpu(p).opsize of
  9680. S_Q:
  9681. begin
  9682. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  9683. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  9684. { The actual optimization }
  9685. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  9686. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  9687. taicpu(p).changeopsize(S_L);
  9688. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  9689. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  9690. end;
  9691. else
  9692. ;
  9693. end;
  9694. end;
  9695. {$endif}
  9696. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  9697. var
  9698. XReg: TRegister;
  9699. begin
  9700. Result := False;
  9701. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  9702. Smaller encoding and slightly faster on some platforms (also works for
  9703. ZMM-sized registers) }
  9704. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  9705. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  9706. begin
  9707. XReg := taicpu(p).oper[0]^.reg;
  9708. if (taicpu(p).oper[1]^.reg = XReg) then
  9709. begin
  9710. taicpu(p).changeopsize(S_XMM);
  9711. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  9712. if (cs_opt_size in current_settings.optimizerswitches) then
  9713. begin
  9714. { Change input registers to %xmm0 to reduce size. Note that
  9715. there's a risk of a false dependency doing this, so only
  9716. optimise for size here }
  9717. XReg := NR_XMM0;
  9718. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  9719. end
  9720. else
  9721. begin
  9722. setsubreg(XReg, R_SUBMMX);
  9723. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  9724. end;
  9725. taicpu(p).oper[0]^.reg := XReg;
  9726. taicpu(p).oper[1]^.reg := XReg;
  9727. Result := True;
  9728. end;
  9729. end;
  9730. end;
  9731. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  9732. var
  9733. OperIdx: Integer;
  9734. begin
  9735. for OperIdx := 0 to p.ops - 1 do
  9736. if p.oper[OperIdx]^.typ = top_ref then
  9737. optimize_ref(p.oper[OperIdx]^.ref^, False);
  9738. end;
  9739. end.