aoptx86.pas 277 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. {$define DEBUG_AOPTCPU}
  20. interface
  21. uses
  22. globtype,
  23. cpubase,
  24. aasmtai,aasmcpu,
  25. cgbase,cgutils,
  26. aopt,aoptobj;
  27. type
  28. TOptsToCheck = (
  29. aoc_MovAnd2Mov_3
  30. );
  31. TX86AsmOptimizer = class(TAsmOptimizer)
  32. { some optimizations are very expensive to check, so the
  33. pre opt pass can be used to set some flags, depending on the found
  34. instructions if it is worth to check a certain optimization }
  35. OptsToCheck : set of TOptsToCheck;
  36. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  37. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  38. function RegReadByInstruction(reg : TRegister; hp : tai) : boolean;
  39. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  40. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  41. {
  42. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  43. the use of a register by allocs/dealloc, so it can ignore calls.
  44. In the following example, GetNextInstructionUsingReg will return the second movq,
  45. GetNextInstructionUsingRegTrackingUse won't.
  46. movq %rdi,%rax
  47. # Register rdi released
  48. # Register rdi allocated
  49. movq %rax,%rdi
  50. While in this example:
  51. movq %rdi,%rax
  52. call proc
  53. movq %rdi,%rax
  54. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  55. won't.
  56. }
  57. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  58. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  59. private
  60. function SkipSimpleInstructions(var hp1: tai): Boolean;
  61. protected
  62. class function IsMOVZXAcceptable: Boolean; static; inline;
  63. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  64. function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  65. { checks whether reading the value in reg1 depends on the value of reg2. This
  66. is very similar to SuperRegisterEquals, except it takes into account that
  67. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  68. depend on the value in AH). }
  69. function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  70. { Replaces all references to AOldReg in a memory reference to ANewReg }
  71. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  72. { Replaces all references to AOldReg in an operand to ANewReg }
  73. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  74. { Replaces all references to AOldReg in an instruction to ANewReg,
  75. except where the register is being written }
  76. function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  77. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  78. or writes to a global symbol }
  79. class function IsRefSafe(const ref: PReference): Boolean; static; inline;
  80. { Returns true if the given MOV instruction can be safely converted to CMOV }
  81. class function CanBeCMOV(p : tai) : boolean; static;
  82. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  83. conversion was successful }
  84. function ConvertLEA(const p : taicpu): Boolean;
  85. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  86. procedure DebugMsg(const s : string; p : tai);inline;
  87. class function IsExitCode(p : tai) : boolean; static;
  88. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  89. procedure RemoveLastDeallocForFuncRes(p : tai);
  90. function DoSubAddOpt(var p : tai) : Boolean;
  91. function PrePeepholeOptSxx(var p : tai) : boolean;
  92. function PrePeepholeOptIMUL(var p : tai) : boolean;
  93. function OptPass1AND(var p : tai) : boolean;
  94. function OptPass1_V_MOVAP(var p : tai) : boolean;
  95. function OptPass1VOP(var p : tai) : boolean;
  96. function OptPass1MOV(var p : tai) : boolean;
  97. function OptPass1Movx(var p : tai) : boolean;
  98. function OptPass1MOVXX(var p : tai) : boolean;
  99. function OptPass1OP(var p : tai) : boolean;
  100. function OptPass1LEA(var p : tai) : boolean;
  101. function OptPass1Sub(var p : tai) : boolean;
  102. function OptPass1SHLSAL(var p : tai) : boolean;
  103. function OptPass1SETcc(var p : tai) : boolean;
  104. function OptPass1FSTP(var p : tai) : boolean;
  105. function OptPass1FLD(var p : tai) : boolean;
  106. function OptPass1Cmp(var p : tai) : boolean;
  107. function OptPass1PXor(var p : tai) : boolean;
  108. function OptPass1VPXor(var p: tai): boolean;
  109. function OptPass1Imul(var p : tai) : boolean;
  110. function OptPass2MOV(var p : tai) : boolean;
  111. function OptPass2Imul(var p : tai) : boolean;
  112. function OptPass2Jmp(var p : tai) : boolean;
  113. function OptPass2Jcc(var p : tai) : boolean;
  114. function OptPass2Lea(var p: tai): Boolean;
  115. function OptPass2SUB(var p: tai): Boolean;
  116. function PostPeepholeOptMov(var p : tai) : Boolean;
  117. {$ifdef x86_64} { These post-peephole optimisations only affect 64-bit registers. [Kit] }
  118. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  119. function PostPeepholeOptXor(var p : tai) : Boolean;
  120. {$endif}
  121. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  122. function PostPeepholeOptCmp(var p : tai) : Boolean;
  123. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  124. function PostPeepholeOptCall(var p : tai) : Boolean;
  125. function PostPeepholeOptLea(var p : tai) : Boolean;
  126. function PostPeepholeOptPush(var p: tai): Boolean;
  127. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  128. { Processor-dependent reference optimisation }
  129. class procedure OptimizeRefs(var p: taicpu); static;
  130. end;
  131. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  132. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  133. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  134. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  135. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  136. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  137. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  138. {$if max_operands>2}
  139. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  140. {$endif max_operands>2}
  141. function RefsEqual(const r1, r2: treference): boolean;
  142. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  143. { returns true, if ref is a reference using only the registers passed as base and index
  144. and having an offset }
  145. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  146. implementation
  147. uses
  148. cutils,verbose,
  149. systems,
  150. globals,
  151. cpuinfo,
  152. procinfo,
  153. paramgr,
  154. aasmbase,
  155. aoptbase,aoptutils,
  156. symconst,symsym,
  157. cgx86,
  158. itcpugas;
  159. {$ifdef DEBUG_AOPTCPU}
  160. const
  161. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  162. {$else DEBUG_AOPTCPU}
  163. { Empty strings help the optimizer to remove string concatenations that won't
  164. ever appear to the user on release builds. [Kit] }
  165. const
  166. SPeepholeOptimization = '';
  167. {$endif DEBUG_AOPTCPU}
  168. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  169. begin
  170. result :=
  171. (instr.typ = ait_instruction) and
  172. (taicpu(instr).opcode = op) and
  173. ((opsize = []) or (taicpu(instr).opsize in opsize));
  174. end;
  175. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  176. begin
  177. result :=
  178. (instr.typ = ait_instruction) and
  179. ((taicpu(instr).opcode = op1) or
  180. (taicpu(instr).opcode = op2)
  181. ) and
  182. ((opsize = []) or (taicpu(instr).opsize in opsize));
  183. end;
  184. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  185. begin
  186. result :=
  187. (instr.typ = ait_instruction) and
  188. ((taicpu(instr).opcode = op1) or
  189. (taicpu(instr).opcode = op2) or
  190. (taicpu(instr).opcode = op3)
  191. ) and
  192. ((opsize = []) or (taicpu(instr).opsize in opsize));
  193. end;
  194. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  195. const opsize : topsizes) : boolean;
  196. var
  197. op : TAsmOp;
  198. begin
  199. result:=false;
  200. for op in ops do
  201. begin
  202. if (instr.typ = ait_instruction) and
  203. (taicpu(instr).opcode = op) and
  204. ((opsize = []) or (taicpu(instr).opsize in opsize)) then
  205. begin
  206. result:=true;
  207. exit;
  208. end;
  209. end;
  210. end;
  211. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  212. begin
  213. result := (oper.typ = top_reg) and (oper.reg = reg);
  214. end;
  215. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  216. begin
  217. result := (oper.typ = top_const) and (oper.val = a);
  218. end;
  219. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  220. begin
  221. result := oper1.typ = oper2.typ;
  222. if result then
  223. case oper1.typ of
  224. top_const:
  225. Result:=oper1.val = oper2.val;
  226. top_reg:
  227. Result:=oper1.reg = oper2.reg;
  228. top_ref:
  229. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  230. else
  231. internalerror(2013102801);
  232. end
  233. end;
  234. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  235. begin
  236. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  237. if result then
  238. case oper1.typ of
  239. top_const:
  240. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  241. top_reg:
  242. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  243. top_ref:
  244. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  245. else
  246. internalerror(2020052401);
  247. end
  248. end;
  249. function RefsEqual(const r1, r2: treference): boolean;
  250. begin
  251. RefsEqual :=
  252. (r1.offset = r2.offset) and
  253. (r1.segment = r2.segment) and (r1.base = r2.base) and
  254. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  255. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  256. (r1.relsymbol = r2.relsymbol) and
  257. (r1.volatility=[]) and
  258. (r2.volatility=[]);
  259. end;
  260. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  261. begin
  262. Result:=(ref.offset=0) and
  263. (ref.scalefactor in [0,1]) and
  264. (ref.segment=NR_NO) and
  265. (ref.symbol=nil) and
  266. (ref.relsymbol=nil) and
  267. ((base=NR_INVALID) or
  268. (ref.base=base)) and
  269. ((index=NR_INVALID) or
  270. (ref.index=index)) and
  271. (ref.volatility=[]);
  272. end;
  273. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  274. begin
  275. Result:=(ref.scalefactor in [0,1]) and
  276. (ref.segment=NR_NO) and
  277. (ref.symbol=nil) and
  278. (ref.relsymbol=nil) and
  279. ((base=NR_INVALID) or
  280. (ref.base=base)) and
  281. ((index=NR_INVALID) or
  282. (ref.index=index)) and
  283. (ref.volatility=[]);
  284. end;
  285. function InstrReadsFlags(p: tai): boolean;
  286. begin
  287. InstrReadsFlags := true;
  288. case p.typ of
  289. ait_instruction:
  290. if InsProp[taicpu(p).opcode].Ch*
  291. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  292. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  293. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  294. exit;
  295. ait_label:
  296. exit;
  297. else
  298. ;
  299. end;
  300. InstrReadsFlags := false;
  301. end;
  302. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  303. begin
  304. Next:=Current;
  305. repeat
  306. Result:=GetNextInstruction(Next,Next);
  307. until not (Result) or
  308. not(cs_opt_level3 in current_settings.optimizerswitches) or
  309. (Next.typ<>ait_instruction) or
  310. RegInInstruction(reg,Next) or
  311. is_calljmp(taicpu(Next).opcode);
  312. end;
  313. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  314. begin
  315. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  316. begin
  317. Result:=GetNextInstruction(Current,Next);
  318. exit;
  319. end;
  320. Next:=tai(Current.Next);
  321. Result:=false;
  322. while assigned(Next) do
  323. begin
  324. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  325. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  326. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  327. exit
  328. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  329. begin
  330. Result:=true;
  331. exit;
  332. end;
  333. Next:=tai(Next.Next);
  334. end;
  335. end;
  336. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  337. begin
  338. Result:=RegReadByInstruction(reg,hp);
  339. end;
  340. function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  341. var
  342. p: taicpu;
  343. opcount: longint;
  344. begin
  345. RegReadByInstruction := false;
  346. if hp.typ <> ait_instruction then
  347. exit;
  348. p := taicpu(hp);
  349. case p.opcode of
  350. A_CALL:
  351. regreadbyinstruction := true;
  352. A_IMUL:
  353. case p.ops of
  354. 1:
  355. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  356. (
  357. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  358. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  359. );
  360. 2,3:
  361. regReadByInstruction :=
  362. reginop(reg,p.oper[0]^) or
  363. reginop(reg,p.oper[1]^);
  364. else
  365. InternalError(2019112801);
  366. end;
  367. A_MUL:
  368. begin
  369. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  370. (
  371. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  372. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  373. );
  374. end;
  375. A_IDIV,A_DIV:
  376. begin
  377. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  378. (
  379. (getregtype(reg)=R_INTREGISTER) and
  380. (
  381. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  382. )
  383. );
  384. end;
  385. else
  386. begin
  387. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  388. begin
  389. RegReadByInstruction := false;
  390. exit;
  391. end;
  392. for opcount := 0 to p.ops-1 do
  393. if (p.oper[opCount]^.typ = top_ref) and
  394. RegInRef(reg,p.oper[opcount]^.ref^) then
  395. begin
  396. RegReadByInstruction := true;
  397. exit
  398. end;
  399. { special handling for SSE MOVSD }
  400. if (p.opcode=A_MOVSD) and (p.ops>0) then
  401. begin
  402. if p.ops<>2 then
  403. internalerror(2017042702);
  404. regReadByInstruction := reginop(reg,p.oper[0]^) or
  405. (
  406. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  407. );
  408. exit;
  409. end;
  410. with insprop[p.opcode] do
  411. begin
  412. if getregtype(reg)=R_INTREGISTER then
  413. begin
  414. case getsupreg(reg) of
  415. RS_EAX:
  416. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  417. begin
  418. RegReadByInstruction := true;
  419. exit
  420. end;
  421. RS_ECX:
  422. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  423. begin
  424. RegReadByInstruction := true;
  425. exit
  426. end;
  427. RS_EDX:
  428. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  429. begin
  430. RegReadByInstruction := true;
  431. exit
  432. end;
  433. RS_EBX:
  434. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  435. begin
  436. RegReadByInstruction := true;
  437. exit
  438. end;
  439. RS_ESP:
  440. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  441. begin
  442. RegReadByInstruction := true;
  443. exit
  444. end;
  445. RS_EBP:
  446. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  447. begin
  448. RegReadByInstruction := true;
  449. exit
  450. end;
  451. RS_ESI:
  452. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  453. begin
  454. RegReadByInstruction := true;
  455. exit
  456. end;
  457. RS_EDI:
  458. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  459. begin
  460. RegReadByInstruction := true;
  461. exit
  462. end;
  463. end;
  464. end;
  465. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  466. begin
  467. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  468. begin
  469. case p.condition of
  470. C_A,C_NBE, { CF=0 and ZF=0 }
  471. C_BE,C_NA: { CF=1 or ZF=1 }
  472. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  473. C_AE,C_NB,C_NC, { CF=0 }
  474. C_B,C_NAE,C_C: { CF=1 }
  475. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  476. C_NE,C_NZ, { ZF=0 }
  477. C_E,C_Z: { ZF=1 }
  478. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  479. C_G,C_NLE, { ZF=0 and SF=OF }
  480. C_LE,C_NG: { ZF=1 or SF<>OF }
  481. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  482. C_GE,C_NL, { SF=OF }
  483. C_L,C_NGE: { SF<>OF }
  484. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  485. C_NO, { OF=0 }
  486. C_O: { OF=1 }
  487. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  488. C_NP,C_PO, { PF=0 }
  489. C_P,C_PE: { PF=1 }
  490. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  491. C_NS, { SF=0 }
  492. C_S: { SF=1 }
  493. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  494. else
  495. internalerror(2017042701);
  496. end;
  497. if RegReadByInstruction then
  498. exit;
  499. end;
  500. case getsubreg(reg) of
  501. R_SUBW,R_SUBD,R_SUBQ:
  502. RegReadByInstruction :=
  503. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  504. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  505. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  506. R_SUBFLAGCARRY:
  507. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  508. R_SUBFLAGPARITY:
  509. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  510. R_SUBFLAGAUXILIARY:
  511. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  512. R_SUBFLAGZERO:
  513. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  514. R_SUBFLAGSIGN:
  515. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  516. R_SUBFLAGOVERFLOW:
  517. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  518. R_SUBFLAGINTERRUPT:
  519. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  520. R_SUBFLAGDIRECTION:
  521. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  522. else
  523. internalerror(2017042601);
  524. end;
  525. exit;
  526. end;
  527. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  528. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  529. (p.oper[0]^.reg=p.oper[1]^.reg) then
  530. exit;
  531. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  532. begin
  533. RegReadByInstruction := true;
  534. exit
  535. end;
  536. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  537. begin
  538. RegReadByInstruction := true;
  539. exit
  540. end;
  541. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  542. begin
  543. RegReadByInstruction := true;
  544. exit
  545. end;
  546. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  547. begin
  548. RegReadByInstruction := true;
  549. exit
  550. end;
  551. end;
  552. end;
  553. end;
  554. end;
  555. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  556. begin
  557. result:=false;
  558. if p1.typ<>ait_instruction then
  559. exit;
  560. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  561. exit(true);
  562. if (getregtype(reg)=R_INTREGISTER) and
  563. { change information for xmm movsd are not correct }
  564. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  565. begin
  566. case getsupreg(reg) of
  567. { RS_EAX = RS_RAX on x86-64 }
  568. RS_EAX:
  569. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  570. RS_ECX:
  571. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  572. RS_EDX:
  573. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  574. RS_EBX:
  575. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  576. RS_ESP:
  577. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  578. RS_EBP:
  579. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  580. RS_ESI:
  581. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  582. RS_EDI:
  583. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  584. else
  585. ;
  586. end;
  587. if result then
  588. exit;
  589. end
  590. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  591. begin
  592. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  593. exit(true);
  594. case getsubreg(reg) of
  595. R_SUBFLAGCARRY:
  596. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  597. R_SUBFLAGPARITY:
  598. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  599. R_SUBFLAGAUXILIARY:
  600. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  601. R_SUBFLAGZERO:
  602. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  603. R_SUBFLAGSIGN:
  604. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  605. R_SUBFLAGOVERFLOW:
  606. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  607. R_SUBFLAGINTERRUPT:
  608. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  609. R_SUBFLAGDIRECTION:
  610. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  611. else
  612. ;
  613. end;
  614. if result then
  615. exit;
  616. end
  617. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  618. exit(true);
  619. Result:=inherited RegInInstruction(Reg, p1);
  620. end;
  621. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  622. begin
  623. Result := False;
  624. if p1.typ <> ait_instruction then
  625. exit;
  626. with insprop[taicpu(p1).opcode] do
  627. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  628. begin
  629. case getsubreg(reg) of
  630. R_SUBW,R_SUBD,R_SUBQ:
  631. Result :=
  632. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  633. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  634. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  635. R_SUBFLAGCARRY:
  636. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  637. R_SUBFLAGPARITY:
  638. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  639. R_SUBFLAGAUXILIARY:
  640. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  641. R_SUBFLAGZERO:
  642. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  643. R_SUBFLAGSIGN:
  644. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  645. R_SUBFLAGOVERFLOW:
  646. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  647. R_SUBFLAGINTERRUPT:
  648. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  649. R_SUBFLAGDIRECTION:
  650. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  651. else
  652. internalerror(2017042602);
  653. end;
  654. exit;
  655. end;
  656. case taicpu(p1).opcode of
  657. A_CALL:
  658. { We could potentially set Result to False if the register in
  659. question is non-volatile for the subroutine's calling convention,
  660. but this would require detecting the calling convention in use and
  661. also assuming that the routine doesn't contain malformed assembly
  662. language, for example... so it could only be done under -O4 as it
  663. would be considered a side-effect. [Kit] }
  664. Result := True;
  665. A_MOVSD:
  666. { special handling for SSE MOVSD }
  667. if (taicpu(p1).ops>0) then
  668. begin
  669. if taicpu(p1).ops<>2 then
  670. internalerror(2017042703);
  671. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  672. end;
  673. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  674. so fix it here (FK)
  675. }
  676. A_VMOVSS,
  677. A_VMOVSD:
  678. begin
  679. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  680. exit;
  681. end;
  682. A_IMUL:
  683. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  684. else
  685. ;
  686. end;
  687. if Result then
  688. exit;
  689. with insprop[taicpu(p1).opcode] do
  690. begin
  691. if getregtype(reg)=R_INTREGISTER then
  692. begin
  693. case getsupreg(reg) of
  694. RS_EAX:
  695. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  696. begin
  697. Result := True;
  698. exit
  699. end;
  700. RS_ECX:
  701. if [Ch_WECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  702. begin
  703. Result := True;
  704. exit
  705. end;
  706. RS_EDX:
  707. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  708. begin
  709. Result := True;
  710. exit
  711. end;
  712. RS_EBX:
  713. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  714. begin
  715. Result := True;
  716. exit
  717. end;
  718. RS_ESP:
  719. if [Ch_WESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  720. begin
  721. Result := True;
  722. exit
  723. end;
  724. RS_EBP:
  725. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  726. begin
  727. Result := True;
  728. exit
  729. end;
  730. RS_ESI:
  731. if [Ch_WESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  732. begin
  733. Result := True;
  734. exit
  735. end;
  736. RS_EDI:
  737. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  738. begin
  739. Result := True;
  740. exit
  741. end;
  742. end;
  743. end;
  744. if ([CH_RWOP1,CH_WOP1,CH_MOP1]*Ch<>[]) and reginop(reg,taicpu(p1).oper[0]^) then
  745. begin
  746. Result := true;
  747. exit
  748. end;
  749. if ([Ch_RWOP2,Ch_WOP2,Ch_MOP2]*Ch<>[]) and reginop(reg,taicpu(p1).oper[1]^) then
  750. begin
  751. Result := true;
  752. exit
  753. end;
  754. if ([Ch_RWOP3,Ch_WOP3,Ch_MOP3]*Ch<>[]) and reginop(reg,taicpu(p1).oper[2]^) then
  755. begin
  756. Result := true;
  757. exit
  758. end;
  759. if ([Ch_RWOP4,Ch_WOP4,Ch_MOP4]*Ch<>[]) and reginop(reg,taicpu(p1).oper[3]^) then
  760. begin
  761. Result := true;
  762. exit
  763. end;
  764. end;
  765. end;
  766. {$ifdef DEBUG_AOPTCPU}
  767. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  768. begin
  769. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  770. end;
  771. function debug_tostr(i: tcgint): string; inline;
  772. begin
  773. Result := tostr(i);
  774. end;
  775. function debug_regname(r: TRegister): string; inline;
  776. begin
  777. Result := '%' + std_regname(r);
  778. end;
  779. { Debug output function - creates a string representation of an operator }
  780. function debug_operstr(oper: TOper): string;
  781. begin
  782. case oper.typ of
  783. top_const:
  784. Result := '$' + debug_tostr(oper.val);
  785. top_reg:
  786. Result := debug_regname(oper.reg);
  787. top_ref:
  788. begin
  789. if oper.ref^.offset <> 0 then
  790. Result := debug_tostr(oper.ref^.offset) + '('
  791. else
  792. Result := '(';
  793. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  794. begin
  795. Result := Result + debug_regname(oper.ref^.base);
  796. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  797. Result := Result + ',' + debug_regname(oper.ref^.index);
  798. end
  799. else
  800. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  801. Result := Result + debug_regname(oper.ref^.index);
  802. if (oper.ref^.scalefactor > 1) then
  803. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  804. else
  805. Result := Result + ')';
  806. end;
  807. else
  808. Result := '[UNKNOWN]';
  809. end;
  810. end;
  811. function debug_op2str(opcode: tasmop): string; inline;
  812. begin
  813. Result := std_op2str[opcode];
  814. end;
  815. function debug_opsize2str(opsize: topsize): string; inline;
  816. begin
  817. Result := gas_opsize2str[opsize];
  818. end;
  819. {$else DEBUG_AOPTCPU}
  820. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  821. begin
  822. end;
  823. function debug_tostr(i: tcgint): string; inline;
  824. begin
  825. Result := '';
  826. end;
  827. function debug_regname(r: TRegister): string; inline;
  828. begin
  829. Result := '';
  830. end;
  831. function debug_operstr(oper: TOper): string; inline;
  832. begin
  833. Result := '';
  834. end;
  835. function debug_op2str(opcode: tasmop): string; inline;
  836. begin
  837. Result := '';
  838. end;
  839. function debug_opsize2str(opsize: topsize): string; inline;
  840. begin
  841. Result := '';
  842. end;
  843. {$endif DEBUG_AOPTCPU}
  844. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  845. begin
  846. {$ifdef x86_64}
  847. { Always fine on x86-64 }
  848. Result := True;
  849. {$else x86_64}
  850. Result :=
  851. {$ifdef i8086}
  852. (current_settings.cputype >= cpu_386) and
  853. {$endif i8086}
  854. (
  855. { Always accept if optimising for size }
  856. (cs_opt_size in current_settings.optimizerswitches) or
  857. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  858. (current_settings.optimizecputype >= cpu_Pentium2)
  859. );
  860. {$endif x86_64}
  861. end;
  862. function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  863. begin
  864. if not SuperRegistersEqual(reg1,reg2) then
  865. exit(false);
  866. if getregtype(reg1)<>R_INTREGISTER then
  867. exit(true); {because SuperRegisterEqual is true}
  868. case getsubreg(reg1) of
  869. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  870. higher, it preserves the high bits, so the new value depends on
  871. reg2's previous value. In other words, it is equivalent to doing:
  872. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  873. R_SUBL:
  874. exit(getsubreg(reg2)=R_SUBL);
  875. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  876. higher, it actually does a:
  877. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  878. R_SUBH:
  879. exit(getsubreg(reg2)=R_SUBH);
  880. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  881. bits of reg2:
  882. reg2 := (reg2 and $ffff0000) or word(reg1); }
  883. R_SUBW:
  884. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  885. { a write to R_SUBD always overwrites every other subregister,
  886. because it clears the high 32 bits of R_SUBQ on x86_64 }
  887. R_SUBD,
  888. R_SUBQ:
  889. exit(true);
  890. else
  891. internalerror(2017042801);
  892. end;
  893. end;
  894. function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  895. begin
  896. if not SuperRegistersEqual(reg1,reg2) then
  897. exit(false);
  898. if getregtype(reg1)<>R_INTREGISTER then
  899. exit(true); {because SuperRegisterEqual is true}
  900. case getsubreg(reg1) of
  901. R_SUBL:
  902. exit(getsubreg(reg2)<>R_SUBH);
  903. R_SUBH:
  904. exit(getsubreg(reg2)<>R_SUBL);
  905. R_SUBW,
  906. R_SUBD,
  907. R_SUBQ:
  908. exit(true);
  909. else
  910. internalerror(2017042802);
  911. end;
  912. end;
  913. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  914. var
  915. hp1 : tai;
  916. l : TCGInt;
  917. begin
  918. result:=false;
  919. { changes the code sequence
  920. shr/sar const1, x
  921. shl const2, x
  922. to
  923. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  924. if GetNextInstruction(p, hp1) and
  925. MatchInstruction(hp1,A_SHL,[]) and
  926. (taicpu(p).oper[0]^.typ = top_const) and
  927. (taicpu(hp1).oper[0]^.typ = top_const) and
  928. (taicpu(hp1).opsize = taicpu(p).opsize) and
  929. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  930. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  931. begin
  932. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  933. not(cs_opt_size in current_settings.optimizerswitches) then
  934. begin
  935. { shr/sar const1, %reg
  936. shl const2, %reg
  937. with const1 > const2 }
  938. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  939. taicpu(hp1).opcode := A_AND;
  940. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  941. case taicpu(p).opsize Of
  942. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  943. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  944. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  945. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  946. else
  947. Internalerror(2017050703)
  948. end;
  949. end
  950. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  951. not(cs_opt_size in current_settings.optimizerswitches) then
  952. begin
  953. { shr/sar const1, %reg
  954. shl const2, %reg
  955. with const1 < const2 }
  956. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  957. taicpu(p).opcode := A_AND;
  958. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  959. case taicpu(p).opsize Of
  960. S_B: taicpu(p).loadConst(0,l Xor $ff);
  961. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  962. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  963. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  964. else
  965. Internalerror(2017050702)
  966. end;
  967. end
  968. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  969. begin
  970. { shr/sar const1, %reg
  971. shl const2, %reg
  972. with const1 = const2 }
  973. taicpu(p).opcode := A_AND;
  974. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  975. case taicpu(p).opsize Of
  976. S_B: taicpu(p).loadConst(0,l Xor $ff);
  977. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  978. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  979. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  980. else
  981. Internalerror(2017050701)
  982. end;
  983. RemoveInstruction(hp1);
  984. end;
  985. end;
  986. end;
  987. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  988. var
  989. opsize : topsize;
  990. hp1 : tai;
  991. tmpref : treference;
  992. ShiftValue : Cardinal;
  993. BaseValue : TCGInt;
  994. begin
  995. result:=false;
  996. opsize:=taicpu(p).opsize;
  997. { changes certain "imul const, %reg"'s to lea sequences }
  998. if (MatchOpType(taicpu(p),top_const,top_reg) or
  999. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1000. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1001. if (taicpu(p).oper[0]^.val = 1) then
  1002. if (taicpu(p).ops = 2) then
  1003. { remove "imul $1, reg" }
  1004. begin
  1005. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1006. Result := RemoveCurrentP(p);
  1007. end
  1008. else
  1009. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1010. begin
  1011. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1012. InsertLLItem(p.previous, p.next, hp1);
  1013. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1014. p.free;
  1015. p := hp1;
  1016. end
  1017. else if ((taicpu(p).ops <= 2) or
  1018. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1019. not(cs_opt_size in current_settings.optimizerswitches) and
  1020. (not(GetNextInstruction(p, hp1)) or
  1021. not((tai(hp1).typ = ait_instruction) and
  1022. ((taicpu(hp1).opcode=A_Jcc) and
  1023. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1024. begin
  1025. {
  1026. imul X, reg1, reg2 to
  1027. lea (reg1,reg1,Y), reg2
  1028. shl ZZ,reg2
  1029. imul XX, reg1 to
  1030. lea (reg1,reg1,YY), reg1
  1031. shl ZZ,reg2
  1032. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1033. it does not exist as a separate optimization target in FPC though.
  1034. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1035. at most two zeros
  1036. }
  1037. reference_reset(tmpref,1,[]);
  1038. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1039. begin
  1040. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1041. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1042. TmpRef.base := taicpu(p).oper[1]^.reg;
  1043. TmpRef.index := taicpu(p).oper[1]^.reg;
  1044. if not(BaseValue in [3,5,9]) then
  1045. Internalerror(2018110101);
  1046. TmpRef.ScaleFactor := BaseValue-1;
  1047. if (taicpu(p).ops = 2) then
  1048. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1049. else
  1050. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1051. AsmL.InsertAfter(hp1,p);
  1052. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1053. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1054. RemoveCurrentP(p, hp1);
  1055. if ShiftValue>0 then
  1056. AsmL.InsertAfter(taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg),hp1);
  1057. end;
  1058. end;
  1059. end;
  1060. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1061. var
  1062. p: taicpu;
  1063. begin
  1064. if not assigned(hp) or
  1065. (hp.typ <> ait_instruction) then
  1066. begin
  1067. Result := false;
  1068. exit;
  1069. end;
  1070. p := taicpu(hp);
  1071. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1072. with insprop[p.opcode] do
  1073. begin
  1074. case getsubreg(reg) of
  1075. R_SUBW,R_SUBD,R_SUBQ:
  1076. Result:=
  1077. RegLoadedWithNewValue(NR_CARRYFLAG,hp) and
  1078. RegLoadedWithNewValue(NR_PARITYFLAG,hp) and
  1079. RegLoadedWithNewValue(NR_AUXILIARYFLAG,hp) and
  1080. RegLoadedWithNewValue(NR_ZEROFLAG,hp) and
  1081. RegLoadedWithNewValue(NR_SIGNFLAG,hp) and
  1082. RegLoadedWithNewValue(NR_OVERFLOWFLAG,hp);
  1083. R_SUBFLAGCARRY:
  1084. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1085. R_SUBFLAGPARITY:
  1086. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1087. R_SUBFLAGAUXILIARY:
  1088. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1089. R_SUBFLAGZERO:
  1090. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1091. R_SUBFLAGSIGN:
  1092. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1093. R_SUBFLAGOVERFLOW:
  1094. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1095. R_SUBFLAGINTERRUPT:
  1096. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1097. R_SUBFLAGDIRECTION:
  1098. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1099. else
  1100. begin
  1101. writeln(getsubreg(reg));
  1102. internalerror(2017050501);
  1103. end;
  1104. end;
  1105. exit;
  1106. end;
  1107. Result :=
  1108. (((p.opcode = A_MOV) or
  1109. (p.opcode = A_MOVZX) or
  1110. (p.opcode = A_MOVSX) or
  1111. (p.opcode = A_LEA) or
  1112. (p.opcode = A_VMOVSS) or
  1113. (p.opcode = A_VMOVSD) or
  1114. (p.opcode = A_VMOVAPD) or
  1115. (p.opcode = A_VMOVAPS) or
  1116. (p.opcode = A_VMOVQ) or
  1117. (p.opcode = A_MOVSS) or
  1118. (p.opcode = A_MOVSD) or
  1119. (p.opcode = A_MOVQ) or
  1120. (p.opcode = A_MOVAPD) or
  1121. (p.opcode = A_MOVAPS) or
  1122. {$ifndef x86_64}
  1123. (p.opcode = A_LDS) or
  1124. (p.opcode = A_LES) or
  1125. {$endif not x86_64}
  1126. (p.opcode = A_LFS) or
  1127. (p.opcode = A_LGS) or
  1128. (p.opcode = A_LSS)) and
  1129. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1130. (p.oper[1]^.typ = top_reg) and
  1131. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1132. ((p.oper[0]^.typ = top_const) or
  1133. ((p.oper[0]^.typ = top_reg) and
  1134. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))) or
  1135. ((p.oper[0]^.typ = top_ref) and
  1136. not RegInRef(reg,p.oper[0]^.ref^)))) or
  1137. ((p.opcode = A_POP) and
  1138. (Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg))) or
  1139. ((p.opcode = A_IMUL) and
  1140. (p.ops=3) and
  1141. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1142. (((p.oper[1]^.typ=top_reg) and not(Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg))) or
  1143. ((p.oper[1]^.typ=top_ref) and not(RegInRef(reg,p.oper[1]^.ref^))))) or
  1144. ((((p.opcode = A_IMUL) or
  1145. (p.opcode = A_MUL)) and
  1146. (p.ops=1)) and
  1147. (((p.oper[0]^.typ=top_reg) and not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))) or
  1148. ((p.oper[0]^.typ=top_ref) and not(RegInRef(reg,p.oper[0]^.ref^)))) and
  1149. (((p.opsize=S_B) and Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg))) or
  1150. ((p.opsize=S_W) and Reg1WriteOverwritesReg2Entirely(NR_DX,reg)) or
  1151. ((p.opsize=S_L) and Reg1WriteOverwritesReg2Entirely(NR_EDX,reg))
  1152. {$ifdef x86_64}
  1153. or ((p.opsize=S_Q) and Reg1WriteOverwritesReg2Entirely(NR_RDX,reg))
  1154. {$endif x86_64}
  1155. )) or
  1156. ((p.opcode = A_CWD) and Reg1WriteOverwritesReg2Entirely(NR_DX,reg)) or
  1157. ((p.opcode = A_CDQ) and Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)) or
  1158. {$ifdef x86_64}
  1159. ((p.opcode = A_CQO) and Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)) or
  1160. {$endif x86_64}
  1161. ((p.opcode = A_CBW) and Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg))) or
  1162. {$ifndef x86_64}
  1163. ((p.opcode = A_LDS) and (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^))) or
  1164. ((p.opcode = A_LES) and (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^))) or
  1165. {$endif not x86_64}
  1166. ((p.opcode = A_LFS) and (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^))) or
  1167. ((p.opcode = A_LGS) and (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^))) or
  1168. ((p.opcode = A_LSS) and (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^))) or
  1169. {$ifndef x86_64}
  1170. ((p.opcode = A_AAM) and Reg1WriteOverwritesReg2Entirely(NR_AH,reg)) or
  1171. {$endif not x86_64}
  1172. ((p.opcode = A_LAHF) and Reg1WriteOverwritesReg2Entirely(NR_AH,reg)) or
  1173. ((p.opcode = A_LODSB) and Reg1WriteOverwritesReg2Entirely(NR_AL,reg)) or
  1174. ((p.opcode = A_LODSW) and Reg1WriteOverwritesReg2Entirely(NR_AX,reg)) or
  1175. ((p.opcode = A_LODSD) and Reg1WriteOverwritesReg2Entirely(NR_EAX,reg)) or
  1176. {$ifdef x86_64}
  1177. ((p.opcode = A_LODSQ) and Reg1WriteOverwritesReg2Entirely(NR_RAX,reg)) or
  1178. {$endif x86_64}
  1179. ((p.opcode = A_SETcc) and (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg)) or
  1180. (((p.opcode = A_FSTSW) or
  1181. (p.opcode = A_FNSTSW)) and
  1182. (p.oper[0]^.typ=top_reg) and
  1183. Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg)) or
  1184. (((p.opcode = A_XOR) or (p.opcode = A_SUB) or (p.opcode = A_SBB)) and
  1185. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  1186. (p.oper[0]^.reg=p.oper[1]^.reg) and
  1187. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg));
  1188. end;
  1189. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1190. var
  1191. hp2,hp3 : tai;
  1192. begin
  1193. { some x86-64 issue a NOP before the real exit code }
  1194. if MatchInstruction(p,A_NOP,[]) then
  1195. GetNextInstruction(p,p);
  1196. result:=assigned(p) and (p.typ=ait_instruction) and
  1197. ((taicpu(p).opcode = A_RET) or
  1198. ((taicpu(p).opcode=A_LEAVE) and
  1199. GetNextInstruction(p,hp2) and
  1200. MatchInstruction(hp2,A_RET,[S_NO])
  1201. ) or
  1202. (((taicpu(p).opcode=A_LEA) and
  1203. MatchOpType(taicpu(p),top_ref,top_reg) and
  1204. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1205. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1206. ) and
  1207. GetNextInstruction(p,hp2) and
  1208. MatchInstruction(hp2,A_RET,[S_NO])
  1209. ) or
  1210. ((((taicpu(p).opcode=A_MOV) and
  1211. MatchOpType(taicpu(p),top_reg,top_reg) and
  1212. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1213. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1214. ((taicpu(p).opcode=A_LEA) and
  1215. MatchOpType(taicpu(p),top_ref,top_reg) and
  1216. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1217. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1218. )
  1219. ) and
  1220. GetNextInstruction(p,hp2) and
  1221. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1222. MatchOpType(taicpu(hp2),top_reg) and
  1223. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1224. GetNextInstruction(hp2,hp3) and
  1225. MatchInstruction(hp3,A_RET,[S_NO])
  1226. )
  1227. );
  1228. end;
  1229. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1230. begin
  1231. isFoldableArithOp := False;
  1232. case hp1.opcode of
  1233. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1234. isFoldableArithOp :=
  1235. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1236. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1237. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1238. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1239. (taicpu(hp1).oper[1]^.reg = reg);
  1240. A_INC,A_DEC,A_NEG,A_NOT:
  1241. isFoldableArithOp :=
  1242. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1243. (taicpu(hp1).oper[0]^.reg = reg);
  1244. else
  1245. ;
  1246. end;
  1247. end;
  1248. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1249. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1250. var
  1251. hp2: tai;
  1252. begin
  1253. hp2 := p;
  1254. repeat
  1255. hp2 := tai(hp2.previous);
  1256. if assigned(hp2) and
  1257. (hp2.typ = ait_regalloc) and
  1258. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1259. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1260. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1261. begin
  1262. RemoveInstruction(hp2);
  1263. break;
  1264. end;
  1265. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1266. end;
  1267. begin
  1268. case current_procinfo.procdef.returndef.typ of
  1269. arraydef,recorddef,pointerdef,
  1270. stringdef,enumdef,procdef,objectdef,errordef,
  1271. filedef,setdef,procvardef,
  1272. classrefdef,forwarddef:
  1273. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1274. orddef:
  1275. if current_procinfo.procdef.returndef.size <> 0 then
  1276. begin
  1277. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1278. { for int64/qword }
  1279. if current_procinfo.procdef.returndef.size = 8 then
  1280. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1281. end;
  1282. else
  1283. ;
  1284. end;
  1285. end;
  1286. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1287. var
  1288. hp1,hp2 : tai;
  1289. begin
  1290. result:=false;
  1291. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1292. begin
  1293. { vmova* reg1,reg1
  1294. =>
  1295. <nop> }
  1296. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1297. begin
  1298. RemoveCurrentP(p);
  1299. result:=true;
  1300. exit;
  1301. end
  1302. else if GetNextInstruction(p,hp1) then
  1303. begin
  1304. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1305. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1306. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1307. begin
  1308. { vmova* reg1,reg2
  1309. vmova* reg2,reg3
  1310. dealloc reg2
  1311. =>
  1312. vmova* reg1,reg3 }
  1313. TransferUsedRegs(TmpUsedRegs);
  1314. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1315. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1316. begin
  1317. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1318. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1319. RemoveInstruction(hp1);
  1320. result:=true;
  1321. exit;
  1322. end
  1323. { special case:
  1324. vmova* reg1,reg2
  1325. vmova* reg2,reg1
  1326. =>
  1327. vmova* reg1,reg2 }
  1328. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) then
  1329. begin
  1330. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1331. RemoveInstruction(hp1);
  1332. result:=true;
  1333. exit;
  1334. end
  1335. end
  1336. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  1337. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  1338. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  1339. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  1340. ) and
  1341. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1342. begin
  1343. { vmova* reg1,reg2
  1344. vmovs* reg2,<op>
  1345. dealloc reg2
  1346. =>
  1347. vmovs* reg1,reg3 }
  1348. TransferUsedRegs(TmpUsedRegs);
  1349. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1350. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1351. begin
  1352. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  1353. taicpu(p).opcode:=taicpu(hp1).opcode;
  1354. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1355. RemoveInstruction(hp1);
  1356. result:=true;
  1357. exit;
  1358. end
  1359. end;
  1360. end;
  1361. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  1362. begin
  1363. if MatchInstruction(hp1,[A_VFMADDPD,
  1364. A_VFMADD132PD,
  1365. A_VFMADD132PS,
  1366. A_VFMADD132SD,
  1367. A_VFMADD132SS,
  1368. A_VFMADD213PD,
  1369. A_VFMADD213PS,
  1370. A_VFMADD213SD,
  1371. A_VFMADD213SS,
  1372. A_VFMADD231PD,
  1373. A_VFMADD231PS,
  1374. A_VFMADD231SD,
  1375. A_VFMADD231SS,
  1376. A_VFMADDSUB132PD,
  1377. A_VFMADDSUB132PS,
  1378. A_VFMADDSUB213PD,
  1379. A_VFMADDSUB213PS,
  1380. A_VFMADDSUB231PD,
  1381. A_VFMADDSUB231PS,
  1382. A_VFMSUB132PD,
  1383. A_VFMSUB132PS,
  1384. A_VFMSUB132SD,
  1385. A_VFMSUB132SS,
  1386. A_VFMSUB213PD,
  1387. A_VFMSUB213PS,
  1388. A_VFMSUB213SD,
  1389. A_VFMSUB213SS,
  1390. A_VFMSUB231PD,
  1391. A_VFMSUB231PS,
  1392. A_VFMSUB231SD,
  1393. A_VFMSUB231SS,
  1394. A_VFMSUBADD132PD,
  1395. A_VFMSUBADD132PS,
  1396. A_VFMSUBADD213PD,
  1397. A_VFMSUBADD213PS,
  1398. A_VFMSUBADD231PD,
  1399. A_VFMSUBADD231PS,
  1400. A_VFNMADD132PD,
  1401. A_VFNMADD132PS,
  1402. A_VFNMADD132SD,
  1403. A_VFNMADD132SS,
  1404. A_VFNMADD213PD,
  1405. A_VFNMADD213PS,
  1406. A_VFNMADD213SD,
  1407. A_VFNMADD213SS,
  1408. A_VFNMADD231PD,
  1409. A_VFNMADD231PS,
  1410. A_VFNMADD231SD,
  1411. A_VFNMADD231SS,
  1412. A_VFNMSUB132PD,
  1413. A_VFNMSUB132PS,
  1414. A_VFNMSUB132SD,
  1415. A_VFNMSUB132SS,
  1416. A_VFNMSUB213PD,
  1417. A_VFNMSUB213PS,
  1418. A_VFNMSUB213SD,
  1419. A_VFNMSUB213SS,
  1420. A_VFNMSUB231PD,
  1421. A_VFNMSUB231PS,
  1422. A_VFNMSUB231SD,
  1423. A_VFNMSUB231SS],[S_NO]) and
  1424. { we mix single and double opperations here because we assume that the compiler
  1425. generates vmovapd only after double operations and vmovaps only after single operations }
  1426. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  1427. GetNextInstruction(hp1,hp2) and
  1428. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  1429. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  1430. begin
  1431. TransferUsedRegs(TmpUsedRegs);
  1432. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1433. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1434. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1435. begin
  1436. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  1437. RemoveCurrentP(p, hp1); // <-- Is this actually safe? hp1 is not necessarily the next instruction. [Kit]
  1438. RemoveInstruction(hp2);
  1439. end;
  1440. end
  1441. else if (hp1.typ = ait_instruction) and
  1442. GetNextInstruction(hp1, hp2) and
  1443. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  1444. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  1445. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  1446. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  1447. (((taicpu(p).opcode=A_MOVAPS) and
  1448. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  1449. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  1450. ((taicpu(p).opcode=A_MOVAPD) and
  1451. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  1452. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  1453. ) then
  1454. { change
  1455. movapX reg,reg2
  1456. addsX/subsX/... reg3, reg2
  1457. movapX reg2,reg
  1458. to
  1459. addsX/subsX/... reg3,reg
  1460. }
  1461. begin
  1462. TransferUsedRegs(TmpUsedRegs);
  1463. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1464. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1465. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1466. begin
  1467. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  1468. debug_op2str(taicpu(p).opcode)+' '+
  1469. debug_op2str(taicpu(hp1).opcode)+' '+
  1470. debug_op2str(taicpu(hp2).opcode)+') done',p);
  1471. { we cannot eliminate the first move if
  1472. the operations uses the same register for source and dest }
  1473. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  1474. RemoveCurrentP(p, nil);
  1475. p:=hp1;
  1476. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  1477. RemoveInstruction(hp2);
  1478. result:=true;
  1479. end;
  1480. end;
  1481. end;
  1482. end;
  1483. end;
  1484. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  1485. var
  1486. hp1 : tai;
  1487. begin
  1488. result:=false;
  1489. { replace
  1490. V<Op>X %mreg1,%mreg2,%mreg3
  1491. VMovX %mreg3,%mreg4
  1492. dealloc %mreg3
  1493. by
  1494. V<Op>X %mreg1,%mreg2,%mreg4
  1495. ?
  1496. }
  1497. if GetNextInstruction(p,hp1) and
  1498. { we mix single and double operations here because we assume that the compiler
  1499. generates vmovapd only after double operations and vmovaps only after single operations }
  1500. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  1501. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  1502. (taicpu(hp1).oper[1]^.typ=top_reg) then
  1503. begin
  1504. TransferUsedRegs(TmpUsedRegs);
  1505. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1506. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  1507. begin
  1508. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  1509. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  1510. RemoveInstruction(hp1);
  1511. result:=true;
  1512. end;
  1513. end;
  1514. end;
  1515. { Replaces all references to AOldReg in a memory reference to ANewReg }
  1516. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  1517. var
  1518. OldSupReg: TSuperRegister;
  1519. OldSubReg, MemSubReg: TSubRegister;
  1520. begin
  1521. Result := False;
  1522. { For safety reasons, only check for exact register matches }
  1523. { Check base register }
  1524. if (ref.base = AOldReg) then
  1525. begin
  1526. ref.base := ANewReg;
  1527. Result := True;
  1528. end;
  1529. { Check index register }
  1530. if (ref.index = AOldReg) then
  1531. begin
  1532. ref.index := ANewReg;
  1533. Result := True;
  1534. end;
  1535. end;
  1536. { Replaces all references to AOldReg in an operand to ANewReg }
  1537. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  1538. var
  1539. OldSupReg, NewSupReg: TSuperRegister;
  1540. OldSubReg, NewSubReg, MemSubReg: TSubRegister;
  1541. OldRegType: TRegisterType;
  1542. ThisOper: POper;
  1543. begin
  1544. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  1545. Result := False;
  1546. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  1547. InternalError(2020011801);
  1548. OldSupReg := getsupreg(AOldReg);
  1549. OldSubReg := getsubreg(AOldReg);
  1550. OldRegType := getregtype(AOldReg);
  1551. NewSupReg := getsupreg(ANewReg);
  1552. NewSubReg := getsubreg(ANewReg);
  1553. if OldRegType <> getregtype(ANewReg) then
  1554. InternalError(2020011802);
  1555. if OldSubReg <> NewSubReg then
  1556. InternalError(2020011803);
  1557. case ThisOper^.typ of
  1558. top_reg:
  1559. if (
  1560. (ThisOper^.reg = AOldReg) or
  1561. (
  1562. (OldRegType = R_INTREGISTER) and
  1563. (getsupreg(ThisOper^.reg) = OldSupReg) and
  1564. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  1565. (
  1566. (getsubreg(ThisOper^.reg) <= OldSubReg)
  1567. {$ifndef x86_64}
  1568. and (
  1569. { Under i386 and i8086, ESI, EDI, EBP and ESP
  1570. don't have an 8-bit representation }
  1571. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  1572. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  1573. )
  1574. {$endif x86_64}
  1575. )
  1576. )
  1577. ) then
  1578. begin
  1579. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  1580. Result := True;
  1581. end;
  1582. top_ref:
  1583. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  1584. Result := True;
  1585. else
  1586. ;
  1587. end;
  1588. end;
  1589. { Replaces all references to AOldReg in an instruction to ANewReg }
  1590. function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  1591. const
  1592. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  1593. var
  1594. OperIdx: Integer;
  1595. begin
  1596. Result := False;
  1597. for OperIdx := 0 to p.ops - 1 do
  1598. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) and
  1599. { The shift and rotate instructions can only use CL }
  1600. not (
  1601. (OperIdx = 0) and
  1602. { This second condition just helps to avoid unnecessarily
  1603. calling MatchInstruction for 10 different opcodes }
  1604. (p.oper[0]^.reg = NR_CL) and
  1605. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  1606. ) then
  1607. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  1608. end;
  1609. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean; inline;
  1610. begin
  1611. Result :=
  1612. (ref^.index = NR_NO) and
  1613. (
  1614. {$ifdef x86_64}
  1615. (
  1616. (ref^.base = NR_RIP) and
  1617. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  1618. ) or
  1619. {$endif x86_64}
  1620. (ref^.base = NR_STACK_POINTER_REG) or
  1621. (ref^.base = current_procinfo.framepointer)
  1622. );
  1623. end;
  1624. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  1625. var
  1626. l: asizeint;
  1627. begin
  1628. Result := False;
  1629. { Should have been checked previously }
  1630. if p.opcode <> A_LEA then
  1631. InternalError(2020072501);
  1632. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  1633. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  1634. not(cs_opt_size in current_settings.optimizerswitches) then
  1635. exit;
  1636. with p.oper[0]^.ref^ do
  1637. begin
  1638. if (base <> p.oper[1]^.reg) or
  1639. (index <> NR_NO) or
  1640. assigned(symbol) then
  1641. exit;
  1642. l:=offset;
  1643. if (l=1) and UseIncDec then
  1644. begin
  1645. p.opcode:=A_INC;
  1646. p.loadreg(0,p.oper[1]^.reg);
  1647. p.ops:=1;
  1648. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  1649. end
  1650. else if (l=-1) and UseIncDec then
  1651. begin
  1652. p.opcode:=A_DEC;
  1653. p.loadreg(0,p.oper[1]^.reg);
  1654. p.ops:=1;
  1655. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  1656. end
  1657. else
  1658. begin
  1659. if (l<0) and (l<>-2147483648) then
  1660. begin
  1661. p.opcode:=A_SUB;
  1662. p.loadConst(0,-l);
  1663. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  1664. end
  1665. else
  1666. begin
  1667. p.opcode:=A_ADD;
  1668. p.loadConst(0,l);
  1669. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  1670. end;
  1671. end;
  1672. end;
  1673. Result := True;
  1674. end;
  1675. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  1676. var
  1677. CurrentReg, ReplaceReg: TRegister;
  1678. SubReg: TSubRegister;
  1679. begin
  1680. Result := False;
  1681. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  1682. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  1683. case hp.opcode of
  1684. A_FSTSW, A_FNSTSW,
  1685. A_IN, A_INS, A_OUT, A_OUTS,
  1686. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  1687. { These routines have explicit operands, but they are restricted in
  1688. what they can be (e.g. IN and OUT can only read from AL, AX or
  1689. EAX. }
  1690. Exit;
  1691. A_IMUL:
  1692. begin
  1693. { The 1-operand version writes to implicit registers
  1694. The 2-operand version reads from the first operator, and reads
  1695. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  1696. the 3-operand version reads from a register that it doesn't write to
  1697. }
  1698. case hp.ops of
  1699. 1:
  1700. if (
  1701. (
  1702. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  1703. ) or
  1704. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  1705. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  1706. begin
  1707. Result := True;
  1708. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  1709. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  1710. end;
  1711. 2:
  1712. { Only modify the first parameter }
  1713. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  1714. begin
  1715. Result := True;
  1716. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  1717. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  1718. end;
  1719. 3:
  1720. { Only modify the second parameter }
  1721. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  1722. begin
  1723. Result := True;
  1724. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  1725. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  1726. end;
  1727. else
  1728. InternalError(2020012901);
  1729. end;
  1730. end;
  1731. else
  1732. if (hp.ops > 0) and
  1733. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  1734. begin
  1735. Result := True;
  1736. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  1737. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  1738. end;
  1739. end;
  1740. end;
  1741. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  1742. var
  1743. hp1, hp2, hp3: tai;
  1744. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  1745. begin
  1746. if taicpu(hp1).opcode = signed_movop then
  1747. begin
  1748. if taicpu(p).oper[0]^.val > max_value shr 1 then
  1749. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  1750. end
  1751. else
  1752. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  1753. end;
  1754. var
  1755. GetNextInstruction_p, TempRegUsed: Boolean;
  1756. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  1757. NewSize: topsize;
  1758. CurrentReg: TRegister;
  1759. begin
  1760. Result:=false;
  1761. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  1762. { remove mov reg1,reg1? }
  1763. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  1764. then
  1765. begin
  1766. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  1767. { take care of the register (de)allocs following p }
  1768. RemoveCurrentP(p, hp1);
  1769. Result:=true;
  1770. exit;
  1771. end;
  1772. { All the next optimisations require a next instruction }
  1773. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  1774. Exit;
  1775. { Look for:
  1776. mov %reg1,%reg2
  1777. ??? %reg2,r/m
  1778. Change to:
  1779. mov %reg1,%reg2
  1780. ??? %reg1,r/m
  1781. }
  1782. if MatchOpType(taicpu(p), top_reg, top_reg) then
  1783. begin
  1784. CurrentReg := taicpu(p).oper[1]^.reg;
  1785. if RegReadByInstruction(CurrentReg, hp1) and
  1786. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  1787. begin
  1788. TransferUsedRegs(TmpUsedRegs);
  1789. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  1790. if not RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs) and
  1791. { Just in case something didn't get modified (e.g. an
  1792. implicit register) }
  1793. not RegReadByInstruction(CurrentReg, hp1) then
  1794. begin
  1795. { We can remove the original MOV }
  1796. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  1797. RemoveCurrentp(p, hp1);
  1798. { TmpUsedRegs contains the results of "UpdateUsedRegs(tai(p.Next))" already,
  1799. so just restore it to UsedRegs instead of calculating it again }
  1800. RestoreUsedRegs(TmpUsedRegs);
  1801. Result := True;
  1802. Exit;
  1803. end;
  1804. { If we know a MOV instruction has become a null operation, we might as well
  1805. get rid of it now to save time. }
  1806. if (taicpu(hp1).opcode = A_MOV) and
  1807. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1808. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  1809. { Just being a register is enough to confirm it's a null operation }
  1810. (taicpu(hp1).oper[0]^.typ = top_reg) then
  1811. begin
  1812. Result := True;
  1813. { Speed-up to reduce a pipeline stall... if we had something like...
  1814. movl %eax,%edx
  1815. movw %dx,%ax
  1816. ... the second instruction would change to movw %ax,%ax, but
  1817. given that it is now %ax that's active rather than %eax,
  1818. penalties might occur due to a partial register write, so instead,
  1819. change it to a MOVZX instruction when optimising for speed.
  1820. }
  1821. if not (cs_opt_size in current_settings.optimizerswitches) and
  1822. IsMOVZXAcceptable and
  1823. (taicpu(hp1).opsize < taicpu(p).opsize)
  1824. {$ifdef x86_64}
  1825. { operations already implicitly set the upper 64 bits to zero }
  1826. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  1827. {$endif x86_64}
  1828. then
  1829. begin
  1830. CurrentReg := taicpu(hp1).oper[1]^.reg;
  1831. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  1832. case taicpu(p).opsize of
  1833. S_W:
  1834. if taicpu(hp1).opsize = S_B then
  1835. taicpu(hp1).opsize := S_BL
  1836. else
  1837. InternalError(2020012911);
  1838. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  1839. case taicpu(hp1).opsize of
  1840. S_B:
  1841. taicpu(hp1).opsize := S_BL;
  1842. S_W:
  1843. taicpu(hp1).opsize := S_WL;
  1844. else
  1845. InternalError(2020012912);
  1846. end;
  1847. else
  1848. InternalError(2020012910);
  1849. end;
  1850. taicpu(hp1).opcode := A_MOVZX;
  1851. taicpu(hp1).oper[1]^.reg := newreg(getregtype(CurrentReg), getsupreg(CurrentReg), R_SUBD)
  1852. end
  1853. else
  1854. begin
  1855. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  1856. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  1857. RemoveInstruction(hp1);
  1858. { The instruction after what was hp1 is now the immediate next instruction,
  1859. so we can continue to make optimisations if it's present }
  1860. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  1861. Exit;
  1862. hp1 := hp2;
  1863. end;
  1864. end;
  1865. end;
  1866. end;
  1867. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  1868. overwrites the original destination register. e.g.
  1869. movl ###,%reg2d
  1870. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  1871. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  1872. }
  1873. if (taicpu(p).oper[1]^.typ = top_reg) and
  1874. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  1875. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1876. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  1877. begin
  1878. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  1879. begin
  1880. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  1881. case taicpu(p).oper[0]^.typ of
  1882. top_const:
  1883. { We have something like:
  1884. movb $x, %regb
  1885. movzbl %regb,%regd
  1886. Change to:
  1887. movl $x, %regd
  1888. }
  1889. begin
  1890. case taicpu(hp1).opsize of
  1891. S_BW:
  1892. begin
  1893. convert_mov_value(A_MOVSX, $FF);
  1894. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  1895. taicpu(p).opsize := S_W;
  1896. end;
  1897. S_BL:
  1898. begin
  1899. convert_mov_value(A_MOVSX, $FF);
  1900. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  1901. taicpu(p).opsize := S_L;
  1902. end;
  1903. S_WL:
  1904. begin
  1905. convert_mov_value(A_MOVSX, $FFFF);
  1906. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  1907. taicpu(p).opsize := S_L;
  1908. end;
  1909. {$ifdef x86_64}
  1910. S_BQ:
  1911. begin
  1912. convert_mov_value(A_MOVSX, $FF);
  1913. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  1914. taicpu(p).opsize := S_Q;
  1915. end;
  1916. S_WQ:
  1917. begin
  1918. convert_mov_value(A_MOVSX, $FFFF);
  1919. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  1920. taicpu(p).opsize := S_Q;
  1921. end;
  1922. S_LQ:
  1923. begin
  1924. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  1925. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  1926. taicpu(p).opsize := S_Q;
  1927. end;
  1928. {$endif x86_64}
  1929. else
  1930. { If hp1 was a MOV instruction, it should have been
  1931. optimised already }
  1932. InternalError(2020021001);
  1933. end;
  1934. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  1935. RemoveInstruction(hp1);
  1936. Result := True;
  1937. Exit;
  1938. end;
  1939. top_ref:
  1940. { We have something like:
  1941. movb mem, %regb
  1942. movzbl %regb,%regd
  1943. Change to:
  1944. movzbl mem, %regd
  1945. }
  1946. if (taicpu(p).oper[0]^.ref^.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  1947. begin
  1948. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  1949. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  1950. RemoveCurrentP(p, hp1);
  1951. Result:=True;
  1952. Exit;
  1953. end;
  1954. else
  1955. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  1956. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  1957. Exit;
  1958. end;
  1959. end
  1960. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  1961. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  1962. optimised }
  1963. else
  1964. begin
  1965. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  1966. RemoveCurrentP(p, hp1);
  1967. Result := True;
  1968. Exit;
  1969. end;
  1970. end;
  1971. if (taicpu(hp1).opcode = A_AND) and
  1972. (taicpu(p).oper[1]^.typ = top_reg) and
  1973. MatchOpType(taicpu(hp1),top_const,top_reg) then
  1974. begin
  1975. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  1976. begin
  1977. case taicpu(p).opsize of
  1978. S_L:
  1979. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  1980. begin
  1981. { Optimize out:
  1982. mov x, %reg
  1983. and ffffffffh, %reg
  1984. }
  1985. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  1986. RemoveInstruction(hp1);
  1987. Result:=true;
  1988. exit;
  1989. end;
  1990. S_Q: { TODO: Confirm if this is even possible }
  1991. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  1992. begin
  1993. { Optimize out:
  1994. mov x, %reg
  1995. and ffffffffffffffffh, %reg
  1996. }
  1997. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  1998. RemoveInstruction(hp1);
  1999. Result:=true;
  2000. exit;
  2001. end;
  2002. else
  2003. ;
  2004. end;
  2005. if ((taicpu(p).oper[0]^.typ=top_reg) or
  2006. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  2007. GetNextInstruction(hp1,hp2) and
  2008. MatchInstruction(hp2,A_TEST,[taicpu(p).opsize]) and
  2009. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) and
  2010. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) and
  2011. GetNextInstruction(hp2,hp3) and
  2012. MatchInstruction(hp3,A_Jcc,A_Setcc,[S_NO]) and
  2013. (taicpu(hp3).condition in [C_E,C_NE]) then
  2014. begin
  2015. TransferUsedRegs(TmpUsedRegs);
  2016. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2017. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2018. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2019. begin
  2020. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2021. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2022. taicpu(hp1).opcode:=A_TEST;
  2023. RemoveInstruction(hp2);
  2024. RemoveCurrentP(p, hp1);
  2025. Result:=true;
  2026. exit;
  2027. end;
  2028. end;
  2029. end
  2030. else if IsMOVZXAcceptable and
  2031. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  2032. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  2033. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  2034. then
  2035. begin
  2036. InputVal := debug_operstr(taicpu(p).oper[0]^);
  2037. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  2038. case taicpu(p).opsize of
  2039. S_B:
  2040. if (taicpu(hp1).oper[0]^.val = $ff) then
  2041. begin
  2042. { Convert:
  2043. movb x, %regl movb x, %regl
  2044. andw ffh, %regw andl ffh, %regd
  2045. To:
  2046. movzbw x, %regd movzbl x, %regd
  2047. (Identical registers, just different sizes)
  2048. }
  2049. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  2050. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  2051. case taicpu(hp1).opsize of
  2052. S_W: NewSize := S_BW;
  2053. S_L: NewSize := S_BL;
  2054. {$ifdef x86_64}
  2055. S_Q: NewSize := S_BQ;
  2056. {$endif x86_64}
  2057. else
  2058. InternalError(2018011510);
  2059. end;
  2060. end
  2061. else
  2062. NewSize := S_NO;
  2063. S_W:
  2064. if (taicpu(hp1).oper[0]^.val = $ffff) then
  2065. begin
  2066. { Convert:
  2067. movw x, %regw
  2068. andl ffffh, %regd
  2069. To:
  2070. movzwl x, %regd
  2071. (Identical registers, just different sizes)
  2072. }
  2073. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  2074. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  2075. case taicpu(hp1).opsize of
  2076. S_L: NewSize := S_WL;
  2077. {$ifdef x86_64}
  2078. S_Q: NewSize := S_WQ;
  2079. {$endif x86_64}
  2080. else
  2081. InternalError(2018011511);
  2082. end;
  2083. end
  2084. else
  2085. NewSize := S_NO;
  2086. else
  2087. NewSize := S_NO;
  2088. end;
  2089. if NewSize <> S_NO then
  2090. begin
  2091. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  2092. { The actual optimization }
  2093. taicpu(p).opcode := A_MOVZX;
  2094. taicpu(p).changeopsize(NewSize);
  2095. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  2096. { Safeguard if "and" is followed by a conditional command }
  2097. TransferUsedRegs(TmpUsedRegs);
  2098. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  2099. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  2100. begin
  2101. { At this point, the "and" command is effectively equivalent to
  2102. "test %reg,%reg". This will be handled separately by the
  2103. Peephole Optimizer. [Kit] }
  2104. DebugMsg(SPeepholeOptimization + PreMessage +
  2105. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2106. end
  2107. else
  2108. begin
  2109. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  2110. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2111. RemoveInstruction(hp1);
  2112. end;
  2113. Result := True;
  2114. Exit;
  2115. end;
  2116. end;
  2117. end;
  2118. { Next instruction is also a MOV ? }
  2119. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  2120. begin
  2121. if (taicpu(p).oper[1]^.typ = top_reg) and
  2122. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2123. begin
  2124. CurrentReg := taicpu(p).oper[1]^.reg;
  2125. TransferUsedRegs(TmpUsedRegs);
  2126. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2127. { we have
  2128. mov x, %treg
  2129. mov %treg, y
  2130. }
  2131. if not(RegInOp(CurrentReg, taicpu(hp1).oper[1]^)) then
  2132. if not(RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs)) then
  2133. { we've got
  2134. mov x, %treg
  2135. mov %treg, y
  2136. with %treg is not used after }
  2137. case taicpu(p).oper[0]^.typ Of
  2138. { top_reg is covered by DeepMOVOpt }
  2139. top_const:
  2140. begin
  2141. { change
  2142. mov const, %treg
  2143. mov %treg, y
  2144. to
  2145. mov const, y
  2146. }
  2147. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  2148. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  2149. begin
  2150. if taicpu(hp1).oper[1]^.typ=top_reg then
  2151. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2152. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  2153. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  2154. RemoveInstruction(hp1);
  2155. Result:=true;
  2156. Exit;
  2157. end;
  2158. end;
  2159. top_ref:
  2160. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  2161. begin
  2162. { change
  2163. mov mem, %treg
  2164. mov %treg, %reg
  2165. to
  2166. mov mem, %reg"
  2167. }
  2168. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  2169. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  2170. RemoveInstruction(hp1);
  2171. Result:=true;
  2172. Exit;
  2173. end;
  2174. else
  2175. ;
  2176. end
  2177. else
  2178. { %treg is used afterwards, but all eventualities
  2179. other than the first MOV instruction being a constant
  2180. are covered by DeepMOVOpt, so only check for that }
  2181. if (taicpu(p).oper[0]^.typ = top_const) and
  2182. (
  2183. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  2184. not (cs_opt_size in current_settings.optimizerswitches) or
  2185. (taicpu(hp1).opsize = S_B)
  2186. ) and
  2187. (
  2188. (taicpu(hp1).oper[1]^.typ = top_reg) or
  2189. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  2190. ) then
  2191. begin
  2192. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  2193. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  2194. end;
  2195. end;
  2196. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  2197. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  2198. { mov reg1, mem1 or mov mem1, reg1
  2199. mov mem2, reg2 mov reg2, mem2}
  2200. begin
  2201. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  2202. { mov reg1, mem1 or mov mem1, reg1
  2203. mov mem2, reg1 mov reg2, mem1}
  2204. begin
  2205. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  2206. { Removes the second statement from
  2207. mov reg1, mem1/reg2
  2208. mov mem1/reg2, reg1 }
  2209. begin
  2210. if taicpu(p).oper[0]^.typ=top_reg then
  2211. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  2212. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  2213. RemoveInstruction(hp1);
  2214. Result:=true;
  2215. exit;
  2216. end
  2217. else
  2218. begin
  2219. TransferUsedRegs(TmpUsedRegs);
  2220. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2221. if (taicpu(p).oper[1]^.typ = top_ref) and
  2222. { mov reg1, mem1
  2223. mov mem2, reg1 }
  2224. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  2225. GetNextInstruction(hp1, hp2) and
  2226. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  2227. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  2228. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  2229. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  2230. { change to
  2231. mov reg1, mem1 mov reg1, mem1
  2232. mov mem2, reg1 cmp reg1, mem2
  2233. cmp mem1, reg1
  2234. }
  2235. begin
  2236. RemoveInstruction(hp2);
  2237. taicpu(hp1).opcode := A_CMP;
  2238. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  2239. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  2240. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  2241. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  2242. end;
  2243. end;
  2244. end
  2245. else if (taicpu(p).oper[1]^.typ=top_ref) and
  2246. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  2247. begin
  2248. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  2249. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  2250. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  2251. end
  2252. else
  2253. begin
  2254. TransferUsedRegs(TmpUsedRegs);
  2255. if GetNextInstruction(hp1, hp2) and
  2256. MatchOpType(taicpu(p),top_ref,top_reg) and
  2257. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  2258. (taicpu(hp1).oper[1]^.typ = top_ref) and
  2259. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  2260. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  2261. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  2262. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  2263. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  2264. { mov mem1, %reg1
  2265. mov %reg1, mem2
  2266. mov mem2, reg2
  2267. to:
  2268. mov mem1, reg2
  2269. mov reg2, mem2}
  2270. begin
  2271. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  2272. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  2273. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  2274. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  2275. RemoveInstruction(hp2);
  2276. end
  2277. {$ifdef i386}
  2278. { this is enabled for i386 only, as the rules to create the reg sets below
  2279. are too complicated for x86-64, so this makes this code too error prone
  2280. on x86-64
  2281. }
  2282. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  2283. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  2284. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  2285. { mov mem1, reg1 mov mem1, reg1
  2286. mov reg1, mem2 mov reg1, mem2
  2287. mov mem2, reg2 mov mem2, reg1
  2288. to: to:
  2289. mov mem1, reg1 mov mem1, reg1
  2290. mov mem1, reg2 mov reg1, mem2
  2291. mov reg1, mem2
  2292. or (if mem1 depends on reg1
  2293. and/or if mem2 depends on reg2)
  2294. to:
  2295. mov mem1, reg1
  2296. mov reg1, mem2
  2297. mov reg1, reg2
  2298. }
  2299. begin
  2300. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  2301. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  2302. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  2303. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  2304. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  2305. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  2306. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  2307. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  2308. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  2309. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  2310. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  2311. end
  2312. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  2313. begin
  2314. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  2315. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  2316. end
  2317. else
  2318. begin
  2319. RemoveInstruction(hp2);
  2320. end
  2321. {$endif i386}
  2322. ;
  2323. end;
  2324. end
  2325. { movl [mem1],reg1
  2326. movl [mem1],reg2
  2327. to
  2328. movl [mem1],reg1
  2329. movl reg1,reg2
  2330. }
  2331. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  2332. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2333. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2334. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2335. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2336. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2337. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2338. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2339. begin
  2340. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2341. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2342. end;
  2343. { movl const1,[mem1]
  2344. movl [mem1],reg1
  2345. to
  2346. movl const1,reg1
  2347. movl reg1,[mem1]
  2348. }
  2349. if MatchOpType(Taicpu(p),top_const,top_ref) and
  2350. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  2351. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2352. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  2353. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  2354. begin
  2355. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2356. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  2357. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  2358. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  2359. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  2360. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  2361. Result:=true;
  2362. exit;
  2363. end;
  2364. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  2365. end;
  2366. { search further than the next instruction for a mov }
  2367. if
  2368. { check as much as possible before the expensive GetNextInstructionUsingReg call }
  2369. (taicpu(p).oper[1]^.typ = top_reg) and
  2370. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  2371. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) and
  2372. { we work with hp2 here, so hp1 can be still used later on when
  2373. checking for GetNextInstruction_p }
  2374. { GetNextInstructionUsingReg only searches one instruction ahead unless -O3 is specified }
  2375. GetNextInstructionUsingReg(hp1,hp2,taicpu(p).oper[1]^.reg) and
  2376. (hp2.typ=ait_instruction) then
  2377. begin
  2378. case taicpu(hp2).opcode of
  2379. A_MOV:
  2380. if MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^.reg) and
  2381. ((taicpu(p).oper[0]^.typ=top_const) or
  2382. ((taicpu(p).oper[0]^.typ=top_reg) and
  2383. not(RegUsedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  2384. )
  2385. ) then
  2386. begin
  2387. { we have
  2388. mov x, %treg
  2389. mov %treg, y
  2390. }
  2391. TransferUsedRegs(TmpUsedRegs);
  2392. TmpUsedRegs[R_INTREGISTER].Update(tai(p.Next));
  2393. { We don't need to call UpdateUsedRegs for every instruction between
  2394. p and hp2 because the register we're concerned about will not
  2395. become deallocated (otherwise GetNextInstructionUsingReg would
  2396. have stopped at an earlier instruction). [Kit] }
  2397. TempRegUsed :=
  2398. RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) or
  2399. RegReadByInstruction(taicpu(p).oper[1]^.reg, hp1);
  2400. case taicpu(p).oper[0]^.typ Of
  2401. top_reg:
  2402. begin
  2403. { change
  2404. mov %reg, %treg
  2405. mov %treg, y
  2406. to
  2407. mov %reg, y
  2408. }
  2409. CurrentReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  2410. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  2411. if taicpu(hp2).oper[1]^.reg = CurrentReg then
  2412. begin
  2413. { %reg = y - remove hp2 completely (doing it here instead of relying on
  2414. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  2415. if TempRegUsed then
  2416. begin
  2417. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  2418. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  2419. RemoveInstruction(hp2);
  2420. end
  2421. else
  2422. begin
  2423. RemoveInstruction(hp2);
  2424. { We can remove the original MOV too }
  2425. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  2426. RemoveCurrentP(p, hp1);
  2427. Result:=true;
  2428. Exit;
  2429. end;
  2430. end
  2431. else
  2432. begin
  2433. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  2434. taicpu(hp2).loadReg(0, CurrentReg);
  2435. if TempRegUsed then
  2436. begin
  2437. { Don't remove the first instruction if the temporary register is in use }
  2438. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(CurrentReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  2439. { No need to set Result to True. If there's another instruction later on
  2440. that can be optimised, it will be detected when the main Pass 1 loop
  2441. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  2442. end
  2443. else
  2444. begin
  2445. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  2446. RemoveCurrentP(p, hp1);
  2447. Result:=true;
  2448. Exit;
  2449. end;
  2450. end;
  2451. end;
  2452. top_const:
  2453. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  2454. begin
  2455. { change
  2456. mov const, %treg
  2457. mov %treg, y
  2458. to
  2459. mov const, y
  2460. }
  2461. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  2462. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  2463. begin
  2464. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  2465. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  2466. if TempRegUsed then
  2467. begin
  2468. { Don't remove the first instruction if the temporary register is in use }
  2469. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  2470. { No need to set Result to True. If there's another instruction later on
  2471. that can be optimised, it will be detected when the main Pass 1 loop
  2472. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  2473. end
  2474. else
  2475. begin
  2476. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  2477. RemoveCurrentP(p, hp1);
  2478. Result:=true;
  2479. Exit;
  2480. end;
  2481. end;
  2482. end;
  2483. else
  2484. Internalerror(2019103001);
  2485. end;
  2486. end;
  2487. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  2488. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  2489. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  2490. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2491. begin
  2492. {
  2493. Change from:
  2494. mov ###, %reg
  2495. ...
  2496. movs/z %reg,%reg (Same register, just different sizes)
  2497. To:
  2498. movs/z ###, %reg (Longer version)
  2499. ...
  2500. (remove)
  2501. }
  2502. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  2503. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  2504. { Keep the first instruction as mov if ### is a constant }
  2505. if taicpu(p).oper[0]^.typ = top_const then
  2506. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  2507. else
  2508. begin
  2509. taicpu(p).opcode := taicpu(hp2).opcode;
  2510. taicpu(p).opsize := taicpu(hp2).opsize;
  2511. end;
  2512. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  2513. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  2514. RemoveInstruction(hp2);
  2515. Result := True;
  2516. Exit;
  2517. end;
  2518. else
  2519. ;
  2520. end;
  2521. end;
  2522. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  2523. (taicpu(p).oper[1]^.typ = top_reg) and
  2524. (taicpu(p).opsize = S_L) and
  2525. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  2526. (taicpu(hp2).opcode = A_AND) and
  2527. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  2528. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2529. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  2530. ) then
  2531. begin
  2532. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  2533. begin
  2534. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  2535. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  2536. begin
  2537. { Optimize out:
  2538. mov x, %reg
  2539. and ffffffffh, %reg
  2540. }
  2541. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  2542. RemoveInstruction(hp2);
  2543. Result:=true;
  2544. exit;
  2545. end;
  2546. end;
  2547. end;
  2548. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  2549. x >= RetOffset) as it doesn't do anything (it writes either to a
  2550. parameter or to the temporary storage room for the function
  2551. result)
  2552. }
  2553. if IsExitCode(hp1) and
  2554. (taicpu(p).oper[1]^.typ = top_ref) and
  2555. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  2556. (
  2557. (
  2558. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  2559. not (
  2560. assigned(current_procinfo.procdef.funcretsym) and
  2561. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  2562. )
  2563. ) or
  2564. { Also discard writes to the stack that are below the base pointer,
  2565. as this is temporary storage rather than a function result on the
  2566. stack, say. }
  2567. (
  2568. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  2569. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  2570. )
  2571. ) then
  2572. begin
  2573. RemoveCurrentp(p, hp1);
  2574. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  2575. RemoveLastDeallocForFuncRes(p);
  2576. Result:=true;
  2577. exit;
  2578. end;
  2579. if MatchOpType(taicpu(p),top_reg,top_ref) and
  2580. MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) and
  2581. (taicpu(hp1).oper[1]^.typ = top_ref) and
  2582. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  2583. begin
  2584. { change
  2585. mov reg1, mem1
  2586. test/cmp x, mem1
  2587. to
  2588. mov reg1, mem1
  2589. test/cmp x, reg1
  2590. }
  2591. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  2592. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  2593. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  2594. exit;
  2595. end;
  2596. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  2597. { If the flags register is in use, don't change the instruction to an
  2598. ADD otherwise this will scramble the flags. [Kit] }
  2599. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  2600. begin
  2601. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  2602. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  2603. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  2604. ) or
  2605. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  2606. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  2607. )
  2608. ) then
  2609. { mov reg1,ref
  2610. lea reg2,[reg1,reg2]
  2611. to
  2612. add reg2,ref}
  2613. begin
  2614. TransferUsedRegs(TmpUsedRegs);
  2615. { reg1 may not be used afterwards }
  2616. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  2617. begin
  2618. Taicpu(hp1).opcode:=A_ADD;
  2619. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  2620. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  2621. RemoveCurrentp(p, hp1);
  2622. result:=true;
  2623. exit;
  2624. end;
  2625. end;
  2626. { If the LEA instruction can be converted into an arithmetic instruction,
  2627. it may be possible to then fold it in the next optimisation, otherwise
  2628. there's nothing more that can be optimised here. }
  2629. if not ConvertLEA(taicpu(hp1)) then
  2630. Exit;
  2631. end;
  2632. if (taicpu(p).oper[1]^.typ = top_reg) and
  2633. (hp1.typ = ait_instruction) and
  2634. GetNextInstruction(hp1, hp2) and
  2635. MatchInstruction(hp2,A_MOV,[]) and
  2636. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  2637. (
  2638. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  2639. {$ifdef x86_64}
  2640. or
  2641. (
  2642. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  2643. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  2644. )
  2645. {$endif x86_64}
  2646. ) then
  2647. begin
  2648. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2649. (taicpu(hp2).oper[0]^.typ=top_reg) then
  2650. { change movsX/movzX reg/ref, reg2
  2651. add/sub/or/... reg3/$const, reg2
  2652. mov reg2 reg/ref
  2653. dealloc reg2
  2654. to
  2655. add/sub/or/... reg3/$const, reg/ref }
  2656. begin
  2657. TransferUsedRegs(TmpUsedRegs);
  2658. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2659. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2660. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2661. begin
  2662. { by example:
  2663. movswl %si,%eax movswl %si,%eax p
  2664. decl %eax addl %edx,%eax hp1
  2665. movw %ax,%si movw %ax,%si hp2
  2666. ->
  2667. movswl %si,%eax movswl %si,%eax p
  2668. decw %eax addw %edx,%eax hp1
  2669. movw %ax,%si movw %ax,%si hp2
  2670. }
  2671. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  2672. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  2673. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  2674. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  2675. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  2676. {
  2677. ->
  2678. movswl %si,%eax movswl %si,%eax p
  2679. decw %si addw %dx,%si hp1
  2680. movw %ax,%si movw %ax,%si hp2
  2681. }
  2682. case taicpu(hp1).ops of
  2683. 1:
  2684. begin
  2685. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  2686. if taicpu(hp1).oper[0]^.typ=top_reg then
  2687. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  2688. end;
  2689. 2:
  2690. begin
  2691. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2692. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  2693. (taicpu(hp1).opcode<>A_SHL) and
  2694. (taicpu(hp1).opcode<>A_SHR) and
  2695. (taicpu(hp1).opcode<>A_SAR) then
  2696. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  2697. end;
  2698. else
  2699. internalerror(2008042701);
  2700. end;
  2701. {
  2702. ->
  2703. decw %si addw %dx,%si p
  2704. }
  2705. RemoveInstruction(hp2);
  2706. RemoveCurrentP(p, hp1);
  2707. Result:=True;
  2708. Exit;
  2709. end;
  2710. end;
  2711. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2712. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  2713. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  2714. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  2715. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  2716. )
  2717. {$ifdef i386}
  2718. { byte registers of esi, edi, ebp, esp are not available on i386 }
  2719. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  2720. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  2721. {$endif i386}
  2722. then
  2723. { change movsX/movzX reg/ref, reg2
  2724. add/sub/or/... regX/$const, reg2
  2725. mov reg2, reg3
  2726. dealloc reg2
  2727. to
  2728. movsX/movzX reg/ref, reg3
  2729. add/sub/or/... reg3/$const, reg3
  2730. }
  2731. begin
  2732. TransferUsedRegs(TmpUsedRegs);
  2733. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2734. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2735. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2736. begin
  2737. { by example:
  2738. movswl %si,%eax movswl %si,%eax p
  2739. decl %eax addl %edx,%eax hp1
  2740. movw %ax,%si movw %ax,%si hp2
  2741. ->
  2742. movswl %si,%eax movswl %si,%eax p
  2743. decw %eax addw %edx,%eax hp1
  2744. movw %ax,%si movw %ax,%si hp2
  2745. }
  2746. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  2747. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  2748. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  2749. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  2750. { limit size of constants as well to avoid assembler errors, but
  2751. check opsize to avoid overflow when left shifting the 1 }
  2752. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  2753. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  2754. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  2755. taicpu(p).changeopsize(taicpu(hp2).opsize);
  2756. if taicpu(p).oper[0]^.typ=top_reg then
  2757. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  2758. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  2759. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  2760. {
  2761. ->
  2762. movswl %si,%eax movswl %si,%eax p
  2763. decw %si addw %dx,%si hp1
  2764. movw %ax,%si movw %ax,%si hp2
  2765. }
  2766. case taicpu(hp1).ops of
  2767. 1:
  2768. begin
  2769. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  2770. if taicpu(hp1).oper[0]^.typ=top_reg then
  2771. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  2772. end;
  2773. 2:
  2774. begin
  2775. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2776. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  2777. (taicpu(hp1).opcode<>A_SHL) and
  2778. (taicpu(hp1).opcode<>A_SHR) and
  2779. (taicpu(hp1).opcode<>A_SAR) then
  2780. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  2781. end;
  2782. else
  2783. internalerror(2018111801);
  2784. end;
  2785. {
  2786. ->
  2787. decw %si addw %dx,%si p
  2788. }
  2789. RemoveInstruction(hp2);
  2790. end;
  2791. end;
  2792. end;
  2793. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  2794. GetNextInstruction(hp1, hp2) and
  2795. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  2796. MatchOperand(Taicpu(p).oper[0]^,0) and
  2797. (Taicpu(p).oper[1]^.typ = top_reg) and
  2798. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  2799. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  2800. { mov reg1,0
  2801. bts reg1,operand1 --> mov reg1,operand2
  2802. or reg1,operand2 bts reg1,operand1}
  2803. begin
  2804. Taicpu(hp2).opcode:=A_MOV;
  2805. asml.remove(hp1);
  2806. insertllitem(hp2,hp2.next,hp1);
  2807. RemoveCurrentp(p, hp1);
  2808. Result:=true;
  2809. exit;
  2810. end;
  2811. end;
  2812. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  2813. var
  2814. hp1 : tai;
  2815. begin
  2816. Result:=false;
  2817. if taicpu(p).ops <> 2 then
  2818. exit;
  2819. if GetNextInstruction(p,hp1) and
  2820. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  2821. (taicpu(hp1).ops = 2) then
  2822. begin
  2823. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  2824. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  2825. { movXX reg1, mem1 or movXX mem1, reg1
  2826. movXX mem2, reg2 movXX reg2, mem2}
  2827. begin
  2828. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  2829. { movXX reg1, mem1 or movXX mem1, reg1
  2830. movXX mem2, reg1 movXX reg2, mem1}
  2831. begin
  2832. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  2833. begin
  2834. { Removes the second statement from
  2835. movXX reg1, mem1/reg2
  2836. movXX mem1/reg2, reg1
  2837. }
  2838. if taicpu(p).oper[0]^.typ=top_reg then
  2839. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  2840. { Removes the second statement from
  2841. movXX mem1/reg1, reg2
  2842. movXX reg2, mem1/reg1
  2843. }
  2844. if (taicpu(p).oper[1]^.typ=top_reg) and
  2845. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  2846. begin
  2847. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  2848. RemoveInstruction(hp1);
  2849. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  2850. end
  2851. else
  2852. begin
  2853. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  2854. RemoveInstruction(hp1);
  2855. end;
  2856. Result:=true;
  2857. exit;
  2858. end
  2859. end;
  2860. end;
  2861. end;
  2862. end;
  2863. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  2864. var
  2865. hp1 : tai;
  2866. begin
  2867. result:=false;
  2868. { replace
  2869. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  2870. MovX %mreg2,%mreg1
  2871. dealloc %mreg2
  2872. by
  2873. <Op>X %mreg2,%mreg1
  2874. ?
  2875. }
  2876. if GetNextInstruction(p,hp1) and
  2877. { we mix single and double opperations here because we assume that the compiler
  2878. generates vmovapd only after double operations and vmovaps only after single operations }
  2879. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  2880. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  2881. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2882. (taicpu(p).oper[0]^.typ=top_reg) then
  2883. begin
  2884. TransferUsedRegs(TmpUsedRegs);
  2885. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2886. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2887. begin
  2888. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  2889. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2890. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  2891. RemoveInstruction(hp1);
  2892. result:=true;
  2893. end;
  2894. end;
  2895. end;
  2896. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  2897. var
  2898. hp1, hp2, hp3: tai;
  2899. l : ASizeInt;
  2900. ref: Integer;
  2901. saveref: treference;
  2902. begin
  2903. Result:=false;
  2904. { removes seg register prefixes from LEA operations, as they
  2905. don't do anything}
  2906. taicpu(p).oper[0]^.ref^.Segment:=NR_NO;
  2907. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  2908. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  2909. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  2910. { do not mess with leas acessing the stack pointer }
  2911. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) and
  2912. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  2913. begin
  2914. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  2915. begin
  2916. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  2917. begin
  2918. hp1:=taicpu.op_reg_reg(A_MOV,taicpu(p).opsize,taicpu(p).oper[0]^.ref^.base,
  2919. taicpu(p).oper[1]^.reg);
  2920. InsertLLItem(p.previous,p.next, hp1);
  2921. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',hp1);
  2922. p.free;
  2923. p:=hp1;
  2924. end
  2925. else
  2926. begin
  2927. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  2928. RemoveCurrentP(p);
  2929. end;
  2930. Result:=true;
  2931. exit;
  2932. end
  2933. else if (
  2934. { continue to use lea to adjust the stack pointer,
  2935. it is the recommended way, but only if not optimizing for size }
  2936. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  2937. (cs_opt_size in current_settings.optimizerswitches)
  2938. ) and
  2939. { If the flags register is in use, don't change the instruction
  2940. to an ADD otherwise this will scramble the flags. [Kit] }
  2941. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  2942. ConvertLEA(taicpu(p)) then
  2943. begin
  2944. Result:=true;
  2945. exit;
  2946. end;
  2947. end;
  2948. if GetNextInstruction(p,hp1) and
  2949. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  2950. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  2951. MatchOpType(Taicpu(hp1),top_reg,top_reg) and
  2952. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) then
  2953. begin
  2954. TransferUsedRegs(TmpUsedRegs);
  2955. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2956. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2957. begin
  2958. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2959. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  2960. RemoveInstruction(hp1);
  2961. result:=true;
  2962. end;
  2963. end;
  2964. { changes
  2965. lea offset1(regX), reg1
  2966. lea offset2(reg1), reg1
  2967. to
  2968. lea offset1+offset2(regX), reg1 }
  2969. { for now, we do not mess with the stack pointer, thought it might be usefull to remove
  2970. unneeded lea sequences on the stack pointer, it needs to be tested in detail }
  2971. if (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) and
  2972. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  2973. MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  2974. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) and
  2975. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  2976. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and
  2977. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  2978. (((taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg) and
  2979. (taicpu(p).oper[0]^.ref^.scalefactor in [0,1]) and
  2980. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  2981. (taicpu(p).oper[0]^.ref^.index=taicpu(hp1).oper[0]^.ref^.index) and
  2982. (taicpu(p).oper[0]^.ref^.scalefactor=taicpu(hp1).oper[0]^.ref^.scalefactor)
  2983. ) or
  2984. ((taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg) and
  2985. (taicpu(p).oper[0]^.ref^.index=NR_NO)
  2986. ) or
  2987. ((taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg) and
  2988. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) and
  2989. (taicpu(p).oper[0]^.ref^.base=NR_NO) and
  2990. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1)))
  2991. ) and
  2992. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1)) and
  2993. (taicpu(p).oper[0]^.ref^.relsymbol=taicpu(hp1).oper[0]^.ref^.relsymbol) and
  2994. (taicpu(p).oper[0]^.ref^.segment=taicpu(hp1).oper[0]^.ref^.segment) and
  2995. (taicpu(p).oper[0]^.ref^.symbol=taicpu(hp1).oper[0]^.ref^.symbol) then
  2996. begin
  2997. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea done',p);
  2998. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  2999. begin
  3000. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  3001. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  3002. { if the register is used as index and base, we have to increase for base as well
  3003. and adapt base }
  3004. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  3005. begin
  3006. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  3007. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  3008. end;
  3009. end
  3010. else
  3011. begin
  3012. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  3013. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  3014. end;
  3015. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  3016. begin
  3017. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  3018. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  3019. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  3020. end;
  3021. RemoveCurrentP(p);
  3022. result:=true;
  3023. exit;
  3024. end;
  3025. { changes
  3026. lea <ref1>, reg1
  3027. <op> ...,<ref. with reg1>,...
  3028. to
  3029. <op> ...,<ref1>,... }
  3030. if (taicpu(p).oper[1]^.reg<>current_procinfo.framepointer) and
  3031. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) and
  3032. GetNextInstruction(p,hp1) and
  3033. (hp1.typ=ait_instruction) and
  3034. not(MatchInstruction(hp1,A_LEA,[])) then
  3035. begin
  3036. { find a reference which uses reg1 }
  3037. 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
  3038. ref:=0
  3039. 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
  3040. ref:=1
  3041. else
  3042. ref:=-1;
  3043. if (ref<>-1) and
  3044. { reg1 must be either the base or the index }
  3045. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  3046. begin
  3047. { reg1 can be removed from the reference }
  3048. saveref:=taicpu(hp1).oper[ref]^.ref^;
  3049. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  3050. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  3051. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  3052. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  3053. else
  3054. Internalerror(2019111201);
  3055. { check if the can insert all data of the lea into the second instruction }
  3056. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor in [0,1])) and
  3057. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  3058. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  3059. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  3060. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  3061. ((taicpu(p).oper[0]^.ref^.scalefactor in [0,1]) or (taicpu(hp1).oper[ref]^.ref^.scalefactor in [0,1])) and
  3062. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  3063. {$ifdef x86_64}
  3064. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  3065. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  3066. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  3067. )
  3068. {$endif x86_64}
  3069. then
  3070. begin
  3071. { reg1 might not used by the second instruction after it is remove from the reference }
  3072. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  3073. begin
  3074. TransferUsedRegs(TmpUsedRegs);
  3075. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3076. { reg1 is not updated so it might not be used afterwards }
  3077. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3078. begin
  3079. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  3080. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  3081. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  3082. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  3083. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  3084. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  3085. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  3086. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  3087. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  3088. if not(taicpu(p).oper[0]^.ref^.scalefactor in [0,1]) then
  3089. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  3090. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  3091. RemoveCurrentP(p, hp1);
  3092. result:=true;
  3093. exit;
  3094. end
  3095. end;
  3096. end;
  3097. { recover }
  3098. taicpu(hp1).oper[ref]^.ref^:=saveref;
  3099. end;
  3100. end;
  3101. end;
  3102. function TX86AsmOptimizer.DoSubAddOpt(var p: tai): Boolean;
  3103. var
  3104. hp1 : tai;
  3105. begin
  3106. DoSubAddOpt := False;
  3107. if GetLastInstruction(p, hp1) and
  3108. (hp1.typ = ait_instruction) and
  3109. (taicpu(hp1).opsize = taicpu(p).opsize) then
  3110. case taicpu(hp1).opcode Of
  3111. A_DEC:
  3112. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  3113. MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3114. begin
  3115. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+1);
  3116. RemoveInstruction(hp1);
  3117. end;
  3118. A_SUB:
  3119. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  3120. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  3121. begin
  3122. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val);
  3123. RemoveInstruction(hp1);
  3124. end;
  3125. A_ADD:
  3126. begin
  3127. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  3128. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  3129. begin
  3130. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  3131. RemoveInstruction(hp1);
  3132. if (taicpu(p).oper[0]^.val = 0) then
  3133. begin
  3134. hp1 := tai(p.next);
  3135. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  3136. if not GetLastInstruction(hp1, p) then
  3137. p := hp1;
  3138. DoSubAddOpt := True;
  3139. end
  3140. end;
  3141. end;
  3142. else
  3143. ;
  3144. end;
  3145. end;
  3146. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  3147. {$ifdef i386}
  3148. var
  3149. hp1 : tai;
  3150. {$endif i386}
  3151. begin
  3152. Result:=false;
  3153. { * change "subl $2, %esp; pushw x" to "pushl x"}
  3154. { * change "sub/add const1, reg" or "dec reg" followed by
  3155. "sub const2, reg" to one "sub ..., reg" }
  3156. if MatchOpType(taicpu(p),top_const,top_reg) then
  3157. begin
  3158. {$ifdef i386}
  3159. if (taicpu(p).oper[0]^.val = 2) and
  3160. (taicpu(p).oper[1]^.reg = NR_ESP) and
  3161. { Don't do the sub/push optimization if the sub }
  3162. { comes from setting up the stack frame (JM) }
  3163. (not(GetLastInstruction(p,hp1)) or
  3164. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  3165. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  3166. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  3167. begin
  3168. hp1 := tai(p.next);
  3169. while Assigned(hp1) and
  3170. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  3171. not RegReadByInstruction(NR_ESP,hp1) and
  3172. not RegModifiedByInstruction(NR_ESP,hp1) do
  3173. hp1 := tai(hp1.next);
  3174. if Assigned(hp1) and
  3175. MatchInstruction(hp1,A_PUSH,[S_W]) then
  3176. begin
  3177. taicpu(hp1).changeopsize(S_L);
  3178. if taicpu(hp1).oper[0]^.typ=top_reg then
  3179. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  3180. hp1 := tai(p.next);
  3181. RemoveCurrentp(p, hp1);
  3182. Result:=true;
  3183. exit;
  3184. end;
  3185. end;
  3186. {$endif i386}
  3187. if DoSubAddOpt(p) then
  3188. Result:=true;
  3189. end;
  3190. end;
  3191. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  3192. var
  3193. TmpBool1,TmpBool2 : Boolean;
  3194. tmpref : treference;
  3195. hp1,hp2: tai;
  3196. mask: tcgint;
  3197. begin
  3198. Result:=false;
  3199. { All these optimisations work on "shl/sal const,%reg" }
  3200. if not MatchOpType(taicpu(p),top_const,top_reg) then
  3201. Exit;
  3202. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  3203. (taicpu(p).oper[0]^.val <= 3) then
  3204. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  3205. begin
  3206. { should we check the next instruction? }
  3207. TmpBool1 := True;
  3208. { have we found an add/sub which could be
  3209. integrated in the lea? }
  3210. TmpBool2 := False;
  3211. reference_reset(tmpref,2,[]);
  3212. TmpRef.index := taicpu(p).oper[1]^.reg;
  3213. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  3214. while TmpBool1 and
  3215. GetNextInstruction(p, hp1) and
  3216. (tai(hp1).typ = ait_instruction) and
  3217. ((((taicpu(hp1).opcode = A_ADD) or
  3218. (taicpu(hp1).opcode = A_SUB)) and
  3219. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  3220. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  3221. (((taicpu(hp1).opcode = A_INC) or
  3222. (taicpu(hp1).opcode = A_DEC)) and
  3223. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  3224. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  3225. ((taicpu(hp1).opcode = A_LEA) and
  3226. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  3227. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  3228. (not GetNextInstruction(hp1,hp2) or
  3229. not instrReadsFlags(hp2)) Do
  3230. begin
  3231. TmpBool1 := False;
  3232. if taicpu(hp1).opcode=A_LEA then
  3233. begin
  3234. if (TmpRef.base = NR_NO) and
  3235. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  3236. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  3237. (taicpu(hp1).oper[0]^.ref^.segment=NR_NO) and
  3238. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  3239. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  3240. begin
  3241. TmpBool1 := True;
  3242. TmpBool2 := True;
  3243. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  3244. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  3245. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  3246. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  3247. RemoveInstruction(hp1);
  3248. end
  3249. end
  3250. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  3251. begin
  3252. TmpBool1 := True;
  3253. TmpBool2 := True;
  3254. case taicpu(hp1).opcode of
  3255. A_ADD:
  3256. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  3257. A_SUB:
  3258. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  3259. else
  3260. internalerror(2019050536);
  3261. end;
  3262. RemoveInstruction(hp1);
  3263. end
  3264. else
  3265. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  3266. (((taicpu(hp1).opcode = A_ADD) and
  3267. (TmpRef.base = NR_NO)) or
  3268. (taicpu(hp1).opcode = A_INC) or
  3269. (taicpu(hp1).opcode = A_DEC)) then
  3270. begin
  3271. TmpBool1 := True;
  3272. TmpBool2 := True;
  3273. case taicpu(hp1).opcode of
  3274. A_ADD:
  3275. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  3276. A_INC:
  3277. inc(TmpRef.offset);
  3278. A_DEC:
  3279. dec(TmpRef.offset);
  3280. else
  3281. internalerror(2019050535);
  3282. end;
  3283. RemoveInstruction(hp1);
  3284. end;
  3285. end;
  3286. if TmpBool2
  3287. {$ifndef x86_64}
  3288. or
  3289. ((current_settings.optimizecputype < cpu_Pentium2) and
  3290. (taicpu(p).oper[0]^.val <= 3) and
  3291. not(cs_opt_size in current_settings.optimizerswitches))
  3292. {$endif x86_64}
  3293. then
  3294. begin
  3295. if not(TmpBool2) and
  3296. (taicpu(p).oper[0]^.val=1) then
  3297. begin
  3298. hp1:=taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  3299. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  3300. end
  3301. else
  3302. hp1:=taicpu.op_ref_reg(A_LEA, taicpu(p).opsize, TmpRef,
  3303. taicpu(p).oper[1]^.reg);
  3304. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  3305. InsertLLItem(p.previous, p.next, hp1);
  3306. p.free;
  3307. p := hp1;
  3308. end;
  3309. end
  3310. {$ifndef x86_64}
  3311. else if (current_settings.optimizecputype < cpu_Pentium2) then
  3312. begin
  3313. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  3314. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  3315. (unlike shl, which is only Tairable in the U pipe) }
  3316. if taicpu(p).oper[0]^.val=1 then
  3317. begin
  3318. hp1 := taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  3319. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg);
  3320. InsertLLItem(p.previous, p.next, hp1);
  3321. p.free;
  3322. p := hp1;
  3323. end
  3324. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  3325. "shl $3, %reg" to "lea (,%reg,8), %reg }
  3326. else if (taicpu(p).opsize = S_L) and
  3327. (taicpu(p).oper[0]^.val<= 3) then
  3328. begin
  3329. reference_reset(tmpref,2,[]);
  3330. TmpRef.index := taicpu(p).oper[1]^.reg;
  3331. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  3332. hp1 := taicpu.Op_ref_reg(A_LEA,S_L,TmpRef, taicpu(p).oper[1]^.reg);
  3333. InsertLLItem(p.previous, p.next, hp1);
  3334. p.free;
  3335. p := hp1;
  3336. end;
  3337. end
  3338. {$endif x86_64}
  3339. else if
  3340. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  3341. (
  3342. (
  3343. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  3344. SetAndTest(hp1, hp2)
  3345. {$ifdef x86_64}
  3346. ) or
  3347. (
  3348. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  3349. GetNextInstruction(hp1, hp2) and
  3350. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  3351. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  3352. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  3353. {$endif x86_64}
  3354. )
  3355. ) and
  3356. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  3357. begin
  3358. { Change:
  3359. shl x, %reg1
  3360. mov -(1<<x), %reg2
  3361. and %reg2, %reg1
  3362. Or:
  3363. shl x, %reg1
  3364. and -(1<<x), %reg1
  3365. To just:
  3366. shl x, %reg1
  3367. Since the and operation only zeroes bits that are already zero from the shl operation
  3368. }
  3369. case taicpu(p).oper[0]^.val of
  3370. 8:
  3371. mask:=$FFFFFFFFFFFFFF00;
  3372. 16:
  3373. mask:=$FFFFFFFFFFFF0000;
  3374. 32:
  3375. mask:=$FFFFFFFF00000000;
  3376. 63:
  3377. { Constant pre-calculated to prevent overflow errors with Int64 }
  3378. mask:=$8000000000000000;
  3379. else
  3380. begin
  3381. if taicpu(p).oper[0]^.val >= 64 then
  3382. { Shouldn't happen realistically, since the register
  3383. is guaranteed to be set to zero at this point }
  3384. mask := 0
  3385. else
  3386. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  3387. end;
  3388. end;
  3389. if taicpu(hp1).oper[0]^.val = mask then
  3390. begin
  3391. { Everything checks out, perform the optimisation, as long as
  3392. the FLAGS register isn't being used}
  3393. TransferUsedRegs(TmpUsedRegs);
  3394. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3395. {$ifdef x86_64}
  3396. if (hp1 <> hp2) then
  3397. begin
  3398. { "shl/mov/and" version }
  3399. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3400. { Don't do the optimisation if the FLAGS register is in use }
  3401. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  3402. begin
  3403. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  3404. { Don't remove the 'mov' instruction if its register is used elsewhere }
  3405. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3406. begin
  3407. RemoveInstruction(hp1);
  3408. Result := True;
  3409. end;
  3410. { Only set Result to True if the 'mov' instruction was removed }
  3411. RemoveInstruction(hp2);
  3412. end;
  3413. end
  3414. else
  3415. {$endif x86_64}
  3416. begin
  3417. { "shl/and" version }
  3418. { Don't do the optimisation if the FLAGS register is in use }
  3419. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3420. begin
  3421. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  3422. RemoveInstruction(hp1);
  3423. Result := True;
  3424. end;
  3425. end;
  3426. Exit;
  3427. end
  3428. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  3429. begin
  3430. { Even if the mask doesn't allow for its removal, we might be
  3431. able to optimise the mask for the "shl/and" version, which
  3432. may permit other peephole optimisations }
  3433. {$ifdef DEBUG_AOPTCPU}
  3434. mask := taicpu(hp1).oper[0]^.val and mask;
  3435. if taicpu(hp1).oper[0]^.val <> mask then
  3436. begin
  3437. DebugMsg(
  3438. SPeepholeOptimization +
  3439. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  3440. ' to $' + debug_tostr(mask) +
  3441. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  3442. taicpu(hp1).oper[0]^.val := mask;
  3443. end;
  3444. {$else DEBUG_AOPTCPU}
  3445. { If debugging is off, just set the operand even if it's the same }
  3446. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  3447. {$endif DEBUG_AOPTCPU}
  3448. end;
  3449. end;
  3450. end;
  3451. function TX86AsmOptimizer.OptPass1SETcc(var p: tai): boolean;
  3452. var
  3453. hp1,hp2,next: tai; SetC, JumpC: TAsmCond; Unconditional: Boolean;
  3454. begin
  3455. Result:=false;
  3456. if MatchOpType(taicpu(p),top_reg) and
  3457. GetNextInstruction(p, hp1) and
  3458. ((MatchInstruction(hp1, A_TEST, [S_B]) and
  3459. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  3460. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg)) or
  3461. (MatchInstruction(hp1, A_CMP, [S_B]) and
  3462. MatchOpType(taicpu(hp1),top_const,top_reg) and
  3463. (taicpu(hp1).oper[0]^.val=0))
  3464. ) and
  3465. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  3466. GetNextInstruction(hp1, hp2) and
  3467. MatchInstruction(hp2, A_Jcc, []) then
  3468. { Change from: To:
  3469. set(C) %reg j(~C) label
  3470. test %reg,%reg/cmp $0,%reg
  3471. je label
  3472. set(C) %reg j(C) label
  3473. test %reg,%reg/cmp $0,%reg
  3474. jne label
  3475. }
  3476. begin
  3477. next := tai(p.Next);
  3478. TransferUsedRegs(TmpUsedRegs);
  3479. UpdateUsedRegs(TmpUsedRegs, next);
  3480. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3481. JumpC := taicpu(hp2).condition;
  3482. Unconditional := False;
  3483. if conditions_equal(JumpC, C_E) then
  3484. SetC := inverse_cond(taicpu(p).condition)
  3485. else if conditions_equal(JumpC, C_NE) then
  3486. SetC := taicpu(p).condition
  3487. else
  3488. { We've got something weird here (and inefficent) }
  3489. begin
  3490. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  3491. SetC := C_NONE;
  3492. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  3493. if condition_in(C_AE, JumpC) then
  3494. Unconditional := True
  3495. else
  3496. { Not sure what to do with this jump - drop out }
  3497. Exit;
  3498. end;
  3499. RemoveInstruction(hp1);
  3500. if Unconditional then
  3501. MakeUnconditional(taicpu(hp2))
  3502. else
  3503. begin
  3504. if SetC = C_NONE then
  3505. InternalError(2018061401);
  3506. taicpu(hp2).SetCondition(SetC);
  3507. end;
  3508. if not RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs) then
  3509. begin
  3510. RemoveCurrentp(p, hp2);
  3511. Result := True;
  3512. end;
  3513. DebugMsg(SPeepholeOptimization + 'SETcc/TESTCmp/Jcc -> Jcc',p);
  3514. end;
  3515. end;
  3516. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  3517. { returns true if a "continue" should be done after this optimization }
  3518. var
  3519. hp1, hp2: tai;
  3520. begin
  3521. Result := false;
  3522. if MatchOpType(taicpu(p),top_ref) and
  3523. GetNextInstruction(p, hp1) and
  3524. (hp1.typ = ait_instruction) and
  3525. (((taicpu(hp1).opcode = A_FLD) and
  3526. (taicpu(p).opcode = A_FSTP)) or
  3527. ((taicpu(p).opcode = A_FISTP) and
  3528. (taicpu(hp1).opcode = A_FILD))) and
  3529. MatchOpType(taicpu(hp1),top_ref) and
  3530. (taicpu(hp1).opsize = taicpu(p).opsize) and
  3531. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  3532. begin
  3533. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  3534. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  3535. GetNextInstruction(hp1, hp2) and
  3536. (hp2.typ = ait_instruction) and
  3537. IsExitCode(hp2) and
  3538. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  3539. not(assigned(current_procinfo.procdef.funcretsym) and
  3540. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  3541. (taicpu(p).oper[0]^.ref^.index = NR_NO) then
  3542. begin
  3543. RemoveInstruction(hp1);
  3544. RemoveCurrentP(p, hp2);
  3545. RemoveLastDeallocForFuncRes(p);
  3546. Result := true;
  3547. end
  3548. else
  3549. { we can do this only in fast math mode as fstp is rounding ...
  3550. ... still disabled as it breaks the compiler and/or rtl }
  3551. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  3552. { ... or if another fstp equal to the first one follows }
  3553. (GetNextInstruction(hp1,hp2) and
  3554. (hp2.typ = ait_instruction) and
  3555. (taicpu(p).opcode=taicpu(hp2).opcode) and
  3556. (taicpu(p).opsize=taicpu(hp2).opsize))
  3557. ) and
  3558. { fst can't store an extended/comp value }
  3559. (taicpu(p).opsize <> S_FX) and
  3560. (taicpu(p).opsize <> S_IQ) then
  3561. begin
  3562. if (taicpu(p).opcode = A_FSTP) then
  3563. taicpu(p).opcode := A_FST
  3564. else
  3565. taicpu(p).opcode := A_FIST;
  3566. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  3567. RemoveInstruction(hp1);
  3568. end;
  3569. end;
  3570. end;
  3571. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  3572. var
  3573. hp1, hp2: tai;
  3574. begin
  3575. result:=false;
  3576. if MatchOpType(taicpu(p),top_reg) and
  3577. GetNextInstruction(p, hp1) and
  3578. (hp1.typ = Ait_Instruction) and
  3579. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  3580. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  3581. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  3582. { change to
  3583. fld reg fxxx reg,st
  3584. fxxxp st, st1 (hp1)
  3585. Remark: non commutative operations must be reversed!
  3586. }
  3587. begin
  3588. case taicpu(hp1).opcode Of
  3589. A_FMULP,A_FADDP,
  3590. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  3591. begin
  3592. case taicpu(hp1).opcode Of
  3593. A_FADDP: taicpu(hp1).opcode := A_FADD;
  3594. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  3595. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  3596. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  3597. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  3598. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  3599. else
  3600. internalerror(2019050534);
  3601. end;
  3602. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  3603. taicpu(hp1).oper[1]^.reg := NR_ST;
  3604. RemoveCurrentP(p, hp1);
  3605. Result:=true;
  3606. exit;
  3607. end;
  3608. else
  3609. ;
  3610. end;
  3611. end
  3612. else
  3613. if MatchOpType(taicpu(p),top_ref) and
  3614. GetNextInstruction(p, hp2) and
  3615. (hp2.typ = Ait_Instruction) and
  3616. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3617. (taicpu(p).opsize in [S_FS, S_FL]) and
  3618. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  3619. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  3620. if GetLastInstruction(p, hp1) and
  3621. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  3622. MatchOpType(taicpu(hp1),top_ref) and
  3623. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  3624. if ((taicpu(hp2).opcode = A_FMULP) or
  3625. (taicpu(hp2).opcode = A_FADDP)) then
  3626. { change to
  3627. fld/fst mem1 (hp1) fld/fst mem1
  3628. fld mem1 (p) fadd/
  3629. faddp/ fmul st, st
  3630. fmulp st, st1 (hp2) }
  3631. begin
  3632. RemoveCurrentP(p, hp1);
  3633. if (taicpu(hp2).opcode = A_FADDP) then
  3634. taicpu(hp2).opcode := A_FADD
  3635. else
  3636. taicpu(hp2).opcode := A_FMUL;
  3637. taicpu(hp2).oper[1]^.reg := NR_ST;
  3638. end
  3639. else
  3640. { change to
  3641. fld/fst mem1 (hp1) fld/fst mem1
  3642. fld mem1 (p) fld st}
  3643. begin
  3644. taicpu(p).changeopsize(S_FL);
  3645. taicpu(p).loadreg(0,NR_ST);
  3646. end
  3647. else
  3648. begin
  3649. case taicpu(hp2).opcode Of
  3650. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  3651. { change to
  3652. fld/fst mem1 (hp1) fld/fst mem1
  3653. fld mem2 (p) fxxx mem2
  3654. fxxxp st, st1 (hp2) }
  3655. begin
  3656. case taicpu(hp2).opcode Of
  3657. A_FADDP: taicpu(p).opcode := A_FADD;
  3658. A_FMULP: taicpu(p).opcode := A_FMUL;
  3659. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  3660. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  3661. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  3662. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  3663. else
  3664. internalerror(2019050533);
  3665. end;
  3666. RemoveInstruction(hp2);
  3667. end
  3668. else
  3669. ;
  3670. end
  3671. end
  3672. end;
  3673. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  3674. var
  3675. v: TCGInt;
  3676. hp1, hp2: tai;
  3677. begin
  3678. Result:=false;
  3679. if taicpu(p).oper[0]^.typ = top_const then
  3680. begin
  3681. { Though GetNextInstruction can be factored out, it is an expensive
  3682. call, so delay calling it until we have first checked cheaper
  3683. conditions that are independent of it. }
  3684. if (taicpu(p).oper[0]^.val = 0) and
  3685. (taicpu(p).oper[1]^.typ = top_reg) and
  3686. GetNextInstruction(p, hp1) and
  3687. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  3688. begin
  3689. hp2 := p;
  3690. { When dealing with "cmp $0,%reg", only ZF and SF contain
  3691. anything meaningful once it's converted to "test %reg,%reg";
  3692. additionally, some jumps will always (or never) branch, so
  3693. evaluate every jump immediately following the
  3694. comparison, optimising the conditions if possible.
  3695. Similarly with SETcc... those that are always set to 0 or 1
  3696. are changed to MOV instructions }
  3697. while GetNextInstruction(hp2, hp1) and
  3698. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) do
  3699. begin
  3700. case taicpu(hp1).condition of
  3701. C_B, C_C, C_NAE, C_O:
  3702. { For B/NAE:
  3703. Will never branch since an unsigned integer can never be below zero
  3704. For C/O:
  3705. Result cannot overflow because 0 is being subtracted
  3706. }
  3707. begin
  3708. if taicpu(hp1).opcode = A_Jcc then
  3709. begin
  3710. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  3711. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  3712. RemoveInstruction(hp1);
  3713. { Since hp1 was deleted, hp2 must not be updated }
  3714. Continue;
  3715. end
  3716. else
  3717. begin
  3718. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  3719. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3720. taicpu(hp1).opcode := A_MOV;
  3721. taicpu(hp1).ops := 2;
  3722. taicpu(hp1).condition := C_None;
  3723. taicpu(hp1).opsize := S_B;
  3724. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  3725. taicpu(hp1).loadconst(0, 0);
  3726. end;
  3727. end;
  3728. C_BE, C_NA:
  3729. begin
  3730. { Will only branch if equal to zero }
  3731. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  3732. taicpu(hp1).condition := C_E;
  3733. end;
  3734. C_A, C_NBE:
  3735. begin
  3736. { Will only branch if not equal to zero }
  3737. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  3738. taicpu(hp1).condition := C_NE;
  3739. end;
  3740. C_AE, C_NB, C_NC, C_NO:
  3741. begin
  3742. { Will always branch }
  3743. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  3744. if taicpu(hp1).opcode = A_Jcc then
  3745. begin
  3746. MakeUnconditional(taicpu(hp1));
  3747. { Any jumps/set that follow will now be dead code }
  3748. RemoveDeadCodeAfterJump(taicpu(hp1));
  3749. Break;
  3750. end
  3751. else
  3752. begin
  3753. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3754. taicpu(hp1).opcode := A_MOV;
  3755. taicpu(hp1).ops := 2;
  3756. taicpu(hp1).condition := C_None;
  3757. taicpu(hp1).opsize := S_B;
  3758. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  3759. taicpu(hp1).loadconst(0, 1);
  3760. end;
  3761. end;
  3762. C_None:
  3763. InternalError(2020012201);
  3764. C_P, C_PE, C_NP, C_PO:
  3765. { We can't handle parity checks and they should never be generated
  3766. after a general-purpose CMP (it's used in some floating-point
  3767. comparisons that don't use CMP) }
  3768. InternalError(2020012202);
  3769. else
  3770. { Zero/Equality, Sign, their complements and all of the
  3771. signed comparisons do not need to be converted };
  3772. end;
  3773. hp2 := hp1;
  3774. end;
  3775. { Convert the instruction to a TEST }
  3776. taicpu(p).opcode := A_TEST;
  3777. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  3778. Result := True;
  3779. Exit;
  3780. end
  3781. else if (taicpu(p).oper[0]^.val = 1) and
  3782. GetNextInstruction(p, hp1) and
  3783. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  3784. (taicpu(hp1).condition in [C_L, C_NGE]) then
  3785. begin
  3786. { Convert; To:
  3787. cmp $1,r/m cmp $0,r/m
  3788. jl @lbl jle @lbl
  3789. }
  3790. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  3791. taicpu(p).oper[0]^.val := 0;
  3792. taicpu(hp1).condition := C_LE;
  3793. { If the instruction is now "cmp $0,%reg", convert it to a
  3794. TEST (and effectively do the work of the "cmp $0,%reg" in
  3795. the block above)
  3796. If it's a reference, we can get away with not setting
  3797. Result to True because he haven't evaluated the jump
  3798. in this pass yet.
  3799. }
  3800. if (taicpu(p).oper[1]^.typ = top_reg) then
  3801. begin
  3802. taicpu(p).opcode := A_TEST;
  3803. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  3804. Result := True;
  3805. end;
  3806. Exit;
  3807. end
  3808. else if (taicpu(p).oper[1]^.typ = top_reg) then
  3809. begin
  3810. { cmp register,$8000 neg register
  3811. je target --> jo target
  3812. .... only if register is deallocated before jump.}
  3813. case Taicpu(p).opsize of
  3814. S_B: v:=$80;
  3815. S_W: v:=$8000;
  3816. S_L: v:=qword($80000000);
  3817. { S_Q will never happen: cmp with 64 bit constants is not possible }
  3818. S_Q:
  3819. Exit;
  3820. else
  3821. internalerror(2013112905);
  3822. end;
  3823. if (taicpu(p).oper[0]^.val=v) and
  3824. GetNextInstruction(p, hp1) and
  3825. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  3826. (Taicpu(hp1).condition in [C_E,C_NE]) then
  3827. begin
  3828. TransferUsedRegs(TmpUsedRegs);
  3829. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  3830. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  3831. begin
  3832. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  3833. Taicpu(p).opcode:=A_NEG;
  3834. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  3835. Taicpu(p).clearop(1);
  3836. Taicpu(p).ops:=1;
  3837. if Taicpu(hp1).condition=C_E then
  3838. Taicpu(hp1).condition:=C_O
  3839. else
  3840. Taicpu(hp1).condition:=C_NO;
  3841. Result:=true;
  3842. exit;
  3843. end;
  3844. end;
  3845. end;
  3846. end;
  3847. end;
  3848. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  3849. var
  3850. hp1: tai;
  3851. begin
  3852. {
  3853. remove the second (v)pxor from
  3854. pxor reg,reg
  3855. ...
  3856. pxor reg,reg
  3857. }
  3858. Result:=false;
  3859. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  3860. MatchOpType(taicpu(p),top_reg,top_reg) and
  3861. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  3862. MatchInstruction(taicpu(hp1),taicpu(p).opcode,[taicpu(p).opsize]) and
  3863. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  3864. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  3865. begin
  3866. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  3867. RemoveInstruction(hp1);
  3868. Result:=true;
  3869. Exit;
  3870. end;
  3871. end;
  3872. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  3873. var
  3874. hp1: tai;
  3875. begin
  3876. {
  3877. remove the second (v)pxor from
  3878. (v)pxor reg,reg
  3879. ...
  3880. (v)pxor reg,reg
  3881. }
  3882. Result:=false;
  3883. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  3884. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  3885. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  3886. MatchInstruction(taicpu(hp1),taicpu(p).opcode,[taicpu(p).opsize]) and
  3887. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  3888. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  3889. begin
  3890. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2PXor done',hp1);
  3891. RemoveInstruction(hp1);
  3892. Result:=true;
  3893. Exit;
  3894. end;
  3895. end;
  3896. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  3897. var
  3898. hp1 : tai;
  3899. begin
  3900. result:=false;
  3901. { replace
  3902. IMul const,%mreg1,%mreg2
  3903. Mov %reg2,%mreg3
  3904. dealloc %mreg3
  3905. by
  3906. Imul const,%mreg1,%mreg23
  3907. }
  3908. if (taicpu(p).ops=3) and
  3909. GetNextInstruction(p,hp1) and
  3910. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  3911. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  3912. (taicpu(hp1).oper[1]^.typ=top_reg) then
  3913. begin
  3914. TransferUsedRegs(TmpUsedRegs);
  3915. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3916. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  3917. begin
  3918. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  3919. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  3920. RemoveInstruction(hp1);
  3921. result:=true;
  3922. end;
  3923. end;
  3924. end;
  3925. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  3926. function IsXCHGAcceptable: Boolean; inline;
  3927. begin
  3928. { Always accept if optimising for size }
  3929. Result := (cs_opt_size in current_settings.optimizerswitches) or
  3930. (
  3931. {$ifdef x86_64}
  3932. { XCHG takes 3 cycles on AMD Athlon64 }
  3933. (current_settings.optimizecputype >= cpu_core_i)
  3934. {$else x86_64}
  3935. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  3936. than 3, so it becomes a saving compared to three MOVs with two of
  3937. them able to execute simultaneously. [Kit] }
  3938. (current_settings.optimizecputype >= cpu_PentiumM)
  3939. {$endif x86_64}
  3940. );
  3941. end;
  3942. var
  3943. NewRef: TReference;
  3944. hp1,hp2,hp3: tai;
  3945. {$ifndef x86_64}
  3946. hp4: tai;
  3947. OperIdx: Integer;
  3948. {$endif x86_64}
  3949. begin
  3950. Result:=false;
  3951. if not GetNextInstruction(p, hp1) then
  3952. Exit;
  3953. if MatchInstruction(hp1, A_JMP, [S_NO]) then
  3954. begin
  3955. { Sometimes the MOVs that OptPass2JMP produces can be improved
  3956. further, but we can't just put this jump optimisation in pass 1
  3957. because it tends to perform worse when conditional jumps are
  3958. nearby (e.g. when converting CMOV instructions). [Kit] }
  3959. if OptPass2JMP(hp1) then
  3960. { call OptPass1MOV once to potentially merge any MOVs that were created }
  3961. Result := OptPass1MOV(p)
  3962. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  3963. returned True and the instruction is still a MOV, thus checking
  3964. the optimisations below }
  3965. { If OptPass2JMP returned False, no optimisations were done to
  3966. the jump and there are no further optimisations that can be done
  3967. to the MOV instruction on this pass }
  3968. end
  3969. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  3970. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  3971. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  3972. MatchOpType(taicpu(hp1),top_const,top_reg) and
  3973. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  3974. { be lazy, checking separately for sub would be slightly better }
  3975. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  3976. begin
  3977. { Change:
  3978. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  3979. addl/q $x,%reg2 subl/q $x,%reg2
  3980. To:
  3981. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  3982. }
  3983. TransferUsedRegs(TmpUsedRegs);
  3984. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3985. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3986. if not GetNextInstruction(hp1, hp2) or
  3987. (
  3988. { The FLAGS register isn't always tracked properly, so do not
  3989. perform this optimisation if a conditional statement follows }
  3990. not RegReadByInstruction(NR_DEFAULTFLAGS, hp2) and
  3991. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)
  3992. ) then
  3993. begin
  3994. reference_reset(NewRef, 1, []);
  3995. NewRef.base := taicpu(p).oper[0]^.reg;
  3996. NewRef.scalefactor := 1;
  3997. if taicpu(hp1).opcode = A_ADD then
  3998. begin
  3999. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  4000. NewRef.offset := taicpu(hp1).oper[0]^.val;
  4001. end
  4002. else
  4003. begin
  4004. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  4005. NewRef.offset := -taicpu(hp1).oper[0]^.val;
  4006. end;
  4007. taicpu(p).opcode := A_LEA;
  4008. taicpu(p).loadref(0, NewRef);
  4009. RemoveInstruction(hp1);
  4010. Result := True;
  4011. Exit;
  4012. end;
  4013. end
  4014. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  4015. {$ifdef x86_64}
  4016. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  4017. {$else x86_64}
  4018. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  4019. {$endif x86_64}
  4020. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4021. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  4022. { mov reg1, reg2 mov reg1, reg2
  4023. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  4024. begin
  4025. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  4026. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  4027. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  4028. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  4029. TransferUsedRegs(TmpUsedRegs);
  4030. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4031. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  4032. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  4033. then
  4034. begin
  4035. RemoveCurrentP(p, hp1);
  4036. Result:=true;
  4037. end;
  4038. exit;
  4039. end
  4040. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  4041. IsXCHGAcceptable and
  4042. { XCHG doesn't support 8-byte registers }
  4043. (taicpu(p).opsize <> S_B) and
  4044. MatchInstruction(hp1, A_MOV, []) and
  4045. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4046. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  4047. GetNextInstruction(hp1, hp2) and
  4048. MatchInstruction(hp2, A_MOV, []) and
  4049. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  4050. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  4051. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  4052. begin
  4053. { mov %reg1,%reg2
  4054. mov %reg3,%reg1 -> xchg %reg3,%reg1
  4055. mov %reg2,%reg3
  4056. (%reg2 not used afterwards)
  4057. Note that xchg takes 3 cycles to execute, and generally mov's take
  4058. only one cycle apiece, but the first two mov's can be executed in
  4059. parallel, only taking 2 cycles overall. Older processors should
  4060. therefore only optimise for size. [Kit]
  4061. }
  4062. TransferUsedRegs(TmpUsedRegs);
  4063. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4064. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4065. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  4066. begin
  4067. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  4068. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  4069. taicpu(hp1).opcode := A_XCHG;
  4070. RemoveCurrentP(p, hp1);
  4071. RemoveInstruction(hp2);
  4072. Result := True;
  4073. Exit;
  4074. end;
  4075. end
  4076. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  4077. MatchInstruction(hp1, A_SAR, []) then
  4078. begin
  4079. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  4080. begin
  4081. { the use of %edx also covers the opsize being S_L }
  4082. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  4083. begin
  4084. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  4085. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  4086. (taicpu(p).oper[1]^.reg = NR_EDX) then
  4087. begin
  4088. { Change:
  4089. movl %eax,%edx
  4090. sarl $31,%edx
  4091. To:
  4092. cltd
  4093. }
  4094. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  4095. RemoveInstruction(hp1);
  4096. taicpu(p).opcode := A_CDQ;
  4097. taicpu(p).opsize := S_NO;
  4098. taicpu(p).clearop(1);
  4099. taicpu(p).clearop(0);
  4100. taicpu(p).ops:=0;
  4101. Result := True;
  4102. end
  4103. else if (cs_opt_size in current_settings.optimizerswitches) and
  4104. (taicpu(p).oper[0]^.reg = NR_EDX) and
  4105. (taicpu(p).oper[1]^.reg = NR_EAX) then
  4106. begin
  4107. { Change:
  4108. movl %edx,%eax
  4109. sarl $31,%edx
  4110. To:
  4111. movl %edx,%eax
  4112. cltd
  4113. Note that this creates a dependency between the two instructions,
  4114. so only perform if optimising for size.
  4115. }
  4116. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  4117. taicpu(hp1).opcode := A_CDQ;
  4118. taicpu(hp1).opsize := S_NO;
  4119. taicpu(hp1).clearop(1);
  4120. taicpu(hp1).clearop(0);
  4121. taicpu(hp1).ops:=0;
  4122. end;
  4123. {$ifndef x86_64}
  4124. end
  4125. { Don't bother if CMOV is supported, because a more optimal
  4126. sequence would have been generated for the Abs() intrinsic }
  4127. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  4128. { the use of %eax also covers the opsize being S_L }
  4129. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  4130. (taicpu(p).oper[0]^.reg = NR_EAX) and
  4131. (taicpu(p).oper[1]^.reg = NR_EDX) and
  4132. GetNextInstruction(hp1, hp2) and
  4133. MatchInstruction(hp2, A_XOR, [S_L]) and
  4134. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  4135. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  4136. GetNextInstruction(hp2, hp3) and
  4137. MatchInstruction(hp3, A_SUB, [S_L]) and
  4138. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  4139. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  4140. begin
  4141. { Change:
  4142. movl %eax,%edx
  4143. sarl $31,%eax
  4144. xorl %eax,%edx
  4145. subl %eax,%edx
  4146. (Instruction that uses %edx)
  4147. (%eax deallocated)
  4148. (%edx deallocated)
  4149. To:
  4150. cltd
  4151. xorl %edx,%eax <-- Note the registers have swapped
  4152. subl %edx,%eax
  4153. (Instruction that uses %eax) <-- %eax rather than %edx
  4154. }
  4155. TransferUsedRegs(TmpUsedRegs);
  4156. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4157. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4158. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  4159. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  4160. begin
  4161. if GetNextInstruction(hp3, hp4) and
  4162. not RegModifiedByInstruction(NR_EDX, hp4) and
  4163. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  4164. begin
  4165. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  4166. taicpu(p).opcode := A_CDQ;
  4167. taicpu(p).clearop(1);
  4168. taicpu(p).clearop(0);
  4169. taicpu(p).ops:=0;
  4170. RemoveInstruction(hp1);
  4171. taicpu(hp2).loadreg(0, NR_EDX);
  4172. taicpu(hp2).loadreg(1, NR_EAX);
  4173. taicpu(hp3).loadreg(0, NR_EDX);
  4174. taicpu(hp3).loadreg(1, NR_EAX);
  4175. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  4176. { Convert references in the following instruction (hp4) from %edx to %eax }
  4177. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  4178. with taicpu(hp4).oper[OperIdx]^ do
  4179. case typ of
  4180. top_reg:
  4181. if getsupreg(reg) = RS_EDX then
  4182. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  4183. top_ref:
  4184. begin
  4185. if getsupreg(reg) = RS_EDX then
  4186. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  4187. if getsupreg(reg) = RS_EDX then
  4188. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  4189. end;
  4190. else
  4191. ;
  4192. end;
  4193. end;
  4194. end;
  4195. {$else x86_64}
  4196. end;
  4197. end
  4198. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  4199. { the use of %rdx also covers the opsize being S_Q }
  4200. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  4201. begin
  4202. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  4203. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  4204. (taicpu(p).oper[1]^.reg = NR_RDX) then
  4205. begin
  4206. { Change:
  4207. movq %rax,%rdx
  4208. sarq $63,%rdx
  4209. To:
  4210. cqto
  4211. }
  4212. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  4213. RemoveInstruction(hp1);
  4214. taicpu(p).opcode := A_CQO;
  4215. taicpu(p).opsize := S_NO;
  4216. taicpu(p).clearop(1);
  4217. taicpu(p).clearop(0);
  4218. taicpu(p).ops:=0;
  4219. Result := True;
  4220. end
  4221. else if (cs_opt_size in current_settings.optimizerswitches) and
  4222. (taicpu(p).oper[0]^.reg = NR_RDX) and
  4223. (taicpu(p).oper[1]^.reg = NR_RAX) then
  4224. begin
  4225. { Change:
  4226. movq %rdx,%rax
  4227. sarq $63,%rdx
  4228. To:
  4229. movq %rdx,%rax
  4230. cqto
  4231. Note that this creates a dependency between the two instructions,
  4232. so only perform if optimising for size.
  4233. }
  4234. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  4235. taicpu(hp1).opcode := A_CQO;
  4236. taicpu(hp1).opsize := S_NO;
  4237. taicpu(hp1).clearop(1);
  4238. taicpu(hp1).clearop(0);
  4239. taicpu(hp1).ops:=0;
  4240. {$endif x86_64}
  4241. end;
  4242. end;
  4243. end
  4244. else if MatchInstruction(hp1, A_MOV, []) and
  4245. (taicpu(hp1).oper[1]^.typ = top_reg) then
  4246. { Though "GetNextInstruction" could be factored out, along with
  4247. the instructions that depend on hp2, it is an expensive call that
  4248. should be delayed for as long as possible, hence we do cheaper
  4249. checks first that are likely to be False. [Kit] }
  4250. begin
  4251. if MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  4252. (
  4253. (
  4254. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  4255. (
  4256. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  4257. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  4258. )
  4259. ) or
  4260. (
  4261. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  4262. (
  4263. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  4264. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  4265. )
  4266. )
  4267. ) and
  4268. GetNextInstruction(hp1, hp2) and
  4269. MatchInstruction(hp2, A_SAR, []) and
  4270. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  4271. begin
  4272. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  4273. begin
  4274. { Change:
  4275. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  4276. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  4277. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  4278. To:
  4279. movl r/m,%eax <- Note the change in register
  4280. cltd
  4281. }
  4282. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  4283. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  4284. taicpu(p).loadreg(1, NR_EAX);
  4285. taicpu(hp1).opcode := A_CDQ;
  4286. taicpu(hp1).clearop(1);
  4287. taicpu(hp1).clearop(0);
  4288. taicpu(hp1).ops:=0;
  4289. RemoveInstruction(hp2);
  4290. (*
  4291. {$ifdef x86_64}
  4292. end
  4293. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  4294. { This code sequence does not get generated - however it might become useful
  4295. if and when 128-bit signed integer types make an appearance, so the code
  4296. is kept here for when it is eventually needed. [Kit] }
  4297. (
  4298. (
  4299. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  4300. (
  4301. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  4302. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  4303. )
  4304. ) or
  4305. (
  4306. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  4307. (
  4308. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  4309. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  4310. )
  4311. )
  4312. ) and
  4313. GetNextInstruction(hp1, hp2) and
  4314. MatchInstruction(hp2, A_SAR, [S_Q]) and
  4315. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  4316. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  4317. begin
  4318. { Change:
  4319. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  4320. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  4321. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  4322. To:
  4323. movq r/m,%rax <- Note the change in register
  4324. cqto
  4325. }
  4326. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  4327. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  4328. taicpu(p).loadreg(1, NR_RAX);
  4329. taicpu(hp1).opcode := A_CQO;
  4330. taicpu(hp1).clearop(1);
  4331. taicpu(hp1).clearop(0);
  4332. taicpu(hp1).ops:=0;
  4333. RemoveInstruction(hp2);
  4334. {$endif x86_64}
  4335. *)
  4336. end;
  4337. end;
  4338. {$ifdef x86_64}
  4339. end
  4340. else if (taicpu(p).opsize = S_L) and
  4341. (taicpu(p).oper[1]^.typ = top_reg) and
  4342. (
  4343. MatchInstruction(hp1, A_MOV,[]) and
  4344. (taicpu(hp1).opsize = S_L) and
  4345. (taicpu(hp1).oper[1]^.typ = top_reg)
  4346. ) and (
  4347. GetNextInstruction(hp1, hp2) and
  4348. (tai(hp2).typ=ait_instruction) and
  4349. (taicpu(hp2).opsize = S_Q) and
  4350. (
  4351. (
  4352. MatchInstruction(hp2, A_ADD,[]) and
  4353. (taicpu(hp2).opsize = S_Q) and
  4354. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  4355. (
  4356. (
  4357. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  4358. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  4359. ) or (
  4360. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  4361. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  4362. )
  4363. )
  4364. ) or (
  4365. MatchInstruction(hp2, A_LEA,[]) and
  4366. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  4367. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  4368. (
  4369. (
  4370. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  4371. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  4372. ) or (
  4373. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  4374. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  4375. )
  4376. ) and (
  4377. (
  4378. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  4379. ) or (
  4380. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  4381. )
  4382. )
  4383. )
  4384. )
  4385. ) and (
  4386. GetNextInstruction(hp2, hp3) and
  4387. MatchInstruction(hp3, A_SHR,[]) and
  4388. (taicpu(hp3).opsize = S_Q) and
  4389. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  4390. (taicpu(hp3).oper[0]^.val = 1) and
  4391. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  4392. ) then
  4393. begin
  4394. { Change movl x, reg1d movl x, reg1d
  4395. movl y, reg2d movl y, reg2d
  4396. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  4397. shrq $1, reg1q shrq $1, reg1q
  4398. ( reg1d and reg2d can be switched around in the first two instructions )
  4399. To movl x, reg1d
  4400. addl y, reg1d
  4401. rcrl $1, reg1d
  4402. This corresponds to the common expression (x + y) shr 1, where
  4403. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  4404. smaller code, but won't account for x + y causing an overflow). [Kit]
  4405. }
  4406. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  4407. { Change first MOV command to have the same register as the final output }
  4408. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  4409. else
  4410. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  4411. { Change second MOV command to an ADD command. This is easier than
  4412. converting the existing command because it means we don't have to
  4413. touch 'y', which might be a complicated reference, and also the
  4414. fact that the third command might either be ADD or LEA. [Kit] }
  4415. taicpu(hp1).opcode := A_ADD;
  4416. { Delete old ADD/LEA instruction }
  4417. RemoveInstruction(hp2);
  4418. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  4419. taicpu(hp3).opcode := A_RCR;
  4420. taicpu(hp3).changeopsize(S_L);
  4421. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  4422. {$endif x86_64}
  4423. end;
  4424. end;
  4425. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  4426. var
  4427. hp1 : tai;
  4428. begin
  4429. Result:=false;
  4430. if (taicpu(p).ops >= 2) and
  4431. ((taicpu(p).oper[0]^.typ = top_const) or
  4432. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  4433. (taicpu(p).oper[1]^.typ = top_reg) and
  4434. ((taicpu(p).ops = 2) or
  4435. ((taicpu(p).oper[2]^.typ = top_reg) and
  4436. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  4437. GetLastInstruction(p,hp1) and
  4438. MatchInstruction(hp1,A_MOV,[]) and
  4439. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4440. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4441. begin
  4442. TransferUsedRegs(TmpUsedRegs);
  4443. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  4444. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  4445. { change
  4446. mov reg1,reg2
  4447. imul y,reg2 to imul y,reg1,reg2 }
  4448. begin
  4449. taicpu(p).ops := 3;
  4450. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  4451. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  4452. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  4453. RemoveInstruction(hp1);
  4454. result:=true;
  4455. end;
  4456. end;
  4457. end;
  4458. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  4459. var
  4460. ThisLabel: TAsmLabel;
  4461. begin
  4462. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  4463. ThisLabel.decrefs;
  4464. taicpu(p).opcode := A_RET;
  4465. taicpu(p).is_jmp := false;
  4466. taicpu(p).ops := taicpu(ret_p).ops;
  4467. case taicpu(ret_p).ops of
  4468. 0:
  4469. taicpu(p).clearop(0);
  4470. 1:
  4471. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  4472. else
  4473. internalerror(2016041301);
  4474. end;
  4475. { If the original label is now dead, it might turn out that the label
  4476. immediately follows p. As a result, everything beyond it, which will
  4477. be just some final register configuration and a RET instruction, is
  4478. now dead code. [Kit] }
  4479. { NOTE: This is much faster than introducing a OptPass2RET routine and
  4480. running RemoveDeadCodeAfterJump for each RET instruction, because
  4481. this optimisation rarely happens and most RETs appear at the end of
  4482. routines where there is nothing that can be stripped. [Kit] }
  4483. if not ThisLabel.is_used then
  4484. RemoveDeadCodeAfterJump(p);
  4485. end;
  4486. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  4487. var
  4488. hp1, hp2, hp3: tai;
  4489. OperIdx: Integer;
  4490. begin
  4491. result:=false;
  4492. 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
  4493. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  4494. begin
  4495. hp1:=getlabelwithsym(tasmlabel(taicpu(p).oper[0]^.ref^.symbol));
  4496. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  4497. begin
  4498. case taicpu(hp1).opcode of
  4499. A_RET:
  4500. {
  4501. change
  4502. jmp .L1
  4503. ...
  4504. .L1:
  4505. ret
  4506. into
  4507. ret
  4508. }
  4509. begin
  4510. ConvertJumpToRET(p, hp1);
  4511. result:=true;
  4512. end;
  4513. A_MOV:
  4514. {
  4515. change
  4516. jmp .L1
  4517. ...
  4518. .L1:
  4519. mov ##, ##
  4520. ret
  4521. into
  4522. mov ##, ##
  4523. ret
  4524. }
  4525. { This optimisation tends to increase code size if the pass 1 MOV optimisations aren't
  4526. re-run, so only do this particular optimisation if optimising for speed or when
  4527. optimisations are very in-depth. [Kit] }
  4528. if (current_settings.optimizerswitches * [cs_opt_level3, cs_opt_size]) <> [cs_opt_size] then
  4529. begin
  4530. GetNextInstruction(hp1, hp2);
  4531. if not Assigned(hp2) then
  4532. Exit;
  4533. if (hp2.typ in [ait_label, ait_align]) then
  4534. SkipLabels(hp2,hp2);
  4535. if Assigned(hp2) and MatchInstruction(hp2, A_RET, [S_NO]) then
  4536. begin
  4537. { Duplicate the MOV instruction }
  4538. hp3:=tai(hp1.getcopy);
  4539. asml.InsertBefore(hp3, p);
  4540. { Make sure the compiler knows about any final registers written here }
  4541. for OperIdx := 0 to 1 do
  4542. with taicpu(hp3).oper[OperIdx]^ do
  4543. begin
  4544. case typ of
  4545. top_ref:
  4546. begin
  4547. if (ref^.base <> NR_NO) {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64} then
  4548. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  4549. if (ref^.index <> NR_NO) {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} then
  4550. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  4551. end;
  4552. top_reg:
  4553. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  4554. else
  4555. ;
  4556. end;
  4557. end;
  4558. { Now change the jump into a RET instruction }
  4559. ConvertJumpToRET(p, hp2);
  4560. result:=true;
  4561. end;
  4562. end;
  4563. else
  4564. ;
  4565. end;
  4566. end;
  4567. end;
  4568. end;
  4569. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  4570. begin
  4571. CanBeCMOV:=assigned(p) and
  4572. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  4573. { we can't use cmov ref,reg because
  4574. ref could be nil and cmov still throws an exception
  4575. if ref=nil but the mov isn't done (FK)
  4576. or ((taicpu(p).oper[0]^.typ = top_ref) and
  4577. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  4578. }
  4579. (taicpu(p).oper[1]^.typ = top_reg) and
  4580. (
  4581. (taicpu(p).oper[0]^.typ = top_reg) or
  4582. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  4583. it is not expected that this can cause a seg. violation }
  4584. (
  4585. (taicpu(p).oper[0]^.typ = top_ref) and
  4586. IsRefSafe(taicpu(p).oper[0]^.ref)
  4587. )
  4588. );
  4589. end;
  4590. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  4591. var
  4592. hp1,hp2,hp3,hp4,hpmov2: tai;
  4593. carryadd_opcode : TAsmOp;
  4594. l : Longint;
  4595. condition : TAsmCond;
  4596. symbol: TAsmSymbol;
  4597. reg: tsuperregister;
  4598. regavailable: Boolean;
  4599. begin
  4600. result:=false;
  4601. symbol:=nil;
  4602. if GetNextInstruction(p,hp1) then
  4603. begin
  4604. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  4605. if (hp1.typ=ait_instruction) and
  4606. GetNextInstruction(hp1,hp2) and
  4607. ((hp2.typ=ait_label) or
  4608. { trick to skip align }
  4609. ((hp2.typ=ait_align) and GetNextInstruction(hp2,hp2) and (hp2.typ=ait_label))
  4610. ) and
  4611. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  4612. { jb @@1 cmc
  4613. inc/dec operand --> adc/sbb operand,0
  4614. @@1:
  4615. ... and ...
  4616. jnb @@1
  4617. inc/dec operand --> adc/sbb operand,0
  4618. @@1: }
  4619. begin
  4620. carryadd_opcode:=A_NONE;
  4621. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  4622. begin
  4623. if (Taicpu(hp1).opcode=A_INC) or
  4624. ((Taicpu(hp1).opcode=A_ADD) and
  4625. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  4626. (Taicpu(hp1).oper[0]^.val=1)
  4627. ) then
  4628. carryadd_opcode:=A_ADC;
  4629. if (Taicpu(hp1).opcode=A_DEC) or
  4630. ((Taicpu(hp1).opcode=A_SUB) and
  4631. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  4632. (Taicpu(hp1).oper[0]^.val=1)
  4633. ) then
  4634. carryadd_opcode:=A_SBB;
  4635. if carryadd_opcode<>A_NONE then
  4636. begin
  4637. Taicpu(p).clearop(0);
  4638. Taicpu(p).ops:=0;
  4639. Taicpu(p).is_jmp:=false;
  4640. Taicpu(p).opcode:=A_CMC;
  4641. Taicpu(p).condition:=C_NONE;
  4642. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  4643. Taicpu(hp1).ops:=2;
  4644. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  4645. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  4646. else
  4647. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  4648. Taicpu(hp1).loadconst(0,0);
  4649. Taicpu(hp1).opcode:=carryadd_opcode;
  4650. result:=true;
  4651. exit;
  4652. end;
  4653. end
  4654. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  4655. begin
  4656. if (Taicpu(hp1).opcode=A_INC) or
  4657. ((Taicpu(hp1).opcode=A_ADD) and
  4658. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  4659. (Taicpu(hp1).oper[0]^.val=1)
  4660. ) then
  4661. carryadd_opcode:=A_ADC;
  4662. if (Taicpu(hp1).opcode=A_DEC) or
  4663. ((Taicpu(hp1).opcode=A_SUB) and
  4664. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  4665. (Taicpu(hp1).oper[0]^.val=1)
  4666. ) then
  4667. carryadd_opcode:=A_SBB;
  4668. if carryadd_opcode<>A_NONE then
  4669. begin
  4670. Taicpu(hp1).ops:=2;
  4671. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  4672. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  4673. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  4674. else
  4675. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  4676. Taicpu(hp1).loadconst(0,0);
  4677. Taicpu(hp1).opcode:=carryadd_opcode;
  4678. RemoveCurrentP(p, hp1);
  4679. result:=true;
  4680. exit;
  4681. end;
  4682. end
  4683. {
  4684. jcc @@1 setcc tmpreg
  4685. inc/dec/add/sub operand -> (movzx tmpreg)
  4686. @@1: add/sub tmpreg,operand
  4687. While this increases code size slightly, it makes the code much faster if the
  4688. jump is unpredictable
  4689. }
  4690. else if not(cs_opt_size in current_settings.optimizerswitches) and
  4691. ((((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  4692. (Taicpu(hp1).oper[0]^.typ=top_const) and
  4693. (Taicpu(hp1).oper[1]^.typ=top_reg) and
  4694. (Taicpu(hp1).oper[0]^.val=1)) or
  4695. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  4696. ) then
  4697. begin
  4698. TransferUsedRegs(TmpUsedRegs);
  4699. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4700. { search for an available register which is volatile }
  4701. regavailable:=false;
  4702. for reg in tcpuregisterset do
  4703. begin
  4704. if (reg in paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption)) and
  4705. not(reg in TmpUsedRegs[R_INTREGISTER].GetUsedRegs) and
  4706. not(RegInInstruction(newreg(R_INTREGISTER,reg,R_SUBL),hp1))
  4707. {$ifdef i386}
  4708. and (reg in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  4709. {$endif i386}
  4710. then
  4711. begin
  4712. regavailable:=true;
  4713. break;
  4714. end;
  4715. end;
  4716. if regavailable then
  4717. begin
  4718. Taicpu(p).clearop(0);
  4719. Taicpu(p).ops:=1;
  4720. Taicpu(p).is_jmp:=false;
  4721. Taicpu(p).opcode:=A_SETcc;
  4722. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  4723. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  4724. Taicpu(p).loadreg(0,newreg(R_INTREGISTER,reg,R_SUBL));
  4725. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  4726. begin
  4727. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  4728. R_SUBW:
  4729. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,newreg(R_INTREGISTER,reg,R_SUBL),
  4730. newreg(R_INTREGISTER,reg,R_SUBW));
  4731. R_SUBD,
  4732. R_SUBQ:
  4733. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,newreg(R_INTREGISTER,reg,R_SUBL),
  4734. newreg(R_INTREGISTER,reg,R_SUBD));
  4735. else
  4736. Internalerror(2020030601);
  4737. end;
  4738. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  4739. asml.InsertAfter(hp2,p);
  4740. end;
  4741. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  4742. begin
  4743. Taicpu(hp1).ops:=2;
  4744. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  4745. end;
  4746. Taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,reg,getsubreg(Taicpu(hp1).oper[1]^.reg)));
  4747. AllocRegBetween(newreg(R_INTREGISTER,reg,getsubreg(Taicpu(hp1).oper[1]^.reg)),p,hp1,UsedRegs);
  4748. end;
  4749. end;
  4750. end;
  4751. { Detect the following:
  4752. jmp<cond> @Lbl1
  4753. jmp @Lbl2
  4754. ...
  4755. @Lbl1:
  4756. ret
  4757. Change to:
  4758. jmp<inv_cond> @Lbl2
  4759. ret
  4760. }
  4761. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  4762. begin
  4763. hp2:=getlabelwithsym(TAsmLabel(symbol));
  4764. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  4765. MatchInstruction(hp2,A_RET,[S_NO]) then
  4766. begin
  4767. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  4768. { Change label address to that of the unconditional jump }
  4769. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  4770. TAsmLabel(symbol).DecRefs;
  4771. taicpu(hp1).opcode := A_RET;
  4772. taicpu(hp1).is_jmp := false;
  4773. taicpu(hp1).ops := taicpu(hp2).ops;
  4774. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  4775. case taicpu(hp2).ops of
  4776. 0:
  4777. taicpu(hp1).clearop(0);
  4778. 1:
  4779. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  4780. else
  4781. internalerror(2016041302);
  4782. end;
  4783. end;
  4784. end;
  4785. end;
  4786. {$ifndef i8086}
  4787. if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  4788. begin
  4789. { check for
  4790. jCC xxx
  4791. <several movs>
  4792. xxx:
  4793. }
  4794. l:=0;
  4795. GetNextInstruction(p, hp1);
  4796. while assigned(hp1) and
  4797. CanBeCMOV(hp1) and
  4798. { stop on labels }
  4799. not(hp1.typ=ait_label) do
  4800. begin
  4801. inc(l);
  4802. GetNextInstruction(hp1,hp1);
  4803. end;
  4804. if assigned(hp1) then
  4805. begin
  4806. if FindLabel(tasmlabel(symbol),hp1) then
  4807. begin
  4808. if (l<=4) and (l>0) then
  4809. begin
  4810. condition:=inverse_cond(taicpu(p).condition);
  4811. GetNextInstruction(p,hp1);
  4812. repeat
  4813. if not Assigned(hp1) then
  4814. InternalError(2018062900);
  4815. taicpu(hp1).opcode:=A_CMOVcc;
  4816. taicpu(hp1).condition:=condition;
  4817. UpdateUsedRegs(hp1);
  4818. GetNextInstruction(hp1,hp1);
  4819. until not(CanBeCMOV(hp1));
  4820. { Remember what hp1 is in case there's multiple aligns to get rid of }
  4821. hp2 := hp1;
  4822. repeat
  4823. if not Assigned(hp2) then
  4824. InternalError(2018062910);
  4825. case hp2.typ of
  4826. ait_label:
  4827. { What we expected - break out of the loop (it won't be a dead label at the top of
  4828. a cluster because that was optimised at an earlier stage) }
  4829. Break;
  4830. ait_align:
  4831. { Go to the next entry until a label is found (may be multiple aligns before it) }
  4832. begin
  4833. hp2 := tai(hp2.Next);
  4834. Continue;
  4835. end;
  4836. else
  4837. begin
  4838. { Might be a comment or temporary allocation entry }
  4839. if not (hp2.typ in SkipInstr) then
  4840. InternalError(2018062911);
  4841. hp2 := tai(hp2.Next);
  4842. Continue;
  4843. end;
  4844. end;
  4845. until False;
  4846. { Now we can safely decrement the reference count }
  4847. tasmlabel(symbol).decrefs;
  4848. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  4849. { Remove the original jump }
  4850. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  4851. GetNextInstruction(hp2, p); { Instruction after the label }
  4852. { Remove the label if this is its final reference }
  4853. if (tasmlabel(symbol).getrefs=0) then
  4854. StripLabelFast(hp1);
  4855. if Assigned(p) then
  4856. begin
  4857. UpdateUsedRegs(p);
  4858. result:=true;
  4859. end;
  4860. exit;
  4861. end;
  4862. end
  4863. else
  4864. begin
  4865. { check further for
  4866. jCC xxx
  4867. <several movs 1>
  4868. jmp yyy
  4869. xxx:
  4870. <several movs 2>
  4871. yyy:
  4872. }
  4873. { hp2 points to jmp yyy }
  4874. hp2:=hp1;
  4875. { skip hp1 to xxx (or an align right before it) }
  4876. GetNextInstruction(hp1, hp1);
  4877. if assigned(hp2) and
  4878. assigned(hp1) and
  4879. (l<=3) and
  4880. (hp2.typ=ait_instruction) and
  4881. (taicpu(hp2).is_jmp) and
  4882. (taicpu(hp2).condition=C_None) and
  4883. { real label and jump, no further references to the
  4884. label are allowed }
  4885. (tasmlabel(symbol).getrefs=1) and
  4886. FindLabel(tasmlabel(symbol),hp1) then
  4887. begin
  4888. l:=0;
  4889. { skip hp1 to <several moves 2> }
  4890. if (hp1.typ = ait_align) then
  4891. GetNextInstruction(hp1, hp1);
  4892. GetNextInstruction(hp1, hpmov2);
  4893. hp1 := hpmov2;
  4894. while assigned(hp1) and
  4895. CanBeCMOV(hp1) do
  4896. begin
  4897. inc(l);
  4898. GetNextInstruction(hp1, hp1);
  4899. end;
  4900. { hp1 points to yyy (or an align right before it) }
  4901. hp3 := hp1;
  4902. if assigned(hp1) and
  4903. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  4904. begin
  4905. condition:=inverse_cond(taicpu(p).condition);
  4906. GetNextInstruction(p,hp1);
  4907. repeat
  4908. taicpu(hp1).opcode:=A_CMOVcc;
  4909. taicpu(hp1).condition:=condition;
  4910. UpdateUsedRegs(hp1);
  4911. GetNextInstruction(hp1,hp1);
  4912. until not(assigned(hp1)) or
  4913. not(CanBeCMOV(hp1));
  4914. condition:=inverse_cond(condition);
  4915. hp1 := hpmov2;
  4916. { hp1 is now at <several movs 2> }
  4917. while Assigned(hp1) and CanBeCMOV(hp1) do
  4918. begin
  4919. taicpu(hp1).opcode:=A_CMOVcc;
  4920. taicpu(hp1).condition:=condition;
  4921. UpdateUsedRegs(hp1);
  4922. GetNextInstruction(hp1,hp1);
  4923. end;
  4924. hp1 := p;
  4925. { Get first instruction after label }
  4926. GetNextInstruction(hp3, p);
  4927. if assigned(p) and (hp3.typ = ait_align) then
  4928. GetNextInstruction(p, p);
  4929. { Don't dereference yet, as doing so will cause
  4930. GetNextInstruction to skip the label and
  4931. optional align marker. [Kit] }
  4932. GetNextInstruction(hp2, hp4);
  4933. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  4934. { remove jCC }
  4935. RemoveInstruction(hp1);
  4936. { Now we can safely decrement it }
  4937. tasmlabel(symbol).decrefs;
  4938. { Remove label xxx (it will have a ref of zero due to the initial check }
  4939. StripLabelFast(hp4);
  4940. { remove jmp }
  4941. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  4942. RemoveInstruction(hp2);
  4943. { As before, now we can safely decrement it }
  4944. tasmlabel(symbol).decrefs;
  4945. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  4946. if tasmlabel(symbol).getrefs = 0 then
  4947. StripLabelFast(hp3);
  4948. if Assigned(p) then
  4949. begin
  4950. UpdateUsedRegs(p);
  4951. result:=true;
  4952. end;
  4953. exit;
  4954. end;
  4955. end;
  4956. end;
  4957. end;
  4958. end;
  4959. {$endif i8086}
  4960. end;
  4961. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  4962. var
  4963. hp1,hp2: tai;
  4964. reg_and_hp1_is_instr: Boolean;
  4965. begin
  4966. result:=false;
  4967. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  4968. GetNextInstruction(p,hp1) and
  4969. (hp1.typ = ait_instruction);
  4970. if reg_and_hp1_is_instr and
  4971. (
  4972. (taicpu(hp1).opcode <> A_LEA) or
  4973. { If the LEA instruction can be converted into an arithmetic instruction,
  4974. it may be possible to then fold it. }
  4975. (
  4976. { If the flags register is in use, don't change the instruction
  4977. to an ADD otherwise this will scramble the flags. [Kit] }
  4978. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  4979. ConvertLEA(taicpu(hp1))
  4980. )
  4981. ) and
  4982. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  4983. GetNextInstruction(hp1,hp2) and
  4984. MatchInstruction(hp2,A_MOV,[]) and
  4985. (taicpu(hp2).oper[0]^.typ = top_reg) and
  4986. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  4987. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  4988. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  4989. {$ifdef i386}
  4990. { not all registers have byte size sub registers on i386 }
  4991. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  4992. {$endif i386}
  4993. (((taicpu(hp1).ops=2) and
  4994. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  4995. ((taicpu(hp1).ops=1) and
  4996. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  4997. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  4998. begin
  4999. { change movsX/movzX reg/ref, reg2
  5000. add/sub/or/... reg3/$const, reg2
  5001. mov reg2 reg/ref
  5002. to add/sub/or/... reg3/$const, reg/ref }
  5003. { by example:
  5004. movswl %si,%eax movswl %si,%eax p
  5005. decl %eax addl %edx,%eax hp1
  5006. movw %ax,%si movw %ax,%si hp2
  5007. ->
  5008. movswl %si,%eax movswl %si,%eax p
  5009. decw %eax addw %edx,%eax hp1
  5010. movw %ax,%si movw %ax,%si hp2
  5011. }
  5012. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  5013. {
  5014. ->
  5015. movswl %si,%eax movswl %si,%eax p
  5016. decw %si addw %dx,%si hp1
  5017. movw %ax,%si movw %ax,%si hp2
  5018. }
  5019. case taicpu(hp1).ops of
  5020. 1:
  5021. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  5022. 2:
  5023. begin
  5024. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  5025. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  5026. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  5027. end;
  5028. else
  5029. internalerror(2008042701);
  5030. end;
  5031. {
  5032. ->
  5033. decw %si addw %dx,%si p
  5034. }
  5035. DebugMsg(SPeepholeOptimization + 'var3',p);
  5036. RemoveCurrentP(p, hp1);
  5037. RemoveInstruction(hp2);
  5038. end
  5039. else if reg_and_hp1_is_instr and
  5040. (taicpu(hp1).opcode = A_MOV) and
  5041. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5042. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  5043. {$ifdef x86_64}
  5044. { check for implicit extension to 64 bit }
  5045. or
  5046. ((taicpu(p).opsize in [S_BL,S_WL]) and
  5047. (taicpu(hp1).opsize=S_Q) and
  5048. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  5049. )
  5050. {$endif x86_64}
  5051. )
  5052. then
  5053. begin
  5054. { change
  5055. movx %reg1,%reg2
  5056. mov %reg2,%reg3
  5057. dealloc %reg2
  5058. into
  5059. movx %reg,%reg3
  5060. }
  5061. TransferUsedRegs(TmpUsedRegs);
  5062. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5063. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5064. begin
  5065. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  5066. {$ifdef x86_64}
  5067. if (taicpu(p).opsize in [S_BL,S_WL]) and
  5068. (taicpu(hp1).opsize=S_Q) then
  5069. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  5070. else
  5071. {$endif x86_64}
  5072. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  5073. RemoveInstruction(hp1);
  5074. end;
  5075. end
  5076. else if reg_and_hp1_is_instr and
  5077. (taicpu(p).oper[0]^.typ = top_reg) and
  5078. (
  5079. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  5080. ) and
  5081. (taicpu(hp1).oper[0]^.typ = top_const) and
  5082. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  5083. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5084. { Minimum shift value allowed is the bit difference between the sizes }
  5085. (taicpu(hp1).oper[0]^.val >=
  5086. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  5087. 8 * (
  5088. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  5089. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  5090. )
  5091. ) then
  5092. begin
  5093. { For:
  5094. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  5095. shl/sal ##, %reg1
  5096. Remove the movsx/movzx instruction if the shift overwrites the
  5097. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  5098. }
  5099. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  5100. RemoveCurrentP(p, hp1);
  5101. Result := True;
  5102. Exit;
  5103. end
  5104. else if taicpu(p).opcode=A_MOVZX then
  5105. begin
  5106. { removes superfluous And's after movzx's }
  5107. if reg_and_hp1_is_instr and
  5108. (taicpu(hp1).opcode = A_AND) and
  5109. MatchOpType(taicpu(hp1),top_const,top_reg) and
  5110. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  5111. {$ifdef x86_64}
  5112. { check for implicit extension to 64 bit }
  5113. or
  5114. ((taicpu(p).opsize in [S_BL,S_WL]) and
  5115. (taicpu(hp1).opsize=S_Q) and
  5116. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  5117. )
  5118. {$endif x86_64}
  5119. )
  5120. then
  5121. begin
  5122. case taicpu(p).opsize Of
  5123. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  5124. if (taicpu(hp1).oper[0]^.val = $ff) then
  5125. begin
  5126. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  5127. RemoveInstruction(hp1);
  5128. Result:=true;
  5129. exit;
  5130. end;
  5131. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  5132. if (taicpu(hp1).oper[0]^.val = $ffff) then
  5133. begin
  5134. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  5135. RemoveInstruction(hp1);
  5136. Result:=true;
  5137. exit;
  5138. end;
  5139. {$ifdef x86_64}
  5140. S_LQ:
  5141. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  5142. begin
  5143. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  5144. RemoveInstruction(hp1);
  5145. Result:=true;
  5146. exit;
  5147. end;
  5148. {$endif x86_64}
  5149. else
  5150. ;
  5151. end;
  5152. { we cannot get rid of the and, but can we get rid of the movz ?}
  5153. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  5154. begin
  5155. case taicpu(p).opsize Of
  5156. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  5157. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  5158. begin
  5159. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  5160. RemoveCurrentP(p,hp1);
  5161. Result:=true;
  5162. exit;
  5163. end;
  5164. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  5165. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  5166. begin
  5167. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  5168. RemoveCurrentP(p,hp1);
  5169. Result:=true;
  5170. exit;
  5171. end;
  5172. {$ifdef x86_64}
  5173. S_LQ:
  5174. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  5175. begin
  5176. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  5177. RemoveCurrentP(p,hp1);
  5178. Result:=true;
  5179. exit;
  5180. end;
  5181. {$endif x86_64}
  5182. else
  5183. ;
  5184. end;
  5185. end;
  5186. end;
  5187. { changes some movzx constructs to faster synonyms (all examples
  5188. are given with eax/ax, but are also valid for other registers)}
  5189. if MatchOpType(taicpu(p),top_reg,top_reg) then
  5190. begin
  5191. case taicpu(p).opsize of
  5192. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  5193. (the machine code is equivalent to movzbl %al,%eax), but the
  5194. code generator still generates that assembler instruction and
  5195. it is silently converted. This should probably be checked.
  5196. [Kit] }
  5197. S_BW:
  5198. begin
  5199. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  5200. (
  5201. not IsMOVZXAcceptable
  5202. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  5203. or (
  5204. (cs_opt_size in current_settings.optimizerswitches) and
  5205. (taicpu(p).oper[1]^.reg = NR_AX)
  5206. )
  5207. ) then
  5208. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  5209. begin
  5210. DebugMsg(SPeepholeOptimization + 'var7',p);
  5211. taicpu(p).opcode := A_AND;
  5212. taicpu(p).changeopsize(S_W);
  5213. taicpu(p).loadConst(0,$ff);
  5214. Result := True;
  5215. end
  5216. else if not IsMOVZXAcceptable and
  5217. GetNextInstruction(p, hp1) and
  5218. (tai(hp1).typ = ait_instruction) and
  5219. (taicpu(hp1).opcode = A_AND) and
  5220. MatchOpType(taicpu(hp1),top_const,top_reg) and
  5221. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  5222. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  5223. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  5224. begin
  5225. DebugMsg(SPeepholeOptimization + 'var8',p);
  5226. taicpu(p).opcode := A_MOV;
  5227. taicpu(p).changeopsize(S_W);
  5228. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  5229. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  5230. Result := True;
  5231. end;
  5232. end;
  5233. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  5234. S_BL:
  5235. begin
  5236. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  5237. (
  5238. not IsMOVZXAcceptable
  5239. { and $0xff,%eax has a smaller encoding but risks a partial write penalty }
  5240. or (
  5241. (cs_opt_size in current_settings.optimizerswitches) and
  5242. (taicpu(p).oper[1]^.reg = NR_EAX)
  5243. )
  5244. ) then
  5245. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  5246. begin
  5247. DebugMsg(SPeepholeOptimization + 'var9',p);
  5248. taicpu(p).opcode := A_AND;
  5249. taicpu(p).changeopsize(S_L);
  5250. taicpu(p).loadConst(0,$ff);
  5251. Result := True;
  5252. end
  5253. else if not IsMOVZXAcceptable and
  5254. GetNextInstruction(p, hp1) and
  5255. (tai(hp1).typ = ait_instruction) and
  5256. (taicpu(hp1).opcode = A_AND) and
  5257. MatchOpType(taicpu(hp1),top_const,top_reg) and
  5258. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  5259. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  5260. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  5261. begin
  5262. DebugMsg(SPeepholeOptimization + 'var10',p);
  5263. taicpu(p).opcode := A_MOV;
  5264. taicpu(p).changeopsize(S_L);
  5265. { do not use R_SUBWHOLE
  5266. as movl %rdx,%eax
  5267. is invalid in assembler PM }
  5268. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  5269. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  5270. Result := True;
  5271. end;
  5272. end;
  5273. {$endif i8086}
  5274. S_WL:
  5275. if not IsMOVZXAcceptable then
  5276. begin
  5277. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  5278. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  5279. begin
  5280. DebugMsg(SPeepholeOptimization + 'var11',p);
  5281. taicpu(p).opcode := A_AND;
  5282. taicpu(p).changeopsize(S_L);
  5283. taicpu(p).loadConst(0,$ffff);
  5284. Result := True;
  5285. end
  5286. else if GetNextInstruction(p, hp1) and
  5287. (tai(hp1).typ = ait_instruction) and
  5288. (taicpu(hp1).opcode = A_AND) and
  5289. (taicpu(hp1).oper[0]^.typ = top_const) and
  5290. (taicpu(hp1).oper[1]^.typ = top_reg) and
  5291. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  5292. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  5293. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  5294. begin
  5295. DebugMsg(SPeepholeOptimization + 'var12',p);
  5296. taicpu(p).opcode := A_MOV;
  5297. taicpu(p).changeopsize(S_L);
  5298. { do not use R_SUBWHOLE
  5299. as movl %rdx,%eax
  5300. is invalid in assembler PM }
  5301. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  5302. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  5303. Result := True;
  5304. end;
  5305. end;
  5306. else
  5307. InternalError(2017050705);
  5308. end;
  5309. end
  5310. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  5311. begin
  5312. if GetNextInstruction(p, hp1) and
  5313. (tai(hp1).typ = ait_instruction) and
  5314. (taicpu(hp1).opcode = A_AND) and
  5315. MatchOpType(taicpu(hp1),top_const,top_reg) and
  5316. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  5317. begin
  5318. //taicpu(p).opcode := A_MOV;
  5319. case taicpu(p).opsize Of
  5320. S_BL:
  5321. begin
  5322. DebugMsg(SPeepholeOptimization + 'var13',p);
  5323. taicpu(hp1).changeopsize(S_L);
  5324. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  5325. end;
  5326. S_WL:
  5327. begin
  5328. DebugMsg(SPeepholeOptimization + 'var14',p);
  5329. taicpu(hp1).changeopsize(S_L);
  5330. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  5331. end;
  5332. S_BW:
  5333. begin
  5334. DebugMsg(SPeepholeOptimization + 'var15',p);
  5335. taicpu(hp1).changeopsize(S_W);
  5336. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  5337. end;
  5338. else
  5339. Internalerror(2017050704)
  5340. end;
  5341. Result := True;
  5342. end;
  5343. end;
  5344. end;
  5345. end;
  5346. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  5347. var
  5348. hp1 : tai;
  5349. MaskLength : Cardinal;
  5350. begin
  5351. Result:=false;
  5352. if GetNextInstruction(p, hp1) then
  5353. begin
  5354. if MatchOpType(taicpu(p),top_const,top_reg) and
  5355. MatchInstruction(hp1,A_AND,[]) and
  5356. MatchOpType(taicpu(hp1),top_const,top_reg) and
  5357. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  5358. { the second register must contain the first one, so compare their subreg types }
  5359. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  5360. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  5361. { change
  5362. and const1, reg
  5363. and const2, reg
  5364. to
  5365. and (const1 and const2), reg
  5366. }
  5367. begin
  5368. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  5369. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  5370. RemoveCurrentP(p, hp1);
  5371. Result:=true;
  5372. exit;
  5373. end
  5374. else if MatchOpType(taicpu(p),top_const,top_reg) and
  5375. MatchInstruction(hp1,A_MOVZX,[]) and
  5376. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5377. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  5378. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  5379. (((taicpu(p).opsize=S_W) and
  5380. (taicpu(hp1).opsize=S_BW)) or
  5381. ((taicpu(p).opsize=S_L) and
  5382. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}]))
  5383. {$ifdef x86_64}
  5384. or
  5385. ((taicpu(p).opsize=S_Q) and
  5386. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL]))
  5387. {$endif x86_64}
  5388. ) then
  5389. begin
  5390. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  5391. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  5392. ) or
  5393. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  5394. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  5395. then
  5396. begin
  5397. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  5398. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  5399. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  5400. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  5401. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  5402. }
  5403. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  5404. RemoveInstruction(hp1);
  5405. Exit;
  5406. end;
  5407. end
  5408. else if MatchOpType(taicpu(p),top_const,top_reg) and
  5409. MatchInstruction(hp1,A_SHL,[]) and
  5410. MatchOpType(taicpu(hp1),top_const,top_reg) and
  5411. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  5412. begin
  5413. {$ifopt R+}
  5414. {$define RANGE_WAS_ON}
  5415. {$R-}
  5416. {$endif}
  5417. { get length of potential and mask }
  5418. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  5419. { really a mask? }
  5420. {$ifdef RANGE_WAS_ON}
  5421. {$R+}
  5422. {$endif}
  5423. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  5424. { unmasked part shifted out? }
  5425. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  5426. begin
  5427. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  5428. RemoveCurrentP(p, hp1);
  5429. Result:=true;
  5430. exit;
  5431. end;
  5432. end
  5433. else if MatchOpType(taicpu(p),top_const,top_reg) and
  5434. MatchInstruction(hp1,A_MOVSX{$ifdef x86_64},A_MOVSXD{$endif x86_64},[]) and
  5435. (taicpu(hp1).oper[0]^.typ = top_reg) and
  5436. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) and
  5437. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  5438. (((taicpu(p).opsize=S_W) and
  5439. (taicpu(hp1).opsize=S_BW)) or
  5440. ((taicpu(p).opsize=S_L) and
  5441. (taicpu(hp1).opsize in [S_WL,S_BL]))
  5442. {$ifdef x86_64}
  5443. or
  5444. ((taicpu(p).opsize=S_Q) and
  5445. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_LQ]))
  5446. {$endif x86_64}
  5447. ) then
  5448. begin
  5449. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  5450. ((taicpu(p).oper[0]^.val and $7f)=taicpu(p).oper[0]^.val)
  5451. ) or
  5452. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  5453. ((taicpu(p).oper[0]^.val and $7fff)=taicpu(p).oper[0]^.val))
  5454. {$ifdef x86_64}
  5455. or
  5456. (((taicpu(hp1).opsize)=S_LQ) and
  5457. ((taicpu(p).oper[0]^.val and $7fffffff)=taicpu(p).oper[0]^.val)
  5458. )
  5459. {$endif x86_64}
  5460. then
  5461. begin
  5462. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  5463. RemoveInstruction(hp1);
  5464. Exit;
  5465. end;
  5466. end
  5467. else if (taicpu(p).oper[1]^.typ = top_reg) and
  5468. (hp1.typ = ait_instruction) and
  5469. (taicpu(hp1).is_jmp) and
  5470. (taicpu(hp1).opcode<>A_JMP) and
  5471. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  5472. begin
  5473. { change
  5474. and x, reg
  5475. jxx
  5476. to
  5477. test x, reg
  5478. jxx
  5479. if reg is deallocated before the
  5480. jump, but only if it's a conditional jump (PFV)
  5481. }
  5482. taicpu(p).opcode := A_TEST;
  5483. Exit;
  5484. end;
  5485. end;
  5486. { Lone AND tests }
  5487. if MatchOpType(taicpu(p),top_const,top_reg) then
  5488. begin
  5489. {
  5490. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  5491. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  5492. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  5493. }
  5494. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  5495. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  5496. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  5497. begin
  5498. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  5499. if taicpu(p).opsize = S_L then
  5500. begin
  5501. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  5502. Result := True;
  5503. end;
  5504. end;
  5505. end;
  5506. end;
  5507. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  5508. begin
  5509. Result:=false;
  5510. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) and
  5511. MatchReference(taicpu(p).oper[0]^.ref^,taicpu(p).oper[1]^.reg,NR_INVALID) and
  5512. (taicpu(p).oper[0]^.ref^.index<>NR_NO) then
  5513. begin
  5514. taicpu(p).loadreg(1,taicpu(p).oper[0]^.ref^.base);
  5515. taicpu(p).loadreg(0,taicpu(p).oper[0]^.ref^.index);
  5516. taicpu(p).opcode:=A_ADD;
  5517. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  5518. result:=true;
  5519. end
  5520. else if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) and
  5521. MatchReference(taicpu(p).oper[0]^.ref^,NR_INVALID,taicpu(p).oper[1]^.reg) and
  5522. (taicpu(p).oper[0]^.ref^.base<>NR_NO) then
  5523. begin
  5524. taicpu(p).loadreg(1,taicpu(p).oper[0]^.ref^.index);
  5525. taicpu(p).loadreg(0,taicpu(p).oper[0]^.ref^.base);
  5526. taicpu(p).opcode:=A_ADD;
  5527. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  5528. result:=true;
  5529. end;
  5530. end;
  5531. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  5532. var
  5533. hp1: tai; NewRef: TReference;
  5534. begin
  5535. { Change:
  5536. subl/q $x,%reg1
  5537. movl/q %reg1,%reg2
  5538. To:
  5539. leal/q $-x(%reg1),%reg2
  5540. subl/q $x,%reg1
  5541. Breaks the dependency chain and potentially permits the removal of
  5542. a CMP instruction if one follows.
  5543. }
  5544. Result := False;
  5545. if not (cs_opt_size in current_settings.optimizerswitches) and
  5546. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  5547. MatchOpType(taicpu(p),top_const,top_reg) and
  5548. GetNextInstruction(p, hp1) and
  5549. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  5550. (taicpu(hp1).oper[1]^.typ = top_reg) and
  5551. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) then
  5552. begin
  5553. { Change the MOV instruction to a LEA instruction, and update the
  5554. first operand }
  5555. reference_reset(NewRef, 1, []);
  5556. NewRef.base := taicpu(p).oper[1]^.reg;
  5557. NewRef.scalefactor := 1;
  5558. NewRef.offset := -taicpu(p).oper[0]^.val;
  5559. taicpu(hp1).opcode := A_LEA;
  5560. taicpu(hp1).loadref(0, NewRef);
  5561. { Move what is now the LEA instruction to before the SUB instruction }
  5562. Asml.Remove(hp1);
  5563. Asml.InsertBefore(hp1, p);
  5564. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  5565. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  5566. Result := True;
  5567. end;
  5568. end;
  5569. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  5570. begin
  5571. { we can skip all instructions not messing with the stack pointer }
  5572. while assigned(hp1) and {MatchInstruction(taicpu(hp1),[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  5573. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  5574. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  5575. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  5576. ({(taicpu(hp1).ops=0) or }
  5577. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  5578. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  5579. ) and }
  5580. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  5581. )
  5582. ) do
  5583. GetNextInstruction(hp1,hp1);
  5584. Result:=assigned(hp1);
  5585. end;
  5586. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  5587. var
  5588. hp1, hp2, hp3, hp4: tai;
  5589. begin
  5590. Result:=false;
  5591. { replace
  5592. leal(q) x(<stackpointer>),<stackpointer>
  5593. call procname
  5594. leal(q) -x(<stackpointer>),<stackpointer>
  5595. ret
  5596. by
  5597. jmp procname
  5598. but do it only on level 4 because it destroys stack back traces
  5599. }
  5600. if (cs_opt_level4 in current_settings.optimizerswitches) and
  5601. MatchOpType(taicpu(p),top_ref,top_reg) and
  5602. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  5603. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  5604. { the -8 or -24 are not required, but bail out early if possible,
  5605. higher values are unlikely }
  5606. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  5607. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  5608. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  5609. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  5610. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and
  5611. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  5612. GetNextInstruction(p, hp1) and
  5613. { Take a copy of hp1 }
  5614. SetAndTest(hp1, hp4) and
  5615. { trick to skip label }
  5616. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  5617. SkipSimpleInstructions(hp1) and
  5618. MatchInstruction(hp1,A_CALL,[S_NO]) and
  5619. GetNextInstruction(hp1, hp2) and
  5620. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  5621. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  5622. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  5623. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  5624. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  5625. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  5626. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  5627. (taicpu(hp2).oper[0]^.ref^.segment=NR_NO) and
  5628. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  5629. GetNextInstruction(hp2, hp3) and
  5630. { trick to skip label }
  5631. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  5632. MatchInstruction(hp3,A_RET,[S_NO]) and
  5633. (taicpu(hp3).ops=0) then
  5634. begin
  5635. taicpu(hp1).opcode := A_JMP;
  5636. taicpu(hp1).is_jmp := true;
  5637. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  5638. RemoveCurrentP(p, hp4);
  5639. RemoveInstruction(hp2);
  5640. RemoveInstruction(hp3);
  5641. Result:=true;
  5642. end;
  5643. end;
  5644. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  5645. var
  5646. hp1, hp2, hp3, hp4: tai;
  5647. begin
  5648. Result:=false;
  5649. {$ifdef x86_64}
  5650. { replace
  5651. push %rax
  5652. call procname
  5653. pop %rcx
  5654. ret
  5655. by
  5656. jmp procname
  5657. but do it only on level 4 because it destroys stack back traces
  5658. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  5659. for all supported calling conventions
  5660. }
  5661. if (cs_opt_level4 in current_settings.optimizerswitches) and
  5662. MatchOpType(taicpu(p),top_reg) and
  5663. (taicpu(p).oper[0]^.reg=NR_RAX) and
  5664. GetNextInstruction(p, hp1) and
  5665. { Take a copy of hp1 }
  5666. SetAndTest(hp1, hp4) and
  5667. { trick to skip label }
  5668. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  5669. SkipSimpleInstructions(hp1) and
  5670. MatchInstruction(hp1,A_CALL,[S_NO]) and
  5671. GetNextInstruction(hp1, hp2) and
  5672. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  5673. MatchOpType(taicpu(hp2),top_reg) and
  5674. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  5675. GetNextInstruction(hp2, hp3) and
  5676. { trick to skip label }
  5677. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  5678. MatchInstruction(hp3,A_RET,[S_NO]) and
  5679. (taicpu(hp3).ops=0) then
  5680. begin
  5681. taicpu(hp1).opcode := A_JMP;
  5682. taicpu(hp1).is_jmp := true;
  5683. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  5684. RemoveCurrentP(p, hp4);
  5685. RemoveInstruction(hp2);
  5686. RemoveInstruction(hp3);
  5687. Result:=true;
  5688. end;
  5689. {$endif x86_64}
  5690. end;
  5691. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  5692. var
  5693. Value, RegName: string;
  5694. begin
  5695. Result:=false;
  5696. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  5697. begin
  5698. case taicpu(p).oper[0]^.val of
  5699. 0:
  5700. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  5701. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  5702. begin
  5703. { change "mov $0,%reg" into "xor %reg,%reg" }
  5704. taicpu(p).opcode := A_XOR;
  5705. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  5706. Result := True;
  5707. end;
  5708. $1..$FFFFFFFF:
  5709. begin
  5710. { Code size reduction by J. Gareth "Kit" Moreton }
  5711. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  5712. case taicpu(p).opsize of
  5713. S_Q:
  5714. begin
  5715. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  5716. Value := debug_tostr(taicpu(p).oper[0]^.val);
  5717. { The actual optimization }
  5718. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  5719. taicpu(p).changeopsize(S_L);
  5720. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  5721. Result := True;
  5722. end;
  5723. else
  5724. { Do nothing };
  5725. end;
  5726. end;
  5727. -1:
  5728. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  5729. if (cs_opt_size in current_settings.optimizerswitches) and
  5730. (taicpu(p).opsize <> S_B) and
  5731. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  5732. begin
  5733. { change "mov $-1,%reg" into "or $-1,%reg" }
  5734. { NOTES:
  5735. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  5736. - This operation creates a false dependency on the register, so only do it when optimising for size
  5737. - 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
  5738. }
  5739. taicpu(p).opcode := A_OR;
  5740. Result := True;
  5741. end;
  5742. end;
  5743. end;
  5744. end;
  5745. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  5746. begin
  5747. Result := False;
  5748. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  5749. Exit;
  5750. { Convert:
  5751. movswl %ax,%eax -> cwtl
  5752. movslq %eax,%rax -> cdqe
  5753. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  5754. refer to the same opcode and depends only on the assembler's
  5755. current operand-size attribute. [Kit]
  5756. }
  5757. with taicpu(p) do
  5758. case opsize of
  5759. S_WL:
  5760. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  5761. begin
  5762. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  5763. opcode := A_CWDE;
  5764. clearop(0);
  5765. clearop(1);
  5766. ops := 0;
  5767. Result := True;
  5768. end;
  5769. {$ifdef x86_64}
  5770. S_LQ:
  5771. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  5772. begin
  5773. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  5774. opcode := A_CDQE;
  5775. clearop(0);
  5776. clearop(1);
  5777. ops := 0;
  5778. Result := True;
  5779. end;
  5780. {$endif x86_64}
  5781. else
  5782. ;
  5783. end;
  5784. end;
  5785. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  5786. begin
  5787. Result:=false;
  5788. { change "cmp $0, %reg" to "test %reg, %reg" }
  5789. if MatchOpType(taicpu(p),top_const,top_reg) and
  5790. (taicpu(p).oper[0]^.val = 0) then
  5791. begin
  5792. taicpu(p).opcode := A_TEST;
  5793. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  5794. Result:=true;
  5795. end;
  5796. end;
  5797. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  5798. var
  5799. IsTestConstX : Boolean;
  5800. hp1,hp2 : tai;
  5801. begin
  5802. Result:=false;
  5803. { removes the line marked with (x) from the sequence
  5804. and/or/xor/add/sub/... $x, %y
  5805. test/or %y, %y | test $-1, %y (x)
  5806. j(n)z _Label
  5807. as the first instruction already adjusts the ZF
  5808. %y operand may also be a reference }
  5809. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  5810. MatchOperand(taicpu(p).oper[0]^,-1);
  5811. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  5812. GetLastInstruction(p, hp1) and
  5813. (tai(hp1).typ = ait_instruction) and
  5814. GetNextInstruction(p,hp2) and
  5815. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  5816. case taicpu(hp1).opcode Of
  5817. A_ADD, A_SUB, A_OR, A_XOR, A_AND:
  5818. begin
  5819. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  5820. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  5821. { and in case of carry for A(E)/B(E)/C/NC }
  5822. ((taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  5823. ((taicpu(hp1).opcode <> A_ADD) and
  5824. (taicpu(hp1).opcode <> A_SUB))) then
  5825. begin
  5826. RemoveCurrentP(p, hp2);
  5827. Result:=true;
  5828. end;
  5829. end;
  5830. A_SHL, A_SAL, A_SHR, A_SAR:
  5831. begin
  5832. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  5833. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  5834. { therefore, it's only safe to do this optimization for }
  5835. { shifts by a (nonzero) constant }
  5836. (taicpu(hp1).oper[0]^.typ = top_const) and
  5837. (taicpu(hp1).oper[0]^.val <> 0) and
  5838. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  5839. { and in case of carry for A(E)/B(E)/C/NC }
  5840. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  5841. begin
  5842. RemoveCurrentP(p, hp2);
  5843. Result:=true;
  5844. end;
  5845. end;
  5846. A_DEC, A_INC, A_NEG:
  5847. begin
  5848. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  5849. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  5850. { and in case of carry for A(E)/B(E)/C/NC }
  5851. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  5852. begin
  5853. case taicpu(hp1).opcode of
  5854. A_DEC, A_INC:
  5855. { replace inc/dec with add/sub 1, because inc/dec doesn't set the carry flag }
  5856. begin
  5857. case taicpu(hp1).opcode Of
  5858. A_DEC: taicpu(hp1).opcode := A_SUB;
  5859. A_INC: taicpu(hp1).opcode := A_ADD;
  5860. else
  5861. ;
  5862. end;
  5863. taicpu(hp1).loadoper(1,taicpu(hp1).oper[0]^);
  5864. taicpu(hp1).loadConst(0,1);
  5865. taicpu(hp1).ops:=2;
  5866. end;
  5867. else
  5868. ;
  5869. end;
  5870. RemoveCurrentP(p, hp2);
  5871. Result:=true;
  5872. end;
  5873. end
  5874. else
  5875. { change "test $-1,%reg" into "test %reg,%reg" }
  5876. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  5877. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  5878. end { case }
  5879. { change "test $-1,%reg" into "test %reg,%reg" }
  5880. else if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  5881. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  5882. end;
  5883. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  5884. var
  5885. hp1 : tai;
  5886. {$ifndef x86_64}
  5887. hp2 : taicpu;
  5888. {$endif x86_64}
  5889. begin
  5890. Result:=false;
  5891. {$ifndef x86_64}
  5892. { don't do this on modern CPUs, this really hurts them due to
  5893. broken call/ret pairing }
  5894. if (current_settings.optimizecputype < cpu_Pentium2) and
  5895. not(cs_create_pic in current_settings.moduleswitches) and
  5896. GetNextInstruction(p, hp1) and
  5897. MatchInstruction(hp1,A_JMP,[S_NO]) and
  5898. MatchOpType(taicpu(hp1),top_ref) and
  5899. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  5900. begin
  5901. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  5902. InsertLLItem(p.previous, p, hp2);
  5903. taicpu(p).opcode := A_JMP;
  5904. taicpu(p).is_jmp := true;
  5905. RemoveInstruction(hp1);
  5906. Result:=true;
  5907. end
  5908. else
  5909. {$endif x86_64}
  5910. { replace
  5911. call procname
  5912. ret
  5913. by
  5914. jmp procname
  5915. but do it only on level 4 because it destroys stack back traces
  5916. else if the subroutine is marked as no return, remove the ret
  5917. }
  5918. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  5919. (po_noreturn in current_procinfo.procdef.procoptions)) and
  5920. GetNextInstruction(p, hp1) and
  5921. MatchInstruction(hp1,A_RET,[S_NO]) and
  5922. (taicpu(hp1).ops=0) then
  5923. begin
  5924. if (cs_opt_level4 in current_settings.optimizerswitches) and
  5925. { we might destroy stack alignment here if we do not do a call }
  5926. (target_info.stackalign<=sizeof(SizeUInt)) then
  5927. begin
  5928. taicpu(p).opcode := A_JMP;
  5929. taicpu(p).is_jmp := true;
  5930. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  5931. end
  5932. else
  5933. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  5934. RemoveInstruction(hp1);
  5935. Result:=true;
  5936. end;
  5937. end;
  5938. {$ifdef x86_64}
  5939. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  5940. var
  5941. PreMessage: string;
  5942. begin
  5943. Result := False;
  5944. { Code size reduction by J. Gareth "Kit" Moreton }
  5945. { Convert MOVZBQ and MOVZWQ to MOVZBL and MOVZWL respectively if it removes the REX prefix }
  5946. if (taicpu(p).opsize in [S_BQ, S_WQ]) and
  5947. (getsupreg(taicpu(p).oper[1]^.reg) in [RS_RAX, RS_RCX, RS_RDX, RS_RBX, RS_RSI, RS_RDI, RS_RBP, RS_RSP])
  5948. then
  5949. begin
  5950. { Has 64-bit register name and opcode suffix }
  5951. PreMessage := 'movz' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' -> movz';
  5952. { The actual optimization }
  5953. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  5954. if taicpu(p).opsize = S_BQ then
  5955. taicpu(p).changeopsize(S_BL)
  5956. else
  5957. taicpu(p).changeopsize(S_WL);
  5958. DebugMsg(SPeepholeOptimization + PreMessage +
  5959. debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (removes REX prefix)', p);
  5960. end;
  5961. end;
  5962. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  5963. var
  5964. PreMessage, RegName: string;
  5965. begin
  5966. { Code size reduction by J. Gareth "Kit" Moreton }
  5967. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  5968. as this removes the REX prefix }
  5969. Result := False;
  5970. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  5971. Exit;
  5972. if taicpu(p).oper[0]^.typ <> top_reg then
  5973. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  5974. InternalError(2018011500);
  5975. case taicpu(p).opsize of
  5976. S_Q:
  5977. begin
  5978. if (getsupreg(taicpu(p).oper[0]^.reg) in [RS_RAX, RS_RCX, RS_RDX, RS_RBX, RS_RSI, RS_RDI, RS_RBP, RS_RSP]) then
  5979. begin
  5980. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  5981. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  5982. { The actual optimization }
  5983. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  5984. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  5985. taicpu(p).changeopsize(S_L);
  5986. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  5987. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (removes REX prefix)', p);
  5988. end;
  5989. end;
  5990. else
  5991. ;
  5992. end;
  5993. end;
  5994. {$endif}
  5995. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  5996. var
  5997. OperIdx: Integer;
  5998. begin
  5999. for OperIdx := 0 to p.ops - 1 do
  6000. if p.oper[OperIdx]^.typ = top_ref then
  6001. optimize_ref(p.oper[OperIdx]^.ref^, False);
  6002. end;
  6003. end.