aoptx86.pas 607 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,cclasses,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3,
  33. aoc_ForceNewIteration
  34. );
  35. TX86AsmOptimizer = class(TAsmOptimizer)
  36. { some optimizations are very expensive to check, so the
  37. pre opt pass can be used to set some flags, depending on the found
  38. instructions if it is worth to check a certain optimization }
  39. OptsToCheck : set of TOptsToCheck;
  40. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  41. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  42. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  43. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  44. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  45. { Identical to GetNextInstructionUsingReg, but returns a value indicating
  46. how many instructions away that Next is from Current is.
  47. 0 = failure, equivalent to False in GetNextInstructionUsingReg }
  48. function GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  49. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  50. potentially allowing further optimisation (although it might need to know if
  51. it crossed a conditional jump. }
  52. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  53. {
  54. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  55. the use of a register by allocs/dealloc, so it can ignore calls.
  56. In the following example, GetNextInstructionUsingReg will return the second movq,
  57. GetNextInstructionUsingRegTrackingUse won't.
  58. movq %rdi,%rax
  59. # Register rdi released
  60. # Register rdi allocated
  61. movq %rax,%rdi
  62. While in this example:
  63. movq %rdi,%rax
  64. call proc
  65. movq %rdi,%rax
  66. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  67. won't.
  68. }
  69. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  70. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  71. private
  72. function SkipSimpleInstructions(var hp1: tai): Boolean;
  73. protected
  74. class function IsMOVZXAcceptable: Boolean; static; inline;
  75. { Attempts to allocate a volatile integer register for use between p and hp,
  76. using AUsedRegs for the current register usage information. Returns NR_NO
  77. if no free register could be found }
  78. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  79. { Attempts to allocate a volatile MM register for use between p and hp,
  80. using AUsedRegs for the current register usage information. Returns NR_NO
  81. if no free register could be found }
  82. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  83. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  84. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  85. { checks whether reading the value in reg1 depends on the value of reg2. This
  86. is very similar to SuperRegisterEquals, except it takes into account that
  87. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  88. depend on the value in AH). }
  89. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  90. { Replaces all references to AOldReg in a memory reference to ANewReg }
  91. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  92. { Replaces all references to AOldReg in an operand to ANewReg }
  93. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  94. { Replaces all references to AOldReg in an instruction to ANewReg,
  95. except where the register is being written }
  96. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  97. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  98. or writes to a global symbol }
  99. class function IsRefSafe(const ref: PReference): Boolean; static;
  100. { Returns true if the given MOV instruction can be safely converted to CMOV }
  101. class function CanBeCMOV(p : tai) : boolean; static;
  102. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  103. conversion was successful }
  104. function ConvertLEA(const p : taicpu): Boolean;
  105. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  106. procedure DebugMsg(const s : string; p : tai);inline;
  107. class function IsExitCode(p : tai) : boolean; static;
  108. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  109. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  110. procedure RemoveLastDeallocForFuncRes(p : tai);
  111. function DoSubAddOpt(var p : tai) : Boolean;
  112. function DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  113. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  114. function PrePeepholeOptSxx(var p : tai) : boolean;
  115. function PrePeepholeOptIMUL(var p : tai) : boolean;
  116. function PrePeepholeOptAND(var p : tai) : boolean;
  117. function OptPass1Test(var p: tai): boolean;
  118. function OptPass1Add(var p: tai): boolean;
  119. function OptPass1AND(var p : tai) : boolean;
  120. function OptPass1_V_MOVAP(var p : tai) : boolean;
  121. function OptPass1VOP(var p : tai) : boolean;
  122. function OptPass1MOV(var p : tai) : boolean;
  123. function OptPass1Movx(var p : tai) : boolean;
  124. function OptPass1MOVXX(var p : tai) : boolean;
  125. function OptPass1OP(var p : tai) : boolean;
  126. function OptPass1LEA(var p : tai) : boolean;
  127. function OptPass1Sub(var p : tai) : boolean;
  128. function OptPass1SHLSAL(var p : tai) : boolean;
  129. function OptPass1SHR(var p : tai) : boolean;
  130. function OptPass1FSTP(var p : tai) : boolean;
  131. function OptPass1FLD(var p : tai) : boolean;
  132. function OptPass1Cmp(var p : tai) : boolean;
  133. function OptPass1PXor(var p : tai) : boolean;
  134. function OptPass1VPXor(var p: tai): boolean;
  135. function OptPass1Imul(var p : tai) : boolean;
  136. function OptPass1Jcc(var p : tai) : boolean;
  137. function OptPass1SHXX(var p: tai): boolean;
  138. function OptPass1VMOVDQ(var p: tai): Boolean;
  139. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  140. function OptPass2Movx(var p : tai): Boolean;
  141. function OptPass2MOV(var p : tai) : boolean;
  142. function OptPass2Imul(var p : tai) : boolean;
  143. function OptPass2Jmp(var p : tai) : boolean;
  144. function OptPass2Jcc(var p : tai) : boolean;
  145. function OptPass2Lea(var p: tai): Boolean;
  146. function OptPass2SUB(var p: tai): Boolean;
  147. function OptPass2ADD(var p : tai): Boolean;
  148. function OptPass2SETcc(var p : tai) : boolean;
  149. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  150. function PostPeepholeOptMov(var p : tai) : Boolean;
  151. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  152. {$ifdef x86_64} { These post-peephole optimisations only affect 64-bit registers. [Kit] }
  153. function PostPeepholeOptXor(var p : tai) : Boolean;
  154. {$endif x86_64}
  155. function PostPeepholeOptAnd(var p : tai) : boolean;
  156. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  157. function PostPeepholeOptCmp(var p : tai) : Boolean;
  158. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  159. function PostPeepholeOptCall(var p : tai) : Boolean;
  160. function PostPeepholeOptLea(var p : tai) : Boolean;
  161. function PostPeepholeOptPush(var p: tai): Boolean;
  162. function PostPeepholeOptShr(var p : tai) : boolean;
  163. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  164. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  165. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  166. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  167. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  168. { Processor-dependent reference optimisation }
  169. class procedure OptimizeRefs(var p: taicpu); static;
  170. end;
  171. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  172. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  173. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  174. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  175. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  176. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  177. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  178. {$if max_operands>2}
  179. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  180. {$endif max_operands>2}
  181. function RefsEqual(const r1, r2: treference): boolean;
  182. { Note that Result is set to True if the references COULD overlap but the
  183. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  184. might still overlap because %reg2 could be equal to %reg1-4 }
  185. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  186. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  187. { returns true, if ref is a reference using only the registers passed as base and index
  188. and having an offset }
  189. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  190. implementation
  191. uses
  192. cutils,verbose,
  193. systems,
  194. globals,
  195. cpuinfo,
  196. procinfo,
  197. paramgr,
  198. aasmbase,
  199. aoptbase,aoptutils,
  200. symconst,symsym,
  201. cgx86,
  202. itcpugas;
  203. {$ifdef DEBUG_AOPTCPU}
  204. const
  205. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  206. {$else DEBUG_AOPTCPU}
  207. { Empty strings help the optimizer to remove string concatenations that won't
  208. ever appear to the user on release builds. [Kit] }
  209. const
  210. SPeepholeOptimization = '';
  211. {$endif DEBUG_AOPTCPU}
  212. LIST_STEP_SIZE = 4;
  213. type
  214. TJumpTrackingItem = class(TLinkedListItem)
  215. private
  216. FSymbol: TAsmSymbol;
  217. FRefs: LongInt;
  218. public
  219. constructor Create(ASymbol: TAsmSymbol);
  220. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  221. property Symbol: TAsmSymbol read FSymbol;
  222. property Refs: LongInt read FRefs;
  223. end;
  224. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  225. begin
  226. inherited Create;
  227. FSymbol := ASymbol;
  228. FRefs := 0;
  229. end;
  230. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  231. begin
  232. Inc(FRefs);
  233. end;
  234. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  235. begin
  236. result :=
  237. (instr.typ = ait_instruction) and
  238. (taicpu(instr).opcode = op) and
  239. ((opsize = []) or (taicpu(instr).opsize in opsize));
  240. end;
  241. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  242. begin
  243. result :=
  244. (instr.typ = ait_instruction) and
  245. ((taicpu(instr).opcode = op1) or
  246. (taicpu(instr).opcode = op2)
  247. ) and
  248. ((opsize = []) or (taicpu(instr).opsize in opsize));
  249. end;
  250. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  251. begin
  252. result :=
  253. (instr.typ = ait_instruction) and
  254. ((taicpu(instr).opcode = op1) or
  255. (taicpu(instr).opcode = op2) or
  256. (taicpu(instr).opcode = op3)
  257. ) and
  258. ((opsize = []) or (taicpu(instr).opsize in opsize));
  259. end;
  260. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  261. const opsize : topsizes) : boolean;
  262. var
  263. op : TAsmOp;
  264. begin
  265. result:=false;
  266. if (instr.typ <> ait_instruction) or
  267. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  268. exit;
  269. for op in ops do
  270. begin
  271. if taicpu(instr).opcode = op then
  272. begin
  273. result:=true;
  274. exit;
  275. end;
  276. end;
  277. end;
  278. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  279. begin
  280. result := (oper.typ = top_reg) and (oper.reg = reg);
  281. end;
  282. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  283. begin
  284. result := (oper.typ = top_const) and (oper.val = a);
  285. end;
  286. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  287. begin
  288. result := oper1.typ = oper2.typ;
  289. if result then
  290. case oper1.typ of
  291. top_const:
  292. Result:=oper1.val = oper2.val;
  293. top_reg:
  294. Result:=oper1.reg = oper2.reg;
  295. top_ref:
  296. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  297. else
  298. internalerror(2013102801);
  299. end
  300. end;
  301. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  302. begin
  303. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  304. if result then
  305. case oper1.typ of
  306. top_const:
  307. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  308. top_reg:
  309. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  310. top_ref:
  311. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  312. else
  313. internalerror(2020052401);
  314. end
  315. end;
  316. function RefsEqual(const r1, r2: treference): boolean;
  317. begin
  318. RefsEqual :=
  319. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  320. (r1.relsymbol = r2.relsymbol) and
  321. (r1.segment = r2.segment) and (r1.base = r2.base) and
  322. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  323. (r1.offset = r2.offset) and
  324. (r1.volatility + r2.volatility = []);
  325. end;
  326. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  327. begin
  328. if (r1.symbol<>r2.symbol) then
  329. { If the index registers are different, there's a chance one could
  330. be set so it equals the other symbol }
  331. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  332. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  333. (r1.relsymbol = r2.relsymbol) and
  334. (r1.segment = r2.segment) and (r1.base = r2.base) and
  335. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  336. (r1.volatility + r2.volatility = []) then
  337. { In this case, it all depends on the offsets }
  338. Exit(abs(r1.offset - r2.offset) < Range);
  339. { There's a chance things MIGHT overlap, so take no chances }
  340. Result := True;
  341. end;
  342. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  343. begin
  344. Result:=(ref.offset=0) and
  345. (ref.scalefactor in [0,1]) and
  346. (ref.segment=NR_NO) and
  347. (ref.symbol=nil) and
  348. (ref.relsymbol=nil) and
  349. ((base=NR_INVALID) or
  350. (ref.base=base)) and
  351. ((index=NR_INVALID) or
  352. (ref.index=index)) and
  353. (ref.volatility=[]);
  354. end;
  355. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  356. begin
  357. Result:=(ref.scalefactor in [0,1]) and
  358. (ref.segment=NR_NO) and
  359. (ref.symbol=nil) and
  360. (ref.relsymbol=nil) and
  361. ((base=NR_INVALID) or
  362. (ref.base=base)) and
  363. ((index=NR_INVALID) or
  364. (ref.index=index)) and
  365. (ref.volatility=[]);
  366. end;
  367. function InstrReadsFlags(p: tai): boolean;
  368. begin
  369. InstrReadsFlags := true;
  370. case p.typ of
  371. ait_instruction:
  372. if InsProp[taicpu(p).opcode].Ch*
  373. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  374. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  375. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  376. exit;
  377. ait_label:
  378. exit;
  379. else
  380. ;
  381. end;
  382. InstrReadsFlags := false;
  383. end;
  384. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  385. begin
  386. Next:=Current;
  387. repeat
  388. Result:=GetNextInstruction(Next,Next);
  389. until not (Result) or
  390. not(cs_opt_level3 in current_settings.optimizerswitches) or
  391. (Next.typ<>ait_instruction) or
  392. RegInInstruction(reg,Next) or
  393. is_calljmp(taicpu(Next).opcode);
  394. end;
  395. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  396. var
  397. GetNextResult: Boolean;
  398. begin
  399. Result:=0;
  400. Next:=Current;
  401. repeat
  402. GetNextResult := GetNextInstruction(Next,Next);
  403. if GetNextResult then
  404. Inc(Result)
  405. else
  406. { Must return zero upon hitting the end of the linked list without a match }
  407. Result := 0;
  408. until not (GetNextResult) or
  409. not(cs_opt_level3 in current_settings.optimizerswitches) or
  410. (Next.typ<>ait_instruction) or
  411. RegInInstruction(reg,Next) or
  412. is_calljmp(taicpu(Next).opcode);
  413. end;
  414. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  415. procedure TrackJump(Symbol: TAsmSymbol);
  416. var
  417. Search: TJumpTrackingItem;
  418. begin
  419. { See if an entry already exists in our jump tracking list
  420. (faster to search backwards due to the higher chance of
  421. matching destinations) }
  422. Search := TJumpTrackingItem(JumpTracking.Last);
  423. while Assigned(Search) do
  424. begin
  425. if Search.Symbol = Symbol then
  426. begin
  427. { Found it - remove it so it can be pushed to the front }
  428. JumpTracking.Remove(Search);
  429. Break;
  430. end;
  431. Search := TJumpTrackingItem(Search.Previous);
  432. end;
  433. if not Assigned(Search) then
  434. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  435. JumpTracking.Concat(Search);
  436. Search.IncRefs;
  437. end;
  438. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  439. var
  440. Search: TJumpTrackingItem;
  441. begin
  442. Result := False;
  443. { See if this label appears in the tracking list }
  444. Search := TJumpTrackingItem(JumpTracking.Last);
  445. while Assigned(Search) do
  446. begin
  447. if Search.Symbol = Symbol then
  448. begin
  449. { Found it - let's see what we can discover }
  450. if Search.Symbol.getrefs = Search.Refs then
  451. begin
  452. { Success - all the references are accounted for }
  453. JumpTracking.Remove(Search);
  454. Search.Free;
  455. { It is logically impossible for CrossJump to be false here
  456. because we must have run into a conditional jump for
  457. this label at some point }
  458. if not CrossJump then
  459. InternalError(2022041710);
  460. if JumpTracking.First = nil then
  461. { Tracking list is now empty - no more cross jumps }
  462. CrossJump := False;
  463. Result := True;
  464. Exit;
  465. end;
  466. { If the references don't match, it's possible to enter
  467. this label through other means, so drop out }
  468. Exit;
  469. end;
  470. Search := TJumpTrackingItem(Search.Previous);
  471. end;
  472. end;
  473. var
  474. Next_Label: tai;
  475. begin
  476. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  477. Next := Current;
  478. repeat
  479. Result := GetNextInstruction(Next,Next);
  480. if not Result then
  481. Break;
  482. if Next.typ = ait_align then
  483. Result := SkipAligns(Next, Next);
  484. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  485. if is_calljmpuncondret(taicpu(Next).opcode) then
  486. begin
  487. if (taicpu(Next).opcode = A_JMP) and
  488. { Remove dead code now to save time }
  489. RemoveDeadCodeAfterJump(taicpu(Next)) then
  490. { A jump was removed, but not the current instruction, and
  491. Result doesn't necessarily translate into an optimisation
  492. routine's Result, so use the "Force New Iteration" flag so
  493. mark a new pass }
  494. Include(OptsToCheck, aoc_ForceNewIteration);
  495. if not Assigned(JumpTracking) then
  496. begin
  497. { Cross-label optimisations often causes other optimisations
  498. to perform worse because they're not given the chance to
  499. optimise locally. In this case, don't do the cross-label
  500. optimisations yet, but flag them as a potential possibility
  501. for the next iteration of Pass 1 }
  502. if not NotFirstIteration then
  503. Include(OptsToCheck, aoc_ForceNewIteration);
  504. end
  505. else if IsJumpToLabel(taicpu(Next)) and
  506. GetNextInstruction(Next, Next_Label) and
  507. SkipAligns(Next_Label, Next_Label) then
  508. begin
  509. { If we have JMP .lbl, and the label after it has all of its
  510. references tracked, then this is probably an if-else style of
  511. block and we can keep tracking. If the label for this jump
  512. then appears later and is fully tracked, then it's the end
  513. of the if-else blocks and the code paths converge (thus
  514. marking the end of the cross-jump) }
  515. if (Next_Label.typ = ait_label) then
  516. begin
  517. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  518. begin
  519. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  520. Next := Next_Label;
  521. { CrossJump gets set to false by LabelAccountedFor if the
  522. list is completely emptied (as it indicates that all
  523. code paths have converged). We could avoid this nuance
  524. by moving the TrackJump call to before the
  525. LabelAccountedFor call, but this is slower in situations
  526. where LabelAccountedFor would return False due to the
  527. creation of a new object that is not used and destroyed
  528. soon after. }
  529. CrossJump := True;
  530. Continue;
  531. end;
  532. end
  533. else if (Next_Label.typ <> ait_marker) then
  534. { We just did a RemoveDeadCodeAfterJump, so either we find
  535. a label, the end of the procedure or some kind of marker}
  536. InternalError(2022041720);
  537. end;
  538. Result := False;
  539. Exit;
  540. end
  541. else
  542. begin
  543. if not Assigned(JumpTracking) then
  544. begin
  545. { Cross-label optimisations often causes other optimisations
  546. to perform worse because they're not given the chance to
  547. optimise locally. In this case, don't do the cross-label
  548. optimisations yet, but flag them as a potential possibility
  549. for the next iteration of Pass 1 }
  550. if not NotFirstIteration then
  551. Include(OptsToCheck, aoc_ForceNewIteration);
  552. end
  553. else if IsJumpToLabel(taicpu(Next)) then
  554. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  555. else
  556. { Conditional jumps should always be a jump to label }
  557. InternalError(2022041701);
  558. CrossJump := True;
  559. Continue;
  560. end;
  561. if Next.typ = ait_label then
  562. begin
  563. if not Assigned(JumpTracking) then
  564. begin
  565. { Cross-label optimisations often causes other optimisations
  566. to perform worse because they're not given the chance to
  567. optimise locally. In this case, don't do the cross-label
  568. optimisations yet, but flag them as a potential possibility
  569. for the next iteration of Pass 1 }
  570. if not NotFirstIteration then
  571. Include(OptsToCheck, aoc_ForceNewIteration);
  572. end
  573. else if LabelAccountedFor(tai_label(Next).labsym) then
  574. Continue;
  575. { If we reach here, we're at a label that hasn't been seen before
  576. (or JumpTracking was nil) }
  577. Break;
  578. end;
  579. until not Result or
  580. not (cs_opt_level3 in current_settings.optimizerswitches) or
  581. not (Next.typ in [ait_label, ait_instruction]) or
  582. RegInInstruction(reg,Next);
  583. end;
  584. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  585. begin
  586. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  587. begin
  588. Result:=GetNextInstruction(Current,Next);
  589. exit;
  590. end;
  591. Next:=tai(Current.Next);
  592. Result:=false;
  593. while assigned(Next) do
  594. begin
  595. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  596. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  597. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  598. exit
  599. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  600. begin
  601. Result:=true;
  602. exit;
  603. end;
  604. Next:=tai(Next.Next);
  605. end;
  606. end;
  607. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  608. begin
  609. Result:=RegReadByInstruction(reg,hp);
  610. end;
  611. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  612. var
  613. p: taicpu;
  614. opcount: longint;
  615. begin
  616. RegReadByInstruction := false;
  617. if hp.typ <> ait_instruction then
  618. exit;
  619. p := taicpu(hp);
  620. case p.opcode of
  621. A_CALL:
  622. regreadbyinstruction := true;
  623. A_IMUL:
  624. case p.ops of
  625. 1:
  626. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  627. (
  628. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  629. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  630. );
  631. 2,3:
  632. regReadByInstruction :=
  633. reginop(reg,p.oper[0]^) or
  634. reginop(reg,p.oper[1]^);
  635. else
  636. InternalError(2019112801);
  637. end;
  638. A_MUL:
  639. begin
  640. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  641. (
  642. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  643. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  644. );
  645. end;
  646. A_IDIV,A_DIV:
  647. begin
  648. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  649. (
  650. (getregtype(reg)=R_INTREGISTER) and
  651. (
  652. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  653. )
  654. );
  655. end;
  656. else
  657. begin
  658. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  659. begin
  660. RegReadByInstruction := false;
  661. exit;
  662. end;
  663. for opcount := 0 to p.ops-1 do
  664. if (p.oper[opCount]^.typ = top_ref) and
  665. RegInRef(reg,p.oper[opcount]^.ref^) then
  666. begin
  667. RegReadByInstruction := true;
  668. exit
  669. end;
  670. { special handling for SSE MOVSD }
  671. if (p.opcode=A_MOVSD) and (p.ops>0) then
  672. begin
  673. if p.ops<>2 then
  674. internalerror(2017042702);
  675. regReadByInstruction := reginop(reg,p.oper[0]^) or
  676. (
  677. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  678. );
  679. exit;
  680. end;
  681. with insprop[p.opcode] do
  682. begin
  683. case getregtype(reg) of
  684. R_INTREGISTER:
  685. begin
  686. case getsupreg(reg) of
  687. RS_EAX:
  688. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  689. begin
  690. RegReadByInstruction := true;
  691. exit
  692. end;
  693. RS_ECX:
  694. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  695. begin
  696. RegReadByInstruction := true;
  697. exit
  698. end;
  699. RS_EDX:
  700. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  701. begin
  702. RegReadByInstruction := true;
  703. exit
  704. end;
  705. RS_EBX:
  706. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  707. begin
  708. RegReadByInstruction := true;
  709. exit
  710. end;
  711. RS_ESP:
  712. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  713. begin
  714. RegReadByInstruction := true;
  715. exit
  716. end;
  717. RS_EBP:
  718. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  719. begin
  720. RegReadByInstruction := true;
  721. exit
  722. end;
  723. RS_ESI:
  724. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  725. begin
  726. RegReadByInstruction := true;
  727. exit
  728. end;
  729. RS_EDI:
  730. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  731. begin
  732. RegReadByInstruction := true;
  733. exit
  734. end;
  735. end;
  736. end;
  737. R_MMREGISTER:
  738. begin
  739. case getsupreg(reg) of
  740. RS_XMM0:
  741. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  742. begin
  743. RegReadByInstruction := true;
  744. exit
  745. end;
  746. end;
  747. end;
  748. else
  749. ;
  750. end;
  751. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  752. begin
  753. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  754. begin
  755. case p.condition of
  756. C_A,C_NBE, { CF=0 and ZF=0 }
  757. C_BE,C_NA: { CF=1 or ZF=1 }
  758. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  759. C_AE,C_NB,C_NC, { CF=0 }
  760. C_B,C_NAE,C_C: { CF=1 }
  761. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  762. C_NE,C_NZ, { ZF=0 }
  763. C_E,C_Z: { ZF=1 }
  764. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  765. C_G,C_NLE, { ZF=0 and SF=OF }
  766. C_LE,C_NG: { ZF=1 or SF<>OF }
  767. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  768. C_GE,C_NL, { SF=OF }
  769. C_L,C_NGE: { SF<>OF }
  770. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  771. C_NO, { OF=0 }
  772. C_O: { OF=1 }
  773. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  774. C_NP,C_PO, { PF=0 }
  775. C_P,C_PE: { PF=1 }
  776. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  777. C_NS, { SF=0 }
  778. C_S: { SF=1 }
  779. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  780. else
  781. internalerror(2017042701);
  782. end;
  783. if RegReadByInstruction then
  784. exit;
  785. end;
  786. case getsubreg(reg) of
  787. R_SUBW,R_SUBD,R_SUBQ:
  788. RegReadByInstruction :=
  789. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  790. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  791. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  792. R_SUBFLAGCARRY:
  793. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  794. R_SUBFLAGPARITY:
  795. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  796. R_SUBFLAGAUXILIARY:
  797. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  798. R_SUBFLAGZERO:
  799. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  800. R_SUBFLAGSIGN:
  801. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  802. R_SUBFLAGOVERFLOW:
  803. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  804. R_SUBFLAGINTERRUPT:
  805. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  806. R_SUBFLAGDIRECTION:
  807. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  808. else
  809. internalerror(2017042601);
  810. end;
  811. exit;
  812. end;
  813. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  814. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  815. (p.oper[0]^.reg=p.oper[1]^.reg) then
  816. exit;
  817. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  818. begin
  819. RegReadByInstruction := true;
  820. exit
  821. end;
  822. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  823. begin
  824. RegReadByInstruction := true;
  825. exit
  826. end;
  827. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  828. begin
  829. RegReadByInstruction := true;
  830. exit
  831. end;
  832. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  833. begin
  834. RegReadByInstruction := true;
  835. exit
  836. end;
  837. end;
  838. end;
  839. end;
  840. end;
  841. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  842. begin
  843. result:=false;
  844. if p1.typ<>ait_instruction then
  845. exit;
  846. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  847. exit(true);
  848. if (getregtype(reg)=R_INTREGISTER) and
  849. { change information for xmm movsd are not correct }
  850. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  851. begin
  852. case getsupreg(reg) of
  853. { RS_EAX = RS_RAX on x86-64 }
  854. RS_EAX:
  855. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  856. RS_ECX:
  857. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  858. RS_EDX:
  859. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  860. RS_EBX:
  861. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  862. RS_ESP:
  863. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  864. RS_EBP:
  865. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  866. RS_ESI:
  867. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  868. RS_EDI:
  869. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  870. else
  871. ;
  872. end;
  873. if result then
  874. exit;
  875. end
  876. else if getregtype(reg)=R_MMREGISTER then
  877. begin
  878. case getsupreg(reg) of
  879. RS_XMM0:
  880. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  881. else
  882. ;
  883. end;
  884. if result then
  885. exit;
  886. end
  887. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  888. begin
  889. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  890. exit(true);
  891. case getsubreg(reg) of
  892. R_SUBFLAGCARRY:
  893. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  894. R_SUBFLAGPARITY:
  895. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  896. R_SUBFLAGAUXILIARY:
  897. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  898. R_SUBFLAGZERO:
  899. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  900. R_SUBFLAGSIGN:
  901. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  902. R_SUBFLAGOVERFLOW:
  903. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  904. R_SUBFLAGINTERRUPT:
  905. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  906. R_SUBFLAGDIRECTION:
  907. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  908. R_SUBW,R_SUBD,R_SUBQ:
  909. { Everything except the direction bits }
  910. Result:=
  911. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  912. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  913. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  914. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  915. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  916. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  917. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  918. else
  919. ;
  920. end;
  921. if result then
  922. exit;
  923. end
  924. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  925. exit(true);
  926. Result:=inherited RegInInstruction(Reg, p1);
  927. end;
  928. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  929. const
  930. WriteOps: array[0..3] of set of TInsChange =
  931. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  932. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  933. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  934. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  935. var
  936. OperIdx: Integer;
  937. begin
  938. Result := False;
  939. if p1.typ <> ait_instruction then
  940. exit;
  941. with insprop[taicpu(p1).opcode] do
  942. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  943. begin
  944. case getsubreg(reg) of
  945. R_SUBW,R_SUBD,R_SUBQ:
  946. Result :=
  947. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  948. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  949. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  950. R_SUBFLAGCARRY:
  951. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  952. R_SUBFLAGPARITY:
  953. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  954. R_SUBFLAGAUXILIARY:
  955. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  956. R_SUBFLAGZERO:
  957. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  958. R_SUBFLAGSIGN:
  959. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  960. R_SUBFLAGOVERFLOW:
  961. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  962. R_SUBFLAGINTERRUPT:
  963. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  964. R_SUBFLAGDIRECTION:
  965. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  966. else
  967. internalerror(2017042602);
  968. end;
  969. exit;
  970. end;
  971. case taicpu(p1).opcode of
  972. A_CALL:
  973. { We could potentially set Result to False if the register in
  974. question is non-volatile for the subroutine's calling convention,
  975. but this would require detecting the calling convention in use and
  976. also assuming that the routine doesn't contain malformed assembly
  977. language, for example... so it could only be done under -O4 as it
  978. would be considered a side-effect. [Kit] }
  979. Result := True;
  980. A_MOVSD:
  981. { special handling for SSE MOVSD }
  982. if (taicpu(p1).ops>0) then
  983. begin
  984. if taicpu(p1).ops<>2 then
  985. internalerror(2017042703);
  986. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  987. end;
  988. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  989. so fix it here (FK)
  990. }
  991. A_VMOVSS,
  992. A_VMOVSD:
  993. begin
  994. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  995. exit;
  996. end;
  997. A_IMUL:
  998. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  999. else
  1000. ;
  1001. end;
  1002. if Result then
  1003. exit;
  1004. with insprop[taicpu(p1).opcode] do
  1005. begin
  1006. if getregtype(reg)=R_INTREGISTER then
  1007. begin
  1008. case getsupreg(reg) of
  1009. RS_EAX:
  1010. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1011. begin
  1012. Result := True;
  1013. exit
  1014. end;
  1015. RS_ECX:
  1016. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1017. begin
  1018. Result := True;
  1019. exit
  1020. end;
  1021. RS_EDX:
  1022. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1023. begin
  1024. Result := True;
  1025. exit
  1026. end;
  1027. RS_EBX:
  1028. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1029. begin
  1030. Result := True;
  1031. exit
  1032. end;
  1033. RS_ESP:
  1034. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1035. begin
  1036. Result := True;
  1037. exit
  1038. end;
  1039. RS_EBP:
  1040. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1041. begin
  1042. Result := True;
  1043. exit
  1044. end;
  1045. RS_ESI:
  1046. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1047. begin
  1048. Result := True;
  1049. exit
  1050. end;
  1051. RS_EDI:
  1052. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1053. begin
  1054. Result := True;
  1055. exit
  1056. end;
  1057. end;
  1058. end;
  1059. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1060. if (WriteOps[OperIdx]*Ch<>[]) and
  1061. { The register doesn't get modified inside a reference }
  1062. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1063. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1064. begin
  1065. Result := true;
  1066. exit
  1067. end;
  1068. end;
  1069. end;
  1070. {$ifdef DEBUG_AOPTCPU}
  1071. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1072. begin
  1073. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1074. end;
  1075. function debug_tostr(i: tcgint): string; inline;
  1076. begin
  1077. Result := tostr(i);
  1078. end;
  1079. function debug_regname(r: TRegister): string; inline;
  1080. begin
  1081. Result := '%' + std_regname(r);
  1082. end;
  1083. { Debug output function - creates a string representation of an operator }
  1084. function debug_operstr(oper: TOper): string;
  1085. begin
  1086. case oper.typ of
  1087. top_const:
  1088. Result := '$' + debug_tostr(oper.val);
  1089. top_reg:
  1090. Result := debug_regname(oper.reg);
  1091. top_ref:
  1092. begin
  1093. if oper.ref^.offset <> 0 then
  1094. Result := debug_tostr(oper.ref^.offset) + '('
  1095. else
  1096. Result := '(';
  1097. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1098. begin
  1099. Result := Result + debug_regname(oper.ref^.base);
  1100. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1101. Result := Result + ',' + debug_regname(oper.ref^.index);
  1102. end
  1103. else
  1104. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1105. Result := Result + debug_regname(oper.ref^.index);
  1106. if (oper.ref^.scalefactor > 1) then
  1107. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1108. else
  1109. Result := Result + ')';
  1110. end;
  1111. else
  1112. Result := '[UNKNOWN]';
  1113. end;
  1114. end;
  1115. function debug_op2str(opcode: tasmop): string; inline;
  1116. begin
  1117. Result := std_op2str[opcode];
  1118. end;
  1119. function debug_opsize2str(opsize: topsize): string; inline;
  1120. begin
  1121. Result := gas_opsize2str[opsize];
  1122. end;
  1123. {$else DEBUG_AOPTCPU}
  1124. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1125. begin
  1126. end;
  1127. function debug_tostr(i: tcgint): string; inline;
  1128. begin
  1129. Result := '';
  1130. end;
  1131. function debug_regname(r: TRegister): string; inline;
  1132. begin
  1133. Result := '';
  1134. end;
  1135. function debug_operstr(oper: TOper): string; inline;
  1136. begin
  1137. Result := '';
  1138. end;
  1139. function debug_op2str(opcode: tasmop): string; inline;
  1140. begin
  1141. Result := '';
  1142. end;
  1143. function debug_opsize2str(opsize: topsize): string; inline;
  1144. begin
  1145. Result := '';
  1146. end;
  1147. {$endif DEBUG_AOPTCPU}
  1148. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1149. begin
  1150. {$ifdef x86_64}
  1151. { Always fine on x86-64 }
  1152. Result := True;
  1153. {$else x86_64}
  1154. Result :=
  1155. {$ifdef i8086}
  1156. (current_settings.cputype >= cpu_386) and
  1157. {$endif i8086}
  1158. (
  1159. { Always accept if optimising for size }
  1160. (cs_opt_size in current_settings.optimizerswitches) or
  1161. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1162. (current_settings.optimizecputype >= cpu_Pentium2)
  1163. );
  1164. {$endif x86_64}
  1165. end;
  1166. { Attempts to allocate a volatile integer register for use between p and hp,
  1167. using AUsedRegs for the current register usage information. Returns NR_NO
  1168. if no free register could be found }
  1169. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1170. var
  1171. RegSet: TCPURegisterSet;
  1172. CurrentSuperReg: Integer;
  1173. CurrentReg: TRegister;
  1174. Currentp: tai;
  1175. Breakout: Boolean;
  1176. begin
  1177. Result := NR_NO;
  1178. RegSet :=
  1179. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1180. current_procinfo.saved_regs_int;
  1181. for CurrentSuperReg in RegSet do
  1182. begin
  1183. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1184. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1185. {$if defined(i386) or defined(i8086)}
  1186. { If the target size is 8-bit, make sure we can actually encode it }
  1187. and (
  1188. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1189. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1190. )
  1191. {$endif i386 or i8086}
  1192. then
  1193. begin
  1194. Currentp := p;
  1195. Breakout := False;
  1196. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1197. begin
  1198. case Currentp.typ of
  1199. ait_instruction:
  1200. begin
  1201. if RegInInstruction(CurrentReg, Currentp) then
  1202. begin
  1203. Breakout := True;
  1204. Break;
  1205. end;
  1206. { Cannot allocate across an unconditional jump }
  1207. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1208. Exit;
  1209. end;
  1210. ait_marker:
  1211. { Don't try anything more if a marker is hit }
  1212. Exit;
  1213. ait_regalloc:
  1214. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1215. begin
  1216. Breakout := True;
  1217. Break;
  1218. end;
  1219. else
  1220. ;
  1221. end;
  1222. end;
  1223. if Breakout then
  1224. { Try the next register }
  1225. Continue;
  1226. { We have a free register available }
  1227. Result := CurrentReg;
  1228. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1229. Exit;
  1230. end;
  1231. end;
  1232. end;
  1233. { Attempts to allocate a volatile MM register for use between p and hp,
  1234. using AUsedRegs for the current register usage information. Returns NR_NO
  1235. if no free register could be found }
  1236. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1237. var
  1238. RegSet: TCPURegisterSet;
  1239. CurrentSuperReg: Integer;
  1240. CurrentReg: TRegister;
  1241. Currentp: tai;
  1242. Breakout: Boolean;
  1243. begin
  1244. Result := NR_NO;
  1245. RegSet :=
  1246. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1247. current_procinfo.saved_regs_mm;
  1248. for CurrentSuperReg in RegSet do
  1249. begin
  1250. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1251. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1252. begin
  1253. Currentp := p;
  1254. Breakout := False;
  1255. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1256. begin
  1257. case Currentp.typ of
  1258. ait_instruction:
  1259. begin
  1260. if RegInInstruction(CurrentReg, Currentp) then
  1261. begin
  1262. Breakout := True;
  1263. Break;
  1264. end;
  1265. { Cannot allocate across an unconditional jump }
  1266. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1267. Exit;
  1268. end;
  1269. ait_marker:
  1270. { Don't try anything more if a marker is hit }
  1271. Exit;
  1272. ait_regalloc:
  1273. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1274. begin
  1275. Breakout := True;
  1276. Break;
  1277. end;
  1278. else
  1279. ;
  1280. end;
  1281. end;
  1282. if Breakout then
  1283. { Try the next register }
  1284. Continue;
  1285. { We have a free register available }
  1286. Result := CurrentReg;
  1287. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1288. Exit;
  1289. end;
  1290. end;
  1291. end;
  1292. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1293. begin
  1294. if not SuperRegistersEqual(reg1,reg2) then
  1295. exit(false);
  1296. if getregtype(reg1)<>R_INTREGISTER then
  1297. exit(true); {because SuperRegisterEqual is true}
  1298. case getsubreg(reg1) of
  1299. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1300. higher, it preserves the high bits, so the new value depends on
  1301. reg2's previous value. In other words, it is equivalent to doing:
  1302. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1303. R_SUBL:
  1304. exit(getsubreg(reg2)=R_SUBL);
  1305. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1306. higher, it actually does a:
  1307. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1308. R_SUBH:
  1309. exit(getsubreg(reg2)=R_SUBH);
  1310. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1311. bits of reg2:
  1312. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1313. R_SUBW:
  1314. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1315. { a write to R_SUBD always overwrites every other subregister,
  1316. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1317. R_SUBD,
  1318. R_SUBQ:
  1319. exit(true);
  1320. else
  1321. internalerror(2017042801);
  1322. end;
  1323. end;
  1324. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1325. begin
  1326. if not SuperRegistersEqual(reg1,reg2) then
  1327. exit(false);
  1328. if getregtype(reg1)<>R_INTREGISTER then
  1329. exit(true); {because SuperRegisterEqual is true}
  1330. case getsubreg(reg1) of
  1331. R_SUBL:
  1332. exit(getsubreg(reg2)<>R_SUBH);
  1333. R_SUBH:
  1334. exit(getsubreg(reg2)<>R_SUBL);
  1335. R_SUBW,
  1336. R_SUBD,
  1337. R_SUBQ:
  1338. exit(true);
  1339. else
  1340. internalerror(2017042802);
  1341. end;
  1342. end;
  1343. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1344. var
  1345. hp1 : tai;
  1346. l : TCGInt;
  1347. begin
  1348. result:=false;
  1349. { changes the code sequence
  1350. shr/sar const1, x
  1351. shl const2, x
  1352. to
  1353. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1354. if GetNextInstruction(p, hp1) and
  1355. MatchInstruction(hp1,A_SHL,[]) and
  1356. (taicpu(p).oper[0]^.typ = top_const) and
  1357. (taicpu(hp1).oper[0]^.typ = top_const) and
  1358. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1359. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1360. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1361. begin
  1362. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1363. not(cs_opt_size in current_settings.optimizerswitches) then
  1364. begin
  1365. { shr/sar const1, %reg
  1366. shl const2, %reg
  1367. with const1 > const2 }
  1368. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1369. taicpu(hp1).opcode := A_AND;
  1370. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1371. case taicpu(p).opsize Of
  1372. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1373. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1374. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1375. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1376. else
  1377. Internalerror(2017050703)
  1378. end;
  1379. end
  1380. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1381. not(cs_opt_size in current_settings.optimizerswitches) then
  1382. begin
  1383. { shr/sar const1, %reg
  1384. shl const2, %reg
  1385. with const1 < const2 }
  1386. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1387. taicpu(p).opcode := A_AND;
  1388. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1389. case taicpu(p).opsize Of
  1390. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1391. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1392. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1393. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1394. else
  1395. Internalerror(2017050702)
  1396. end;
  1397. end
  1398. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1399. begin
  1400. { shr/sar const1, %reg
  1401. shl const2, %reg
  1402. with const1 = const2 }
  1403. taicpu(p).opcode := A_AND;
  1404. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1405. case taicpu(p).opsize Of
  1406. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1407. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1408. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1409. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1410. else
  1411. Internalerror(2017050701)
  1412. end;
  1413. RemoveInstruction(hp1);
  1414. end;
  1415. end;
  1416. end;
  1417. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1418. var
  1419. opsize : topsize;
  1420. hp1, hp2 : tai;
  1421. tmpref : treference;
  1422. ShiftValue : Cardinal;
  1423. BaseValue : TCGInt;
  1424. begin
  1425. result:=false;
  1426. opsize:=taicpu(p).opsize;
  1427. { changes certain "imul const, %reg"'s to lea sequences }
  1428. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1429. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1430. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1431. if (taicpu(p).oper[0]^.val = 1) then
  1432. if (taicpu(p).ops = 2) then
  1433. { remove "imul $1, reg" }
  1434. begin
  1435. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1436. Result := RemoveCurrentP(p);
  1437. end
  1438. else
  1439. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1440. begin
  1441. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1442. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1443. asml.InsertAfter(hp1, p);
  1444. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1445. RemoveCurrentP(p, hp1);
  1446. Result := True;
  1447. end
  1448. else if ((taicpu(p).ops <= 2) or
  1449. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1450. not(cs_opt_size in current_settings.optimizerswitches) and
  1451. (not(GetNextInstruction(p, hp1)) or
  1452. not((tai(hp1).typ = ait_instruction) and
  1453. ((taicpu(hp1).opcode=A_Jcc) and
  1454. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1455. begin
  1456. {
  1457. imul X, reg1, reg2 to
  1458. lea (reg1,reg1,Y), reg2
  1459. shl ZZ,reg2
  1460. imul XX, reg1 to
  1461. lea (reg1,reg1,YY), reg1
  1462. shl ZZ,reg2
  1463. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1464. it does not exist as a separate optimization target in FPC though.
  1465. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1466. at most two zeros
  1467. }
  1468. reference_reset(tmpref,1,[]);
  1469. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1470. begin
  1471. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1472. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1473. TmpRef.base := taicpu(p).oper[1]^.reg;
  1474. TmpRef.index := taicpu(p).oper[1]^.reg;
  1475. if not(BaseValue in [3,5,9]) then
  1476. Internalerror(2018110101);
  1477. TmpRef.ScaleFactor := BaseValue-1;
  1478. if (taicpu(p).ops = 2) then
  1479. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1480. else
  1481. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1482. AsmL.InsertAfter(hp1,p);
  1483. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1484. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1485. RemoveCurrentP(p, hp1);
  1486. if ShiftValue>0 then
  1487. begin
  1488. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1489. AsmL.InsertAfter(hp2,hp1);
  1490. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1491. end;
  1492. Result := True;
  1493. end;
  1494. end;
  1495. end;
  1496. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1497. begin
  1498. Result := False;
  1499. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1500. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1501. begin
  1502. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1503. taicpu(p).opcode := A_MOV;
  1504. Result := True;
  1505. end;
  1506. end;
  1507. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1508. var
  1509. p: taicpu absolute hp; { Implicit typecast }
  1510. i: Integer;
  1511. begin
  1512. Result := False;
  1513. if not assigned(hp) or
  1514. (hp.typ <> ait_instruction) then
  1515. Exit;
  1516. Prefetch(insprop[p.opcode]);
  1517. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1518. with insprop[p.opcode] do
  1519. begin
  1520. case getsubreg(reg) of
  1521. R_SUBW,R_SUBD,R_SUBQ:
  1522. Result:=
  1523. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1524. uncommon flags are checked first }
  1525. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1526. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1527. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1528. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1529. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1530. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1531. R_SUBFLAGCARRY:
  1532. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1533. R_SUBFLAGPARITY:
  1534. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1535. R_SUBFLAGAUXILIARY:
  1536. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1537. R_SUBFLAGZERO:
  1538. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1539. R_SUBFLAGSIGN:
  1540. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1541. R_SUBFLAGOVERFLOW:
  1542. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1543. R_SUBFLAGINTERRUPT:
  1544. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1545. R_SUBFLAGDIRECTION:
  1546. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1547. else
  1548. internalerror(2017050501);
  1549. end;
  1550. exit;
  1551. end;
  1552. { Handle special cases first }
  1553. case p.opcode of
  1554. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1555. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1556. begin
  1557. Result :=
  1558. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1559. (p.oper[1]^.typ = top_reg) and
  1560. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1561. (
  1562. (p.oper[0]^.typ = top_const) or
  1563. (
  1564. (p.oper[0]^.typ = top_reg) and
  1565. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1566. ) or (
  1567. (p.oper[0]^.typ = top_ref) and
  1568. not RegInRef(reg,p.oper[0]^.ref^)
  1569. )
  1570. );
  1571. end;
  1572. A_MUL, A_IMUL:
  1573. Result :=
  1574. (
  1575. (p.ops=3) and { IMUL only }
  1576. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1577. (
  1578. (
  1579. (p.oper[1]^.typ=top_reg) and
  1580. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1581. ) or (
  1582. (p.oper[1]^.typ=top_ref) and
  1583. not RegInRef(reg,p.oper[1]^.ref^)
  1584. )
  1585. )
  1586. ) or (
  1587. (
  1588. (p.ops=1) and
  1589. (
  1590. (
  1591. (
  1592. (p.oper[0]^.typ=top_reg) and
  1593. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1594. )
  1595. ) or (
  1596. (p.oper[0]^.typ=top_ref) and
  1597. not RegInRef(reg,p.oper[0]^.ref^)
  1598. )
  1599. ) and (
  1600. (
  1601. (p.opsize=S_B) and
  1602. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1603. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1604. ) or (
  1605. (p.opsize=S_W) and
  1606. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1607. ) or (
  1608. (p.opsize=S_L) and
  1609. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1610. {$ifdef x86_64}
  1611. ) or (
  1612. (p.opsize=S_Q) and
  1613. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1614. {$endif x86_64}
  1615. )
  1616. )
  1617. )
  1618. );
  1619. A_CBW:
  1620. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1621. {$ifndef x86_64}
  1622. A_LDS:
  1623. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1624. A_LES:
  1625. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1626. {$endif not x86_64}
  1627. A_LFS:
  1628. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1629. A_LGS:
  1630. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1631. A_LSS:
  1632. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1633. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1634. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1635. A_LODSB:
  1636. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1637. A_LODSW:
  1638. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1639. {$ifdef x86_64}
  1640. A_LODSQ:
  1641. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1642. {$endif x86_64}
  1643. A_LODSD:
  1644. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1645. A_FSTSW, A_FNSTSW:
  1646. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1647. else
  1648. begin
  1649. with insprop[p.opcode] do
  1650. begin
  1651. if (
  1652. { xor %reg,%reg etc. is classed as a new value }
  1653. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1654. MatchOpType(p, top_reg, top_reg) and
  1655. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1656. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1657. ) then
  1658. begin
  1659. Result := True;
  1660. Exit;
  1661. end;
  1662. { Make sure the entire register is overwritten }
  1663. if (getregtype(reg) = R_INTREGISTER) then
  1664. begin
  1665. if (p.ops > 0) then
  1666. begin
  1667. if RegInOp(reg, p.oper[0]^) then
  1668. begin
  1669. if (p.oper[0]^.typ = top_ref) then
  1670. begin
  1671. if RegInRef(reg, p.oper[0]^.ref^) then
  1672. begin
  1673. Result := False;
  1674. Exit;
  1675. end;
  1676. end
  1677. else if (p.oper[0]^.typ = top_reg) then
  1678. begin
  1679. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1680. begin
  1681. Result := False;
  1682. Exit;
  1683. end
  1684. else if ([Ch_WOp1]*Ch<>[]) then
  1685. begin
  1686. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1687. Result := True
  1688. else
  1689. begin
  1690. Result := False;
  1691. Exit;
  1692. end;
  1693. end;
  1694. end;
  1695. end;
  1696. if (p.ops > 1) then
  1697. begin
  1698. if RegInOp(reg, p.oper[1]^) then
  1699. begin
  1700. if (p.oper[1]^.typ = top_ref) then
  1701. begin
  1702. if RegInRef(reg, p.oper[1]^.ref^) then
  1703. begin
  1704. Result := False;
  1705. Exit;
  1706. end;
  1707. end
  1708. else if (p.oper[1]^.typ = top_reg) then
  1709. begin
  1710. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1711. begin
  1712. Result := False;
  1713. Exit;
  1714. end
  1715. else if ([Ch_WOp2]*Ch<>[]) then
  1716. begin
  1717. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1718. Result := True
  1719. else
  1720. begin
  1721. Result := False;
  1722. Exit;
  1723. end;
  1724. end;
  1725. end;
  1726. end;
  1727. if (p.ops > 2) then
  1728. begin
  1729. if RegInOp(reg, p.oper[2]^) then
  1730. begin
  1731. if (p.oper[2]^.typ = top_ref) then
  1732. begin
  1733. if RegInRef(reg, p.oper[2]^.ref^) then
  1734. begin
  1735. Result := False;
  1736. Exit;
  1737. end;
  1738. end
  1739. else if (p.oper[2]^.typ = top_reg) then
  1740. begin
  1741. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1742. begin
  1743. Result := False;
  1744. Exit;
  1745. end
  1746. else if ([Ch_WOp3]*Ch<>[]) then
  1747. begin
  1748. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1749. Result := True
  1750. else
  1751. begin
  1752. Result := False;
  1753. Exit;
  1754. end;
  1755. end;
  1756. end;
  1757. end;
  1758. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1759. begin
  1760. if (p.oper[3]^.typ = top_ref) then
  1761. begin
  1762. if RegInRef(reg, p.oper[3]^.ref^) then
  1763. begin
  1764. Result := False;
  1765. Exit;
  1766. end;
  1767. end
  1768. else if (p.oper[3]^.typ = top_reg) then
  1769. begin
  1770. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1771. begin
  1772. Result := False;
  1773. Exit;
  1774. end
  1775. else if ([Ch_WOp4]*Ch<>[]) then
  1776. begin
  1777. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1778. Result := True
  1779. else
  1780. begin
  1781. Result := False;
  1782. Exit;
  1783. end;
  1784. end;
  1785. end;
  1786. end;
  1787. end;
  1788. end;
  1789. end;
  1790. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1791. case getsupreg(reg) of
  1792. RS_EAX:
  1793. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1794. begin
  1795. Result := True;
  1796. Exit;
  1797. end;
  1798. RS_ECX:
  1799. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1800. begin
  1801. Result := True;
  1802. Exit;
  1803. end;
  1804. RS_EDX:
  1805. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1806. begin
  1807. Result := True;
  1808. Exit;
  1809. end;
  1810. RS_EBX:
  1811. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1812. begin
  1813. Result := True;
  1814. Exit;
  1815. end;
  1816. RS_ESP:
  1817. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1818. begin
  1819. Result := True;
  1820. Exit;
  1821. end;
  1822. RS_EBP:
  1823. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1824. begin
  1825. Result := True;
  1826. Exit;
  1827. end;
  1828. RS_ESI:
  1829. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1830. begin
  1831. Result := True;
  1832. Exit;
  1833. end;
  1834. RS_EDI:
  1835. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1836. begin
  1837. Result := True;
  1838. Exit;
  1839. end;
  1840. else
  1841. ;
  1842. end;
  1843. end;
  1844. end;
  1845. end;
  1846. end;
  1847. end;
  1848. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1849. var
  1850. hp2,hp3 : tai;
  1851. begin
  1852. { some x86-64 issue a NOP before the real exit code }
  1853. if MatchInstruction(p,A_NOP,[]) then
  1854. GetNextInstruction(p,p);
  1855. result:=assigned(p) and (p.typ=ait_instruction) and
  1856. ((taicpu(p).opcode = A_RET) or
  1857. ((taicpu(p).opcode=A_LEAVE) and
  1858. GetNextInstruction(p,hp2) and
  1859. MatchInstruction(hp2,A_RET,[S_NO])
  1860. ) or
  1861. (((taicpu(p).opcode=A_LEA) and
  1862. MatchOpType(taicpu(p),top_ref,top_reg) and
  1863. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1864. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1865. ) and
  1866. GetNextInstruction(p,hp2) and
  1867. MatchInstruction(hp2,A_RET,[S_NO])
  1868. ) or
  1869. ((((taicpu(p).opcode=A_MOV) and
  1870. MatchOpType(taicpu(p),top_reg,top_reg) and
  1871. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1872. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1873. ((taicpu(p).opcode=A_LEA) and
  1874. MatchOpType(taicpu(p),top_ref,top_reg) and
  1875. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1876. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1877. )
  1878. ) and
  1879. GetNextInstruction(p,hp2) and
  1880. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1881. MatchOpType(taicpu(hp2),top_reg) and
  1882. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1883. GetNextInstruction(hp2,hp3) and
  1884. MatchInstruction(hp3,A_RET,[S_NO])
  1885. )
  1886. );
  1887. end;
  1888. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1889. begin
  1890. isFoldableArithOp := False;
  1891. case hp1.opcode of
  1892. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1893. isFoldableArithOp :=
  1894. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1895. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1896. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1897. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1898. (taicpu(hp1).oper[1]^.reg = reg);
  1899. A_INC,A_DEC,A_NEG,A_NOT:
  1900. isFoldableArithOp :=
  1901. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1902. (taicpu(hp1).oper[0]^.reg = reg);
  1903. else
  1904. ;
  1905. end;
  1906. end;
  1907. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1908. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1909. var
  1910. hp2: tai;
  1911. begin
  1912. hp2 := p;
  1913. repeat
  1914. hp2 := tai(hp2.previous);
  1915. if assigned(hp2) and
  1916. (hp2.typ = ait_regalloc) and
  1917. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1918. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1919. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1920. begin
  1921. RemoveInstruction(hp2);
  1922. break;
  1923. end;
  1924. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1925. end;
  1926. begin
  1927. case current_procinfo.procdef.returndef.typ of
  1928. arraydef,recorddef,pointerdef,
  1929. stringdef,enumdef,procdef,objectdef,errordef,
  1930. filedef,setdef,procvardef,
  1931. classrefdef,forwarddef:
  1932. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1933. orddef:
  1934. if current_procinfo.procdef.returndef.size <> 0 then
  1935. begin
  1936. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1937. { for int64/qword }
  1938. if current_procinfo.procdef.returndef.size = 8 then
  1939. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1940. end;
  1941. else
  1942. ;
  1943. end;
  1944. end;
  1945. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1946. var
  1947. hp1,hp2 : tai;
  1948. begin
  1949. result:=false;
  1950. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1951. begin
  1952. { vmova* reg1,reg1
  1953. =>
  1954. <nop> }
  1955. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1956. begin
  1957. RemoveCurrentP(p);
  1958. result:=true;
  1959. exit;
  1960. end
  1961. else if GetNextInstruction(p,hp1) then
  1962. begin
  1963. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1964. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1965. begin
  1966. { vmova* reg1,reg2
  1967. vmova* reg2,reg3
  1968. dealloc reg2
  1969. =>
  1970. vmova* reg1,reg3 }
  1971. TransferUsedRegs(TmpUsedRegs);
  1972. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1973. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1974. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1975. begin
  1976. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1977. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1978. RemoveInstruction(hp1);
  1979. result:=true;
  1980. exit;
  1981. end
  1982. { special case:
  1983. vmova* reg1,<op>
  1984. vmova* <op>,reg1
  1985. =>
  1986. vmova* reg1,<op> }
  1987. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1988. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1989. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1990. ) then
  1991. begin
  1992. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1993. RemoveInstruction(hp1);
  1994. result:=true;
  1995. exit;
  1996. end
  1997. end
  1998. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  1999. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2000. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2001. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2002. ) and
  2003. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2004. begin
  2005. { vmova* reg1,reg2
  2006. vmovs* reg2,<op>
  2007. dealloc reg2
  2008. =>
  2009. vmovs* reg1,reg3 }
  2010. TransferUsedRegs(TmpUsedRegs);
  2011. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2012. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2013. begin
  2014. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2015. taicpu(p).opcode:=taicpu(hp1).opcode;
  2016. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2017. RemoveInstruction(hp1);
  2018. result:=true;
  2019. exit;
  2020. end
  2021. end;
  2022. end;
  2023. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  2024. begin
  2025. if MatchInstruction(hp1,[A_VFMADDPD,
  2026. A_VFMADD132PD,
  2027. A_VFMADD132PS,
  2028. A_VFMADD132SD,
  2029. A_VFMADD132SS,
  2030. A_VFMADD213PD,
  2031. A_VFMADD213PS,
  2032. A_VFMADD213SD,
  2033. A_VFMADD213SS,
  2034. A_VFMADD231PD,
  2035. A_VFMADD231PS,
  2036. A_VFMADD231SD,
  2037. A_VFMADD231SS,
  2038. A_VFMADDSUB132PD,
  2039. A_VFMADDSUB132PS,
  2040. A_VFMADDSUB213PD,
  2041. A_VFMADDSUB213PS,
  2042. A_VFMADDSUB231PD,
  2043. A_VFMADDSUB231PS,
  2044. A_VFMSUB132PD,
  2045. A_VFMSUB132PS,
  2046. A_VFMSUB132SD,
  2047. A_VFMSUB132SS,
  2048. A_VFMSUB213PD,
  2049. A_VFMSUB213PS,
  2050. A_VFMSUB213SD,
  2051. A_VFMSUB213SS,
  2052. A_VFMSUB231PD,
  2053. A_VFMSUB231PS,
  2054. A_VFMSUB231SD,
  2055. A_VFMSUB231SS,
  2056. A_VFMSUBADD132PD,
  2057. A_VFMSUBADD132PS,
  2058. A_VFMSUBADD213PD,
  2059. A_VFMSUBADD213PS,
  2060. A_VFMSUBADD231PD,
  2061. A_VFMSUBADD231PS,
  2062. A_VFNMADD132PD,
  2063. A_VFNMADD132PS,
  2064. A_VFNMADD132SD,
  2065. A_VFNMADD132SS,
  2066. A_VFNMADD213PD,
  2067. A_VFNMADD213PS,
  2068. A_VFNMADD213SD,
  2069. A_VFNMADD213SS,
  2070. A_VFNMADD231PD,
  2071. A_VFNMADD231PS,
  2072. A_VFNMADD231SD,
  2073. A_VFNMADD231SS,
  2074. A_VFNMSUB132PD,
  2075. A_VFNMSUB132PS,
  2076. A_VFNMSUB132SD,
  2077. A_VFNMSUB132SS,
  2078. A_VFNMSUB213PD,
  2079. A_VFNMSUB213PS,
  2080. A_VFNMSUB213SD,
  2081. A_VFNMSUB213SS,
  2082. A_VFNMSUB231PD,
  2083. A_VFNMSUB231PS,
  2084. A_VFNMSUB231SD,
  2085. A_VFNMSUB231SS],[S_NO]) and
  2086. { we mix single and double opperations here because we assume that the compiler
  2087. generates vmovapd only after double operations and vmovaps only after single operations }
  2088. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  2089. GetNextInstruction(hp1,hp2) and
  2090. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2091. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2092. begin
  2093. TransferUsedRegs(TmpUsedRegs);
  2094. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2095. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2096. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2097. begin
  2098. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2099. RemoveCurrentP(p);
  2100. RemoveInstruction(hp2);
  2101. end;
  2102. end
  2103. else if (hp1.typ = ait_instruction) and
  2104. GetNextInstruction(hp1, hp2) and
  2105. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2106. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2107. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2108. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  2109. (((taicpu(p).opcode=A_MOVAPS) and
  2110. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2111. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2112. ((taicpu(p).opcode=A_MOVAPD) and
  2113. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2114. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2115. ) then
  2116. { change
  2117. movapX reg,reg2
  2118. addsX/subsX/... reg3, reg2
  2119. movapX reg2,reg
  2120. to
  2121. addsX/subsX/... reg3,reg
  2122. }
  2123. begin
  2124. TransferUsedRegs(TmpUsedRegs);
  2125. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2126. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2127. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2128. begin
  2129. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2130. debug_op2str(taicpu(p).opcode)+' '+
  2131. debug_op2str(taicpu(hp1).opcode)+' '+
  2132. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2133. { we cannot eliminate the first move if
  2134. the operations uses the same register for source and dest }
  2135. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2136. { Remember that hp1 is not necessarily the immediate
  2137. next instruction }
  2138. RemoveCurrentP(p);
  2139. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2140. RemoveInstruction(hp2);
  2141. result:=true;
  2142. end;
  2143. end
  2144. else if (hp1.typ = ait_instruction) and
  2145. (((taicpu(p).opcode=A_VMOVAPD) and
  2146. (taicpu(hp1).opcode=A_VCOMISD)) or
  2147. ((taicpu(p).opcode=A_VMOVAPS) and
  2148. ((taicpu(hp1).opcode=A_VCOMISS))
  2149. )
  2150. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2151. { change
  2152. movapX reg,reg1
  2153. vcomisX reg1,reg1
  2154. to
  2155. vcomisX reg,reg
  2156. }
  2157. begin
  2158. TransferUsedRegs(TmpUsedRegs);
  2159. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2160. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2161. begin
  2162. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2163. debug_op2str(taicpu(p).opcode)+' '+
  2164. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2165. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2166. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2167. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2168. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2169. RemoveCurrentP(p);
  2170. result:=true;
  2171. exit;
  2172. end;
  2173. end
  2174. end;
  2175. end;
  2176. end;
  2177. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2178. var
  2179. hp1 : tai;
  2180. begin
  2181. result:=false;
  2182. { replace
  2183. V<Op>X %mreg1,%mreg2,%mreg3
  2184. VMovX %mreg3,%mreg4
  2185. dealloc %mreg3
  2186. by
  2187. V<Op>X %mreg1,%mreg2,%mreg4
  2188. ?
  2189. }
  2190. if GetNextInstruction(p,hp1) and
  2191. { we mix single and double operations here because we assume that the compiler
  2192. generates vmovapd only after double operations and vmovaps only after single operations }
  2193. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2194. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2195. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2196. begin
  2197. TransferUsedRegs(TmpUsedRegs);
  2198. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2199. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2200. begin
  2201. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2202. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2203. RemoveInstruction(hp1);
  2204. result:=true;
  2205. end;
  2206. end;
  2207. end;
  2208. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2209. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2210. begin
  2211. Result := False;
  2212. { For safety reasons, only check for exact register matches }
  2213. { Check base register }
  2214. if (ref.base = AOldReg) then
  2215. begin
  2216. ref.base := ANewReg;
  2217. Result := True;
  2218. end;
  2219. { Check index register }
  2220. if (ref.index = AOldReg) then
  2221. begin
  2222. ref.index := ANewReg;
  2223. Result := True;
  2224. end;
  2225. end;
  2226. { Replaces all references to AOldReg in an operand to ANewReg }
  2227. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2228. var
  2229. OldSupReg, NewSupReg: TSuperRegister;
  2230. OldSubReg, NewSubReg: TSubRegister;
  2231. OldRegType: TRegisterType;
  2232. ThisOper: POper;
  2233. begin
  2234. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2235. Result := False;
  2236. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2237. InternalError(2020011801);
  2238. OldSupReg := getsupreg(AOldReg);
  2239. OldSubReg := getsubreg(AOldReg);
  2240. OldRegType := getregtype(AOldReg);
  2241. NewSupReg := getsupreg(ANewReg);
  2242. NewSubReg := getsubreg(ANewReg);
  2243. if OldRegType <> getregtype(ANewReg) then
  2244. InternalError(2020011802);
  2245. if OldSubReg <> NewSubReg then
  2246. InternalError(2020011803);
  2247. case ThisOper^.typ of
  2248. top_reg:
  2249. if (
  2250. (ThisOper^.reg = AOldReg) or
  2251. (
  2252. (OldRegType = R_INTREGISTER) and
  2253. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2254. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2255. (
  2256. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2257. {$ifndef x86_64}
  2258. and (
  2259. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2260. don't have an 8-bit representation }
  2261. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2262. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2263. )
  2264. {$endif x86_64}
  2265. )
  2266. )
  2267. ) then
  2268. begin
  2269. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2270. Result := True;
  2271. end;
  2272. top_ref:
  2273. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2274. Result := True;
  2275. else
  2276. ;
  2277. end;
  2278. end;
  2279. { Replaces all references to AOldReg in an instruction to ANewReg }
  2280. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2281. const
  2282. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2283. var
  2284. OperIdx: Integer;
  2285. begin
  2286. Result := False;
  2287. for OperIdx := 0 to p.ops - 1 do
  2288. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2289. begin
  2290. { The shift and rotate instructions can only use CL }
  2291. if not (
  2292. (OperIdx = 0) and
  2293. { This second condition just helps to avoid unnecessarily
  2294. calling MatchInstruction for 10 different opcodes }
  2295. (p.oper[0]^.reg = NR_CL) and
  2296. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2297. ) then
  2298. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2299. end
  2300. else if p.oper[OperIdx]^.typ = top_ref then
  2301. { It's okay to replace registers in references that get written to }
  2302. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2303. end;
  2304. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2305. begin
  2306. with ref^ do
  2307. Result :=
  2308. (index = NR_NO) and
  2309. (
  2310. {$ifdef x86_64}
  2311. (
  2312. (base = NR_RIP) and
  2313. (refaddr in [addr_pic, addr_pic_no_got])
  2314. ) or
  2315. {$endif x86_64}
  2316. (base = NR_STACK_POINTER_REG) or
  2317. (base = current_procinfo.framepointer)
  2318. );
  2319. end;
  2320. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2321. var
  2322. l: asizeint;
  2323. begin
  2324. Result := False;
  2325. { Should have been checked previously }
  2326. if p.opcode <> A_LEA then
  2327. InternalError(2020072501);
  2328. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2329. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2330. not(cs_opt_size in current_settings.optimizerswitches) then
  2331. exit;
  2332. with p.oper[0]^.ref^ do
  2333. begin
  2334. if (base <> p.oper[1]^.reg) or
  2335. (index <> NR_NO) or
  2336. assigned(symbol) then
  2337. exit;
  2338. l:=offset;
  2339. if (l=1) and UseIncDec then
  2340. begin
  2341. p.opcode:=A_INC;
  2342. p.loadreg(0,p.oper[1]^.reg);
  2343. p.ops:=1;
  2344. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2345. end
  2346. else if (l=-1) and UseIncDec then
  2347. begin
  2348. p.opcode:=A_DEC;
  2349. p.loadreg(0,p.oper[1]^.reg);
  2350. p.ops:=1;
  2351. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2352. end
  2353. else
  2354. begin
  2355. if (l<0) and (l<>-2147483648) then
  2356. begin
  2357. p.opcode:=A_SUB;
  2358. p.loadConst(0,-l);
  2359. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2360. end
  2361. else
  2362. begin
  2363. p.opcode:=A_ADD;
  2364. p.loadConst(0,l);
  2365. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2366. end;
  2367. end;
  2368. end;
  2369. Result := True;
  2370. end;
  2371. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2372. var
  2373. CurrentReg, ReplaceReg: TRegister;
  2374. begin
  2375. Result := False;
  2376. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2377. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2378. case hp.opcode of
  2379. A_FSTSW, A_FNSTSW,
  2380. A_IN, A_INS, A_OUT, A_OUTS,
  2381. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2382. { These routines have explicit operands, but they are restricted in
  2383. what they can be (e.g. IN and OUT can only read from AL, AX or
  2384. EAX. }
  2385. Exit;
  2386. A_IMUL:
  2387. begin
  2388. { The 1-operand version writes to implicit registers
  2389. The 2-operand version reads from the first operator, and reads
  2390. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2391. the 3-operand version reads from a register that it doesn't write to
  2392. }
  2393. case hp.ops of
  2394. 1:
  2395. if (
  2396. (
  2397. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2398. ) or
  2399. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2400. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2401. begin
  2402. Result := True;
  2403. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2404. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2405. end;
  2406. 2:
  2407. { Only modify the first parameter }
  2408. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2409. begin
  2410. Result := True;
  2411. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2412. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2413. end;
  2414. 3:
  2415. { Only modify the second parameter }
  2416. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2417. begin
  2418. Result := True;
  2419. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2420. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2421. end;
  2422. else
  2423. InternalError(2020012901);
  2424. end;
  2425. end;
  2426. else
  2427. if (hp.ops > 0) and
  2428. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2429. begin
  2430. Result := True;
  2431. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2432. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2433. end;
  2434. end;
  2435. end;
  2436. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2437. var
  2438. hp1, hp2, hp3: tai;
  2439. DoOptimisation, TempBool: Boolean;
  2440. {$ifdef x86_64}
  2441. NewConst: TCGInt;
  2442. {$endif x86_64}
  2443. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2444. begin
  2445. if taicpu(hp1).opcode = signed_movop then
  2446. begin
  2447. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2448. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2449. end
  2450. else
  2451. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2452. end;
  2453. function TryConstMerge(var p1, p2: tai): Boolean;
  2454. var
  2455. ThisRef: TReference;
  2456. begin
  2457. Result := False;
  2458. ThisRef := taicpu(p2).oper[1]^.ref^;
  2459. { Only permit writes to the stack, since we can guarantee alignment with that }
  2460. if (ThisRef.index = NR_NO) and
  2461. (
  2462. (ThisRef.base = NR_STACK_POINTER_REG) or
  2463. (ThisRef.base = current_procinfo.framepointer)
  2464. ) then
  2465. begin
  2466. case taicpu(p).opsize of
  2467. S_B:
  2468. begin
  2469. { Word writes must be on a 2-byte boundary }
  2470. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2471. begin
  2472. { Reduce offset of second reference to see if it is sequential with the first }
  2473. Dec(ThisRef.offset, 1);
  2474. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2475. begin
  2476. { Make sure the constants aren't represented as a
  2477. negative number, as these won't merge properly }
  2478. taicpu(p1).opsize := S_W;
  2479. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2480. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2481. RemoveInstruction(p2);
  2482. Result := True;
  2483. end;
  2484. end;
  2485. end;
  2486. S_W:
  2487. begin
  2488. { Longword writes must be on a 4-byte boundary }
  2489. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2490. begin
  2491. { Reduce offset of second reference to see if it is sequential with the first }
  2492. Dec(ThisRef.offset, 2);
  2493. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2494. begin
  2495. { Make sure the constants aren't represented as a
  2496. negative number, as these won't merge properly }
  2497. taicpu(p1).opsize := S_L;
  2498. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2499. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2500. RemoveInstruction(p2);
  2501. Result := True;
  2502. end;
  2503. end;
  2504. end;
  2505. {$ifdef x86_64}
  2506. S_L:
  2507. begin
  2508. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2509. see if the constants can be encoded this way. }
  2510. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2511. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2512. { Quadword writes must be on an 8-byte boundary }
  2513. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2514. begin
  2515. { Reduce offset of second reference to see if it is sequential with the first }
  2516. Dec(ThisRef.offset, 4);
  2517. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2518. begin
  2519. { Make sure the constants aren't represented as a
  2520. negative number, as these won't merge properly }
  2521. taicpu(p1).opsize := S_Q;
  2522. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2523. taicpu(p1).oper[0]^.val := NewConst;
  2524. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2525. RemoveInstruction(p2);
  2526. Result := True;
  2527. end;
  2528. end;
  2529. end;
  2530. {$endif x86_64}
  2531. else
  2532. ;
  2533. end;
  2534. end;
  2535. end;
  2536. var
  2537. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2538. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2539. NewSize: topsize; NewOffset: asizeint;
  2540. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2541. SourceRef, TargetRef: TReference;
  2542. MovAligned, MovUnaligned: TAsmOp;
  2543. ThisRef: TReference;
  2544. JumpTracking: TLinkedList;
  2545. begin
  2546. Result:=false;
  2547. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2548. { remove mov reg1,reg1? }
  2549. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2550. then
  2551. begin
  2552. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2553. { take care of the register (de)allocs following p }
  2554. RemoveCurrentP(p, hp1);
  2555. Result:=true;
  2556. exit;
  2557. end;
  2558. { All the next optimisations require a next instruction }
  2559. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2560. Exit;
  2561. { Prevent compiler warnings }
  2562. p_TargetReg := NR_NO;
  2563. if taicpu(p).oper[1]^.typ = top_reg then
  2564. begin
  2565. { Saves on a large number of dereferences }
  2566. p_TargetReg := taicpu(p).oper[1]^.reg;
  2567. { Look for:
  2568. mov %reg1,%reg2
  2569. ??? %reg2,r/m
  2570. Change to:
  2571. mov %reg1,%reg2
  2572. ??? %reg1,r/m
  2573. }
  2574. if taicpu(p).oper[0]^.typ = top_reg then
  2575. begin
  2576. if RegReadByInstruction(p_TargetReg, hp1) and
  2577. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2578. begin
  2579. { A change has occurred, just not in p }
  2580. Result := True;
  2581. TransferUsedRegs(TmpUsedRegs);
  2582. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2583. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2584. { Just in case something didn't get modified (e.g. an
  2585. implicit register) }
  2586. not RegReadByInstruction(p_TargetReg, hp1) then
  2587. begin
  2588. { We can remove the original MOV }
  2589. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2590. RemoveCurrentp(p, hp1);
  2591. { UsedRegs got updated by RemoveCurrentp }
  2592. Result := True;
  2593. Exit;
  2594. end;
  2595. { If we know a MOV instruction has become a null operation, we might as well
  2596. get rid of it now to save time. }
  2597. if (taicpu(hp1).opcode = A_MOV) and
  2598. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2599. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2600. { Just being a register is enough to confirm it's a null operation }
  2601. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2602. begin
  2603. Result := True;
  2604. { Speed-up to reduce a pipeline stall... if we had something like...
  2605. movl %eax,%edx
  2606. movw %dx,%ax
  2607. ... the second instruction would change to movw %ax,%ax, but
  2608. given that it is now %ax that's active rather than %eax,
  2609. penalties might occur due to a partial register write, so instead,
  2610. change it to a MOVZX instruction when optimising for speed.
  2611. }
  2612. if not (cs_opt_size in current_settings.optimizerswitches) and
  2613. IsMOVZXAcceptable and
  2614. (taicpu(hp1).opsize < taicpu(p).opsize)
  2615. {$ifdef x86_64}
  2616. { operations already implicitly set the upper 64 bits to zero }
  2617. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2618. {$endif x86_64}
  2619. then
  2620. begin
  2621. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2622. case taicpu(p).opsize of
  2623. S_W:
  2624. if taicpu(hp1).opsize = S_B then
  2625. taicpu(hp1).opsize := S_BL
  2626. else
  2627. InternalError(2020012911);
  2628. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2629. case taicpu(hp1).opsize of
  2630. S_B:
  2631. taicpu(hp1).opsize := S_BL;
  2632. S_W:
  2633. taicpu(hp1).opsize := S_WL;
  2634. else
  2635. InternalError(2020012912);
  2636. end;
  2637. else
  2638. InternalError(2020012910);
  2639. end;
  2640. taicpu(hp1).opcode := A_MOVZX;
  2641. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2642. end
  2643. else
  2644. begin
  2645. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2646. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2647. RemoveInstruction(hp1);
  2648. { The instruction after what was hp1 is now the immediate next instruction,
  2649. so we can continue to make optimisations if it's present }
  2650. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2651. Exit;
  2652. hp1 := hp2;
  2653. end;
  2654. end;
  2655. end;
  2656. end;
  2657. end;
  2658. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2659. overwrites the original destination register. e.g.
  2660. movl ###,%reg2d
  2661. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2662. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2663. }
  2664. if (taicpu(p).oper[1]^.typ = top_reg) and
  2665. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2666. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2667. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2668. begin
  2669. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2670. begin
  2671. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2672. case taicpu(p).oper[0]^.typ of
  2673. top_const:
  2674. { We have something like:
  2675. movb $x, %regb
  2676. movzbl %regb,%regd
  2677. Change to:
  2678. movl $x, %regd
  2679. }
  2680. begin
  2681. case taicpu(hp1).opsize of
  2682. S_BW:
  2683. begin
  2684. convert_mov_value(A_MOVSX, $FF);
  2685. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2686. taicpu(p).opsize := S_W;
  2687. end;
  2688. S_BL:
  2689. begin
  2690. convert_mov_value(A_MOVSX, $FF);
  2691. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2692. taicpu(p).opsize := S_L;
  2693. end;
  2694. S_WL:
  2695. begin
  2696. convert_mov_value(A_MOVSX, $FFFF);
  2697. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2698. taicpu(p).opsize := S_L;
  2699. end;
  2700. {$ifdef x86_64}
  2701. S_BQ:
  2702. begin
  2703. convert_mov_value(A_MOVSX, $FF);
  2704. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2705. taicpu(p).opsize := S_Q;
  2706. end;
  2707. S_WQ:
  2708. begin
  2709. convert_mov_value(A_MOVSX, $FFFF);
  2710. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2711. taicpu(p).opsize := S_Q;
  2712. end;
  2713. S_LQ:
  2714. begin
  2715. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2716. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2717. taicpu(p).opsize := S_Q;
  2718. end;
  2719. {$endif x86_64}
  2720. else
  2721. { If hp1 was a MOV instruction, it should have been
  2722. optimised already }
  2723. InternalError(2020021001);
  2724. end;
  2725. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2726. RemoveInstruction(hp1);
  2727. Result := True;
  2728. Exit;
  2729. end;
  2730. top_ref:
  2731. begin
  2732. { We have something like:
  2733. movb mem, %regb
  2734. movzbl %regb,%regd
  2735. Change to:
  2736. movzbl mem, %regd
  2737. }
  2738. ThisRef := taicpu(p).oper[0]^.ref^;
  2739. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2740. begin
  2741. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2742. taicpu(hp1).loadref(0, ThisRef);
  2743. { Make sure any registers in the references are properly tracked }
  2744. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2745. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2746. if (ThisRef.index <> NR_NO) then
  2747. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2748. RemoveCurrentP(p, hp1);
  2749. Result := True;
  2750. Exit;
  2751. end;
  2752. end;
  2753. else
  2754. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2755. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2756. Exit;
  2757. end;
  2758. end
  2759. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2760. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2761. optimised }
  2762. else
  2763. begin
  2764. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2765. RemoveCurrentP(p, hp1);
  2766. Result := True;
  2767. Exit;
  2768. end;
  2769. end;
  2770. if (taicpu(hp1).opcode = A_AND) and
  2771. (taicpu(p).oper[1]^.typ = top_reg) and
  2772. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2773. begin
  2774. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2775. begin
  2776. case taicpu(p).opsize of
  2777. S_L:
  2778. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2779. begin
  2780. { Optimize out:
  2781. mov x, %reg
  2782. and ffffffffh, %reg
  2783. }
  2784. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2785. RemoveInstruction(hp1);
  2786. Result:=true;
  2787. exit;
  2788. end;
  2789. S_Q: { TODO: Confirm if this is even possible }
  2790. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2791. begin
  2792. { Optimize out:
  2793. mov x, %reg
  2794. and ffffffffffffffffh, %reg
  2795. }
  2796. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2797. RemoveInstruction(hp1);
  2798. Result:=true;
  2799. exit;
  2800. end;
  2801. else
  2802. ;
  2803. end;
  2804. if (
  2805. (taicpu(p).oper[0]^.typ=top_reg) or
  2806. (
  2807. (taicpu(p).oper[0]^.typ=top_ref) and
  2808. (taicpu(p).oper[0]^.ref^.refaddr<>addr_full)
  2809. )
  2810. ) and
  2811. GetNextInstruction(hp1,hp2) and
  2812. MatchInstruction(hp2,A_TEST,[]) and
  2813. (
  2814. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  2815. (
  2816. { If the register being tested is smaller than the one
  2817. that received a bitwise AND, permit it if the constant
  2818. fits into the smaller size }
  2819. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  2820. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  2821. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  2822. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  2823. (
  2824. (
  2825. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  2826. (taicpu(hp1).oper[0]^.val <= $FF)
  2827. ) or
  2828. (
  2829. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  2830. (taicpu(hp1).oper[0]^.val <= $FFFF)
  2831. {$ifdef x86_64}
  2832. ) or
  2833. (
  2834. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  2835. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  2836. {$endif x86_64}
  2837. )
  2838. )
  2839. )
  2840. ) and
  2841. (
  2842. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2843. MatchOperand(taicpu(hp2).oper[0]^,-1)
  2844. ) and
  2845. GetNextInstruction(hp2,hp3) and
  2846. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2847. (taicpu(hp3).condition in [C_E,C_NE]) then
  2848. begin
  2849. TransferUsedRegs(TmpUsedRegs);
  2850. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2851. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2852. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2853. begin
  2854. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2855. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2856. taicpu(hp1).opcode:=A_TEST;
  2857. { Shrink the TEST instruction down to the smallest possible size }
  2858. case taicpu(hp1).oper[0]^.val of
  2859. 0..255:
  2860. if (taicpu(hp1).opsize <> S_B)
  2861. {$ifndef x86_64}
  2862. and (
  2863. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  2864. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  2865. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  2866. )
  2867. {$endif x86_64}
  2868. then
  2869. begin
  2870. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  2871. { Only print debug message if the TEST instruction
  2872. is a different size before and after }
  2873. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  2874. taicpu(hp1).opsize := S_B;
  2875. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  2876. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  2877. end;
  2878. 256..65535:
  2879. if (taicpu(hp1).opsize <> S_W) then
  2880. begin
  2881. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  2882. { Only print debug message if the TEST instruction
  2883. is a different size before and after }
  2884. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  2885. taicpu(hp1).opsize := S_W;
  2886. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  2887. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  2888. end;
  2889. {$ifdef x86_64}
  2890. 65536..$7FFFFFFF:
  2891. if (taicpu(hp1).opsize <> S_L) then
  2892. begin
  2893. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  2894. { Only print debug message if the TEST instruction
  2895. is a different size before and after }
  2896. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  2897. taicpu(hp1).opsize := S_L;
  2898. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  2899. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2900. end;
  2901. {$endif x86_64}
  2902. else
  2903. ;
  2904. end;
  2905. RemoveInstruction(hp2);
  2906. RemoveCurrentP(p, hp1);
  2907. Result:=true;
  2908. exit;
  2909. end;
  2910. end;
  2911. end
  2912. else if IsMOVZXAcceptable and
  2913. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  2914. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  2915. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  2916. then
  2917. begin
  2918. InputVal := debug_operstr(taicpu(p).oper[0]^);
  2919. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  2920. case taicpu(p).opsize of
  2921. S_B:
  2922. if (taicpu(hp1).oper[0]^.val = $ff) then
  2923. begin
  2924. { Convert:
  2925. movb x, %regl movb x, %regl
  2926. andw ffh, %regw andl ffh, %regd
  2927. To:
  2928. movzbw x, %regd movzbl x, %regd
  2929. (Identical registers, just different sizes)
  2930. }
  2931. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  2932. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  2933. case taicpu(hp1).opsize of
  2934. S_W: NewSize := S_BW;
  2935. S_L: NewSize := S_BL;
  2936. {$ifdef x86_64}
  2937. S_Q: NewSize := S_BQ;
  2938. {$endif x86_64}
  2939. else
  2940. InternalError(2018011510);
  2941. end;
  2942. end
  2943. else
  2944. NewSize := S_NO;
  2945. S_W:
  2946. if (taicpu(hp1).oper[0]^.val = $ffff) then
  2947. begin
  2948. { Convert:
  2949. movw x, %regw
  2950. andl ffffh, %regd
  2951. To:
  2952. movzwl x, %regd
  2953. (Identical registers, just different sizes)
  2954. }
  2955. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  2956. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  2957. case taicpu(hp1).opsize of
  2958. S_L: NewSize := S_WL;
  2959. {$ifdef x86_64}
  2960. S_Q: NewSize := S_WQ;
  2961. {$endif x86_64}
  2962. else
  2963. InternalError(2018011511);
  2964. end;
  2965. end
  2966. else
  2967. NewSize := S_NO;
  2968. else
  2969. NewSize := S_NO;
  2970. end;
  2971. if NewSize <> S_NO then
  2972. begin
  2973. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  2974. { The actual optimization }
  2975. taicpu(p).opcode := A_MOVZX;
  2976. taicpu(p).changeopsize(NewSize);
  2977. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  2978. { Safeguard if "and" is followed by a conditional command }
  2979. TransferUsedRegs(TmpUsedRegs);
  2980. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  2981. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  2982. begin
  2983. { At this point, the "and" command is effectively equivalent to
  2984. "test %reg,%reg". This will be handled separately by the
  2985. Peephole Optimizer. [Kit] }
  2986. DebugMsg(SPeepholeOptimization + PreMessage +
  2987. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2988. end
  2989. else
  2990. begin
  2991. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  2992. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2993. RemoveInstruction(hp1);
  2994. end;
  2995. Result := True;
  2996. Exit;
  2997. end;
  2998. end;
  2999. end;
  3000. if (taicpu(hp1).opcode = A_OR) and
  3001. (taicpu(p).oper[1]^.typ = top_reg) and
  3002. MatchOperand(taicpu(p).oper[0]^, 0) and
  3003. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3004. begin
  3005. { mov 0, %reg
  3006. or ###,%reg
  3007. Change to (only if the flags are not used):
  3008. mov ###,%reg
  3009. }
  3010. TransferUsedRegs(TmpUsedRegs);
  3011. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3012. DoOptimisation := True;
  3013. { Even if the flags are used, we might be able to do the optimisation
  3014. if the conditions are predictable }
  3015. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3016. begin
  3017. { Only perform if ### = %reg (the same register) or equal to 0,
  3018. so %reg is guaranteed to still have a value of zero }
  3019. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3020. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3021. begin
  3022. hp2 := hp1;
  3023. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3024. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3025. GetNextInstruction(hp2, hp3) do
  3026. begin
  3027. { Don't continue modifying if the flags state is getting changed }
  3028. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3029. Break;
  3030. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  3031. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3032. begin
  3033. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3034. begin
  3035. { Condition is always true }
  3036. case taicpu(hp3).opcode of
  3037. A_Jcc:
  3038. begin
  3039. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3040. { Check for jump shortcuts before we destroy the condition }
  3041. DoJumpOptimizations(hp3, TempBool);
  3042. MakeUnconditional(taicpu(hp3));
  3043. Result := True;
  3044. end;
  3045. A_CMOVcc:
  3046. begin
  3047. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3048. taicpu(hp3).opcode := A_MOV;
  3049. taicpu(hp3).condition := C_None;
  3050. Result := True;
  3051. end;
  3052. A_SETcc:
  3053. begin
  3054. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3055. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3056. taicpu(hp3).opcode := A_MOV;
  3057. taicpu(hp3).ops := 2;
  3058. taicpu(hp3).condition := C_None;
  3059. taicpu(hp3).opsize := S_B;
  3060. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3061. taicpu(hp3).loadconst(0, 1);
  3062. Result := True;
  3063. end;
  3064. else
  3065. InternalError(2021090701);
  3066. end;
  3067. end
  3068. else if (taicpu(hp3).condition in [C_A, C_B, C_C, C_G, C_L, C_NE, C_NZ, C_O, C_S]) then
  3069. begin
  3070. { Condition is always false }
  3071. case taicpu(hp3).opcode of
  3072. A_Jcc:
  3073. begin
  3074. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3075. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3076. RemoveInstruction(hp3);
  3077. Result := True;
  3078. { Since hp3 was deleted, hp2 must not be updated }
  3079. Continue;
  3080. end;
  3081. A_CMOVcc:
  3082. begin
  3083. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3084. RemoveInstruction(hp3);
  3085. Result := True;
  3086. { Since hp3 was deleted, hp2 must not be updated }
  3087. Continue;
  3088. end;
  3089. A_SETcc:
  3090. begin
  3091. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3092. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3093. taicpu(hp3).opcode := A_MOV;
  3094. taicpu(hp3).ops := 2;
  3095. taicpu(hp3).condition := C_None;
  3096. taicpu(hp3).opsize := S_B;
  3097. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3098. taicpu(hp3).loadconst(0, 0);
  3099. Result := True;
  3100. end;
  3101. else
  3102. InternalError(2021090702);
  3103. end;
  3104. end
  3105. else
  3106. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3107. DoOptimisation := False;
  3108. end;
  3109. hp2 := hp3;
  3110. end;
  3111. { Flags are still in use - don't optimise }
  3112. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3113. DoOptimisation := False;
  3114. end
  3115. else
  3116. DoOptimisation := False;
  3117. end;
  3118. if DoOptimisation then
  3119. begin
  3120. {$ifdef x86_64}
  3121. { OR only supports 32-bit sign-extended constants for 64-bit
  3122. instructions, so compensate for this if the constant is
  3123. encoded as a value greater than or equal to 2^31 }
  3124. if (taicpu(hp1).opsize = S_Q) and
  3125. (taicpu(hp1).oper[0]^.typ = top_const) and
  3126. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3127. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3128. {$endif x86_64}
  3129. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3130. taicpu(hp1).opcode := A_MOV;
  3131. RemoveCurrentP(p, hp1);
  3132. Result := True;
  3133. Exit;
  3134. end;
  3135. end;
  3136. { Next instruction is also a MOV ? }
  3137. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3138. begin
  3139. if MatchOpType(taicpu(p), top_const, top_ref) and
  3140. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3141. TryConstMerge(p, hp1) then
  3142. begin
  3143. Result := True;
  3144. { In case we have four byte writes in a row, check for 2 more
  3145. right now so we don't have to wait for another iteration of
  3146. pass 1
  3147. }
  3148. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3149. case taicpu(p).opsize of
  3150. S_W:
  3151. begin
  3152. if GetNextInstruction(p, hp1) and
  3153. MatchInstruction(hp1, A_MOV, [S_B]) and
  3154. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3155. GetNextInstruction(hp1, hp2) and
  3156. MatchInstruction(hp2, A_MOV, [S_B]) and
  3157. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3158. { Try to merge the two bytes }
  3159. TryConstMerge(hp1, hp2) then
  3160. { Now try to merge the two words (hp2 will get deleted) }
  3161. TryConstMerge(p, hp1);
  3162. end;
  3163. S_L:
  3164. begin
  3165. { Though this only really benefits x86_64 and not i386, it
  3166. gets a potential optimisation done faster and hence
  3167. reduces the number of times OptPass1MOV is entered }
  3168. if GetNextInstruction(p, hp1) and
  3169. MatchInstruction(hp1, A_MOV, [S_W]) and
  3170. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3171. GetNextInstruction(hp1, hp2) and
  3172. MatchInstruction(hp2, A_MOV, [S_W]) and
  3173. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3174. { Try to merge the two words }
  3175. TryConstMerge(hp1, hp2) then
  3176. { This will always fail on i386, so don't bother
  3177. calling it unless we're doing x86_64 }
  3178. {$ifdef x86_64}
  3179. { Now try to merge the two longwords (hp2 will get deleted) }
  3180. TryConstMerge(p, hp1)
  3181. {$endif x86_64}
  3182. ;
  3183. end;
  3184. else
  3185. ;
  3186. end;
  3187. Exit;
  3188. end;
  3189. if (taicpu(p).oper[1]^.typ = top_reg) and
  3190. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3191. begin
  3192. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3193. TransferUsedRegs(TmpUsedRegs);
  3194. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3195. { we have
  3196. mov x, %treg
  3197. mov %treg, y
  3198. }
  3199. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3200. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3201. { we've got
  3202. mov x, %treg
  3203. mov %treg, y
  3204. with %treg is not used after }
  3205. case taicpu(p).oper[0]^.typ Of
  3206. { top_reg is covered by DeepMOVOpt }
  3207. top_const:
  3208. begin
  3209. { change
  3210. mov const, %treg
  3211. mov %treg, y
  3212. to
  3213. mov const, y
  3214. }
  3215. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3216. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3217. begin
  3218. if taicpu(hp1).oper[1]^.typ=top_reg then
  3219. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3220. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3221. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3222. RemoveInstruction(hp1);
  3223. Result:=true;
  3224. Exit;
  3225. end;
  3226. end;
  3227. top_ref:
  3228. case taicpu(hp1).oper[1]^.typ of
  3229. top_reg:
  3230. begin
  3231. { change
  3232. mov mem, %treg
  3233. mov %treg, %reg
  3234. to
  3235. mov mem, %reg"
  3236. }
  3237. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3238. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3239. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3240. RemoveInstruction(hp1);
  3241. Result:=true;
  3242. Exit;
  3243. end;
  3244. top_ref:
  3245. begin
  3246. {$ifdef x86_64}
  3247. { Look for the following to simplify:
  3248. mov x(mem1), %reg
  3249. mov %reg, y(mem2)
  3250. mov x+8(mem1), %reg
  3251. mov %reg, y+8(mem2)
  3252. Change to:
  3253. movdqu x(mem1), %xmmreg
  3254. movdqu %xmmreg, y(mem2)
  3255. ...but only as long as the memory blocks don't overlap
  3256. }
  3257. SourceRef := taicpu(p).oper[0]^.ref^;
  3258. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3259. if (taicpu(p).opsize = S_Q) and
  3260. GetNextInstruction(hp1, hp2) and
  3261. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3262. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3263. begin
  3264. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3265. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3266. Inc(SourceRef.offset, 8);
  3267. if UseAVX then
  3268. begin
  3269. MovAligned := A_VMOVDQA;
  3270. MovUnaligned := A_VMOVDQU;
  3271. end
  3272. else
  3273. begin
  3274. MovAligned := A_MOVDQA;
  3275. MovUnaligned := A_MOVDQU;
  3276. end;
  3277. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3278. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3279. begin
  3280. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3281. Inc(TargetRef.offset, 8);
  3282. if GetNextInstruction(hp2, hp3) and
  3283. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3284. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3285. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3286. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3287. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3288. begin
  3289. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3290. if NewMMReg <> NR_NO then
  3291. begin
  3292. { Remember that the offsets are 8 ahead }
  3293. if ((SourceRef.offset mod 16) = 8) and
  3294. (
  3295. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3296. (SourceRef.base = current_procinfo.framepointer) or
  3297. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3298. ) then
  3299. taicpu(p).opcode := MovAligned
  3300. else
  3301. taicpu(p).opcode := MovUnaligned;
  3302. taicpu(p).opsize := S_XMM;
  3303. taicpu(p).oper[1]^.reg := NewMMReg;
  3304. if ((TargetRef.offset mod 16) = 8) and
  3305. (
  3306. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3307. (TargetRef.base = current_procinfo.framepointer) or
  3308. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3309. ) then
  3310. taicpu(hp1).opcode := MovAligned
  3311. else
  3312. taicpu(hp1).opcode := MovUnaligned;
  3313. taicpu(hp1).opsize := S_XMM;
  3314. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3315. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3316. RemoveInstruction(hp2);
  3317. RemoveInstruction(hp3);
  3318. Result := True;
  3319. Exit;
  3320. end;
  3321. end;
  3322. end
  3323. else
  3324. begin
  3325. { See if the next references are 8 less rather than 8 greater }
  3326. Dec(SourceRef.offset, 16); { -8 the other way }
  3327. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3328. begin
  3329. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3330. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3331. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3332. GetNextInstruction(hp2, hp3) and
  3333. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3334. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3335. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3336. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3337. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3338. begin
  3339. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3340. if NewMMReg <> NR_NO then
  3341. begin
  3342. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3343. if ((SourceRef.offset mod 16) = 0) and
  3344. (
  3345. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3346. (SourceRef.base = current_procinfo.framepointer) or
  3347. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3348. ) then
  3349. taicpu(hp2).opcode := MovAligned
  3350. else
  3351. taicpu(hp2).opcode := MovUnaligned;
  3352. taicpu(hp2).opsize := S_XMM;
  3353. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3354. if ((TargetRef.offset mod 16) = 0) and
  3355. (
  3356. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3357. (TargetRef.base = current_procinfo.framepointer) or
  3358. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3359. ) then
  3360. taicpu(hp3).opcode := MovAligned
  3361. else
  3362. taicpu(hp3).opcode := MovUnaligned;
  3363. taicpu(hp3).opsize := S_XMM;
  3364. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3365. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3366. RemoveInstruction(hp1);
  3367. RemoveCurrentP(p, hp2);
  3368. Result := True;
  3369. Exit;
  3370. end;
  3371. end;
  3372. end;
  3373. end;
  3374. end;
  3375. {$endif x86_64}
  3376. end;
  3377. else
  3378. { The write target should be a reg or a ref }
  3379. InternalError(2021091601);
  3380. end;
  3381. else
  3382. ;
  3383. end
  3384. else
  3385. { %treg is used afterwards, but all eventualities
  3386. other than the first MOV instruction being a constant
  3387. are covered by DeepMOVOpt, so only check for that }
  3388. if (taicpu(p).oper[0]^.typ = top_const) and
  3389. (
  3390. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3391. not (cs_opt_size in current_settings.optimizerswitches) or
  3392. (taicpu(hp1).opsize = S_B)
  3393. ) and
  3394. (
  3395. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3396. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3397. ) then
  3398. begin
  3399. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3400. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3401. end;
  3402. end;
  3403. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3404. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3405. { mov reg1, mem1 or mov mem1, reg1
  3406. mov mem2, reg2 mov reg2, mem2}
  3407. begin
  3408. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3409. { mov reg1, mem1 or mov mem1, reg1
  3410. mov mem2, reg1 mov reg2, mem1}
  3411. begin
  3412. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3413. { Removes the second statement from
  3414. mov reg1, mem1/reg2
  3415. mov mem1/reg2, reg1 }
  3416. begin
  3417. if taicpu(p).oper[0]^.typ=top_reg then
  3418. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3419. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3420. RemoveInstruction(hp1);
  3421. Result:=true;
  3422. exit;
  3423. end
  3424. else
  3425. begin
  3426. TransferUsedRegs(TmpUsedRegs);
  3427. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3428. if (taicpu(p).oper[1]^.typ = top_ref) and
  3429. { mov reg1, mem1
  3430. mov mem2, reg1 }
  3431. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3432. GetNextInstruction(hp1, hp2) and
  3433. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3434. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3435. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3436. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3437. { change to
  3438. mov reg1, mem1 mov reg1, mem1
  3439. mov mem2, reg1 cmp reg1, mem2
  3440. cmp mem1, reg1
  3441. }
  3442. begin
  3443. RemoveInstruction(hp2);
  3444. taicpu(hp1).opcode := A_CMP;
  3445. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3446. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3447. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3448. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3449. end;
  3450. end;
  3451. end
  3452. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3453. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3454. begin
  3455. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3456. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3457. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3458. end
  3459. else
  3460. begin
  3461. TransferUsedRegs(TmpUsedRegs);
  3462. if GetNextInstruction(hp1, hp2) and
  3463. MatchOpType(taicpu(p),top_ref,top_reg) and
  3464. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3465. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3466. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3467. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3468. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3469. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3470. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3471. { mov mem1, %reg1
  3472. mov %reg1, mem2
  3473. mov mem2, reg2
  3474. to:
  3475. mov mem1, reg2
  3476. mov reg2, mem2}
  3477. begin
  3478. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3479. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3480. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3481. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3482. RemoveInstruction(hp2);
  3483. Result := True;
  3484. end
  3485. {$ifdef i386}
  3486. { this is enabled for i386 only, as the rules to create the reg sets below
  3487. are too complicated for x86-64, so this makes this code too error prone
  3488. on x86-64
  3489. }
  3490. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3491. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3492. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3493. { mov mem1, reg1 mov mem1, reg1
  3494. mov reg1, mem2 mov reg1, mem2
  3495. mov mem2, reg2 mov mem2, reg1
  3496. to: to:
  3497. mov mem1, reg1 mov mem1, reg1
  3498. mov mem1, reg2 mov reg1, mem2
  3499. mov reg1, mem2
  3500. or (if mem1 depends on reg1
  3501. and/or if mem2 depends on reg2)
  3502. to:
  3503. mov mem1, reg1
  3504. mov reg1, mem2
  3505. mov reg1, reg2
  3506. }
  3507. begin
  3508. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3509. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3510. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3511. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3512. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3513. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3514. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3515. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3516. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3517. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3518. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3519. end
  3520. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3521. begin
  3522. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3523. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3524. end
  3525. else
  3526. begin
  3527. RemoveInstruction(hp2);
  3528. end
  3529. {$endif i386}
  3530. ;
  3531. end;
  3532. end
  3533. { movl [mem1],reg1
  3534. movl [mem1],reg2
  3535. to
  3536. movl [mem1],reg1
  3537. movl reg1,reg2
  3538. }
  3539. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3540. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3541. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3542. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3543. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3544. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3545. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3546. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3547. begin
  3548. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3549. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3550. end;
  3551. { movl const1,[mem1]
  3552. movl [mem1],reg1
  3553. to
  3554. movl const1,reg1
  3555. movl reg1,[mem1]
  3556. }
  3557. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3558. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3559. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3560. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3561. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3562. begin
  3563. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3564. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3565. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3566. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3567. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3568. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3569. Result:=true;
  3570. exit;
  3571. end;
  3572. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3573. { Change:
  3574. movl %reg1,%reg2
  3575. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3576. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3577. To:
  3578. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3579. movl x(%reg1),%reg1
  3580. movl %reg1,%regX
  3581. }
  3582. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3583. begin
  3584. p_SourceReg := taicpu(p).oper[0]^.reg;
  3585. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3586. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3587. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3588. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3589. GetNextInstruction(hp1, hp2) and
  3590. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3591. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3592. begin
  3593. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3594. if RegInRef(p_TargetReg, SourceRef) and
  3595. { If %reg1 also appears in the second reference, then it will
  3596. not refer to the same memory block as the first reference }
  3597. not RegInRef(p_SourceReg, SourceRef) then
  3598. begin
  3599. { Check to see if the references match if %reg2 is changed to %reg1 }
  3600. if SourceRef.base = p_TargetReg then
  3601. SourceRef.base := p_SourceReg;
  3602. if SourceRef.index = p_TargetReg then
  3603. SourceRef.index := p_SourceReg;
  3604. { RefsEqual also checks to ensure both references are non-volatile }
  3605. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3606. begin
  3607. taicpu(hp2).loadreg(0, p_SourceReg);
  3608. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3609. Result := True;
  3610. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3611. begin
  3612. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3613. RemoveCurrentP(p, hp1);
  3614. Exit;
  3615. end
  3616. else
  3617. begin
  3618. { Check to see if %reg2 is no longer in use }
  3619. TransferUsedRegs(TmpUsedRegs);
  3620. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3621. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3622. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3623. begin
  3624. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3625. RemoveCurrentP(p, hp1);
  3626. Exit;
  3627. end;
  3628. end;
  3629. { If we reach this point, p and hp1 weren't actually modified,
  3630. so we can do a bit more work on this pass }
  3631. end;
  3632. end;
  3633. end;
  3634. end;
  3635. end;
  3636. { search further than the next instruction for a mov (as long as it's not a jump) }
  3637. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3638. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3639. (taicpu(p).oper[1]^.typ = top_reg) and
  3640. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3641. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3642. begin
  3643. { we work with hp2 here, so hp1 can be still used later on when
  3644. checking for GetNextInstruction_p }
  3645. hp3 := hp1;
  3646. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3647. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3648. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3649. TransferUsedRegs(TmpUsedRegs);
  3650. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3651. if NotFirstIteration then
  3652. JumpTracking := TLinkedList.Create
  3653. else
  3654. JumpTracking := nil;
  3655. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3656. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3657. (hp2.typ=ait_instruction) do
  3658. begin
  3659. case taicpu(hp2).opcode of
  3660. A_POP:
  3661. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3662. begin
  3663. if not CrossJump and
  3664. not RegUsedBetween(p_TargetReg, p, hp2) then
  3665. begin
  3666. { We can remove the original MOV since the register
  3667. wasn't used between it and its popping from the stack }
  3668. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3669. RemoveCurrentp(p, hp1);
  3670. Result := True;
  3671. JumpTracking.Free;
  3672. Exit;
  3673. end;
  3674. { Can't go any further }
  3675. Break;
  3676. end;
  3677. A_MOV:
  3678. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3679. ((taicpu(p).oper[0]^.typ=top_const) or
  3680. ((taicpu(p).oper[0]^.typ=top_reg) and
  3681. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3682. )
  3683. ) then
  3684. begin
  3685. { we have
  3686. mov x, %treg
  3687. mov %treg, y
  3688. }
  3689. { We don't need to call UpdateUsedRegs for every instruction between
  3690. p and hp2 because the register we're concerned about will not
  3691. become deallocated (otherwise GetNextInstructionUsingReg would
  3692. have stopped at an earlier instruction). [Kit] }
  3693. TempRegUsed :=
  3694. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3695. RegReadByInstruction(p_TargetReg, hp3) or
  3696. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3697. case taicpu(p).oper[0]^.typ Of
  3698. top_reg:
  3699. begin
  3700. { change
  3701. mov %reg, %treg
  3702. mov %treg, y
  3703. to
  3704. mov %reg, y
  3705. }
  3706. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3707. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3708. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3709. begin
  3710. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3711. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3712. if TempRegUsed then
  3713. begin
  3714. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3715. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3716. { Set the start of the next GetNextInstructionUsingRegCond search
  3717. to start at the entry right before hp2 (which is about to be removed) }
  3718. hp3 := tai(hp2.Previous);
  3719. RemoveInstruction(hp2);
  3720. { See if there's more we can optimise }
  3721. Continue;
  3722. end
  3723. else
  3724. begin
  3725. RemoveInstruction(hp2);
  3726. { We can remove the original MOV too }
  3727. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3728. RemoveCurrentP(p, hp1);
  3729. Result:=true;
  3730. JumpTracking.Free;
  3731. Exit;
  3732. end;
  3733. end
  3734. else
  3735. begin
  3736. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3737. taicpu(hp2).loadReg(0, p_SourceReg);
  3738. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3739. { Check to see if the register also appears in the reference }
  3740. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3741. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  3742. { Don't remove the first instruction if the temporary register is in use }
  3743. if not TempRegUsed and
  3744. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3745. not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  3746. begin
  3747. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3748. RemoveCurrentP(p, hp1);
  3749. Result:=true;
  3750. JumpTracking.Free;
  3751. Exit;
  3752. end;
  3753. { No need to set Result to True here. If there's another instruction later
  3754. on that can be optimised, it will be detected when the main Pass 1 loop
  3755. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3756. end;
  3757. end;
  3758. top_const:
  3759. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3760. begin
  3761. { change
  3762. mov const, %treg
  3763. mov %treg, y
  3764. to
  3765. mov const, y
  3766. }
  3767. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3768. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3769. begin
  3770. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3771. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3772. if TempRegUsed then
  3773. begin
  3774. { Don't remove the first instruction if the temporary register is in use }
  3775. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3776. { No need to set Result to True. If there's another instruction later on
  3777. that can be optimised, it will be detected when the main Pass 1 loop
  3778. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3779. end
  3780. else
  3781. begin
  3782. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3783. RemoveCurrentP(p, hp1);
  3784. Result:=true;
  3785. Exit;
  3786. end;
  3787. end;
  3788. end;
  3789. else
  3790. Internalerror(2019103001);
  3791. end;
  3792. end
  3793. else
  3794. if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  3795. begin
  3796. if not CrossJump and
  3797. not RegUsedBetween(p_TargetReg, p, hp2) and
  3798. not RegReadByInstruction(p_TargetReg, hp2) then
  3799. begin
  3800. { Register is not used before it is overwritten }
  3801. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3802. RemoveCurrentp(p, hp1);
  3803. Result := True;
  3804. Exit;
  3805. end;
  3806. if (taicpu(p).oper[0]^.typ = top_const) and
  3807. (taicpu(hp2).oper[0]^.typ = top_const) then
  3808. begin
  3809. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3810. begin
  3811. { Same value - register hasn't changed }
  3812. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3813. RemoveInstruction(hp2);
  3814. Result := True;
  3815. { See if there's more we can optimise }
  3816. Continue;
  3817. end;
  3818. end;
  3819. end;
  3820. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  3821. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  3822. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  3823. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  3824. begin
  3825. {
  3826. Change from:
  3827. mov ###, %reg
  3828. ...
  3829. movs/z %reg,%reg (Same register, just different sizes)
  3830. To:
  3831. movs/z ###, %reg (Longer version)
  3832. ...
  3833. (remove)
  3834. }
  3835. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  3836. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  3837. { Keep the first instruction as mov if ### is a constant }
  3838. if taicpu(p).oper[0]^.typ = top_const then
  3839. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  3840. else
  3841. begin
  3842. taicpu(p).opcode := taicpu(hp2).opcode;
  3843. taicpu(p).opsize := taicpu(hp2).opsize;
  3844. end;
  3845. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  3846. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  3847. RemoveInstruction(hp2);
  3848. Result := True;
  3849. JumpTracking.Free;
  3850. Exit;
  3851. end;
  3852. else
  3853. { Move down to the MatchOpType if-block below };
  3854. end;
  3855. { Also catches MOV/S/Z instructions that aren't modified }
  3856. if taicpu(p).oper[0]^.typ = top_reg then
  3857. begin
  3858. p_SourceReg := taicpu(p).oper[0]^.reg;
  3859. if
  3860. not RegModifiedByInstruction(p_SourceReg, hp3) and
  3861. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  3862. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  3863. begin
  3864. Result := True;
  3865. { Just in case something didn't get modified (e.g. an
  3866. implicit register). Also, if it does read from this
  3867. register, then there's no longer an advantage to
  3868. changing the register on subsequent instructions.}
  3869. if not RegReadByInstruction(p_TargetReg, hp2) then
  3870. begin
  3871. { If a conditional jump was crossed, do not delete
  3872. the original MOV no matter what }
  3873. if not CrossJump and
  3874. { RegEndOfLife returns True if the register is
  3875. deallocated before the next instruction or has
  3876. been loaded with a new value }
  3877. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  3878. begin
  3879. { We can remove the original MOV }
  3880. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  3881. RemoveCurrentp(p, hp1);
  3882. JumpTracking.Free;
  3883. Result := True;
  3884. Exit;
  3885. end;
  3886. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  3887. begin
  3888. { See if there's more we can optimise }
  3889. hp3 := hp2;
  3890. Continue;
  3891. end;
  3892. end;
  3893. end;
  3894. end;
  3895. { Break out of the while loop under normal circumstances }
  3896. Break;
  3897. end;
  3898. JumpTracking.Free;
  3899. end;
  3900. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  3901. (taicpu(p).oper[1]^.typ = top_reg) and
  3902. (taicpu(p).opsize = S_L) and
  3903. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  3904. (hp2.typ = ait_instruction) and
  3905. (taicpu(hp2).opcode = A_AND) and
  3906. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  3907. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3908. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  3909. ) then
  3910. begin
  3911. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  3912. begin
  3913. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  3914. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  3915. begin
  3916. { Optimize out:
  3917. mov x, %reg
  3918. and ffffffffh, %reg
  3919. }
  3920. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  3921. RemoveInstruction(hp2);
  3922. Result:=true;
  3923. exit;
  3924. end;
  3925. end;
  3926. end;
  3927. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  3928. x >= RetOffset) as it doesn't do anything (it writes either to a
  3929. parameter or to the temporary storage room for the function
  3930. result)
  3931. }
  3932. if IsExitCode(hp1) and
  3933. (taicpu(p).oper[1]^.typ = top_ref) and
  3934. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  3935. (
  3936. (
  3937. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  3938. not (
  3939. assigned(current_procinfo.procdef.funcretsym) and
  3940. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  3941. )
  3942. ) or
  3943. { Also discard writes to the stack that are below the base pointer,
  3944. as this is temporary storage rather than a function result on the
  3945. stack, say. }
  3946. (
  3947. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  3948. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  3949. )
  3950. ) then
  3951. begin
  3952. RemoveCurrentp(p, hp1);
  3953. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  3954. RemoveLastDeallocForFuncRes(p);
  3955. Result:=true;
  3956. exit;
  3957. end;
  3958. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  3959. begin
  3960. if MatchOpType(taicpu(p),top_reg,top_ref) and
  3961. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3962. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3963. begin
  3964. { change
  3965. mov reg1, mem1
  3966. test/cmp x, mem1
  3967. to
  3968. mov reg1, mem1
  3969. test/cmp x, reg1
  3970. }
  3971. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  3972. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  3973. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3974. Result := True;
  3975. Exit;
  3976. end;
  3977. if DoMovCmpMemOpt(p, hp1, True) then
  3978. begin
  3979. Result := True;
  3980. Exit;
  3981. end;
  3982. end;
  3983. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  3984. { If the flags register is in use, don't change the instruction to an
  3985. ADD otherwise this will scramble the flags. [Kit] }
  3986. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  3987. begin
  3988. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  3989. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3990. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3991. ) or
  3992. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3993. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3994. )
  3995. ) then
  3996. { mov reg1,ref
  3997. lea reg2,[reg1,reg2]
  3998. to
  3999. add reg2,ref}
  4000. begin
  4001. TransferUsedRegs(TmpUsedRegs);
  4002. { reg1 may not be used afterwards }
  4003. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4004. begin
  4005. Taicpu(hp1).opcode:=A_ADD;
  4006. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  4007. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  4008. RemoveCurrentp(p, hp1);
  4009. result:=true;
  4010. exit;
  4011. end;
  4012. end;
  4013. { If the LEA instruction can be converted into an arithmetic instruction,
  4014. it may be possible to then fold it in the next optimisation, otherwise
  4015. there's nothing more that can be optimised here. }
  4016. if not ConvertLEA(taicpu(hp1)) then
  4017. Exit;
  4018. end;
  4019. if (taicpu(p).oper[1]^.typ = top_reg) and
  4020. (hp1.typ = ait_instruction) and
  4021. GetNextInstruction(hp1, hp2) and
  4022. MatchInstruction(hp2,A_MOV,[]) and
  4023. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4024. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4025. (
  4026. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4027. {$ifdef x86_64}
  4028. or
  4029. (
  4030. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4031. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4032. )
  4033. {$endif x86_64}
  4034. ) then
  4035. begin
  4036. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4037. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4038. { change movsX/movzX reg/ref, reg2
  4039. add/sub/or/... reg3/$const, reg2
  4040. mov reg2 reg/ref
  4041. dealloc reg2
  4042. to
  4043. add/sub/or/... reg3/$const, reg/ref }
  4044. begin
  4045. TransferUsedRegs(TmpUsedRegs);
  4046. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4047. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4048. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4049. begin
  4050. { by example:
  4051. movswl %si,%eax movswl %si,%eax p
  4052. decl %eax addl %edx,%eax hp1
  4053. movw %ax,%si movw %ax,%si hp2
  4054. ->
  4055. movswl %si,%eax movswl %si,%eax p
  4056. decw %eax addw %edx,%eax hp1
  4057. movw %ax,%si movw %ax,%si hp2
  4058. }
  4059. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4060. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4061. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4062. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4063. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4064. {
  4065. ->
  4066. movswl %si,%eax movswl %si,%eax p
  4067. decw %si addw %dx,%si hp1
  4068. movw %ax,%si movw %ax,%si hp2
  4069. }
  4070. case taicpu(hp1).ops of
  4071. 1:
  4072. begin
  4073. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4074. if taicpu(hp1).oper[0]^.typ=top_reg then
  4075. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4076. end;
  4077. 2:
  4078. begin
  4079. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4080. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4081. (taicpu(hp1).opcode<>A_SHL) and
  4082. (taicpu(hp1).opcode<>A_SHR) and
  4083. (taicpu(hp1).opcode<>A_SAR) then
  4084. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4085. end;
  4086. else
  4087. internalerror(2008042701);
  4088. end;
  4089. {
  4090. ->
  4091. decw %si addw %dx,%si p
  4092. }
  4093. RemoveInstruction(hp2);
  4094. RemoveCurrentP(p, hp1);
  4095. Result:=True;
  4096. Exit;
  4097. end;
  4098. end;
  4099. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4100. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4101. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4102. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4103. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4104. )
  4105. {$ifdef i386}
  4106. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4107. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4108. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4109. {$endif i386}
  4110. then
  4111. { change movsX/movzX reg/ref, reg2
  4112. add/sub/or/... regX/$const, reg2
  4113. mov reg2, reg3
  4114. dealloc reg2
  4115. to
  4116. movsX/movzX reg/ref, reg3
  4117. add/sub/or/... reg3/$const, reg3
  4118. }
  4119. begin
  4120. TransferUsedRegs(TmpUsedRegs);
  4121. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4122. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4123. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4124. begin
  4125. { by example:
  4126. movswl %si,%eax movswl %si,%eax p
  4127. decl %eax addl %edx,%eax hp1
  4128. movw %ax,%si movw %ax,%si hp2
  4129. ->
  4130. movswl %si,%eax movswl %si,%eax p
  4131. decw %eax addw %edx,%eax hp1
  4132. movw %ax,%si movw %ax,%si hp2
  4133. }
  4134. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4135. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4136. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4137. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4138. { limit size of constants as well to avoid assembler errors, but
  4139. check opsize to avoid overflow when left shifting the 1 }
  4140. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4141. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4142. {$ifdef x86_64}
  4143. { Be careful of, for example:
  4144. movl %reg1,%reg2
  4145. addl %reg3,%reg2
  4146. movq %reg2,%reg4
  4147. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4148. }
  4149. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4150. begin
  4151. taicpu(hp2).changeopsize(S_L);
  4152. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4153. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4154. end;
  4155. {$endif x86_64}
  4156. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4157. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4158. if taicpu(p).oper[0]^.typ=top_reg then
  4159. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4160. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4161. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4162. {
  4163. ->
  4164. movswl %si,%eax movswl %si,%eax p
  4165. decw %si addw %dx,%si hp1
  4166. movw %ax,%si movw %ax,%si hp2
  4167. }
  4168. case taicpu(hp1).ops of
  4169. 1:
  4170. begin
  4171. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4172. if taicpu(hp1).oper[0]^.typ=top_reg then
  4173. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4174. end;
  4175. 2:
  4176. begin
  4177. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4178. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4179. (taicpu(hp1).opcode<>A_SHL) and
  4180. (taicpu(hp1).opcode<>A_SHR) and
  4181. (taicpu(hp1).opcode<>A_SAR) then
  4182. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4183. end;
  4184. else
  4185. internalerror(2018111801);
  4186. end;
  4187. {
  4188. ->
  4189. decw %si addw %dx,%si p
  4190. }
  4191. RemoveInstruction(hp2);
  4192. end;
  4193. end;
  4194. end;
  4195. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4196. GetNextInstruction(hp1, hp2) and
  4197. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4198. MatchOperand(Taicpu(p).oper[0]^,0) and
  4199. (Taicpu(p).oper[1]^.typ = top_reg) and
  4200. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4201. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4202. { mov reg1,0
  4203. bts reg1,operand1 --> mov reg1,operand2
  4204. or reg1,operand2 bts reg1,operand1}
  4205. begin
  4206. Taicpu(hp2).opcode:=A_MOV;
  4207. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4208. asml.remove(hp1);
  4209. insertllitem(hp2,hp2.next,hp1);
  4210. RemoveCurrentp(p, hp1);
  4211. Result:=true;
  4212. exit;
  4213. end;
  4214. {
  4215. mov ref,reg0
  4216. <op> reg0,reg1
  4217. dealloc reg0
  4218. to
  4219. <op> ref,reg1
  4220. }
  4221. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4222. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4223. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4224. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4225. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4226. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4227. begin
  4228. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4229. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4230. RemoveCurrentp(p, hp1);
  4231. Result:=true;
  4232. exit;
  4233. end;
  4234. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4235. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4236. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4237. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4238. begin
  4239. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4240. {$ifdef x86_64}
  4241. { Convert:
  4242. movq x(ref),%reg64
  4243. shrq y,%reg64
  4244. To:
  4245. movl x+4(ref),%reg32
  4246. shrl y-32,%reg32 (Remove if y = 32)
  4247. }
  4248. if (taicpu(p).opsize = S_Q) and
  4249. (taicpu(hp1).opcode = A_SHR) and
  4250. (taicpu(hp1).oper[0]^.val >= 32) then
  4251. begin
  4252. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4253. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4254. { Convert to 32-bit }
  4255. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4256. taicpu(p).opsize := S_L;
  4257. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4258. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4259. if (taicpu(hp1).oper[0]^.val = 32) then
  4260. begin
  4261. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4262. RemoveInstruction(hp1);
  4263. end
  4264. else
  4265. begin
  4266. { This will potentially open up more arithmetic operations since
  4267. the peephole optimizer now has a big hint that only the lower
  4268. 32 bits are currently in use (and opcodes are smaller in size) }
  4269. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4270. taicpu(hp1).opsize := S_L;
  4271. Dec(taicpu(hp1).oper[0]^.val, 32);
  4272. DebugMsg(SPeepholeOptimization + PreMessage +
  4273. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4274. end;
  4275. Result := True;
  4276. Exit;
  4277. end;
  4278. {$endif x86_64}
  4279. { Convert:
  4280. movl x(ref),%reg
  4281. shrl $24,%reg
  4282. To:
  4283. movzbl x+3(ref),%reg
  4284. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4285. Also accept sar instead of shr, but convert to movsx instead of movzx
  4286. }
  4287. if taicpu(hp1).opcode = A_SHR then
  4288. MovUnaligned := A_MOVZX
  4289. else
  4290. MovUnaligned := A_MOVSX;
  4291. NewSize := S_NO;
  4292. NewOffset := 0;
  4293. case taicpu(p).opsize of
  4294. S_B:
  4295. { No valid combinations };
  4296. S_W:
  4297. if (taicpu(hp1).oper[0]^.val = 8) then
  4298. begin
  4299. NewSize := S_BW;
  4300. NewOffset := 1;
  4301. end;
  4302. S_L:
  4303. case taicpu(hp1).oper[0]^.val of
  4304. 16:
  4305. begin
  4306. NewSize := S_WL;
  4307. NewOffset := 2;
  4308. end;
  4309. 24:
  4310. begin
  4311. NewSize := S_BL;
  4312. NewOffset := 3;
  4313. end;
  4314. else
  4315. ;
  4316. end;
  4317. {$ifdef x86_64}
  4318. S_Q:
  4319. case taicpu(hp1).oper[0]^.val of
  4320. 32:
  4321. begin
  4322. if taicpu(hp1).opcode = A_SAR then
  4323. begin
  4324. { 32-bit to 64-bit is a distinct instruction }
  4325. MovUnaligned := A_MOVSXD;
  4326. NewSize := S_LQ;
  4327. NewOffset := 4;
  4328. end
  4329. else
  4330. { Should have been handled by MovShr2Mov above }
  4331. InternalError(2022081811);
  4332. end;
  4333. 48:
  4334. begin
  4335. NewSize := S_WQ;
  4336. NewOffset := 6;
  4337. end;
  4338. 56:
  4339. begin
  4340. NewSize := S_BQ;
  4341. NewOffset := 7;
  4342. end;
  4343. else
  4344. ;
  4345. end;
  4346. {$endif x86_64}
  4347. else
  4348. InternalError(2022081810);
  4349. end;
  4350. if (NewSize <> S_NO) and
  4351. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4352. begin
  4353. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4354. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4355. debug_op2str(MovUnaligned);
  4356. {$ifdef x86_64}
  4357. if MovUnaligned <> A_MOVSXD then
  4358. { Don't add size suffix for MOVSXD }
  4359. {$endif x86_64}
  4360. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4361. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4362. taicpu(p).opcode := MovUnaligned;
  4363. taicpu(p).opsize := NewSize;
  4364. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4365. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4366. RemoveInstruction(hp1);
  4367. Result := True;
  4368. Exit;
  4369. end;
  4370. end;
  4371. { Backward optimisation. If we have:
  4372. func. %reg1,%reg2
  4373. mov %reg2,%reg3
  4374. (dealloc %reg2)
  4375. Change to:
  4376. func. %reg1,%reg3 (see comment below for what a valid func. is)
  4377. }
  4378. if MatchOpType(taicpu(p), top_reg, top_reg) then
  4379. begin
  4380. p_SourceReg := taicpu(p).oper[0]^.reg;
  4381. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  4382. TransferUsedRegs(TmpUsedRegs);
  4383. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  4384. GetLastInstruction(p, hp2) and
  4385. (hp2.typ = ait_instruction) and
  4386. { Have to make sure it's an instruction that only reads from
  4387. operand 1 and only writes (not reads or modifies) from operand 2;
  4388. in essence, a one-operand pure function such as BSR or POPCNT }
  4389. (taicpu(hp2).ops = 2) and
  4390. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2]) and
  4391. (taicpu(hp2).oper[1]^.typ = top_reg) and
  4392. (taicpu(hp2).oper[1]^.reg = p_SourceReg) then
  4393. begin
  4394. case taicpu(hp2).opcode of
  4395. A_FSTSW, A_FNSTSW,
  4396. A_IN, A_INS, A_OUT, A_OUTS,
  4397. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  4398. { These routines have explicit operands, but they are restricted in
  4399. what they can be (e.g. IN and OUT can only read from AL, AX or
  4400. EAX. }
  4401. ;
  4402. else
  4403. begin
  4404. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  4405. taicpu(hp2).oper[1]^.reg := p_TargetReg;
  4406. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  4407. RemoveCurrentp(p, hp1);
  4408. Result := True;
  4409. Exit;
  4410. end;
  4411. end;
  4412. end;
  4413. end;
  4414. end;
  4415. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4416. var
  4417. hp1 : tai;
  4418. begin
  4419. Result:=false;
  4420. if taicpu(p).ops <> 2 then
  4421. exit;
  4422. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4423. GetNextInstruction(p,hp1) then
  4424. begin
  4425. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4426. (taicpu(hp1).ops = 2) then
  4427. begin
  4428. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4429. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4430. { movXX reg1, mem1 or movXX mem1, reg1
  4431. movXX mem2, reg2 movXX reg2, mem2}
  4432. begin
  4433. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4434. { movXX reg1, mem1 or movXX mem1, reg1
  4435. movXX mem2, reg1 movXX reg2, mem1}
  4436. begin
  4437. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4438. begin
  4439. { Removes the second statement from
  4440. movXX reg1, mem1/reg2
  4441. movXX mem1/reg2, reg1
  4442. }
  4443. if taicpu(p).oper[0]^.typ=top_reg then
  4444. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4445. { Removes the second statement from
  4446. movXX mem1/reg1, reg2
  4447. movXX reg2, mem1/reg1
  4448. }
  4449. if (taicpu(p).oper[1]^.typ=top_reg) and
  4450. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4451. begin
  4452. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4453. RemoveInstruction(hp1);
  4454. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4455. Result:=true;
  4456. exit;
  4457. end
  4458. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4459. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4460. begin
  4461. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4462. RemoveInstruction(hp1);
  4463. Result:=true;
  4464. exit;
  4465. end;
  4466. end
  4467. end;
  4468. end;
  4469. end;
  4470. end;
  4471. end;
  4472. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4473. var
  4474. hp1 : tai;
  4475. begin
  4476. result:=false;
  4477. { replace
  4478. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4479. MovX %mreg2,%mreg1
  4480. dealloc %mreg2
  4481. by
  4482. <Op>X %mreg2,%mreg1
  4483. ?
  4484. }
  4485. if GetNextInstruction(p,hp1) and
  4486. { we mix single and double opperations here because we assume that the compiler
  4487. generates vmovapd only after double operations and vmovaps only after single operations }
  4488. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4489. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4490. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4491. (taicpu(p).oper[0]^.typ=top_reg) then
  4492. begin
  4493. TransferUsedRegs(TmpUsedRegs);
  4494. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4495. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4496. begin
  4497. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4498. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4499. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4500. RemoveInstruction(hp1);
  4501. result:=true;
  4502. end;
  4503. end;
  4504. end;
  4505. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4506. var
  4507. hp1, p_label, p_dist, hp1_dist: tai;
  4508. JumpLabel, JumpLabel_dist: TAsmLabel;
  4509. FirstValue, SecondValue: TCGInt;
  4510. begin
  4511. Result := False;
  4512. if (taicpu(p).oper[0]^.typ = top_const) and
  4513. (taicpu(p).oper[0]^.val <> -1) then
  4514. begin
  4515. { Convert unsigned maximum constants to -1 to aid optimisation }
  4516. case taicpu(p).opsize of
  4517. S_B:
  4518. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4519. begin
  4520. taicpu(p).oper[0]^.val := -1;
  4521. Result := True;
  4522. Exit;
  4523. end;
  4524. S_W:
  4525. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4526. begin
  4527. taicpu(p).oper[0]^.val := -1;
  4528. Result := True;
  4529. Exit;
  4530. end;
  4531. S_L:
  4532. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4533. begin
  4534. taicpu(p).oper[0]^.val := -1;
  4535. Result := True;
  4536. Exit;
  4537. end;
  4538. {$ifdef x86_64}
  4539. S_Q:
  4540. { Storing anything greater than $7FFFFFFF is not possible so do
  4541. nothing };
  4542. {$endif x86_64}
  4543. else
  4544. InternalError(2021121001);
  4545. end;
  4546. end;
  4547. if GetNextInstruction(p, hp1) and
  4548. TrySwapMovCmp(p, hp1) then
  4549. begin
  4550. Result := True;
  4551. Exit;
  4552. end;
  4553. { Search for:
  4554. test $x,(reg/ref)
  4555. jne @lbl1
  4556. test $y,(reg/ref) (same register or reference)
  4557. jne @lbl1
  4558. Change to:
  4559. test $(x or y),(reg/ref)
  4560. jne @lbl1
  4561. (Note, this doesn't work with je instead of jne)
  4562. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4563. Also search for:
  4564. test $x,(reg/ref)
  4565. je @lbl1
  4566. test $y,(reg/ref)
  4567. je/jne @lbl2
  4568. If (x or y) = x, then the second jump is deterministic
  4569. }
  4570. if (
  4571. (
  4572. (taicpu(p).oper[0]^.typ = top_const) or
  4573. (
  4574. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4575. (taicpu(p).oper[0]^.typ = top_reg) and
  4576. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4577. )
  4578. ) and
  4579. MatchInstruction(hp1, A_JCC, [])
  4580. ) then
  4581. begin
  4582. if (taicpu(p).oper[0]^.typ = top_reg) and
  4583. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4584. FirstValue := -1
  4585. else
  4586. FirstValue := taicpu(p).oper[0]^.val;
  4587. { If we have several test/jne's in a row, it might be the case that
  4588. the second label doesn't go to the same location, but the one
  4589. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4590. so accommodate for this with a while loop.
  4591. }
  4592. hp1_dist := hp1;
  4593. if GetNextInstruction(hp1, p_dist) and
  4594. (p_dist.typ = ait_instruction) and
  4595. (
  4596. (
  4597. (taicpu(p_dist).opcode = A_TEST) and
  4598. (
  4599. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4600. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4601. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4602. )
  4603. ) or
  4604. (
  4605. { cmp 0,%reg = test %reg,%reg }
  4606. (taicpu(p_dist).opcode = A_CMP) and
  4607. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4608. )
  4609. ) and
  4610. { Make sure the destination operands are actually the same }
  4611. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4612. GetNextInstruction(p_dist, hp1_dist) and
  4613. MatchInstruction(hp1_dist, A_JCC, []) then
  4614. begin
  4615. if
  4616. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4617. (
  4618. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4619. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4620. ) then
  4621. SecondValue := -1
  4622. else
  4623. SecondValue := taicpu(p_dist).oper[0]^.val;
  4624. { If both of the TEST constants are identical, delete the second
  4625. TEST that is unnecessary. }
  4626. if (FirstValue = SecondValue) then
  4627. begin
  4628. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4629. RemoveInstruction(p_dist);
  4630. { Don't let the flags register become deallocated and reallocated between the jumps }
  4631. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4632. Result := True;
  4633. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4634. begin
  4635. { Since the second jump's condition is a subset of the first, we
  4636. know it will never branch because the first jump dominates it.
  4637. Get it out of the way now rather than wait for the jump
  4638. optimisations for a speed boost. }
  4639. if IsJumpToLabel(taicpu(hp1_dist)) then
  4640. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4641. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4642. RemoveInstruction(hp1_dist);
  4643. end
  4644. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4645. begin
  4646. { If the inverse of the first condition is a subset of the second,
  4647. the second one will definitely branch if the first one doesn't }
  4648. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4649. MakeUnconditional(taicpu(hp1_dist));
  4650. RemoveDeadCodeAfterJump(hp1_dist);
  4651. end;
  4652. Exit;
  4653. end;
  4654. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4655. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4656. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4657. then the second jump will never branch, so it can also be
  4658. removed regardless of where it goes }
  4659. (
  4660. (FirstValue = -1) or
  4661. (SecondValue = -1) or
  4662. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4663. ) then
  4664. begin
  4665. { Same jump location... can be a register since nothing's changed }
  4666. { If any of the entries are equivalent to test %reg,%reg, then the
  4667. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  4668. taicpu(p).loadconst(0, FirstValue or SecondValue);
  4669. if IsJumpToLabel(taicpu(hp1_dist)) then
  4670. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4671. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  4672. RemoveInstruction(hp1_dist);
  4673. { Only remove the second test if no jumps or other conditional instructions follow }
  4674. TransferUsedRegs(TmpUsedRegs);
  4675. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4676. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4677. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  4678. RemoveInstruction(p_dist);
  4679. Result := True;
  4680. Exit;
  4681. end;
  4682. end;
  4683. end;
  4684. { Search for:
  4685. test %reg,%reg
  4686. j(c1) @lbl1
  4687. ...
  4688. @lbl:
  4689. test %reg,%reg (same register)
  4690. j(c2) @lbl2
  4691. If c2 is a subset of c1, change to:
  4692. test %reg,%reg
  4693. j(c1) @lbl2
  4694. (@lbl1 may become a dead label as a result)
  4695. }
  4696. if (taicpu(p).oper[1]^.typ = top_reg) and
  4697. (taicpu(p).oper[0]^.typ = top_reg) and
  4698. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  4699. MatchInstruction(hp1, A_JCC, []) and
  4700. IsJumpToLabel(taicpu(hp1)) then
  4701. begin
  4702. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4703. p_label := nil;
  4704. if Assigned(JumpLabel) then
  4705. p_label := getlabelwithsym(JumpLabel);
  4706. if Assigned(p_label) and
  4707. GetNextInstruction(p_label, p_dist) and
  4708. MatchInstruction(p_dist, A_TEST, []) and
  4709. { It's fine if the second test uses smaller sub-registers }
  4710. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  4711. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  4712. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  4713. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  4714. GetNextInstruction(p_dist, hp1_dist) and
  4715. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4716. begin
  4717. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4718. if JumpLabel = JumpLabel_dist then
  4719. { This is an infinite loop }
  4720. Exit;
  4721. { Best optimisation when the first condition is a subset (or equal) of the second }
  4722. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  4723. begin
  4724. { Any registers used here will already be allocated }
  4725. if Assigned(JumpLabel) then
  4726. JumpLabel.DecRefs;
  4727. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  4728. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  4729. Result := True;
  4730. Exit;
  4731. end;
  4732. end;
  4733. end;
  4734. end;
  4735. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  4736. var
  4737. hp1, hp2: tai;
  4738. ActiveReg: TRegister;
  4739. OldOffset: asizeint;
  4740. ThisConst: TCGInt;
  4741. function RegDeallocated: Boolean;
  4742. begin
  4743. TransferUsedRegs(TmpUsedRegs);
  4744. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4745. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4746. end;
  4747. begin
  4748. result:=false;
  4749. hp1 := nil;
  4750. { replace
  4751. addX const,%reg1
  4752. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4753. dealloc %reg1
  4754. by
  4755. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  4756. }
  4757. if MatchOpType(taicpu(p),top_const,top_reg) then
  4758. begin
  4759. ActiveReg := taicpu(p).oper[1]^.reg;
  4760. { Ensures the entire register was updated }
  4761. if (taicpu(p).opsize >= S_L) and
  4762. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  4763. MatchInstruction(hp1,A_LEA,[]) and
  4764. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  4765. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  4766. (
  4767. { Cover the case where the register in the reference is also the destination register }
  4768. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  4769. (
  4770. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  4771. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  4772. RegDeallocated
  4773. )
  4774. ) then
  4775. begin
  4776. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  4777. {$push}
  4778. {$R-}{$Q-}
  4779. { Explicitly disable overflow checking for these offset calculation
  4780. as those do not matter for the final result }
  4781. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  4782. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  4783. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  4784. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4785. {$pop}
  4786. {$ifdef x86_64}
  4787. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  4788. begin
  4789. { Overflow; abort }
  4790. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  4791. end
  4792. else
  4793. {$endif x86_64}
  4794. begin
  4795. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  4796. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  4797. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  4798. RemoveCurrentP(p, hp1)
  4799. else
  4800. RemoveCurrentP(p);
  4801. result:=true;
  4802. Exit;
  4803. end;
  4804. end;
  4805. if (
  4806. { Save calling GetNextInstructionUsingReg again }
  4807. Assigned(hp1) or
  4808. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  4809. ) and
  4810. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  4811. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  4812. begin
  4813. if taicpu(hp1).oper[0]^.typ = top_const then
  4814. begin
  4815. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  4816. if taicpu(hp1).opcode = A_ADD then
  4817. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  4818. else
  4819. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  4820. Result := True;
  4821. { Handle any overflows }
  4822. case taicpu(p).opsize of
  4823. S_B:
  4824. taicpu(p).oper[0]^.val := ThisConst and $FF;
  4825. S_W:
  4826. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  4827. S_L:
  4828. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  4829. {$ifdef x86_64}
  4830. S_Q:
  4831. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  4832. { Overflow; abort }
  4833. Result := False
  4834. else
  4835. taicpu(p).oper[0]^.val := ThisConst;
  4836. {$endif x86_64}
  4837. else
  4838. InternalError(2021102610);
  4839. end;
  4840. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  4841. if Result then
  4842. begin
  4843. if (taicpu(p).oper[0]^.val < 0) and
  4844. (
  4845. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  4846. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  4847. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  4848. ) then
  4849. begin
  4850. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  4851. taicpu(p).opcode := A_SUB;
  4852. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  4853. end
  4854. else
  4855. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  4856. RemoveInstruction(hp1);
  4857. end;
  4858. end
  4859. else
  4860. begin
  4861. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  4862. TransferUsedRegs(TmpUsedRegs);
  4863. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4864. hp2 := p;
  4865. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  4866. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  4867. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  4868. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  4869. begin
  4870. { Move the constant addition to after the reg/ref addition to improve optimisation }
  4871. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  4872. Asml.Remove(p);
  4873. Asml.InsertAfter(p, hp1);
  4874. p := hp1;
  4875. Result := True;
  4876. end;
  4877. end;
  4878. end;
  4879. end;
  4880. end;
  4881. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  4882. var
  4883. hp1: tai;
  4884. ref: Integer;
  4885. saveref: treference;
  4886. Multiple: TCGInt;
  4887. Adjacent: Boolean;
  4888. begin
  4889. Result:=false;
  4890. { play save and throw an error if LEA uses a seg register prefix,
  4891. this is most likely an error somewhere else }
  4892. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  4893. internalerror(2022022001);
  4894. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  4895. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4896. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  4897. (
  4898. { do not mess with leas accessing the stack pointer
  4899. unless it's a null operation }
  4900. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  4901. (
  4902. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  4903. (taicpu(p).oper[0]^.ref^.offset = 0)
  4904. )
  4905. ) and
  4906. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  4907. begin
  4908. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  4909. begin
  4910. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  4911. begin
  4912. taicpu(p).opcode := A_MOV;
  4913. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  4914. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  4915. end
  4916. else
  4917. begin
  4918. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  4919. RemoveCurrentP(p);
  4920. end;
  4921. Result:=true;
  4922. exit;
  4923. end
  4924. else if (
  4925. { continue to use lea to adjust the stack pointer,
  4926. it is the recommended way, but only if not optimizing for size }
  4927. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  4928. (cs_opt_size in current_settings.optimizerswitches)
  4929. ) and
  4930. { If the flags register is in use, don't change the instruction
  4931. to an ADD otherwise this will scramble the flags. [Kit] }
  4932. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  4933. ConvertLEA(taicpu(p)) then
  4934. begin
  4935. Result:=true;
  4936. exit;
  4937. end;
  4938. end;
  4939. { Don't optimise if the stack or frame pointer is the destination register }
  4940. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  4941. Exit;
  4942. if GetNextInstruction(p,hp1) and
  4943. (hp1.typ=ait_instruction) then
  4944. begin
  4945. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  4946. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4947. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  4948. begin
  4949. TransferUsedRegs(TmpUsedRegs);
  4950. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4951. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4952. begin
  4953. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4954. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  4955. RemoveInstruction(hp1);
  4956. result:=true;
  4957. exit;
  4958. end;
  4959. end;
  4960. { changes
  4961. lea <ref1>, reg1
  4962. <op> ...,<ref. with reg1>,...
  4963. to
  4964. <op> ...,<ref1>,... }
  4965. { find a reference which uses reg1 }
  4966. 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
  4967. ref:=0
  4968. 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
  4969. ref:=1
  4970. else
  4971. ref:=-1;
  4972. if (ref<>-1) and
  4973. { reg1 must be either the base or the index }
  4974. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  4975. begin
  4976. { reg1 can be removed from the reference }
  4977. saveref:=taicpu(hp1).oper[ref]^.ref^;
  4978. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  4979. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  4980. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  4981. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  4982. else
  4983. Internalerror(2019111201);
  4984. { check if the can insert all data of the lea into the second instruction }
  4985. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4986. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  4987. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  4988. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  4989. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  4990. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4991. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  4992. {$ifdef x86_64}
  4993. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  4994. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  4995. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  4996. )
  4997. {$endif x86_64}
  4998. then
  4999. begin
  5000. { reg1 might not used by the second instruction after it is remove from the reference }
  5001. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5002. begin
  5003. TransferUsedRegs(TmpUsedRegs);
  5004. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5005. { reg1 is not updated so it might not be used afterwards }
  5006. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5007. begin
  5008. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5009. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5010. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5011. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5012. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5013. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5014. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5015. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5016. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5017. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5018. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5019. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5020. RemoveCurrentP(p, hp1);
  5021. result:=true;
  5022. exit;
  5023. end
  5024. end;
  5025. end;
  5026. { recover }
  5027. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5028. end;
  5029. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5030. if Adjacent or
  5031. { Check further ahead (up to 2 instructions ahead for -O2) }
  5032. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5033. begin
  5034. { Check common LEA/LEA conditions }
  5035. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5036. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  5037. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5038. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5039. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5040. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5041. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5042. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5043. (
  5044. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5045. calling it (since it calls GetNextInstruction) }
  5046. Adjacent or
  5047. (
  5048. (
  5049. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5050. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5051. ) and (
  5052. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5053. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5054. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5055. )
  5056. )
  5057. ) then
  5058. begin
  5059. { changes
  5060. lea (regX,scale), reg1
  5061. lea offset(reg1,reg1), reg1
  5062. to
  5063. lea offset(regX,scale*2), reg1
  5064. and
  5065. lea (regX,scale1), reg1
  5066. lea offset(reg1,scale2), reg1
  5067. to
  5068. lea offset(regX,scale1*scale2), reg1
  5069. ... so long as the final scale does not exceed 8
  5070. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5071. }
  5072. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5073. (taicpu(p).oper[0]^.ref^.offset = 0) and
  5074. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5075. (
  5076. (
  5077. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5078. ) or (
  5079. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5080. (
  5081. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5082. (
  5083. { RegUsedBetween always returns False if p and hp1 are adjacent }
  5084. Adjacent or
  5085. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  5086. )
  5087. )
  5088. )
  5089. ) and (
  5090. (
  5091. { lea (reg1,scale2), reg1 variant }
  5092. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  5093. (
  5094. (
  5095. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5096. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5097. ) or (
  5098. { lea (regX,regX), reg1 variant }
  5099. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5100. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5101. )
  5102. )
  5103. ) or (
  5104. { lea (reg1,reg1), reg1 variant }
  5105. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5106. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5107. )
  5108. ) then
  5109. begin
  5110. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5111. { Make everything homogeneous to make calculations easier }
  5112. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5113. begin
  5114. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5115. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5116. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5117. else
  5118. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5119. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5120. end;
  5121. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  5122. begin
  5123. { Just to prevent miscalculations }
  5124. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5125. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5126. else
  5127. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  5128. end
  5129. else
  5130. begin
  5131. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5132. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  5133. end;
  5134. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5135. RemoveCurrentP(p);
  5136. result:=true;
  5137. exit;
  5138. end
  5139. { changes
  5140. lea offset1(regX), reg1
  5141. lea offset2(reg1), reg1
  5142. to
  5143. lea offset1+offset2(regX), reg1 }
  5144. else if
  5145. (
  5146. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5147. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5148. ) or (
  5149. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5150. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5151. (
  5152. (
  5153. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5154. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5155. ) or (
  5156. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5157. (
  5158. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5159. (
  5160. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5161. (
  5162. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5163. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5164. )
  5165. )
  5166. )
  5167. )
  5168. )
  5169. ) then
  5170. begin
  5171. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5172. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5173. begin
  5174. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5175. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5176. { if the register is used as index and base, we have to increase for base as well
  5177. and adapt base }
  5178. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5179. begin
  5180. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5181. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5182. end;
  5183. end
  5184. else
  5185. begin
  5186. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5187. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5188. end;
  5189. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5190. begin
  5191. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5192. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5193. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5194. end;
  5195. RemoveCurrentP(p);
  5196. result:=true;
  5197. exit;
  5198. end;
  5199. end;
  5200. { Change:
  5201. leal/q $x(%reg1),%reg2
  5202. ...
  5203. shll/q $y,%reg2
  5204. To:
  5205. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5206. }
  5207. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5208. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5209. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5210. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5211. (taicpu(hp1).oper[0]^.val <= 3) then
  5212. begin
  5213. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5214. TransferUsedRegs(TmpUsedRegs);
  5215. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5216. if
  5217. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5218. (this works even if scalefactor is zero) }
  5219. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5220. { Ensure offset doesn't go out of bounds }
  5221. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5222. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5223. (
  5224. (
  5225. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5226. (
  5227. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5228. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5229. (
  5230. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5231. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5232. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5233. )
  5234. )
  5235. ) or (
  5236. (
  5237. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5238. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5239. ) and
  5240. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5241. )
  5242. ) then
  5243. begin
  5244. repeat
  5245. with taicpu(p).oper[0]^.ref^ do
  5246. begin
  5247. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5248. if index = base then
  5249. begin
  5250. if Multiple > 4 then
  5251. { Optimisation will no longer work because resultant
  5252. scale factor will exceed 8 }
  5253. Break;
  5254. base := NR_NO;
  5255. scalefactor := 2;
  5256. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5257. end
  5258. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5259. begin
  5260. { Scale factor only works on the index register }
  5261. index := base;
  5262. base := NR_NO;
  5263. end;
  5264. { For safety }
  5265. if scalefactor <= 1 then
  5266. begin
  5267. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5268. scalefactor := Multiple;
  5269. end
  5270. else
  5271. begin
  5272. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5273. scalefactor := scalefactor * Multiple;
  5274. end;
  5275. offset := offset * Multiple;
  5276. end;
  5277. RemoveInstruction(hp1);
  5278. Result := True;
  5279. Exit;
  5280. { This repeat..until loop exists for the benefit of Break }
  5281. until True;
  5282. end;
  5283. end;
  5284. end;
  5285. end;
  5286. end;
  5287. function TX86AsmOptimizer.DoSubAddOpt(var p: tai): Boolean;
  5288. var
  5289. hp1 : tai;
  5290. begin
  5291. DoSubAddOpt := False;
  5292. if taicpu(p).oper[0]^.typ <> top_const then
  5293. { Should have been confirmed before calling }
  5294. InternalError(2021102601);
  5295. if GetLastInstruction(p, hp1) and
  5296. (hp1.typ = ait_instruction) and
  5297. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5298. case taicpu(hp1).opcode Of
  5299. A_DEC:
  5300. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5301. begin
  5302. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+1);
  5303. RemoveInstruction(hp1);
  5304. end;
  5305. A_SUB:
  5306. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5307. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5308. begin
  5309. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val);
  5310. RemoveInstruction(hp1);
  5311. end;
  5312. A_ADD:
  5313. begin
  5314. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5315. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5316. begin
  5317. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  5318. RemoveInstruction(hp1);
  5319. if (taicpu(p).oper[0]^.val = 0) then
  5320. begin
  5321. hp1 := tai(p.next);
  5322. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5323. if not GetLastInstruction(hp1, p) then
  5324. p := hp1;
  5325. DoSubAddOpt := True;
  5326. end
  5327. end;
  5328. end;
  5329. else
  5330. ;
  5331. end;
  5332. end;
  5333. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  5334. begin
  5335. Result := False;
  5336. if UpdateTmpUsedRegs then
  5337. TransferUsedRegs(TmpUsedRegs);
  5338. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5339. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5340. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5341. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5342. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5343. (
  5344. (
  5345. (taicpu(hp1).opcode = A_TEST)
  5346. ) or (
  5347. (taicpu(hp1).opcode = A_CMP) and
  5348. { A sanity check more than anything }
  5349. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5350. )
  5351. ) then
  5352. begin
  5353. { change
  5354. mov mem, %reg
  5355. cmp/test x, %reg / test %reg,%reg
  5356. (reg deallocated)
  5357. to
  5358. cmp/test x, mem / cmp 0, mem
  5359. }
  5360. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5361. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5362. begin
  5363. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5364. if (taicpu(hp1).opcode = A_TEST) and
  5365. (
  5366. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5367. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5368. ) then
  5369. begin
  5370. taicpu(hp1).opcode := A_CMP;
  5371. taicpu(hp1).loadconst(0, 0);
  5372. end;
  5373. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  5374. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  5375. RemoveCurrentP(p, hp1);
  5376. Result := True;
  5377. Exit;
  5378. end;
  5379. end;
  5380. end;
  5381. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  5382. var
  5383. hp2, hp3, hp4, hp5, hp6: tai;
  5384. ThisReg: TRegister;
  5385. JumpLoc: TAsmLabel;
  5386. begin
  5387. Result := False;
  5388. {
  5389. Convert:
  5390. j<c> .L1
  5391. .L2:
  5392. mov 1,reg
  5393. jmp .L3 (or ret, although it might not be a RET yet)
  5394. .L1:
  5395. mov 0,reg
  5396. jmp .L3 (or ret)
  5397. ( As long as .L3 <> .L1 or .L2)
  5398. To:
  5399. mov 0,reg
  5400. set<not(c)> reg
  5401. jmp .L3 (or ret)
  5402. .L2:
  5403. mov 1,reg
  5404. jmp .L3 (or ret)
  5405. .L1:
  5406. mov 0,reg
  5407. jmp .L3 (or ret)
  5408. }
  5409. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  5410. Exit;
  5411. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  5412. if GetNextInstruction(hp_label, hp2) and
  5413. MatchInstruction(hp2,A_MOV,[]) and
  5414. (taicpu(hp2).oper[0]^.typ = top_const) and
  5415. (
  5416. (
  5417. (taicpu(hp2).oper[1]^.typ = top_reg)
  5418. {$ifdef i386}
  5419. { Under i386, ESI, EDI, EBP and ESP
  5420. don't have an 8-bit representation }
  5421. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5422. {$endif i386}
  5423. ) or (
  5424. {$ifdef i386}
  5425. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  5426. {$endif i386}
  5427. (taicpu(hp2).opsize = S_B)
  5428. )
  5429. ) and
  5430. GetNextInstruction(hp2, hp3) and
  5431. MatchInstruction(hp3, A_JMP, A_RET, []) and
  5432. (
  5433. (taicpu(hp3).opcode=A_RET) or
  5434. (
  5435. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  5436. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  5437. )
  5438. ) and
  5439. GetNextInstruction(hp3, hp4) and
  5440. SkipAligns(hp4, hp4) and
  5441. (hp4.typ=ait_label) and
  5442. (tai_label(hp4).labsym=JumpLoc) and
  5443. (
  5444. not (cs_opt_size in current_settings.optimizerswitches) or
  5445. { If the initial jump is the label's only reference, then it will
  5446. become a dead label if the other conditions are met and hence
  5447. remove at least 2 instructions, including a jump }
  5448. (JumpLoc.getrefs = 1)
  5449. ) and
  5450. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  5451. that will be optimised out }
  5452. GetNextInstruction(hp4, hp5) and
  5453. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  5454. (taicpu(hp5).oper[0]^.typ = top_const) and
  5455. (
  5456. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  5457. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  5458. ) and
  5459. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  5460. GetNextInstruction(hp5,hp6) and
  5461. (
  5462. (hp6.typ<>ait_label) or
  5463. SkipLabels(hp6, hp6)
  5464. ) and
  5465. (hp6.typ=ait_instruction) then
  5466. begin
  5467. { First, let's look at the two jumps that are hp3 and hp6 }
  5468. if not
  5469. (
  5470. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5471. (
  5472. (taicpu(hp6).opcode=A_RET) or
  5473. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5474. )
  5475. ) then
  5476. { If condition is False, then the JMP/RET instructions matched conventionally }
  5477. begin
  5478. { See if one of the jumps can be instantly converted into a RET }
  5479. if (taicpu(hp3).opcode=A_JMP) then
  5480. begin
  5481. { Reuse hp5 }
  5482. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  5483. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  5484. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  5485. Exit;
  5486. if MatchInstruction(hp5, A_RET, []) then
  5487. begin
  5488. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  5489. ConvertJumpToRET(hp3, hp5);
  5490. Result := True;
  5491. end
  5492. else
  5493. Exit;
  5494. end;
  5495. if (taicpu(hp6).opcode=A_JMP) then
  5496. begin
  5497. { Reuse hp5 }
  5498. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  5499. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  5500. Exit;
  5501. if MatchInstruction(hp5, A_RET, []) then
  5502. begin
  5503. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  5504. ConvertJumpToRET(hp6, hp5);
  5505. Result := True;
  5506. end
  5507. else
  5508. Exit;
  5509. end;
  5510. if not
  5511. (
  5512. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5513. (
  5514. (taicpu(hp6).opcode=A_RET) or
  5515. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5516. )
  5517. ) then
  5518. { Still doesn't match }
  5519. Exit;
  5520. end;
  5521. if (taicpu(hp2).oper[0]^.val = 1) then
  5522. begin
  5523. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5524. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  5525. end
  5526. else
  5527. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  5528. if taicpu(hp2).opsize=S_B then
  5529. begin
  5530. if taicpu(hp2).oper[1]^.typ = top_reg then
  5531. hp4:=taicpu.op_reg(A_SETcc, S_B, taicpu(hp2).oper[1]^.reg)
  5532. else
  5533. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  5534. hp2 := p;
  5535. end
  5536. else
  5537. begin
  5538. { Will be a register because the size can't be S_B otherwise }
  5539. ThisReg:=newreg(R_INTREGISTER,getsupreg(taicpu(hp2).oper[1]^.reg), R_SUBL);
  5540. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  5541. hp2:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, taicpu(hp2).oper[1]^.reg);
  5542. taicpu(hp2).fileinfo:=taicpu(p).fileinfo;
  5543. { Inserting it right before p will guarantee that the flags are also tracked }
  5544. Asml.InsertBefore(hp2, p);
  5545. end;
  5546. taicpu(hp4).fileinfo := taicpu(hp2).fileinfo;
  5547. taicpu(hp4).condition := taicpu(p).condition;
  5548. asml.InsertBefore(hp4, hp2);
  5549. JumpLoc.decrefs;
  5550. if taicpu(hp3).opcode = A_JMP then
  5551. begin
  5552. MakeUnconditional(taicpu(p));
  5553. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  5554. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  5555. end
  5556. else
  5557. begin
  5558. taicpu(p).condition := C_None;
  5559. taicpu(p).opcode := A_RET;
  5560. taicpu(p).clearop(0);
  5561. taicpu(p).ops := 0;
  5562. end;
  5563. if (JumpLoc.getrefs = 0) then
  5564. RemoveDeadCodeAfterJump(hp3);
  5565. Result:=true;
  5566. exit;
  5567. end;
  5568. end;
  5569. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  5570. var
  5571. hp1, hp2: tai;
  5572. ActiveReg: TRegister;
  5573. OldOffset: asizeint;
  5574. ThisConst: TCGInt;
  5575. function RegDeallocated: Boolean;
  5576. begin
  5577. TransferUsedRegs(TmpUsedRegs);
  5578. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5579. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5580. end;
  5581. begin
  5582. Result:=false;
  5583. hp1 := nil;
  5584. { replace
  5585. subX const,%reg1
  5586. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5587. dealloc %reg1
  5588. by
  5589. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  5590. }
  5591. if MatchOpType(taicpu(p),top_const,top_reg) then
  5592. begin
  5593. ActiveReg := taicpu(p).oper[1]^.reg;
  5594. { Ensures the entire register was updated }
  5595. if (taicpu(p).opsize >= S_L) and
  5596. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5597. MatchInstruction(hp1,A_LEA,[]) and
  5598. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5599. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5600. (
  5601. { Cover the case where the register in the reference is also the destination register }
  5602. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5603. (
  5604. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5605. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5606. RegDeallocated
  5607. )
  5608. ) then
  5609. begin
  5610. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5611. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5612. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5613. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5614. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5615. {$ifdef x86_64}
  5616. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5617. begin
  5618. { Overflow; abort }
  5619. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5620. end
  5621. else
  5622. {$endif x86_64}
  5623. begin
  5624. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  5625. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5626. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5627. RemoveCurrentP(p, hp1)
  5628. else
  5629. RemoveCurrentP(p);
  5630. result:=true;
  5631. Exit;
  5632. end;
  5633. end;
  5634. if (
  5635. { Save calling GetNextInstructionUsingReg again }
  5636. Assigned(hp1) or
  5637. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5638. ) and
  5639. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  5640. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5641. begin
  5642. if taicpu(hp1).oper[0]^.typ = top_const then
  5643. begin
  5644. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  5645. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5646. Result := True;
  5647. { Handle any overflows }
  5648. case taicpu(p).opsize of
  5649. S_B:
  5650. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5651. S_W:
  5652. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5653. S_L:
  5654. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5655. {$ifdef x86_64}
  5656. S_Q:
  5657. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5658. { Overflow; abort }
  5659. Result := False
  5660. else
  5661. taicpu(p).oper[0]^.val := ThisConst;
  5662. {$endif x86_64}
  5663. else
  5664. InternalError(2021102611);
  5665. end;
  5666. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5667. if Result then
  5668. begin
  5669. if (taicpu(p).oper[0]^.val < 0) and
  5670. (
  5671. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5672. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5673. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5674. ) then
  5675. begin
  5676. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  5677. taicpu(p).opcode := A_SUB;
  5678. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5679. end
  5680. else
  5681. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  5682. RemoveInstruction(hp1);
  5683. end;
  5684. end
  5685. else
  5686. begin
  5687. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  5688. TransferUsedRegs(TmpUsedRegs);
  5689. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5690. hp2 := p;
  5691. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5692. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5693. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5694. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5695. begin
  5696. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  5697. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  5698. Asml.Remove(p);
  5699. Asml.InsertAfter(p, hp1);
  5700. p := hp1;
  5701. Result := True;
  5702. Exit;
  5703. end;
  5704. end;
  5705. end;
  5706. { * change "subl $2, %esp; pushw x" to "pushl x"}
  5707. { * change "sub/add const1, reg" or "dec reg" followed by
  5708. "sub const2, reg" to one "sub ..., reg" }
  5709. {$ifdef i386}
  5710. if (taicpu(p).oper[0]^.val = 2) and
  5711. (ActiveReg = NR_ESP) and
  5712. { Don't do the sub/push optimization if the sub }
  5713. { comes from setting up the stack frame (JM) }
  5714. (not(GetLastInstruction(p,hp1)) or
  5715. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  5716. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  5717. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  5718. begin
  5719. hp1 := tai(p.next);
  5720. while Assigned(hp1) and
  5721. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  5722. not RegReadByInstruction(NR_ESP,hp1) and
  5723. not RegModifiedByInstruction(NR_ESP,hp1) do
  5724. hp1 := tai(hp1.next);
  5725. if Assigned(hp1) and
  5726. MatchInstruction(hp1,A_PUSH,[S_W]) then
  5727. begin
  5728. taicpu(hp1).changeopsize(S_L);
  5729. if taicpu(hp1).oper[0]^.typ=top_reg then
  5730. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  5731. hp1 := tai(p.next);
  5732. RemoveCurrentp(p, hp1);
  5733. Result:=true;
  5734. exit;
  5735. end;
  5736. end;
  5737. {$endif i386}
  5738. if DoSubAddOpt(p) then
  5739. Result:=true;
  5740. end;
  5741. end;
  5742. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  5743. var
  5744. TmpBool1,TmpBool2 : Boolean;
  5745. tmpref : treference;
  5746. hp1,hp2: tai;
  5747. mask: tcgint;
  5748. begin
  5749. Result:=false;
  5750. { All these optimisations work on "shl/sal const,%reg" }
  5751. if not MatchOpType(taicpu(p),top_const,top_reg) then
  5752. Exit;
  5753. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  5754. (taicpu(p).oper[0]^.val <= 3) then
  5755. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  5756. begin
  5757. { should we check the next instruction? }
  5758. TmpBool1 := True;
  5759. { have we found an add/sub which could be
  5760. integrated in the lea? }
  5761. TmpBool2 := False;
  5762. reference_reset(tmpref,2,[]);
  5763. TmpRef.index := taicpu(p).oper[1]^.reg;
  5764. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5765. while TmpBool1 and
  5766. GetNextInstruction(p, hp1) and
  5767. (tai(hp1).typ = ait_instruction) and
  5768. ((((taicpu(hp1).opcode = A_ADD) or
  5769. (taicpu(hp1).opcode = A_SUB)) and
  5770. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  5771. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  5772. (((taicpu(hp1).opcode = A_INC) or
  5773. (taicpu(hp1).opcode = A_DEC)) and
  5774. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5775. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  5776. ((taicpu(hp1).opcode = A_LEA) and
  5777. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5778. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  5779. (not GetNextInstruction(hp1,hp2) or
  5780. not instrReadsFlags(hp2)) Do
  5781. begin
  5782. TmpBool1 := False;
  5783. if taicpu(hp1).opcode=A_LEA then
  5784. begin
  5785. if (TmpRef.base = NR_NO) and
  5786. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  5787. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  5788. { Segment register isn't a concern here }
  5789. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  5790. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  5791. begin
  5792. TmpBool1 := True;
  5793. TmpBool2 := True;
  5794. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  5795. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  5796. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  5797. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  5798. RemoveInstruction(hp1);
  5799. end
  5800. end
  5801. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  5802. begin
  5803. TmpBool1 := True;
  5804. TmpBool2 := True;
  5805. case taicpu(hp1).opcode of
  5806. A_ADD:
  5807. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5808. A_SUB:
  5809. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5810. else
  5811. internalerror(2019050536);
  5812. end;
  5813. RemoveInstruction(hp1);
  5814. end
  5815. else
  5816. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5817. (((taicpu(hp1).opcode = A_ADD) and
  5818. (TmpRef.base = NR_NO)) or
  5819. (taicpu(hp1).opcode = A_INC) or
  5820. (taicpu(hp1).opcode = A_DEC)) then
  5821. begin
  5822. TmpBool1 := True;
  5823. TmpBool2 := True;
  5824. case taicpu(hp1).opcode of
  5825. A_ADD:
  5826. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  5827. A_INC:
  5828. inc(TmpRef.offset);
  5829. A_DEC:
  5830. dec(TmpRef.offset);
  5831. else
  5832. internalerror(2019050535);
  5833. end;
  5834. RemoveInstruction(hp1);
  5835. end;
  5836. end;
  5837. if TmpBool2
  5838. {$ifndef x86_64}
  5839. or
  5840. ((current_settings.optimizecputype < cpu_Pentium2) and
  5841. (taicpu(p).oper[0]^.val <= 3) and
  5842. not(cs_opt_size in current_settings.optimizerswitches))
  5843. {$endif x86_64}
  5844. then
  5845. begin
  5846. if not(TmpBool2) and
  5847. (taicpu(p).oper[0]^.val=1) then
  5848. begin
  5849. taicpu(p).opcode := A_ADD;
  5850. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  5851. end
  5852. else
  5853. begin
  5854. taicpu(p).opcode := A_LEA;
  5855. taicpu(p).loadref(0, TmpRef);
  5856. end;
  5857. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  5858. Result := True;
  5859. end;
  5860. end
  5861. {$ifndef x86_64}
  5862. else if (current_settings.optimizecputype < cpu_Pentium2) then
  5863. begin
  5864. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  5865. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  5866. (unlike shl, which is only Tairable in the U pipe) }
  5867. if taicpu(p).oper[0]^.val=1 then
  5868. begin
  5869. taicpu(p).opcode := A_ADD;
  5870. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  5871. Result := True;
  5872. end
  5873. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  5874. "shl $3, %reg" to "lea (,%reg,8), %reg }
  5875. else if (taicpu(p).opsize = S_L) and
  5876. (taicpu(p).oper[0]^.val<= 3) then
  5877. begin
  5878. reference_reset(tmpref,2,[]);
  5879. TmpRef.index := taicpu(p).oper[1]^.reg;
  5880. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5881. taicpu(p).opcode := A_LEA;
  5882. taicpu(p).loadref(0, TmpRef);
  5883. Result := True;
  5884. end;
  5885. end
  5886. {$endif x86_64}
  5887. else if
  5888. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  5889. (
  5890. (
  5891. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  5892. SetAndTest(hp1, hp2)
  5893. {$ifdef x86_64}
  5894. ) or
  5895. (
  5896. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  5897. GetNextInstruction(hp1, hp2) and
  5898. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  5899. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  5900. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  5901. {$endif x86_64}
  5902. )
  5903. ) and
  5904. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  5905. begin
  5906. { Change:
  5907. shl x, %reg1
  5908. mov -(1<<x), %reg2
  5909. and %reg2, %reg1
  5910. Or:
  5911. shl x, %reg1
  5912. and -(1<<x), %reg1
  5913. To just:
  5914. shl x, %reg1
  5915. Since the and operation only zeroes bits that are already zero from the shl operation
  5916. }
  5917. case taicpu(p).oper[0]^.val of
  5918. 8:
  5919. mask:=$FFFFFFFFFFFFFF00;
  5920. 16:
  5921. mask:=$FFFFFFFFFFFF0000;
  5922. 32:
  5923. mask:=$FFFFFFFF00000000;
  5924. 63:
  5925. { Constant pre-calculated to prevent overflow errors with Int64 }
  5926. mask:=$8000000000000000;
  5927. else
  5928. begin
  5929. if taicpu(p).oper[0]^.val >= 64 then
  5930. { Shouldn't happen realistically, since the register
  5931. is guaranteed to be set to zero at this point }
  5932. mask := 0
  5933. else
  5934. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  5935. end;
  5936. end;
  5937. if taicpu(hp1).oper[0]^.val = mask then
  5938. begin
  5939. { Everything checks out, perform the optimisation, as long as
  5940. the FLAGS register isn't being used}
  5941. TransferUsedRegs(TmpUsedRegs);
  5942. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5943. {$ifdef x86_64}
  5944. if (hp1 <> hp2) then
  5945. begin
  5946. { "shl/mov/and" version }
  5947. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  5948. { Don't do the optimisation if the FLAGS register is in use }
  5949. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  5950. begin
  5951. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  5952. { Don't remove the 'mov' instruction if its register is used elsewhere }
  5953. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  5954. begin
  5955. RemoveInstruction(hp1);
  5956. Result := True;
  5957. end;
  5958. { Only set Result to True if the 'mov' instruction was removed }
  5959. RemoveInstruction(hp2);
  5960. end;
  5961. end
  5962. else
  5963. {$endif x86_64}
  5964. begin
  5965. { "shl/and" version }
  5966. { Don't do the optimisation if the FLAGS register is in use }
  5967. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  5968. begin
  5969. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  5970. RemoveInstruction(hp1);
  5971. Result := True;
  5972. end;
  5973. end;
  5974. Exit;
  5975. end
  5976. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  5977. begin
  5978. { Even if the mask doesn't allow for its removal, we might be
  5979. able to optimise the mask for the "shl/and" version, which
  5980. may permit other peephole optimisations }
  5981. {$ifdef DEBUG_AOPTCPU}
  5982. mask := taicpu(hp1).oper[0]^.val and mask;
  5983. if taicpu(hp1).oper[0]^.val <> mask then
  5984. begin
  5985. DebugMsg(
  5986. SPeepholeOptimization +
  5987. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  5988. ' to $' + debug_tostr(mask) +
  5989. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  5990. taicpu(hp1).oper[0]^.val := mask;
  5991. end;
  5992. {$else DEBUG_AOPTCPU}
  5993. { If debugging is off, just set the operand even if it's the same }
  5994. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  5995. {$endif DEBUG_AOPTCPU}
  5996. end;
  5997. end;
  5998. {
  5999. change
  6000. shl/sal const,reg
  6001. <op> ...(...,reg,1),...
  6002. into
  6003. <op> ...(...,reg,1 shl const),...
  6004. if const in 1..3
  6005. }
  6006. if MatchOpType(taicpu(p), top_const, top_reg) and
  6007. (taicpu(p).oper[0]^.val in [1..3]) and
  6008. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6009. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6010. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6011. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6012. MatchOpType(taicpu(hp1),top_ref))
  6013. ) and
  6014. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6015. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6016. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6017. begin
  6018. TransferUsedRegs(TmpUsedRegs);
  6019. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6020. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6021. begin
  6022. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6023. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6024. RemoveCurrentP(p);
  6025. Result:=true;
  6026. end;
  6027. end;
  6028. end;
  6029. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6030. begin
  6031. case shr_size of
  6032. S_B:
  6033. { No valid combinations }
  6034. Result := False;
  6035. S_W:
  6036. Result := (Shift >= 8) and (movz_size = S_BW);
  6037. S_L:
  6038. Result :=
  6039. (Shift >= 24) { Any opsize is valid for this shift } or
  6040. ((Shift >= 16) and (movz_size = S_WL));
  6041. {$ifdef x86_64}
  6042. S_Q:
  6043. Result :=
  6044. (Shift >= 56) { Any opsize is valid for this shift } or
  6045. ((Shift >= 48) and (movz_size = S_WL));
  6046. {$endif x86_64}
  6047. else
  6048. InternalError(2022081510);
  6049. end;
  6050. end;
  6051. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6052. var
  6053. hp1, hp2: tai;
  6054. Shift: TCGInt;
  6055. LimitSize: Topsize;
  6056. DoNotMerge: Boolean;
  6057. begin
  6058. Result := False;
  6059. { All these optimisations work on "shr const,%reg" }
  6060. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6061. Exit;
  6062. DoNotMerge := False;
  6063. Shift := taicpu(p).oper[0]^.val;
  6064. LimitSize := taicpu(p).opsize;
  6065. hp1 := p;
  6066. repeat
  6067. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6068. Exit;
  6069. case taicpu(hp1).opcode of
  6070. A_TEST, A_CMP, A_Jcc:
  6071. { Skip over conditional jumps and relevant comparisons }
  6072. Continue;
  6073. A_MOVZX:
  6074. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6075. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6076. begin
  6077. { Since the original register is being read as is, subsequent
  6078. SHRs must not be merged at this point }
  6079. DoNotMerge := True;
  6080. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6081. begin
  6082. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6083. begin
  6084. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6085. taicpu(hp1).opcode := A_MOV;
  6086. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6087. case taicpu(hp1).opsize of
  6088. S_BW:
  6089. taicpu(hp1).opsize := S_W;
  6090. S_BL, S_WL:
  6091. taicpu(hp1).opsize := S_L;
  6092. else
  6093. InternalError(2022081503);
  6094. end;
  6095. { p itself hasn't changed, so no need to set Result to True }
  6096. Include(OptsToCheck, aoc_ForceNewIteration);
  6097. { See if there's anything afterwards that can be
  6098. optimised, since the input register hasn't changed }
  6099. Continue;
  6100. end;
  6101. { NOTE: If the MOVZX instruction reads and writes the same
  6102. register, defer this to the post-peephole optimisation stage }
  6103. Exit;
  6104. end;
  6105. end;
  6106. A_SHL, A_SAL, A_SHR:
  6107. if (taicpu(hp1).opsize <= LimitSize) and
  6108. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6109. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  6110. begin
  6111. { Make sure the sizes don't exceed the register size limit
  6112. (measured by the shift value falling below the limit) }
  6113. if taicpu(hp1).opsize < LimitSize then
  6114. LimitSize := taicpu(hp1).opsize;
  6115. if taicpu(hp1).opcode = A_SHR then
  6116. Inc(Shift, taicpu(hp1).oper[0]^.val)
  6117. else
  6118. begin
  6119. Dec(Shift, taicpu(hp1).oper[0]^.val);
  6120. DoNotMerge := True;
  6121. end;
  6122. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  6123. Exit;
  6124. { Since we've established that the combined shift is within
  6125. limits, we can actually combine the adjacent SHR
  6126. instructions even if they're different sizes }
  6127. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  6128. begin
  6129. hp2 := tai(hp1.Previous);
  6130. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  6131. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  6132. RemoveInstruction(hp1);
  6133. hp1 := hp2;
  6134. { Though p has changed, only the constant has, and its
  6135. effects can still be detected on the next iteration of
  6136. the repeat..until loop }
  6137. Include(OptsToCheck, aoc_ForceNewIteration);
  6138. end;
  6139. { Move onto the next instruction }
  6140. Continue;
  6141. end;
  6142. else
  6143. ;
  6144. end;
  6145. Break;
  6146. until False;
  6147. end;
  6148. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  6149. var
  6150. CurrentRef: TReference;
  6151. FullReg: TRegister;
  6152. hp1, hp2: tai;
  6153. begin
  6154. Result := False;
  6155. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  6156. Exit;
  6157. { We assume you've checked if the operand is actually a reference by
  6158. this point. If it isn't, you'll most likely get an access violation }
  6159. CurrentRef := first_mov.oper[1]^.ref^;
  6160. { Memory must be aligned }
  6161. if (CurrentRef.offset mod 4) <> 0 then
  6162. Exit;
  6163. Inc(CurrentRef.offset);
  6164. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6165. if MatchOperand(second_mov.oper[0]^, 0) and
  6166. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  6167. GetNextInstruction(second_mov, hp1) and
  6168. (hp1.typ = ait_instruction) and
  6169. (taicpu(hp1).opcode = A_MOV) and
  6170. MatchOpType(taicpu(hp1), top_const, top_ref) and
  6171. (taicpu(hp1).oper[0]^.val = 0) then
  6172. begin
  6173. Inc(CurrentRef.offset);
  6174. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  6175. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  6176. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  6177. begin
  6178. case taicpu(hp1).opsize of
  6179. S_B:
  6180. if GetNextInstruction(hp1, hp2) and
  6181. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  6182. MatchOpType(taicpu(hp2), top_const, top_ref) and
  6183. (taicpu(hp2).oper[0]^.val = 0) then
  6184. begin
  6185. Inc(CurrentRef.offset);
  6186. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6187. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  6188. (taicpu(hp2).opsize = S_B) then
  6189. begin
  6190. RemoveInstruction(hp1);
  6191. RemoveInstruction(hp2);
  6192. first_mov.opsize := S_L;
  6193. if first_mov.oper[0]^.typ = top_reg then
  6194. begin
  6195. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  6196. { Reuse second_mov as a MOVZX instruction }
  6197. second_mov.opcode := A_MOVZX;
  6198. second_mov.opsize := S_BL;
  6199. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6200. second_mov.loadreg(1, FullReg);
  6201. first_mov.oper[0]^.reg := FullReg;
  6202. asml.Remove(second_mov);
  6203. asml.InsertBefore(second_mov, first_mov);
  6204. end
  6205. else
  6206. { It's a value }
  6207. begin
  6208. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  6209. RemoveInstruction(second_mov);
  6210. end;
  6211. Result := True;
  6212. Exit;
  6213. end;
  6214. end;
  6215. S_W:
  6216. begin
  6217. RemoveInstruction(hp1);
  6218. first_mov.opsize := S_L;
  6219. if first_mov.oper[0]^.typ = top_reg then
  6220. begin
  6221. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  6222. { Reuse second_mov as a MOVZX instruction }
  6223. second_mov.opcode := A_MOVZX;
  6224. second_mov.opsize := S_BL;
  6225. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6226. second_mov.loadreg(1, FullReg);
  6227. first_mov.oper[0]^.reg := FullReg;
  6228. asml.Remove(second_mov);
  6229. asml.InsertBefore(second_mov, first_mov);
  6230. end
  6231. else
  6232. { It's a value }
  6233. begin
  6234. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  6235. RemoveInstruction(second_mov);
  6236. end;
  6237. Result := True;
  6238. Exit;
  6239. end;
  6240. else
  6241. ;
  6242. end;
  6243. end;
  6244. end;
  6245. end;
  6246. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  6247. { returns true if a "continue" should be done after this optimization }
  6248. var
  6249. hp1, hp2: tai;
  6250. begin
  6251. Result := false;
  6252. if MatchOpType(taicpu(p),top_ref) and
  6253. GetNextInstruction(p, hp1) and
  6254. (hp1.typ = ait_instruction) and
  6255. (((taicpu(hp1).opcode = A_FLD) and
  6256. (taicpu(p).opcode = A_FSTP)) or
  6257. ((taicpu(p).opcode = A_FISTP) and
  6258. (taicpu(hp1).opcode = A_FILD))) and
  6259. MatchOpType(taicpu(hp1),top_ref) and
  6260. (taicpu(hp1).opsize = taicpu(p).opsize) and
  6261. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6262. begin
  6263. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  6264. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  6265. GetNextInstruction(hp1, hp2) and
  6266. (((hp2.typ = ait_instruction) and
  6267. IsExitCode(hp2) and
  6268. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6269. not(assigned(current_procinfo.procdef.funcretsym) and
  6270. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  6271. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  6272. { fstp <temp>
  6273. fld <temp>
  6274. <dealloc> <temp>
  6275. }
  6276. (SetAndTest(tai(hp1.next),hp2) and (hp2.typ = ait_tempalloc) and
  6277. (tai_tempalloc(hp2).allocation=false) and
  6278. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6279. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6280. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6281. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  6282. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  6283. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  6284. )
  6285. )
  6286. ) then
  6287. begin
  6288. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  6289. RemoveInstruction(hp1);
  6290. RemoveCurrentP(p, hp2);
  6291. { first case: exit code }
  6292. if hp2.typ = ait_instruction then
  6293. RemoveLastDeallocForFuncRes(p);
  6294. Result := true;
  6295. end
  6296. else
  6297. { we can do this only in fast math mode as fstp is rounding ...
  6298. ... still disabled as it breaks the compiler and/or rtl }
  6299. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  6300. { ... or if another fstp equal to the first one follows }
  6301. (GetNextInstruction(hp1,hp2) and
  6302. (hp2.typ = ait_instruction) and
  6303. (taicpu(p).opcode=taicpu(hp2).opcode) and
  6304. (taicpu(p).opsize=taicpu(hp2).opsize))
  6305. ) and
  6306. { fst can't store an extended/comp value }
  6307. (taicpu(p).opsize <> S_FX) and
  6308. (taicpu(p).opsize <> S_IQ) then
  6309. begin
  6310. if (taicpu(p).opcode = A_FSTP) then
  6311. taicpu(p).opcode := A_FST
  6312. else
  6313. taicpu(p).opcode := A_FIST;
  6314. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  6315. RemoveInstruction(hp1);
  6316. end;
  6317. end;
  6318. end;
  6319. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  6320. var
  6321. hp1, hp2: tai;
  6322. begin
  6323. result:=false;
  6324. if MatchOpType(taicpu(p),top_reg) and
  6325. GetNextInstruction(p, hp1) and
  6326. (hp1.typ = Ait_Instruction) and
  6327. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6328. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  6329. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  6330. { change to
  6331. fld reg fxxx reg,st
  6332. fxxxp st, st1 (hp1)
  6333. Remark: non commutative operations must be reversed!
  6334. }
  6335. begin
  6336. case taicpu(hp1).opcode Of
  6337. A_FMULP,A_FADDP,
  6338. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6339. begin
  6340. case taicpu(hp1).opcode Of
  6341. A_FADDP: taicpu(hp1).opcode := A_FADD;
  6342. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  6343. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  6344. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  6345. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  6346. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  6347. else
  6348. internalerror(2019050534);
  6349. end;
  6350. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  6351. taicpu(hp1).oper[1]^.reg := NR_ST;
  6352. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  6353. RemoveCurrentP(p, hp1);
  6354. Result:=true;
  6355. exit;
  6356. end;
  6357. else
  6358. ;
  6359. end;
  6360. end
  6361. else
  6362. if MatchOpType(taicpu(p),top_ref) and
  6363. GetNextInstruction(p, hp2) and
  6364. (hp2.typ = Ait_Instruction) and
  6365. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  6366. (taicpu(p).opsize in [S_FS, S_FL]) and
  6367. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  6368. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  6369. if GetLastInstruction(p, hp1) and
  6370. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  6371. MatchOpType(taicpu(hp1),top_ref) and
  6372. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6373. if ((taicpu(hp2).opcode = A_FMULP) or
  6374. (taicpu(hp2).opcode = A_FADDP)) then
  6375. { change to
  6376. fld/fst mem1 (hp1) fld/fst mem1
  6377. fld mem1 (p) fadd/
  6378. faddp/ fmul st, st
  6379. fmulp st, st1 (hp2) }
  6380. begin
  6381. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  6382. RemoveCurrentP(p, hp1);
  6383. if (taicpu(hp2).opcode = A_FADDP) then
  6384. taicpu(hp2).opcode := A_FADD
  6385. else
  6386. taicpu(hp2).opcode := A_FMUL;
  6387. taicpu(hp2).oper[1]^.reg := NR_ST;
  6388. end
  6389. else
  6390. { change to
  6391. fld/fst mem1 (hp1) fld/fst mem1
  6392. fld mem1 (p) fld st
  6393. }
  6394. begin
  6395. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  6396. taicpu(p).changeopsize(S_FL);
  6397. taicpu(p).loadreg(0,NR_ST);
  6398. end
  6399. else
  6400. begin
  6401. case taicpu(hp2).opcode Of
  6402. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6403. { change to
  6404. fld/fst mem1 (hp1) fld/fst mem1
  6405. fld mem2 (p) fxxx mem2
  6406. fxxxp st, st1 (hp2) }
  6407. begin
  6408. case taicpu(hp2).opcode Of
  6409. A_FADDP: taicpu(p).opcode := A_FADD;
  6410. A_FMULP: taicpu(p).opcode := A_FMUL;
  6411. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  6412. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  6413. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  6414. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  6415. else
  6416. internalerror(2019050533);
  6417. end;
  6418. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  6419. RemoveInstruction(hp2);
  6420. end
  6421. else
  6422. ;
  6423. end
  6424. end
  6425. end;
  6426. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  6427. begin
  6428. Result := condition_in(cond1, cond2) or
  6429. { Not strictly subsets due to the actual flags checked, but because we're
  6430. comparing integers, E is a subset of AE and GE and their aliases }
  6431. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  6432. end;
  6433. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  6434. var
  6435. v: TCGInt;
  6436. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  6437. FirstMatch: Boolean;
  6438. NewReg: TRegister;
  6439. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  6440. begin
  6441. Result:=false;
  6442. { All these optimisations need a next instruction }
  6443. if not GetNextInstruction(p, hp1) then
  6444. Exit;
  6445. { Search for:
  6446. cmp ###,###
  6447. j(c1) @lbl1
  6448. ...
  6449. @lbl:
  6450. cmp ###,### (same comparison as above)
  6451. j(c2) @lbl2
  6452. If c1 is a subset of c2, change to:
  6453. cmp ###,###
  6454. j(c1) @lbl2
  6455. (@lbl1 may become a dead label as a result)
  6456. }
  6457. { Also handle cases where there are multiple jumps in a row }
  6458. p_jump := hp1;
  6459. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  6460. begin
  6461. if IsJumpToLabel(taicpu(p_jump)) then
  6462. begin
  6463. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  6464. p_label := nil;
  6465. if Assigned(JumpLabel) then
  6466. p_label := getlabelwithsym(JumpLabel);
  6467. if Assigned(p_label) and
  6468. GetNextInstruction(p_label, p_dist) and
  6469. MatchInstruction(p_dist, A_CMP, []) and
  6470. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  6471. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  6472. GetNextInstruction(p_dist, hp1_dist) and
  6473. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  6474. begin
  6475. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  6476. if JumpLabel = JumpLabel_dist then
  6477. { This is an infinite loop }
  6478. Exit;
  6479. { Best optimisation when the first condition is a subset (or equal) of the second }
  6480. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  6481. begin
  6482. { Any registers used here will already be allocated }
  6483. if Assigned(JumpLabel) then
  6484. JumpLabel.DecRefs;
  6485. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  6486. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  6487. Result := True;
  6488. { Don't exit yet. Since p and p_jump haven't actually been
  6489. removed, we can check for more on this iteration }
  6490. end
  6491. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  6492. GetNextInstruction(hp1_dist, hp1_label) and
  6493. SkipAligns(hp1_label, hp1_label) and
  6494. (hp1_label.typ = ait_label) then
  6495. begin
  6496. JumpLabel_far := tai_label(hp1_label).labsym;
  6497. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  6498. { This is an infinite loop }
  6499. Exit;
  6500. if Assigned(JumpLabel_far) then
  6501. begin
  6502. { In this situation, if the first jump branches, the second one will never,
  6503. branch so change the destination label to after the second jump }
  6504. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  6505. if Assigned(JumpLabel) then
  6506. JumpLabel.DecRefs;
  6507. JumpLabel_far.IncRefs;
  6508. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  6509. Result := True;
  6510. { Don't exit yet. Since p and p_jump haven't actually been
  6511. removed, we can check for more on this iteration }
  6512. Continue;
  6513. end;
  6514. end;
  6515. end;
  6516. end;
  6517. { Search for:
  6518. cmp ###,###
  6519. j(c1) @lbl1
  6520. cmp ###,### (same as first)
  6521. Remove second cmp
  6522. }
  6523. if GetNextInstruction(p_jump, hp2) and
  6524. (
  6525. (
  6526. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  6527. (
  6528. (
  6529. MatchOpType(taicpu(p), top_const, top_reg) and
  6530. MatchOpType(taicpu(hp2), top_const, top_reg) and
  6531. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  6532. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6533. ) or (
  6534. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  6535. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  6536. )
  6537. )
  6538. ) or (
  6539. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  6540. MatchOperand(taicpu(p).oper[0]^, 0) and
  6541. (taicpu(p).oper[1]^.typ = top_reg) and
  6542. MatchInstruction(hp2, A_TEST, []) and
  6543. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6544. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  6545. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6546. )
  6547. ) then
  6548. begin
  6549. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  6550. RemoveInstruction(hp2);
  6551. Result := True;
  6552. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  6553. end;
  6554. GetNextInstruction(p_jump, p_jump);
  6555. end;
  6556. {
  6557. Try to optimise the following:
  6558. cmp $x,### ($x and $y can be registers or constants)
  6559. je @lbl1 (only reference)
  6560. cmp $y,### (### are identical)
  6561. @Lbl:
  6562. sete %reg1
  6563. Change to:
  6564. cmp $x,###
  6565. sete %reg2 (allocate new %reg2)
  6566. cmp $y,###
  6567. sete %reg1
  6568. orb %reg2,%reg1
  6569. (dealloc %reg2)
  6570. This adds an instruction (so don't perform under -Os), but it removes
  6571. a conditional branch.
  6572. }
  6573. if not (cs_opt_size in current_settings.optimizerswitches) and
  6574. (
  6575. (hp1 = p_jump) or
  6576. GetNextInstruction(p, hp1)
  6577. ) and
  6578. MatchInstruction(hp1, A_Jcc, []) and
  6579. IsJumpToLabel(taicpu(hp1)) and
  6580. (taicpu(hp1).condition in [C_E, C_Z]) and
  6581. GetNextInstruction(hp1, hp2) and
  6582. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  6583. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  6584. { The first operand of CMP instructions can only be a register or
  6585. immediate anyway, so no need to check }
  6586. GetNextInstruction(hp2, p_label) and
  6587. (
  6588. (p_label.typ = ait_label) or
  6589. (
  6590. { Sometimes there's a zero-distance jump before the label, so deal with it here
  6591. to potentially cut down on the iterations of Pass 1 }
  6592. MatchInstruction(p_label, A_Jcc, []) and
  6593. IsJumpToLabel(taicpu(p_label)) and
  6594. { Use p_dist to hold the jump briefly }
  6595. SetAndTest(p_label, p_dist) and
  6596. GetNextInstruction(p_dist, p_label) and
  6597. (p_label.typ = ait_label) and
  6598. (tai_label(p_label).labsym.getrefs >= 2) and
  6599. (JumpTargetOp(taicpu(p_dist))^.ref^.symbol = tai_label(p_label).labsym) and
  6600. { We might as well collapse the jump now }
  6601. CollapseZeroDistJump(p_dist, tai_label(p_label).labsym)
  6602. )
  6603. ) and
  6604. (tai_label(p_label).labsym.getrefs = 1) and
  6605. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  6606. GetNextInstruction(p_label, p_dist) and
  6607. MatchInstruction(p_dist, A_SETcc, []) and
  6608. (taicpu(p_dist).condition in [C_E, C_Z]) and
  6609. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  6610. { Get the instruction after the SETcc instruction so we can
  6611. allocate a new register over the entire range }
  6612. GetNextInstruction(p_dist, hp1_dist) then
  6613. begin
  6614. TransferUsedRegs(TmpUsedRegs);
  6615. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6616. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6617. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  6618. // UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  6619. { RegUsedAfterInstruction modifies TmpUsedRegs }
  6620. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  6621. begin
  6622. { Register can appear in p if it's not used afterwards, so only
  6623. allocate between hp1 and hp1_dist }
  6624. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, p_dist);
  6625. if NewReg <> NR_NO then
  6626. begin
  6627. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  6628. { Change the jump instruction into a SETcc instruction }
  6629. taicpu(hp1).opcode := A_SETcc;
  6630. taicpu(hp1).opsize := S_B;
  6631. taicpu(hp1).loadreg(0, NewReg);
  6632. { This is now a dead label }
  6633. tai_label(p_label).labsym.decrefs;
  6634. { Prefer adding before the next instruction so the FLAGS
  6635. register is deallocated first }
  6636. hp2 := taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg);
  6637. taicpu(hp2).fileinfo := taicpu(p_dist).fileinfo;
  6638. AsmL.InsertBefore(
  6639. hp2,
  6640. hp1_dist
  6641. );
  6642. { Make sure the new register is in use over the new instruction
  6643. (long-winded, but things work best when the FLAGS register
  6644. is not allocated here) }
  6645. AllocRegBetween(NewReg, p_dist, hp2, TmpUsedRegs);
  6646. Result := True;
  6647. { Don't exit yet, as p wasn't changed and hp1, while
  6648. modified, is still intact and might be optimised by the
  6649. SETcc optimisation below }
  6650. end;
  6651. end;
  6652. end;
  6653. if taicpu(p).oper[0]^.typ = top_const then
  6654. begin
  6655. if (taicpu(p).oper[0]^.val = 0) and
  6656. (taicpu(p).oper[1]^.typ = top_reg) and
  6657. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  6658. begin
  6659. hp2 := p;
  6660. FirstMatch := True;
  6661. { When dealing with "cmp $0,%reg", only ZF and SF contain
  6662. anything meaningful once it's converted to "test %reg,%reg";
  6663. additionally, some jumps will always (or never) branch, so
  6664. evaluate every jump immediately following the
  6665. comparison, optimising the conditions if possible.
  6666. Similarly with SETcc... those that are always set to 0 or 1
  6667. are changed to MOV instructions }
  6668. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  6669. (
  6670. GetNextInstruction(hp2, hp1) and
  6671. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  6672. ) do
  6673. begin
  6674. FirstMatch := False;
  6675. case taicpu(hp1).condition of
  6676. C_B, C_C, C_NAE, C_O:
  6677. { For B/NAE:
  6678. Will never branch since an unsigned integer can never be below zero
  6679. For C/O:
  6680. Result cannot overflow because 0 is being subtracted
  6681. }
  6682. begin
  6683. if taicpu(hp1).opcode = A_Jcc then
  6684. begin
  6685. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  6686. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  6687. RemoveInstruction(hp1);
  6688. { Since hp1 was deleted, hp2 must not be updated }
  6689. Continue;
  6690. end
  6691. else
  6692. begin
  6693. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  6694. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  6695. taicpu(hp1).opcode := A_MOV;
  6696. taicpu(hp1).ops := 2;
  6697. taicpu(hp1).condition := C_None;
  6698. taicpu(hp1).opsize := S_B;
  6699. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6700. taicpu(hp1).loadconst(0, 0);
  6701. end;
  6702. end;
  6703. C_BE, C_NA:
  6704. begin
  6705. { Will only branch if equal to zero }
  6706. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  6707. taicpu(hp1).condition := C_E;
  6708. end;
  6709. C_A, C_NBE:
  6710. begin
  6711. { Will only branch if not equal to zero }
  6712. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  6713. taicpu(hp1).condition := C_NE;
  6714. end;
  6715. C_AE, C_NB, C_NC, C_NO:
  6716. begin
  6717. { Will always branch }
  6718. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  6719. if taicpu(hp1).opcode = A_Jcc then
  6720. begin
  6721. MakeUnconditional(taicpu(hp1));
  6722. { Any jumps/set that follow will now be dead code }
  6723. RemoveDeadCodeAfterJump(taicpu(hp1));
  6724. Break;
  6725. end
  6726. else
  6727. begin
  6728. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  6729. taicpu(hp1).opcode := A_MOV;
  6730. taicpu(hp1).ops := 2;
  6731. taicpu(hp1).condition := C_None;
  6732. taicpu(hp1).opsize := S_B;
  6733. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6734. taicpu(hp1).loadconst(0, 1);
  6735. end;
  6736. end;
  6737. C_None:
  6738. InternalError(2020012201);
  6739. C_P, C_PE, C_NP, C_PO:
  6740. { We can't handle parity checks and they should never be generated
  6741. after a general-purpose CMP (it's used in some floating-point
  6742. comparisons that don't use CMP) }
  6743. InternalError(2020012202);
  6744. else
  6745. { Zero/Equality, Sign, their complements and all of the
  6746. signed comparisons do not need to be converted };
  6747. end;
  6748. hp2 := hp1;
  6749. end;
  6750. { Convert the instruction to a TEST }
  6751. taicpu(p).opcode := A_TEST;
  6752. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6753. Result := True;
  6754. Exit;
  6755. end
  6756. else if (taicpu(p).oper[0]^.val = 1) and
  6757. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6758. (taicpu(hp1).condition in [C_L, C_NGE]) then
  6759. begin
  6760. { Convert; To:
  6761. cmp $1,r/m cmp $0,r/m
  6762. jl @lbl jle @lbl
  6763. }
  6764. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  6765. taicpu(p).oper[0]^.val := 0;
  6766. taicpu(hp1).condition := C_LE;
  6767. { If the instruction is now "cmp $0,%reg", convert it to a
  6768. TEST (and effectively do the work of the "cmp $0,%reg" in
  6769. the block above)
  6770. If it's a reference, we can get away with not setting
  6771. Result to True because he haven't evaluated the jump
  6772. in this pass yet.
  6773. }
  6774. if (taicpu(p).oper[1]^.typ = top_reg) then
  6775. begin
  6776. taicpu(p).opcode := A_TEST;
  6777. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6778. Result := True;
  6779. end;
  6780. Exit;
  6781. end
  6782. else if (taicpu(p).oper[1]^.typ = top_reg)
  6783. {$ifdef x86_64}
  6784. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  6785. {$endif x86_64}
  6786. then
  6787. begin
  6788. { cmp register,$8000 neg register
  6789. je target --> jo target
  6790. .... only if register is deallocated before jump.}
  6791. case Taicpu(p).opsize of
  6792. S_B: v:=$80;
  6793. S_W: v:=$8000;
  6794. S_L: v:=qword($80000000);
  6795. else
  6796. internalerror(2013112905);
  6797. end;
  6798. if (taicpu(p).oper[0]^.val=v) and
  6799. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6800. (Taicpu(hp1).condition in [C_E,C_NE]) then
  6801. begin
  6802. TransferUsedRegs(TmpUsedRegs);
  6803. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  6804. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  6805. begin
  6806. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  6807. Taicpu(p).opcode:=A_NEG;
  6808. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  6809. Taicpu(p).clearop(1);
  6810. Taicpu(p).ops:=1;
  6811. if Taicpu(hp1).condition=C_E then
  6812. Taicpu(hp1).condition:=C_O
  6813. else
  6814. Taicpu(hp1).condition:=C_NO;
  6815. Result:=true;
  6816. exit;
  6817. end;
  6818. end;
  6819. end;
  6820. end;
  6821. if TrySwapMovCmp(p, hp1) then
  6822. begin
  6823. Result := True;
  6824. Exit;
  6825. end;
  6826. end;
  6827. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  6828. var
  6829. hp1: tai;
  6830. begin
  6831. {
  6832. remove the second (v)pxor from
  6833. pxor reg,reg
  6834. ...
  6835. pxor reg,reg
  6836. }
  6837. Result:=false;
  6838. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6839. MatchOpType(taicpu(p),top_reg,top_reg) and
  6840. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6841. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6842. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6843. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  6844. begin
  6845. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  6846. RemoveInstruction(hp1);
  6847. Result:=true;
  6848. Exit;
  6849. end
  6850. {
  6851. replace
  6852. pxor reg1,reg1
  6853. movapd/s reg1,reg2
  6854. dealloc reg1
  6855. by
  6856. pxor reg2,reg2
  6857. }
  6858. else if GetNextInstruction(p,hp1) and
  6859. { we mix single and double opperations here because we assume that the compiler
  6860. generates vmovapd only after double operations and vmovaps only after single operations }
  6861. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  6862. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6863. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  6864. (taicpu(p).oper[0]^.typ=top_reg) then
  6865. begin
  6866. TransferUsedRegs(TmpUsedRegs);
  6867. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6868. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  6869. begin
  6870. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  6871. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  6872. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  6873. RemoveInstruction(hp1);
  6874. result:=true;
  6875. end;
  6876. end;
  6877. end;
  6878. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  6879. var
  6880. hp1: tai;
  6881. begin
  6882. {
  6883. remove the second (v)pxor from
  6884. (v)pxor reg,reg
  6885. ...
  6886. (v)pxor reg,reg
  6887. }
  6888. Result:=false;
  6889. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  6890. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  6891. begin
  6892. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6893. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6894. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6895. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  6896. begin
  6897. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  6898. RemoveInstruction(hp1);
  6899. Result:=true;
  6900. Exit;
  6901. end;
  6902. {$ifdef x86_64}
  6903. {
  6904. replace
  6905. vpxor reg1,reg1,reg1
  6906. vmov reg,mem
  6907. by
  6908. movq $0,mem
  6909. }
  6910. if GetNextInstruction(p,hp1) and
  6911. MatchInstruction(hp1,A_VMOVSD,[]) and
  6912. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6913. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  6914. begin
  6915. TransferUsedRegs(TmpUsedRegs);
  6916. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6917. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6918. begin
  6919. taicpu(hp1).loadconst(0,0);
  6920. taicpu(hp1).opcode:=A_MOV;
  6921. taicpu(hp1).opsize:=S_Q;
  6922. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  6923. RemoveCurrentP(p);
  6924. result:=true;
  6925. Exit;
  6926. end;
  6927. end;
  6928. {$endif x86_64}
  6929. end
  6930. {
  6931. replace
  6932. vpxor reg1,reg1,reg2
  6933. by
  6934. vpxor reg2,reg2,reg2
  6935. to avoid unncessary data dependencies
  6936. }
  6937. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6938. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  6939. begin
  6940. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  6941. { avoid unncessary data dependency }
  6942. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  6943. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  6944. result:=true;
  6945. exit;
  6946. end;
  6947. Result:=OptPass1VOP(p);
  6948. end;
  6949. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  6950. var
  6951. hp1 : tai;
  6952. begin
  6953. result:=false;
  6954. { replace
  6955. IMul const,%mreg1,%mreg2
  6956. Mov %reg2,%mreg3
  6957. dealloc %mreg3
  6958. by
  6959. Imul const,%mreg1,%mreg23
  6960. }
  6961. if (taicpu(p).ops=3) and
  6962. GetNextInstruction(p,hp1) and
  6963. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6964. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6965. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6966. begin
  6967. TransferUsedRegs(TmpUsedRegs);
  6968. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6969. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6970. begin
  6971. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6972. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  6973. RemoveInstruction(hp1);
  6974. result:=true;
  6975. end;
  6976. end;
  6977. end;
  6978. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  6979. var
  6980. hp1 : tai;
  6981. begin
  6982. result:=false;
  6983. { replace
  6984. IMul %reg0,%reg1,%reg2
  6985. Mov %reg2,%reg3
  6986. dealloc %reg2
  6987. by
  6988. Imul %reg0,%reg1,%reg3
  6989. }
  6990. if GetNextInstruction(p,hp1) and
  6991. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6992. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6993. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6994. begin
  6995. TransferUsedRegs(TmpUsedRegs);
  6996. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6997. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6998. begin
  6999. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7000. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  7001. RemoveInstruction(hp1);
  7002. result:=true;
  7003. end;
  7004. end;
  7005. end;
  7006. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  7007. var
  7008. hp1: tai;
  7009. begin
  7010. Result:=false;
  7011. { get rid of
  7012. (v)cvtss2sd reg0,<reg1,>reg2
  7013. (v)cvtss2sd reg2,<reg2,>reg0
  7014. }
  7015. if GetNextInstruction(p,hp1) and
  7016. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  7017. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  7018. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  7019. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  7020. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  7021. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7022. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7023. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  7024. )
  7025. ) then
  7026. begin
  7027. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7028. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  7029. begin
  7030. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  7031. RemoveCurrentP(p);
  7032. RemoveInstruction(hp1);
  7033. end
  7034. else
  7035. begin
  7036. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  7037. if taicpu(hp1).opcode=A_CVTSD2SS then
  7038. begin
  7039. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7040. taicpu(p).opcode:=A_MOVAPS;
  7041. end
  7042. else
  7043. begin
  7044. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  7045. taicpu(p).opcode:=A_VMOVAPS;
  7046. end;
  7047. taicpu(p).ops:=2;
  7048. RemoveInstruction(hp1);
  7049. end;
  7050. Result:=true;
  7051. Exit;
  7052. end;
  7053. end;
  7054. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  7055. var
  7056. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  7057. ThisReg: TRegister;
  7058. begin
  7059. Result := False;
  7060. if not GetNextInstruction(p,hp1) then
  7061. Exit;
  7062. {
  7063. convert
  7064. j<c> .L1
  7065. mov 1,reg
  7066. jmp .L2
  7067. .L1
  7068. mov 0,reg
  7069. .L2
  7070. into
  7071. mov 0,reg
  7072. set<not(c)> reg
  7073. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7074. would destroy the flag contents
  7075. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  7076. executed at the same time as a previous comparison.
  7077. set<not(c)> reg
  7078. movzx reg, reg
  7079. }
  7080. if MatchInstruction(hp1,A_MOV,[]) and
  7081. (taicpu(hp1).oper[0]^.typ = top_const) and
  7082. (
  7083. (
  7084. (taicpu(hp1).oper[1]^.typ = top_reg)
  7085. {$ifdef i386}
  7086. { Under i386, ESI, EDI, EBP and ESP
  7087. don't have an 8-bit representation }
  7088. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7089. {$endif i386}
  7090. ) or (
  7091. {$ifdef i386}
  7092. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  7093. {$endif i386}
  7094. (taicpu(hp1).opsize = S_B)
  7095. )
  7096. ) and
  7097. GetNextInstruction(hp1,hp2) and
  7098. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7099. GetNextInstruction(hp2,hp3) and
  7100. SkipAligns(hp3, hp3) and
  7101. (hp3.typ=ait_label) and
  7102. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7103. GetNextInstruction(hp3,hp4) and
  7104. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  7105. (taicpu(hp4).oper[0]^.typ = top_const) and
  7106. (
  7107. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  7108. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  7109. ) and
  7110. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7111. GetNextInstruction(hp4,hp5) and
  7112. SkipAligns(hp5, hp5) and
  7113. (hp5.typ=ait_label) and
  7114. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  7115. begin
  7116. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7117. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7118. tai_label(hp3).labsym.DecRefs;
  7119. { If this isn't the only reference to the middle label, we can
  7120. still make a saving - only that the first jump and everything
  7121. that follows will remain. }
  7122. if (tai_label(hp3).labsym.getrefs = 0) then
  7123. begin
  7124. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7125. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  7126. else
  7127. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  7128. { remove jump, first label and second MOV (also catching any aligns) }
  7129. repeat
  7130. if not GetNextInstruction(hp2, hp3) then
  7131. InternalError(2021040810);
  7132. RemoveInstruction(hp2);
  7133. hp2 := hp3;
  7134. until hp2 = hp5;
  7135. { Don't decrement reference count before the removal loop
  7136. above, otherwise GetNextInstruction won't stop on the
  7137. the label }
  7138. tai_label(hp5).labsym.DecRefs;
  7139. end
  7140. else
  7141. begin
  7142. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7143. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  7144. else
  7145. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  7146. end;
  7147. taicpu(p).opcode:=A_SETcc;
  7148. taicpu(p).opsize:=S_B;
  7149. taicpu(p).is_jmp:=False;
  7150. if taicpu(hp1).opsize=S_B then
  7151. begin
  7152. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  7153. if taicpu(hp1).oper[1]^.typ = top_reg then
  7154. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  7155. RemoveInstruction(hp1);
  7156. end
  7157. else
  7158. begin
  7159. { Will be a register because the size can't be S_B otherwise }
  7160. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  7161. taicpu(p).loadreg(0, ThisReg);
  7162. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  7163. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  7164. begin
  7165. case taicpu(hp1).opsize of
  7166. S_W:
  7167. taicpu(hp1).opsize := S_BW;
  7168. S_L:
  7169. taicpu(hp1).opsize := S_BL;
  7170. {$ifdef x86_64}
  7171. S_Q:
  7172. begin
  7173. taicpu(hp1).opsize := S_BL;
  7174. { Change the destination register to 32-bit }
  7175. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  7176. end;
  7177. {$endif x86_64}
  7178. else
  7179. InternalError(2021040820);
  7180. end;
  7181. taicpu(hp1).opcode := A_MOVZX;
  7182. taicpu(hp1).loadreg(0, ThisReg);
  7183. end
  7184. else
  7185. begin
  7186. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  7187. { hp1 is already a MOV instruction with the correct register }
  7188. taicpu(hp1).loadconst(0, 0);
  7189. { Inserting it right before p will guarantee that the flags are also tracked }
  7190. asml.Remove(hp1);
  7191. asml.InsertBefore(hp1, p);
  7192. end;
  7193. end;
  7194. Result:=true;
  7195. exit;
  7196. end
  7197. else if (hp1.typ = ait_label) then
  7198. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  7199. end;
  7200. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  7201. var
  7202. hp1, hp2, hp3: tai;
  7203. SourceRef, TargetRef: TReference;
  7204. CurrentReg: TRegister;
  7205. begin
  7206. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  7207. if not UseAVX then
  7208. InternalError(2021100501);
  7209. Result := False;
  7210. { Look for the following to simplify:
  7211. vmovdqa/u x(mem1), %xmmreg
  7212. vmovdqa/u %xmmreg, y(mem2)
  7213. vmovdqa/u x+16(mem1), %xmmreg
  7214. vmovdqa/u %xmmreg, y+16(mem2)
  7215. Change to:
  7216. vmovdqa/u x(mem1), %ymmreg
  7217. vmovdqa/u %ymmreg, y(mem2)
  7218. vpxor %ymmreg, %ymmreg, %ymmreg
  7219. ( The VPXOR instruction is to zero the upper half, thus removing the
  7220. need to call the potentially expensive VZEROUPPER instruction. Other
  7221. peephole optimisations can remove VPXOR if it's unnecessary )
  7222. }
  7223. TransferUsedRegs(TmpUsedRegs);
  7224. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7225. { NOTE: In the optimisations below, if the references dictate that an
  7226. aligned move is possible (i.e. VMOVDQA), the existing instructions
  7227. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  7228. if (taicpu(p).opsize = S_XMM) and
  7229. MatchOpType(taicpu(p), top_ref, top_reg) and
  7230. GetNextInstruction(p, hp1) and
  7231. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7232. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  7233. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  7234. begin
  7235. SourceRef := taicpu(p).oper[0]^.ref^;
  7236. TargetRef := taicpu(hp1).oper[1]^.ref^;
  7237. if GetNextInstruction(hp1, hp2) and
  7238. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7239. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  7240. begin
  7241. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  7242. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7243. Inc(SourceRef.offset, 16);
  7244. { Reuse the register in the first block move }
  7245. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  7246. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  7247. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  7248. begin
  7249. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7250. Inc(TargetRef.offset, 16);
  7251. if GetNextInstruction(hp2, hp3) and
  7252. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7253. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7254. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7255. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7256. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7257. begin
  7258. { Update the register tracking to the new size }
  7259. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  7260. { Remember that the offsets are 16 ahead }
  7261. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7262. if not (
  7263. ((SourceRef.offset mod 32) = 16) and
  7264. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7265. ) then
  7266. taicpu(p).opcode := A_VMOVDQU;
  7267. taicpu(p).opsize := S_YMM;
  7268. taicpu(p).oper[1]^.reg := CurrentReg;
  7269. if not (
  7270. ((TargetRef.offset mod 32) = 16) and
  7271. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7272. ) then
  7273. taicpu(hp1).opcode := A_VMOVDQU;
  7274. taicpu(hp1).opsize := S_YMM;
  7275. taicpu(hp1).oper[0]^.reg := CurrentReg;
  7276. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  7277. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7278. if (pi_uses_ymm in current_procinfo.flags) then
  7279. RemoveInstruction(hp2)
  7280. else
  7281. begin
  7282. taicpu(hp2).opcode := A_VPXOR;
  7283. taicpu(hp2).opsize := S_YMM;
  7284. taicpu(hp2).loadreg(0, CurrentReg);
  7285. taicpu(hp2).loadreg(1, CurrentReg);
  7286. taicpu(hp2).loadreg(2, CurrentReg);
  7287. taicpu(hp2).ops := 3;
  7288. end;
  7289. RemoveInstruction(hp3);
  7290. Result := True;
  7291. Exit;
  7292. end;
  7293. end
  7294. else
  7295. begin
  7296. { See if the next references are 16 less rather than 16 greater }
  7297. Dec(SourceRef.offset, 32); { -16 the other way }
  7298. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  7299. begin
  7300. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7301. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  7302. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  7303. GetNextInstruction(hp2, hp3) and
  7304. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  7305. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7306. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7307. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7308. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7309. begin
  7310. { Update the register tracking to the new size }
  7311. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  7312. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  7313. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7314. if not(
  7315. ((SourceRef.offset mod 32) = 0) and
  7316. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7317. ) then
  7318. taicpu(hp2).opcode := A_VMOVDQU;
  7319. taicpu(hp2).opsize := S_YMM;
  7320. taicpu(hp2).oper[1]^.reg := CurrentReg;
  7321. if not (
  7322. ((TargetRef.offset mod 32) = 0) and
  7323. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7324. ) then
  7325. taicpu(hp3).opcode := A_VMOVDQU;
  7326. taicpu(hp3).opsize := S_YMM;
  7327. taicpu(hp3).oper[0]^.reg := CurrentReg;
  7328. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  7329. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7330. if (pi_uses_ymm in current_procinfo.flags) then
  7331. RemoveInstruction(hp1)
  7332. else
  7333. begin
  7334. taicpu(hp1).opcode := A_VPXOR;
  7335. taicpu(hp1).opsize := S_YMM;
  7336. taicpu(hp1).loadreg(0, CurrentReg);
  7337. taicpu(hp1).loadreg(1, CurrentReg);
  7338. taicpu(hp1).loadreg(2, CurrentReg);
  7339. taicpu(hp1).ops := 3;
  7340. Asml.Remove(hp1);
  7341. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  7342. end;
  7343. RemoveCurrentP(p, hp2);
  7344. Result := True;
  7345. Exit;
  7346. end;
  7347. end;
  7348. end;
  7349. end;
  7350. end;
  7351. end;
  7352. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  7353. var
  7354. hp2, hp3, first_assignment: tai;
  7355. IncCount, OperIdx: Integer;
  7356. OrigLabel: TAsmLabel;
  7357. begin
  7358. Count := 0;
  7359. Result := False;
  7360. first_assignment := nil;
  7361. if (LoopCount >= 20) then
  7362. begin
  7363. { Guard against infinite loops }
  7364. Exit;
  7365. end;
  7366. if (taicpu(p).oper[0]^.typ <> top_ref) or
  7367. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  7368. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  7369. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  7370. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  7371. Exit;
  7372. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  7373. {
  7374. change
  7375. jmp .L1
  7376. ...
  7377. .L1:
  7378. mov ##, ## ( multiple movs possible )
  7379. jmp/ret
  7380. into
  7381. mov ##, ##
  7382. jmp/ret
  7383. }
  7384. if not Assigned(hp1) then
  7385. begin
  7386. hp1 := GetLabelWithSym(OrigLabel);
  7387. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  7388. Exit;
  7389. end;
  7390. hp2 := hp1;
  7391. while Assigned(hp2) do
  7392. begin
  7393. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  7394. SkipLabels(hp2,hp2);
  7395. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  7396. Break;
  7397. case taicpu(hp2).opcode of
  7398. A_MOVSS:
  7399. begin
  7400. if taicpu(hp2).ops = 0 then
  7401. { Wrong MOVSS }
  7402. Break;
  7403. Inc(Count);
  7404. if Count >= 5 then
  7405. { Too many to be worthwhile }
  7406. Break;
  7407. GetNextInstruction(hp2, hp2);
  7408. Continue;
  7409. end;
  7410. A_MOV,
  7411. A_MOVD,
  7412. A_MOVQ,
  7413. A_MOVSX,
  7414. {$ifdef x86_64}
  7415. A_MOVSXD,
  7416. {$endif x86_64}
  7417. A_MOVZX,
  7418. A_MOVAPS,
  7419. A_MOVUPS,
  7420. A_MOVSD,
  7421. A_MOVAPD,
  7422. A_MOVUPD,
  7423. A_MOVDQA,
  7424. A_MOVDQU,
  7425. A_VMOVSS,
  7426. A_VMOVAPS,
  7427. A_VMOVUPS,
  7428. A_VMOVSD,
  7429. A_VMOVAPD,
  7430. A_VMOVUPD,
  7431. A_VMOVDQA,
  7432. A_VMOVDQU:
  7433. begin
  7434. Inc(Count);
  7435. if Count >= 5 then
  7436. { Too many to be worthwhile }
  7437. Break;
  7438. GetNextInstruction(hp2, hp2);
  7439. Continue;
  7440. end;
  7441. A_JMP:
  7442. begin
  7443. { Guard against infinite loops }
  7444. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  7445. Exit;
  7446. { Analyse this jump first in case it also duplicates assignments }
  7447. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  7448. begin
  7449. { Something did change! }
  7450. Result := True;
  7451. Inc(Count, IncCount);
  7452. if Count >= 5 then
  7453. begin
  7454. { Too many to be worthwhile }
  7455. Exit;
  7456. end;
  7457. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  7458. Break;
  7459. end;
  7460. Result := True;
  7461. Break;
  7462. end;
  7463. A_RET:
  7464. begin
  7465. Result := True;
  7466. Break;
  7467. end;
  7468. else
  7469. Break;
  7470. end;
  7471. end;
  7472. if Result then
  7473. begin
  7474. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  7475. if Count = 0 then
  7476. begin
  7477. Result := False;
  7478. Exit;
  7479. end;
  7480. hp3 := p;
  7481. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  7482. while True do
  7483. begin
  7484. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  7485. SkipLabels(hp1,hp1);
  7486. if (hp1.typ <> ait_instruction) then
  7487. InternalError(2021040720);
  7488. case taicpu(hp1).opcode of
  7489. A_JMP:
  7490. begin
  7491. { Change the original jump to the new destination }
  7492. OrigLabel.decrefs;
  7493. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  7494. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  7495. { Set p to the first duplicated assignment so it can get optimised if needs be }
  7496. if not Assigned(first_assignment) then
  7497. InternalError(2021040810)
  7498. else
  7499. p := first_assignment;
  7500. Exit;
  7501. end;
  7502. A_RET:
  7503. begin
  7504. { Now change the jump into a RET instruction }
  7505. ConvertJumpToRET(p, hp1);
  7506. { Set p to the first duplicated assignment so it can get optimised if needs be }
  7507. if not Assigned(first_assignment) then
  7508. InternalError(2021040811)
  7509. else
  7510. p := first_assignment;
  7511. Exit;
  7512. end;
  7513. else
  7514. begin
  7515. { Duplicate the MOV instruction }
  7516. hp3:=tai(hp1.getcopy);
  7517. if first_assignment = nil then
  7518. first_assignment := hp3;
  7519. asml.InsertBefore(hp3, p);
  7520. { Make sure the compiler knows about any final registers written here }
  7521. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  7522. with taicpu(hp3).oper[OperIdx]^ do
  7523. begin
  7524. case typ of
  7525. top_ref:
  7526. begin
  7527. if (ref^.base <> NR_NO) and
  7528. (getsupreg(ref^.base) <> RS_ESP) and
  7529. (getsupreg(ref^.base) <> RS_EBP)
  7530. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  7531. then
  7532. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  7533. if (ref^.index <> NR_NO) and
  7534. (getsupreg(ref^.index) <> RS_ESP) and
  7535. (getsupreg(ref^.index) <> RS_EBP)
  7536. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  7537. (ref^.index <> ref^.base) then
  7538. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  7539. end;
  7540. top_reg:
  7541. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  7542. else
  7543. ;
  7544. end;
  7545. end;
  7546. end;
  7547. end;
  7548. if not GetNextInstruction(hp1, hp1) then
  7549. { Should have dropped out earlier }
  7550. InternalError(2021040710);
  7551. end;
  7552. end;
  7553. end;
  7554. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  7555. var
  7556. hp2: tai;
  7557. X: Integer;
  7558. const
  7559. WriteOp: array[0..3] of set of TInsChange = (
  7560. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  7561. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  7562. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  7563. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  7564. RegWriteFlags: array[0..7] of set of TInsChange = (
  7565. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  7566. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  7567. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  7568. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  7569. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  7570. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  7571. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  7572. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  7573. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  7574. begin
  7575. { If we have something like:
  7576. cmp ###,%reg1
  7577. mov 0,%reg2
  7578. And no modified registers are shared, move the instruction to before
  7579. the comparison as this means it can be optimised without worrying
  7580. about the FLAGS register. (CMP/MOV is generated by
  7581. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  7582. As long as the second instruction doesn't use the flags or one of the
  7583. registers used by CMP or TEST (also check any references that use the
  7584. registers), then it can be moved prior to the comparison.
  7585. }
  7586. Result := False;
  7587. if (hp1.typ <> ait_instruction) or
  7588. taicpu(hp1).is_jmp or
  7589. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  7590. Exit;
  7591. { NOP is a pipeline fence, likely marking the beginning of the function
  7592. epilogue, so drop out. Similarly, drop out if POP or RET are
  7593. encountered }
  7594. if MatchInstruction(hp1, A_NOP, A_POP, []) then
  7595. Exit;
  7596. if (taicpu(hp1).opcode = A_MOVSS) and
  7597. (taicpu(hp1).ops = 0) then
  7598. { Wrong MOVSS }
  7599. Exit;
  7600. { Check for writes to specific registers first }
  7601. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  7602. for X := 0 to 7 do
  7603. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  7604. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  7605. Exit;
  7606. for X := 0 to taicpu(hp1).ops - 1 do
  7607. begin
  7608. { Check to see if this operand writes to something }
  7609. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  7610. { And matches something in the CMP/TEST instruction }
  7611. (
  7612. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  7613. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  7614. (
  7615. { If it's a register, make sure the register written to doesn't
  7616. appear in the cmp instruction as part of a reference }
  7617. (taicpu(hp1).oper[X]^.typ = top_reg) and
  7618. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  7619. )
  7620. ) then
  7621. Exit;
  7622. end;
  7623. { The instruction can be safely moved }
  7624. asml.Remove(hp1);
  7625. { Try to insert before the FLAGS register is allocated, so "mov $0,%reg"
  7626. can be optimised into "xor %reg,%reg" later }
  7627. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  7628. asml.InsertBefore(hp1, hp2)
  7629. else
  7630. { Note, if p.Previous is nil (even if it should logically never be the
  7631. case), FindRegAllocBackward immediately exits with False and so we
  7632. safely land here (we can't just pass p because FindRegAllocBackward
  7633. immediately exits on an instruction). [Kit] }
  7634. asml.InsertBefore(hp1, p);
  7635. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  7636. for X := 0 to taicpu(hp1).ops - 1 do
  7637. case taicpu(hp1).oper[X]^.typ of
  7638. top_reg:
  7639. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  7640. top_ref:
  7641. begin
  7642. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  7643. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  7644. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  7645. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  7646. end;
  7647. else
  7648. ;
  7649. end;
  7650. if taicpu(hp1).opcode = A_LEA then
  7651. { The flags will be overwritten by the CMP/TEST instruction }
  7652. ConvertLEA(taicpu(hp1));
  7653. Result := True;
  7654. end;
  7655. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  7656. function IsXCHGAcceptable: Boolean; inline;
  7657. begin
  7658. { Always accept if optimising for size }
  7659. Result := (cs_opt_size in current_settings.optimizerswitches) or
  7660. (
  7661. {$ifdef x86_64}
  7662. { XCHG takes 3 cycles on AMD Athlon64 }
  7663. (current_settings.optimizecputype >= cpu_core_i)
  7664. {$else x86_64}
  7665. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  7666. than 3, so it becomes a saving compared to three MOVs with two of
  7667. them able to execute simultaneously. [Kit] }
  7668. (current_settings.optimizecputype >= cpu_PentiumM)
  7669. {$endif x86_64}
  7670. );
  7671. end;
  7672. var
  7673. NewRef: TReference;
  7674. hp1, hp2, hp3, hp4: Tai;
  7675. {$ifndef x86_64}
  7676. OperIdx: Integer;
  7677. {$endif x86_64}
  7678. NewInstr : Taicpu;
  7679. NewAligh : Tai_align;
  7680. DestLabel: TAsmLabel;
  7681. function TryMovArith2Lea(InputInstr: tai): Boolean;
  7682. var
  7683. NextInstr: tai;
  7684. begin
  7685. Result := False;
  7686. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  7687. if not GetNextInstruction(InputInstr, NextInstr) or
  7688. (
  7689. { The FLAGS register isn't always tracked properly, so do not
  7690. perform this optimisation if a conditional statement follows }
  7691. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  7692. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  7693. ) then
  7694. begin
  7695. reference_reset(NewRef, 1, []);
  7696. NewRef.base := taicpu(p).oper[0]^.reg;
  7697. NewRef.scalefactor := 1;
  7698. if taicpu(InputInstr).opcode = A_ADD then
  7699. begin
  7700. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  7701. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  7702. end
  7703. else
  7704. begin
  7705. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  7706. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  7707. end;
  7708. taicpu(p).opcode := A_LEA;
  7709. taicpu(p).loadref(0, NewRef);
  7710. RemoveInstruction(InputInstr);
  7711. Result := True;
  7712. end;
  7713. end;
  7714. begin
  7715. Result:=false;
  7716. { This optimisation adds an instruction, so only do it for speed }
  7717. if not (cs_opt_size in current_settings.optimizerswitches) and
  7718. MatchOpType(taicpu(p), top_const, top_reg) and
  7719. (taicpu(p).oper[0]^.val = 0) then
  7720. begin
  7721. { To avoid compiler warning }
  7722. DestLabel := nil;
  7723. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  7724. InternalError(2021040750);
  7725. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  7726. Exit;
  7727. case hp1.typ of
  7728. ait_label:
  7729. begin
  7730. { Change:
  7731. mov $0,%reg mov $0,%reg
  7732. @Lbl1: @Lbl1:
  7733. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  7734. je @Lbl2 jne @Lbl2
  7735. To: To:
  7736. mov $0,%reg mov $0,%reg
  7737. jmp @Lbl2 jmp @Lbl3
  7738. (align) (align)
  7739. @Lbl1: @Lbl1:
  7740. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  7741. je @Lbl2 je @Lbl2
  7742. @Lbl3: <-- Only if label exists
  7743. (Not if it's optimised for size)
  7744. }
  7745. if not GetNextInstruction(hp1, hp2) then
  7746. Exit;
  7747. if not (cs_opt_size in current_settings.optimizerswitches) and
  7748. (hp2.typ = ait_instruction) and
  7749. (
  7750. { Register sizes must exactly match }
  7751. (
  7752. (taicpu(hp2).opcode = A_CMP) and
  7753. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  7754. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7755. ) or (
  7756. (taicpu(hp2).opcode = A_TEST) and
  7757. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7758. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7759. )
  7760. ) and GetNextInstruction(hp2, hp3) and
  7761. (hp3.typ = ait_instruction) and
  7762. (taicpu(hp3).opcode = A_JCC) and
  7763. (taicpu(hp3).oper[0]^.typ=top_ref) and (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and (taicpu(hp3).oper[0]^.ref^.base=NR_NO) and
  7764. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  7765. begin
  7766. { Check condition of jump }
  7767. { Always true? }
  7768. if condition_in(C_E, taicpu(hp3).condition) then
  7769. begin
  7770. { Copy label symbol and obtain matching label entry for the
  7771. conditional jump, as this will be our destination}
  7772. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  7773. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  7774. Result := True;
  7775. end
  7776. { Always false? }
  7777. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  7778. begin
  7779. { This is only worth it if there's a jump to take }
  7780. case hp2.typ of
  7781. ait_instruction:
  7782. begin
  7783. if taicpu(hp2).opcode = A_JMP then
  7784. begin
  7785. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7786. { An unconditional jump follows the conditional jump which will always be false,
  7787. so use this jump's destination for the new jump }
  7788. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  7789. Result := True;
  7790. end
  7791. else if taicpu(hp2).opcode = A_JCC then
  7792. begin
  7793. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7794. if condition_in(C_E, taicpu(hp2).condition) then
  7795. begin
  7796. { A second conditional jump follows the conditional jump which will always be false,
  7797. while the second jump is always True, so use this jump's destination for the new jump }
  7798. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  7799. Result := True;
  7800. end;
  7801. { Don't risk it if the jump isn't always true (Result remains False) }
  7802. end;
  7803. end;
  7804. else
  7805. { If anything else don't optimise };
  7806. end;
  7807. end;
  7808. if Result then
  7809. begin
  7810. { Just so we have something to insert as a paremeter}
  7811. reference_reset(NewRef, 1, []);
  7812. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  7813. { Now actually load the correct parameter (this also
  7814. increases the reference count) }
  7815. NewInstr.loadsymbol(0, DestLabel, 0);
  7816. { Get instruction before original label (may not be p under -O3) }
  7817. if not GetLastInstruction(hp1, hp2) then
  7818. { Shouldn't fail here }
  7819. InternalError(2021040701);
  7820. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  7821. AsmL.InsertAfter(NewInstr, hp2);
  7822. { Add new alignment field }
  7823. (* AsmL.InsertAfter(
  7824. cai_align.create_max(
  7825. current_settings.alignment.jumpalign,
  7826. current_settings.alignment.jumpalignskipmax
  7827. ),
  7828. NewInstr
  7829. ); *)
  7830. end;
  7831. Exit;
  7832. end;
  7833. end;
  7834. else
  7835. ;
  7836. end;
  7837. end;
  7838. if not GetNextInstruction(p, hp1) then
  7839. Exit;
  7840. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  7841. and DoMovCmpMemOpt(p, hp1, True) then
  7842. begin
  7843. Result := True;
  7844. Exit;
  7845. end
  7846. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  7847. begin
  7848. { Sometimes the MOVs that OptPass2JMP produces can be improved
  7849. further, but we can't just put this jump optimisation in pass 1
  7850. because it tends to perform worse when conditional jumps are
  7851. nearby (e.g. when converting CMOV instructions). [Kit] }
  7852. if OptPass2JMP(hp1) then
  7853. { call OptPass1MOV once to potentially merge any MOVs that were created }
  7854. Result := OptPass1MOV(p)
  7855. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  7856. returned True and the instruction is still a MOV, thus checking
  7857. the optimisations below }
  7858. { If OptPass2JMP returned False, no optimisations were done to
  7859. the jump and there are no further optimisations that can be done
  7860. to the MOV instruction on this pass }
  7861. end
  7862. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7863. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  7864. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  7865. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7866. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7867. begin
  7868. { Change:
  7869. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  7870. addl/q $x,%reg2 subl/q $x,%reg2
  7871. To:
  7872. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  7873. }
  7874. if (taicpu(hp1).oper[0]^.typ = top_const) and
  7875. { be lazy, checking separately for sub would be slightly better }
  7876. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  7877. begin
  7878. TransferUsedRegs(TmpUsedRegs);
  7879. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7880. if TryMovArith2Lea(hp1) then
  7881. begin
  7882. Result := True;
  7883. Exit;
  7884. end
  7885. end
  7886. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  7887. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  7888. { Same as above, but also adds or subtracts to %reg2 in between.
  7889. It's still valid as long as the flags aren't in use }
  7890. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  7891. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7892. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  7893. { be lazy, checking separately for sub would be slightly better }
  7894. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  7895. begin
  7896. TransferUsedRegs(TmpUsedRegs);
  7897. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7898. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7899. if TryMovArith2Lea(hp2) then
  7900. begin
  7901. Result := True;
  7902. Exit;
  7903. end;
  7904. end;
  7905. end
  7906. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7907. {$ifdef x86_64}
  7908. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  7909. {$else x86_64}
  7910. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  7911. {$endif x86_64}
  7912. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7913. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  7914. { mov reg1, reg2 mov reg1, reg2
  7915. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  7916. begin
  7917. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7918. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  7919. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  7920. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  7921. TransferUsedRegs(TmpUsedRegs);
  7922. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7923. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  7924. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  7925. then
  7926. begin
  7927. RemoveCurrentP(p, hp1);
  7928. Result:=true;
  7929. end;
  7930. exit;
  7931. end
  7932. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7933. IsXCHGAcceptable and
  7934. { XCHG doesn't support 8-byte registers }
  7935. (taicpu(p).opsize <> S_B) and
  7936. MatchInstruction(hp1, A_MOV, []) and
  7937. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7938. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  7939. GetNextInstruction(hp1, hp2) and
  7940. MatchInstruction(hp2, A_MOV, []) and
  7941. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  7942. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7943. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  7944. begin
  7945. { mov %reg1,%reg2
  7946. mov %reg3,%reg1 -> xchg %reg3,%reg1
  7947. mov %reg2,%reg3
  7948. (%reg2 not used afterwards)
  7949. Note that xchg takes 3 cycles to execute, and generally mov's take
  7950. only one cycle apiece, but the first two mov's can be executed in
  7951. parallel, only taking 2 cycles overall. Older processors should
  7952. therefore only optimise for size. [Kit]
  7953. }
  7954. TransferUsedRegs(TmpUsedRegs);
  7955. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7956. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7957. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  7958. begin
  7959. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  7960. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  7961. taicpu(hp1).opcode := A_XCHG;
  7962. RemoveCurrentP(p, hp1);
  7963. RemoveInstruction(hp2);
  7964. Result := True;
  7965. Exit;
  7966. end;
  7967. end
  7968. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7969. MatchInstruction(hp1, A_SAR, []) then
  7970. begin
  7971. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  7972. begin
  7973. { the use of %edx also covers the opsize being S_L }
  7974. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  7975. begin
  7976. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  7977. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  7978. (taicpu(p).oper[1]^.reg = NR_EDX) then
  7979. begin
  7980. { Change:
  7981. movl %eax,%edx
  7982. sarl $31,%edx
  7983. To:
  7984. cltd
  7985. }
  7986. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  7987. RemoveInstruction(hp1);
  7988. taicpu(p).opcode := A_CDQ;
  7989. taicpu(p).opsize := S_NO;
  7990. taicpu(p).clearop(1);
  7991. taicpu(p).clearop(0);
  7992. taicpu(p).ops:=0;
  7993. Result := True;
  7994. end
  7995. else if (cs_opt_size in current_settings.optimizerswitches) and
  7996. (taicpu(p).oper[0]^.reg = NR_EDX) and
  7997. (taicpu(p).oper[1]^.reg = NR_EAX) then
  7998. begin
  7999. { Change:
  8000. movl %edx,%eax
  8001. sarl $31,%edx
  8002. To:
  8003. movl %edx,%eax
  8004. cltd
  8005. Note that this creates a dependency between the two instructions,
  8006. so only perform if optimising for size.
  8007. }
  8008. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  8009. taicpu(hp1).opcode := A_CDQ;
  8010. taicpu(hp1).opsize := S_NO;
  8011. taicpu(hp1).clearop(1);
  8012. taicpu(hp1).clearop(0);
  8013. taicpu(hp1).ops:=0;
  8014. end;
  8015. {$ifndef x86_64}
  8016. end
  8017. { Don't bother if CMOV is supported, because a more optimal
  8018. sequence would have been generated for the Abs() intrinsic }
  8019. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  8020. { the use of %eax also covers the opsize being S_L }
  8021. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  8022. (taicpu(p).oper[0]^.reg = NR_EAX) and
  8023. (taicpu(p).oper[1]^.reg = NR_EDX) and
  8024. GetNextInstruction(hp1, hp2) and
  8025. MatchInstruction(hp2, A_XOR, [S_L]) and
  8026. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  8027. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  8028. GetNextInstruction(hp2, hp3) and
  8029. MatchInstruction(hp3, A_SUB, [S_L]) and
  8030. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  8031. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  8032. begin
  8033. { Change:
  8034. movl %eax,%edx
  8035. sarl $31,%eax
  8036. xorl %eax,%edx
  8037. subl %eax,%edx
  8038. (Instruction that uses %edx)
  8039. (%eax deallocated)
  8040. (%edx deallocated)
  8041. To:
  8042. cltd
  8043. xorl %edx,%eax <-- Note the registers have swapped
  8044. subl %edx,%eax
  8045. (Instruction that uses %eax) <-- %eax rather than %edx
  8046. }
  8047. TransferUsedRegs(TmpUsedRegs);
  8048. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8049. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8050. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8051. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  8052. begin
  8053. if GetNextInstruction(hp3, hp4) and
  8054. not RegModifiedByInstruction(NR_EDX, hp4) and
  8055. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  8056. begin
  8057. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  8058. taicpu(p).opcode := A_CDQ;
  8059. taicpu(p).clearop(1);
  8060. taicpu(p).clearop(0);
  8061. taicpu(p).ops:=0;
  8062. RemoveInstruction(hp1);
  8063. taicpu(hp2).loadreg(0, NR_EDX);
  8064. taicpu(hp2).loadreg(1, NR_EAX);
  8065. taicpu(hp3).loadreg(0, NR_EDX);
  8066. taicpu(hp3).loadreg(1, NR_EAX);
  8067. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  8068. { Convert references in the following instruction (hp4) from %edx to %eax }
  8069. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  8070. with taicpu(hp4).oper[OperIdx]^ do
  8071. case typ of
  8072. top_reg:
  8073. if getsupreg(reg) = RS_EDX then
  8074. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8075. top_ref:
  8076. begin
  8077. if getsupreg(reg) = RS_EDX then
  8078. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8079. if getsupreg(reg) = RS_EDX then
  8080. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8081. end;
  8082. else
  8083. ;
  8084. end;
  8085. end;
  8086. end;
  8087. {$else x86_64}
  8088. end;
  8089. end
  8090. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  8091. { the use of %rdx also covers the opsize being S_Q }
  8092. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  8093. begin
  8094. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  8095. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  8096. (taicpu(p).oper[1]^.reg = NR_RDX) then
  8097. begin
  8098. { Change:
  8099. movq %rax,%rdx
  8100. sarq $63,%rdx
  8101. To:
  8102. cqto
  8103. }
  8104. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  8105. RemoveInstruction(hp1);
  8106. taicpu(p).opcode := A_CQO;
  8107. taicpu(p).opsize := S_NO;
  8108. taicpu(p).clearop(1);
  8109. taicpu(p).clearop(0);
  8110. taicpu(p).ops:=0;
  8111. Result := True;
  8112. end
  8113. else if (cs_opt_size in current_settings.optimizerswitches) and
  8114. (taicpu(p).oper[0]^.reg = NR_RDX) and
  8115. (taicpu(p).oper[1]^.reg = NR_RAX) then
  8116. begin
  8117. { Change:
  8118. movq %rdx,%rax
  8119. sarq $63,%rdx
  8120. To:
  8121. movq %rdx,%rax
  8122. cqto
  8123. Note that this creates a dependency between the two instructions,
  8124. so only perform if optimising for size.
  8125. }
  8126. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  8127. taicpu(hp1).opcode := A_CQO;
  8128. taicpu(hp1).opsize := S_NO;
  8129. taicpu(hp1).clearop(1);
  8130. taicpu(hp1).clearop(0);
  8131. taicpu(hp1).ops:=0;
  8132. {$endif x86_64}
  8133. end;
  8134. end;
  8135. end
  8136. else if MatchInstruction(hp1, A_MOV, []) and
  8137. (taicpu(hp1).oper[1]^.typ = top_reg) then
  8138. { Though "GetNextInstruction" could be factored out, along with
  8139. the instructions that depend on hp2, it is an expensive call that
  8140. should be delayed for as long as possible, hence we do cheaper
  8141. checks first that are likely to be False. [Kit] }
  8142. begin
  8143. if (
  8144. (
  8145. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  8146. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  8147. (
  8148. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8149. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  8150. )
  8151. ) or
  8152. (
  8153. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  8154. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  8155. (
  8156. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8157. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  8158. )
  8159. )
  8160. ) and
  8161. GetNextInstruction(hp1, hp2) and
  8162. MatchInstruction(hp2, A_SAR, []) and
  8163. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  8164. begin
  8165. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  8166. begin
  8167. { Change:
  8168. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  8169. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  8170. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  8171. To:
  8172. movl r/m,%eax <- Note the change in register
  8173. cltd
  8174. }
  8175. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  8176. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  8177. taicpu(p).loadreg(1, NR_EAX);
  8178. taicpu(hp1).opcode := A_CDQ;
  8179. taicpu(hp1).clearop(1);
  8180. taicpu(hp1).clearop(0);
  8181. taicpu(hp1).ops:=0;
  8182. RemoveInstruction(hp2);
  8183. (*
  8184. {$ifdef x86_64}
  8185. end
  8186. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  8187. { This code sequence does not get generated - however it might become useful
  8188. if and when 128-bit signed integer types make an appearance, so the code
  8189. is kept here for when it is eventually needed. [Kit] }
  8190. (
  8191. (
  8192. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  8193. (
  8194. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8195. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  8196. )
  8197. ) or
  8198. (
  8199. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  8200. (
  8201. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8202. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  8203. )
  8204. )
  8205. ) and
  8206. GetNextInstruction(hp1, hp2) and
  8207. MatchInstruction(hp2, A_SAR, [S_Q]) and
  8208. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  8209. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  8210. begin
  8211. { Change:
  8212. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  8213. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  8214. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  8215. To:
  8216. movq r/m,%rax <- Note the change in register
  8217. cqto
  8218. }
  8219. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  8220. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  8221. taicpu(p).loadreg(1, NR_RAX);
  8222. taicpu(hp1).opcode := A_CQO;
  8223. taicpu(hp1).clearop(1);
  8224. taicpu(hp1).clearop(0);
  8225. taicpu(hp1).ops:=0;
  8226. RemoveInstruction(hp2);
  8227. {$endif x86_64}
  8228. *)
  8229. end;
  8230. end;
  8231. {$ifdef x86_64}
  8232. end
  8233. else if (taicpu(p).opsize = S_L) and
  8234. (taicpu(p).oper[1]^.typ = top_reg) and
  8235. (
  8236. MatchInstruction(hp1, A_MOV,[]) and
  8237. (taicpu(hp1).opsize = S_L) and
  8238. (taicpu(hp1).oper[1]^.typ = top_reg)
  8239. ) and (
  8240. GetNextInstruction(hp1, hp2) and
  8241. (tai(hp2).typ=ait_instruction) and
  8242. (taicpu(hp2).opsize = S_Q) and
  8243. (
  8244. (
  8245. MatchInstruction(hp2, A_ADD,[]) and
  8246. (taicpu(hp2).opsize = S_Q) and
  8247. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  8248. (
  8249. (
  8250. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8251. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8252. ) or (
  8253. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8254. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8255. )
  8256. )
  8257. ) or (
  8258. MatchInstruction(hp2, A_LEA,[]) and
  8259. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  8260. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  8261. (
  8262. (
  8263. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8264. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8265. ) or (
  8266. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8267. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  8268. )
  8269. ) and (
  8270. (
  8271. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8272. ) or (
  8273. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8274. )
  8275. )
  8276. )
  8277. )
  8278. ) and (
  8279. GetNextInstruction(hp2, hp3) and
  8280. MatchInstruction(hp3, A_SHR,[]) and
  8281. (taicpu(hp3).opsize = S_Q) and
  8282. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  8283. (taicpu(hp3).oper[0]^.val = 1) and
  8284. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  8285. ) then
  8286. begin
  8287. { Change movl x, reg1d movl x, reg1d
  8288. movl y, reg2d movl y, reg2d
  8289. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  8290. shrq $1, reg1q shrq $1, reg1q
  8291. ( reg1d and reg2d can be switched around in the first two instructions )
  8292. To movl x, reg1d
  8293. addl y, reg1d
  8294. rcrl $1, reg1d
  8295. This corresponds to the common expression (x + y) shr 1, where
  8296. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  8297. smaller code, but won't account for x + y causing an overflow). [Kit]
  8298. }
  8299. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  8300. { Change first MOV command to have the same register as the final output }
  8301. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  8302. else
  8303. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  8304. { Change second MOV command to an ADD command. This is easier than
  8305. converting the existing command because it means we don't have to
  8306. touch 'y', which might be a complicated reference, and also the
  8307. fact that the third command might either be ADD or LEA. [Kit] }
  8308. taicpu(hp1).opcode := A_ADD;
  8309. { Delete old ADD/LEA instruction }
  8310. RemoveInstruction(hp2);
  8311. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  8312. taicpu(hp3).opcode := A_RCR;
  8313. taicpu(hp3).changeopsize(S_L);
  8314. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  8315. {$endif x86_64}
  8316. end;
  8317. end;
  8318. {$push}
  8319. {$q-}{$r-}
  8320. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  8321. var
  8322. ThisReg: TRegister;
  8323. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  8324. TargetSubReg: TSubRegister;
  8325. hp1, hp2: tai;
  8326. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  8327. { Store list of found instructions so we don't have to call
  8328. GetNextInstructionUsingReg multiple times }
  8329. InstrList: array of taicpu;
  8330. InstrMax, Index: Integer;
  8331. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  8332. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  8333. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  8334. WorkingValue: TCgInt;
  8335. PreMessage: string;
  8336. { Data flow analysis }
  8337. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  8338. BitwiseOnly, OrXorUsed,
  8339. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  8340. function CheckOverflowConditions: Boolean;
  8341. begin
  8342. Result := True;
  8343. if (TestValSignedMax > SignedUpperLimit) then
  8344. UpperSignedOverflow := True;
  8345. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  8346. LowerSignedOverflow := True;
  8347. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  8348. LowerUnsignedOverflow := True;
  8349. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  8350. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  8351. begin
  8352. { Absolute overflow }
  8353. Result := False;
  8354. Exit;
  8355. end;
  8356. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  8357. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  8358. ShiftDownOverflow := True;
  8359. if (TestValMin < 0) or (TestValMax < 0) then
  8360. begin
  8361. LowerUnsignedOverflow := True;
  8362. UpperUnsignedOverflow := True;
  8363. end;
  8364. end;
  8365. function AdjustInitialLoadAndSize: Boolean;
  8366. begin
  8367. Result := False;
  8368. if not p_removed then
  8369. begin
  8370. if TargetSize = MinSize then
  8371. begin
  8372. { Convert the input MOVZX to a MOV }
  8373. if (taicpu(p).oper[0]^.typ = top_reg) and
  8374. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  8375. begin
  8376. { Or remove it completely! }
  8377. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  8378. RemoveCurrentP(p);
  8379. p_removed := True;
  8380. end
  8381. else
  8382. begin
  8383. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  8384. taicpu(p).opcode := A_MOV;
  8385. taicpu(p).oper[1]^.reg := ThisReg;
  8386. taicpu(p).opsize := TargetSize;
  8387. end;
  8388. Result := True;
  8389. end
  8390. else if TargetSize <> MaxSize then
  8391. begin
  8392. case MaxSize of
  8393. S_L:
  8394. if TargetSize = S_W then
  8395. begin
  8396. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  8397. taicpu(p).opsize := S_BW;
  8398. taicpu(p).oper[1]^.reg := ThisReg;
  8399. Result := True;
  8400. end
  8401. else
  8402. InternalError(2020112341);
  8403. S_W:
  8404. if TargetSize = S_L then
  8405. begin
  8406. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  8407. taicpu(p).opsize := S_BL;
  8408. taicpu(p).oper[1]^.reg := ThisReg;
  8409. Result := True;
  8410. end
  8411. else
  8412. InternalError(2020112342);
  8413. else
  8414. ;
  8415. end;
  8416. end
  8417. else if not hp1_removed and not RegInUse then
  8418. begin
  8419. { If we have something like:
  8420. movzbl (oper),%regd
  8421. add x, %regd
  8422. movzbl %regb, %regd
  8423. We can reduce the register size to the input of the final
  8424. movzbl instruction. Overflows won't have any effect.
  8425. }
  8426. if (taicpu(p).opsize in [S_BW, S_BL]) and
  8427. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  8428. begin
  8429. TargetSize := S_B;
  8430. setsubreg(ThisReg, R_SUBL);
  8431. Result := True;
  8432. end
  8433. else if (taicpu(p).opsize = S_WL) and
  8434. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  8435. begin
  8436. TargetSize := S_W;
  8437. setsubreg(ThisReg, R_SUBW);
  8438. Result := True;
  8439. end;
  8440. if Result then
  8441. begin
  8442. { Convert the input MOVZX to a MOV }
  8443. if (taicpu(p).oper[0]^.typ = top_reg) and
  8444. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  8445. begin
  8446. { Or remove it completely! }
  8447. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  8448. RemoveCurrentP(p);
  8449. p_removed := True;
  8450. end
  8451. else
  8452. begin
  8453. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  8454. taicpu(p).opcode := A_MOV;
  8455. taicpu(p).oper[1]^.reg := ThisReg;
  8456. taicpu(p).opsize := TargetSize;
  8457. end;
  8458. end;
  8459. end;
  8460. end;
  8461. end;
  8462. procedure AdjustFinalLoad;
  8463. begin
  8464. if not LowerUnsignedOverflow then
  8465. begin
  8466. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  8467. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  8468. begin
  8469. { Convert the output MOVZX to a MOV }
  8470. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8471. begin
  8472. { Or remove it completely! }
  8473. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  8474. { Be careful; if p = hp1 and p was also removed, p
  8475. will become a dangling pointer }
  8476. if p = hp1 then
  8477. begin
  8478. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  8479. p_removed := True;
  8480. end
  8481. else
  8482. RemoveInstruction(hp1);
  8483. hp1_removed := True;
  8484. end
  8485. else
  8486. begin
  8487. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  8488. taicpu(hp1).opcode := A_MOV;
  8489. taicpu(hp1).oper[0]^.reg := ThisReg;
  8490. taicpu(hp1).opsize := TargetSize;
  8491. end;
  8492. end
  8493. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  8494. begin
  8495. { Need to change the size of the output }
  8496. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  8497. taicpu(hp1).oper[0]^.reg := ThisReg;
  8498. taicpu(hp1).opsize := S_BL;
  8499. end;
  8500. end;
  8501. end;
  8502. function CompressInstructions: Boolean;
  8503. var
  8504. LocalIndex: Integer;
  8505. begin
  8506. Result := False;
  8507. { The objective here is to try to find a combination that
  8508. removes one of the MOV/Z instructions. }
  8509. if (
  8510. (taicpu(p).oper[0]^.typ <> top_reg) or
  8511. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  8512. ) and
  8513. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8514. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8515. begin
  8516. { Make a preference to remove the second MOVZX instruction }
  8517. case taicpu(hp1).opsize of
  8518. S_BL, S_WL:
  8519. begin
  8520. TargetSize := S_L;
  8521. TargetSubReg := R_SUBD;
  8522. end;
  8523. S_BW:
  8524. begin
  8525. TargetSize := S_W;
  8526. TargetSubReg := R_SUBW;
  8527. end;
  8528. else
  8529. InternalError(2020112302);
  8530. end;
  8531. end
  8532. else
  8533. begin
  8534. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  8535. begin
  8536. { Exceeded lower bound but not upper bound }
  8537. TargetSize := MaxSize;
  8538. end
  8539. else if not LowerUnsignedOverflow then
  8540. begin
  8541. { Size didn't exceed lower bound }
  8542. TargetSize := MinSize;
  8543. end
  8544. else
  8545. Exit;
  8546. end;
  8547. case TargetSize of
  8548. S_B:
  8549. TargetSubReg := R_SUBL;
  8550. S_W:
  8551. TargetSubReg := R_SUBW;
  8552. S_L:
  8553. TargetSubReg := R_SUBD;
  8554. else
  8555. InternalError(2020112350);
  8556. end;
  8557. { Update the register to its new size }
  8558. setsubreg(ThisReg, TargetSubReg);
  8559. RegInUse := False;
  8560. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8561. begin
  8562. { Check to see if the active register is used afterwards;
  8563. if not, we can change it and make a saving. }
  8564. TransferUsedRegs(TmpUsedRegs);
  8565. { The target register may be marked as in use to cross
  8566. a jump to a distant label, so exclude it }
  8567. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  8568. hp2 := p;
  8569. repeat
  8570. { Explicitly check for the excluded register (don't include the first
  8571. instruction as it may be reading from here }
  8572. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  8573. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  8574. begin
  8575. RegInUse := True;
  8576. Break;
  8577. end;
  8578. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  8579. if not GetNextInstruction(hp2, hp2) then
  8580. InternalError(2020112340);
  8581. until (hp2 = hp1);
  8582. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  8583. { We might still be able to get away with this }
  8584. RegInUse := not
  8585. (
  8586. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  8587. (hp2.typ = ait_instruction) and
  8588. (
  8589. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8590. instruction that doesn't actually contain ThisReg }
  8591. (cs_opt_level3 in current_settings.optimizerswitches) or
  8592. RegInInstruction(ThisReg, hp2)
  8593. ) and
  8594. RegLoadedWithNewValue(ThisReg, hp2)
  8595. );
  8596. if not RegInUse then
  8597. begin
  8598. { Force the register size to the same as this instruction so it can be removed}
  8599. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  8600. begin
  8601. TargetSize := S_L;
  8602. TargetSubReg := R_SUBD;
  8603. end
  8604. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  8605. begin
  8606. TargetSize := S_W;
  8607. TargetSubReg := R_SUBW;
  8608. end;
  8609. ThisReg := taicpu(hp1).oper[1]^.reg;
  8610. setsubreg(ThisReg, TargetSubReg);
  8611. RegChanged := True;
  8612. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  8613. TransferUsedRegs(TmpUsedRegs);
  8614. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  8615. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  8616. if p = hp1 then
  8617. begin
  8618. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  8619. p_removed := True;
  8620. end
  8621. else
  8622. RemoveInstruction(hp1);
  8623. hp1_removed := True;
  8624. { Instruction will become "mov %reg,%reg" }
  8625. if not p_removed and (taicpu(p).opcode = A_MOV) and
  8626. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  8627. begin
  8628. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  8629. RemoveCurrentP(p);
  8630. p_removed := True;
  8631. end
  8632. else
  8633. taicpu(p).oper[1]^.reg := ThisReg;
  8634. Result := True;
  8635. end
  8636. else
  8637. begin
  8638. if TargetSize <> MaxSize then
  8639. begin
  8640. { Since the register is in use, we have to force it to
  8641. MaxSize otherwise part of it may become undefined later on }
  8642. TargetSize := MaxSize;
  8643. case TargetSize of
  8644. S_B:
  8645. TargetSubReg := R_SUBL;
  8646. S_W:
  8647. TargetSubReg := R_SUBW;
  8648. S_L:
  8649. TargetSubReg := R_SUBD;
  8650. else
  8651. InternalError(2020112351);
  8652. end;
  8653. setsubreg(ThisReg, TargetSubReg);
  8654. end;
  8655. AdjustFinalLoad;
  8656. end;
  8657. end
  8658. else
  8659. AdjustFinalLoad;
  8660. Result := AdjustInitialLoadAndSize or Result;
  8661. { Now go through every instruction we found and change the
  8662. size. If TargetSize = MaxSize, then almost no changes are
  8663. needed and Result can remain False if it hasn't been set
  8664. yet.
  8665. If RegChanged is True, then the register requires changing
  8666. and so the point about TargetSize = MaxSize doesn't apply. }
  8667. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  8668. begin
  8669. for LocalIndex := 0 to InstrMax do
  8670. begin
  8671. { If p_removed is true, then the original MOV/Z was removed
  8672. and removing the AND instruction may not be safe if it
  8673. appears first }
  8674. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  8675. InternalError(2020112310);
  8676. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  8677. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  8678. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  8679. InstrList[LocalIndex].opsize := TargetSize;
  8680. end;
  8681. Result := True;
  8682. end;
  8683. end;
  8684. begin
  8685. Result := False;
  8686. p_removed := False;
  8687. hp1_removed := False;
  8688. ThisReg := taicpu(p).oper[1]^.reg;
  8689. { Check for:
  8690. movs/z ###,%ecx (or %cx or %rcx)
  8691. ...
  8692. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8693. (dealloc %ecx)
  8694. Change to:
  8695. mov ###,%cl (if ### = %cl, then remove completely)
  8696. ...
  8697. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8698. }
  8699. if (getsupreg(ThisReg) = RS_ECX) and
  8700. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  8701. (hp1.typ = ait_instruction) and
  8702. (
  8703. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8704. instruction that doesn't actually contain ECX }
  8705. (cs_opt_level3 in current_settings.optimizerswitches) or
  8706. RegInInstruction(NR_ECX, hp1) or
  8707. (
  8708. { It's common for the shift/rotate's read/write register to be
  8709. initialised in between, so under -O2 and under, search ahead
  8710. one more instruction
  8711. }
  8712. GetNextInstruction(hp1, hp1) and
  8713. (hp1.typ = ait_instruction) and
  8714. RegInInstruction(NR_ECX, hp1)
  8715. )
  8716. ) and
  8717. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  8718. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  8719. begin
  8720. TransferUsedRegs(TmpUsedRegs);
  8721. hp2 := p;
  8722. repeat
  8723. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8724. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  8725. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  8726. begin
  8727. case taicpu(p).opsize of
  8728. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8729. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  8730. begin
  8731. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  8732. RemoveCurrentP(p);
  8733. end
  8734. else
  8735. begin
  8736. taicpu(p).opcode := A_MOV;
  8737. taicpu(p).opsize := S_B;
  8738. taicpu(p).oper[1]^.reg := NR_CL;
  8739. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  8740. end;
  8741. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8742. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  8743. begin
  8744. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  8745. RemoveCurrentP(p);
  8746. end
  8747. else
  8748. begin
  8749. taicpu(p).opcode := A_MOV;
  8750. taicpu(p).opsize := S_W;
  8751. taicpu(p).oper[1]^.reg := NR_CX;
  8752. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  8753. end;
  8754. {$ifdef x86_64}
  8755. S_LQ:
  8756. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  8757. begin
  8758. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  8759. RemoveCurrentP(p);
  8760. end
  8761. else
  8762. begin
  8763. taicpu(p).opcode := A_MOV;
  8764. taicpu(p).opsize := S_L;
  8765. taicpu(p).oper[1]^.reg := NR_ECX;
  8766. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  8767. end;
  8768. {$endif x86_64}
  8769. else
  8770. InternalError(2021120401);
  8771. end;
  8772. Result := True;
  8773. Exit;
  8774. end;
  8775. end;
  8776. { This is anything but quick! }
  8777. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  8778. Exit;
  8779. SetLength(InstrList, 0);
  8780. InstrMax := -1;
  8781. case taicpu(p).opsize of
  8782. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8783. begin
  8784. {$if defined(i386) or defined(i8086)}
  8785. { If the target size is 8-bit, make sure we can actually encode it }
  8786. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  8787. Exit;
  8788. {$endif i386 or i8086}
  8789. LowerLimit := $FF;
  8790. SignedLowerLimit := $7F;
  8791. SignedLowerLimitBottom := -128;
  8792. MinSize := S_B;
  8793. if taicpu(p).opsize = S_BW then
  8794. begin
  8795. MaxSize := S_W;
  8796. UpperLimit := $FFFF;
  8797. SignedUpperLimit := $7FFF;
  8798. SignedUpperLimitBottom := -32768;
  8799. end
  8800. else
  8801. begin
  8802. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  8803. MaxSize := S_L;
  8804. UpperLimit := $FFFFFFFF;
  8805. SignedUpperLimit := $7FFFFFFF;
  8806. SignedUpperLimitBottom := -2147483648;
  8807. end;
  8808. end;
  8809. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8810. begin
  8811. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  8812. LowerLimit := $FFFF;
  8813. SignedLowerLimit := $7FFF;
  8814. SignedLowerLimitBottom := -32768;
  8815. UpperLimit := $FFFFFFFF;
  8816. SignedUpperLimit := $7FFFFFFF;
  8817. SignedUpperLimitBottom := -2147483648;
  8818. MinSize := S_W;
  8819. MaxSize := S_L;
  8820. end;
  8821. {$ifdef x86_64}
  8822. S_LQ:
  8823. begin
  8824. { Both the lower and upper limits are set to 32-bit. If a limit
  8825. is breached, then optimisation is impossible }
  8826. LowerLimit := $FFFFFFFF;
  8827. SignedLowerLimit := $7FFFFFFF;
  8828. SignedLowerLimitBottom := -2147483648;
  8829. UpperLimit := $FFFFFFFF;
  8830. SignedUpperLimit := $7FFFFFFF;
  8831. SignedUpperLimitBottom := -2147483648;
  8832. MinSize := S_L;
  8833. MaxSize := S_L;
  8834. end;
  8835. {$endif x86_64}
  8836. else
  8837. InternalError(2020112301);
  8838. end;
  8839. TestValMin := 0;
  8840. TestValMax := LowerLimit;
  8841. TestValSignedMax := SignedLowerLimit;
  8842. TryShiftDownLimit := LowerLimit;
  8843. TryShiftDown := S_NO;
  8844. ShiftDownOverflow := False;
  8845. RegChanged := False;
  8846. BitwiseOnly := True;
  8847. OrXorUsed := False;
  8848. UpperSignedOverflow := False;
  8849. LowerSignedOverflow := False;
  8850. UpperUnsignedOverflow := False;
  8851. LowerUnsignedOverflow := False;
  8852. hp1 := p;
  8853. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  8854. (hp1.typ = ait_instruction) and
  8855. (
  8856. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8857. instruction that doesn't actually contain ThisReg }
  8858. (cs_opt_level3 in current_settings.optimizerswitches) or
  8859. { This allows this Movx optimisation to work through the SETcc instructions
  8860. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  8861. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  8862. skip over these SETcc instructions). }
  8863. (taicpu(hp1).opcode = A_SETcc) or
  8864. RegInInstruction(ThisReg, hp1)
  8865. ) do
  8866. begin
  8867. case taicpu(hp1).opcode of
  8868. A_INC,A_DEC:
  8869. begin
  8870. { Has to be an exact match on the register }
  8871. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  8872. Break;
  8873. if taicpu(hp1).opcode = A_INC then
  8874. begin
  8875. Inc(TestValMin);
  8876. Inc(TestValMax);
  8877. Inc(TestValSignedMax);
  8878. end
  8879. else
  8880. begin
  8881. Dec(TestValMin);
  8882. Dec(TestValMax);
  8883. Dec(TestValSignedMax);
  8884. end;
  8885. end;
  8886. A_TEST, A_CMP:
  8887. begin
  8888. if (
  8889. { Too high a risk of non-linear behaviour that breaks DFA
  8890. here, unless it's cmp $0,%reg, which is equivalent to
  8891. test %reg,%reg }
  8892. OrXorUsed and
  8893. (taicpu(hp1).opcode = A_CMP) and
  8894. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  8895. ) or
  8896. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  8897. { Has to be an exact match on the register }
  8898. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8899. (
  8900. { Permit "test %reg,%reg" }
  8901. (taicpu(hp1).opcode = A_TEST) and
  8902. (taicpu(hp1).oper[0]^.typ = top_reg) and
  8903. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  8904. ) or
  8905. (taicpu(hp1).oper[0]^.typ <> top_const) or
  8906. { Make sure the comparison value is not smaller than the
  8907. smallest allowed signed value for the minimum size (e.g.
  8908. -128 for 8-bit) }
  8909. not (
  8910. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  8911. { Is it in the negative range? }
  8912. (
  8913. (taicpu(hp1).oper[0]^.val < 0) and
  8914. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  8915. )
  8916. ) then
  8917. Break;
  8918. { Check to see if the active register is used afterwards }
  8919. TransferUsedRegs(TmpUsedRegs);
  8920. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  8921. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  8922. begin
  8923. { Make sure the comparison or any previous instructions
  8924. hasn't pushed the test values outside of the range of
  8925. MinSize }
  8926. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  8927. begin
  8928. { Exceeded lower bound but not upper bound }
  8929. Exit;
  8930. end
  8931. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  8932. begin
  8933. { Size didn't exceed lower bound }
  8934. TargetSize := MinSize;
  8935. end
  8936. else
  8937. Break;
  8938. case TargetSize of
  8939. S_B:
  8940. TargetSubReg := R_SUBL;
  8941. S_W:
  8942. TargetSubReg := R_SUBW;
  8943. S_L:
  8944. TargetSubReg := R_SUBD;
  8945. else
  8946. InternalError(2021051002);
  8947. end;
  8948. if TargetSize <> MaxSize then
  8949. begin
  8950. { Update the register to its new size }
  8951. setsubreg(ThisReg, TargetSubReg);
  8952. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  8953. taicpu(hp1).oper[1]^.reg := ThisReg;
  8954. taicpu(hp1).opsize := TargetSize;
  8955. { Convert the input MOVZX to a MOV if necessary }
  8956. AdjustInitialLoadAndSize;
  8957. if (InstrMax >= 0) then
  8958. begin
  8959. for Index := 0 to InstrMax do
  8960. begin
  8961. { If p_removed is true, then the original MOV/Z was removed
  8962. and removing the AND instruction may not be safe if it
  8963. appears first }
  8964. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  8965. InternalError(2020112311);
  8966. if InstrList[Index].oper[0]^.typ = top_reg then
  8967. InstrList[Index].oper[0]^.reg := ThisReg;
  8968. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  8969. InstrList[Index].opsize := MinSize;
  8970. end;
  8971. end;
  8972. Result := True;
  8973. end;
  8974. Exit;
  8975. end;
  8976. end;
  8977. A_SETcc:
  8978. begin
  8979. { This allows this Movx optimisation to work through the SETcc instructions
  8980. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  8981. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  8982. skip over these SETcc instructions). }
  8983. if (cs_opt_level3 in current_settings.optimizerswitches) or
  8984. { Of course, break out if the current register is used }
  8985. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  8986. Break
  8987. else
  8988. { We must use Continue so the instruction doesn't get added
  8989. to InstrList }
  8990. Continue;
  8991. end;
  8992. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  8993. begin
  8994. if
  8995. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  8996. { Has to be an exact match on the register }
  8997. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  8998. (
  8999. (
  9000. (taicpu(hp1).oper[0]^.typ = top_const) and
  9001. (
  9002. (
  9003. (taicpu(hp1).opcode = A_SHL) and
  9004. (
  9005. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  9006. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  9007. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  9008. )
  9009. ) or (
  9010. (taicpu(hp1).opcode <> A_SHL) and
  9011. (
  9012. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9013. { Is it in the negative range? }
  9014. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  9015. )
  9016. )
  9017. )
  9018. ) or (
  9019. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  9020. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  9021. )
  9022. ) then
  9023. Break;
  9024. { Only process OR and XOR if there are only bitwise operations,
  9025. since otherwise they can too easily fool the data flow
  9026. analysis (they can cause non-linear behaviour) }
  9027. case taicpu(hp1).opcode of
  9028. A_ADD:
  9029. begin
  9030. if OrXorUsed then
  9031. { Too high a risk of non-linear behaviour that breaks DFA here }
  9032. Break
  9033. else
  9034. BitwiseOnly := False;
  9035. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9036. begin
  9037. TestValMin := TestValMin * 2;
  9038. TestValMax := TestValMax * 2;
  9039. TestValSignedMax := TestValSignedMax * 2;
  9040. end
  9041. else
  9042. begin
  9043. WorkingValue := taicpu(hp1).oper[0]^.val;
  9044. TestValMin := TestValMin + WorkingValue;
  9045. TestValMax := TestValMax + WorkingValue;
  9046. TestValSignedMax := TestValSignedMax + WorkingValue;
  9047. end;
  9048. end;
  9049. A_SUB:
  9050. begin
  9051. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9052. begin
  9053. TestValMin := 0;
  9054. TestValMax := 0;
  9055. TestValSignedMax := 0;
  9056. end
  9057. else
  9058. begin
  9059. if OrXorUsed then
  9060. { Too high a risk of non-linear behaviour that breaks DFA here }
  9061. Break
  9062. else
  9063. BitwiseOnly := False;
  9064. WorkingValue := taicpu(hp1).oper[0]^.val;
  9065. TestValMin := TestValMin - WorkingValue;
  9066. TestValMax := TestValMax - WorkingValue;
  9067. TestValSignedMax := TestValSignedMax - WorkingValue;
  9068. end;
  9069. end;
  9070. A_AND:
  9071. if (taicpu(hp1).oper[0]^.typ = top_const) then
  9072. begin
  9073. { we might be able to go smaller if AND appears first }
  9074. if InstrMax = -1 then
  9075. case MinSize of
  9076. S_B:
  9077. ;
  9078. S_W:
  9079. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9080. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9081. begin
  9082. TryShiftDown := S_B;
  9083. TryShiftDownLimit := $FF;
  9084. end;
  9085. S_L:
  9086. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9087. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9088. begin
  9089. TryShiftDown := S_B;
  9090. TryShiftDownLimit := $FF;
  9091. end
  9092. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  9093. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  9094. begin
  9095. TryShiftDown := S_W;
  9096. TryShiftDownLimit := $FFFF;
  9097. end;
  9098. else
  9099. InternalError(2020112320);
  9100. end;
  9101. WorkingValue := taicpu(hp1).oper[0]^.val;
  9102. TestValMin := TestValMin and WorkingValue;
  9103. TestValMax := TestValMax and WorkingValue;
  9104. TestValSignedMax := TestValSignedMax and WorkingValue;
  9105. end;
  9106. A_OR:
  9107. begin
  9108. if not BitwiseOnly then
  9109. Break;
  9110. OrXorUsed := True;
  9111. WorkingValue := taicpu(hp1).oper[0]^.val;
  9112. TestValMin := TestValMin or WorkingValue;
  9113. TestValMax := TestValMax or WorkingValue;
  9114. TestValSignedMax := TestValSignedMax or WorkingValue;
  9115. end;
  9116. A_XOR:
  9117. begin
  9118. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9119. begin
  9120. TestValMin := 0;
  9121. TestValMax := 0;
  9122. TestValSignedMax := 0;
  9123. end
  9124. else
  9125. begin
  9126. if not BitwiseOnly then
  9127. Break;
  9128. OrXorUsed := True;
  9129. WorkingValue := taicpu(hp1).oper[0]^.val;
  9130. TestValMin := TestValMin xor WorkingValue;
  9131. TestValMax := TestValMax xor WorkingValue;
  9132. TestValSignedMax := TestValSignedMax xor WorkingValue;
  9133. end;
  9134. end;
  9135. A_SHL:
  9136. begin
  9137. BitwiseOnly := False;
  9138. WorkingValue := taicpu(hp1).oper[0]^.val;
  9139. TestValMin := TestValMin shl WorkingValue;
  9140. TestValMax := TestValMax shl WorkingValue;
  9141. TestValSignedMax := TestValSignedMax shl WorkingValue;
  9142. end;
  9143. A_SHR,
  9144. { The first instruction was MOVZX, so the value won't be negative }
  9145. A_SAR:
  9146. begin
  9147. if InstrMax <> -1 then
  9148. BitwiseOnly := False
  9149. else
  9150. { we might be able to go smaller if SHR appears first }
  9151. case MinSize of
  9152. S_B:
  9153. ;
  9154. S_W:
  9155. if (taicpu(hp1).oper[0]^.val >= 8) then
  9156. begin
  9157. TryShiftDown := S_B;
  9158. TryShiftDownLimit := $FF;
  9159. TryShiftDownSignedLimit := $7F;
  9160. TryShiftDownSignedLimitLower := -128;
  9161. end;
  9162. S_L:
  9163. if (taicpu(hp1).oper[0]^.val >= 24) then
  9164. begin
  9165. TryShiftDown := S_B;
  9166. TryShiftDownLimit := $FF;
  9167. TryShiftDownSignedLimit := $7F;
  9168. TryShiftDownSignedLimitLower := -128;
  9169. end
  9170. else if (taicpu(hp1).oper[0]^.val >= 16) then
  9171. begin
  9172. TryShiftDown := S_W;
  9173. TryShiftDownLimit := $FFFF;
  9174. TryShiftDownSignedLimit := $7FFF;
  9175. TryShiftDownSignedLimitLower := -32768;
  9176. end;
  9177. else
  9178. InternalError(2020112321);
  9179. end;
  9180. WorkingValue := taicpu(hp1).oper[0]^.val;
  9181. if taicpu(hp1).opcode = A_SAR then
  9182. begin
  9183. TestValMin := SarInt64(TestValMin, WorkingValue);
  9184. TestValMax := SarInt64(TestValMax, WorkingValue);
  9185. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  9186. end
  9187. else
  9188. begin
  9189. TestValMin := TestValMin shr WorkingValue;
  9190. TestValMax := TestValMax shr WorkingValue;
  9191. TestValSignedMax := TestValSignedMax shr WorkingValue;
  9192. end;
  9193. end;
  9194. else
  9195. InternalError(2020112303);
  9196. end;
  9197. end;
  9198. (*
  9199. A_IMUL:
  9200. case taicpu(hp1).ops of
  9201. 2:
  9202. begin
  9203. if not MatchOpType(hp1, top_reg, top_reg) or
  9204. { Has to be an exact match on the register }
  9205. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  9206. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  9207. Break;
  9208. TestValMin := TestValMin * TestValMin;
  9209. TestValMax := TestValMax * TestValMax;
  9210. TestValSignedMax := TestValSignedMax * TestValMax;
  9211. end;
  9212. 3:
  9213. begin
  9214. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9215. { Has to be an exact match on the register }
  9216. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9217. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9218. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9219. { Is it in the negative range? }
  9220. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9221. Break;
  9222. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  9223. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  9224. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  9225. end;
  9226. else
  9227. Break;
  9228. end;
  9229. A_IDIV:
  9230. case taicpu(hp1).ops of
  9231. 3:
  9232. begin
  9233. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9234. { Has to be an exact match on the register }
  9235. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9236. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9237. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9238. { Is it in the negative range? }
  9239. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9240. Break;
  9241. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  9242. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  9243. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  9244. end;
  9245. else
  9246. Break;
  9247. end;
  9248. *)
  9249. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  9250. begin
  9251. { If there are no instructions in between, then we might be able to make a saving }
  9252. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  9253. Break;
  9254. { We have something like:
  9255. movzbw %dl,%dx
  9256. ...
  9257. movswl %dx,%edx
  9258. Change the latter to a zero-extension then enter the
  9259. A_MOVZX case branch.
  9260. }
  9261. {$ifdef x86_64}
  9262. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9263. begin
  9264. { this becomes a zero extension from 32-bit to 64-bit, but
  9265. the upper 32 bits are already zero, so just delete the
  9266. instruction }
  9267. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  9268. RemoveInstruction(hp1);
  9269. Result := True;
  9270. Exit;
  9271. end
  9272. else
  9273. {$endif x86_64}
  9274. begin
  9275. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  9276. taicpu(hp1).opcode := A_MOVZX;
  9277. {$ifdef x86_64}
  9278. case taicpu(hp1).opsize of
  9279. S_BQ:
  9280. begin
  9281. taicpu(hp1).opsize := S_BL;
  9282. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9283. end;
  9284. S_WQ:
  9285. begin
  9286. taicpu(hp1).opsize := S_WL;
  9287. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9288. end;
  9289. S_LQ:
  9290. begin
  9291. taicpu(hp1).opcode := A_MOV;
  9292. taicpu(hp1).opsize := S_L;
  9293. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9294. { In this instance, we need to break out because the
  9295. instruction is no longer MOVZX or MOVSXD }
  9296. Result := True;
  9297. Exit;
  9298. end;
  9299. else
  9300. ;
  9301. end;
  9302. {$endif x86_64}
  9303. Result := CompressInstructions;
  9304. Exit;
  9305. end;
  9306. end;
  9307. A_MOVZX:
  9308. begin
  9309. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  9310. Break;
  9311. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  9312. begin
  9313. if (InstrMax = -1) and
  9314. { Will return false if the second parameter isn't ThisReg
  9315. (can happen on -O2 and under) }
  9316. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9317. begin
  9318. { The two MOVZX instructions are adjacent, so remove the first one }
  9319. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  9320. RemoveCurrentP(p);
  9321. Result := True;
  9322. Exit;
  9323. end;
  9324. Break;
  9325. end;
  9326. Result := CompressInstructions;
  9327. Exit;
  9328. end;
  9329. else
  9330. { This includes ADC, SBB and IDIV }
  9331. Break;
  9332. end;
  9333. if not CheckOverflowConditions then
  9334. Break;
  9335. { Contains highest index (so instruction count - 1) }
  9336. Inc(InstrMax);
  9337. if InstrMax > High(InstrList) then
  9338. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  9339. InstrList[InstrMax] := taicpu(hp1);
  9340. end;
  9341. end;
  9342. {$pop}
  9343. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  9344. var
  9345. hp1 : tai;
  9346. begin
  9347. Result:=false;
  9348. if (taicpu(p).ops >= 2) and
  9349. ((taicpu(p).oper[0]^.typ = top_const) or
  9350. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  9351. (taicpu(p).oper[1]^.typ = top_reg) and
  9352. ((taicpu(p).ops = 2) or
  9353. ((taicpu(p).oper[2]^.typ = top_reg) and
  9354. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  9355. GetLastInstruction(p,hp1) and
  9356. MatchInstruction(hp1,A_MOV,[]) and
  9357. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9358. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9359. begin
  9360. TransferUsedRegs(TmpUsedRegs);
  9361. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  9362. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  9363. { change
  9364. mov reg1,reg2
  9365. imul y,reg2 to imul y,reg1,reg2 }
  9366. begin
  9367. taicpu(p).ops := 3;
  9368. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  9369. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  9370. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  9371. RemoveInstruction(hp1);
  9372. result:=true;
  9373. end;
  9374. end;
  9375. end;
  9376. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  9377. var
  9378. ThisLabel: TAsmLabel;
  9379. begin
  9380. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  9381. ThisLabel.decrefs;
  9382. taicpu(p).opcode := A_RET;
  9383. taicpu(p).is_jmp := false;
  9384. taicpu(p).ops := taicpu(ret_p).ops;
  9385. case taicpu(ret_p).ops of
  9386. 0:
  9387. taicpu(p).clearop(0);
  9388. 1:
  9389. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  9390. else
  9391. internalerror(2016041301);
  9392. end;
  9393. { If the original label is now dead, it might turn out that the label
  9394. immediately follows p. As a result, everything beyond it, which will
  9395. be just some final register configuration and a RET instruction, is
  9396. now dead code. [Kit] }
  9397. { NOTE: This is much faster than introducing a OptPass2RET routine and
  9398. running RemoveDeadCodeAfterJump for each RET instruction, because
  9399. this optimisation rarely happens and most RETs appear at the end of
  9400. routines where there is nothing that can be stripped. [Kit] }
  9401. if not ThisLabel.is_used then
  9402. RemoveDeadCodeAfterJump(p);
  9403. end;
  9404. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  9405. var
  9406. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  9407. Unconditional, PotentialModified: Boolean;
  9408. OperPtr: POper;
  9409. NewRef: TReference;
  9410. InstrList: array of taicpu;
  9411. InstrMax, Index: Integer;
  9412. const
  9413. {$ifdef DEBUG_AOPTCPU}
  9414. SNoFlags: shortstring = ' so the flags aren''t modified';
  9415. {$else DEBUG_AOPTCPU}
  9416. SNoFlags = '';
  9417. {$endif DEBUG_AOPTCPU}
  9418. begin
  9419. Result:=false;
  9420. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  9421. begin
  9422. if MatchInstruction(hp1, A_TEST, [S_B]) and
  9423. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9424. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9425. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9426. GetNextInstruction(hp1, hp2) and
  9427. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  9428. { Change from: To:
  9429. set(C) %reg j(~C) label
  9430. test %reg,%reg/cmp $0,%reg
  9431. je label
  9432. set(C) %reg j(C) label
  9433. test %reg,%reg/cmp $0,%reg
  9434. jne label
  9435. (Also do something similar with sete/setne instead of je/jne)
  9436. }
  9437. begin
  9438. { Before we do anything else, we need to check the instructions
  9439. in between SETcc and TEST to make sure they don't modify the
  9440. FLAGS register - if -O2 or under, there won't be any
  9441. instructions between SET and TEST }
  9442. TransferUsedRegs(TmpUsedRegs);
  9443. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9444. if (cs_opt_level3 in current_settings.optimizerswitches) then
  9445. begin
  9446. next := p;
  9447. SetLength(InstrList, 0);
  9448. InstrMax := -1;
  9449. PotentialModified := False;
  9450. { Make a note of every instruction that modifies the FLAGS
  9451. register }
  9452. while GetNextInstruction(next, next) and (next <> hp1) do
  9453. begin
  9454. if next.typ <> ait_instruction then
  9455. { GetNextInstructionUsingReg should have returned False }
  9456. InternalError(2021051701);
  9457. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  9458. begin
  9459. case taicpu(next).opcode of
  9460. A_SETcc,
  9461. A_CMOVcc,
  9462. A_Jcc:
  9463. begin
  9464. if PotentialModified then
  9465. { Not safe because the flags were modified earlier }
  9466. Exit
  9467. else
  9468. { Condition is the same as the initial SETcc, so this is safe
  9469. (don't add to instruction list though) }
  9470. Continue;
  9471. end;
  9472. A_ADD:
  9473. begin
  9474. if (taicpu(next).opsize = S_B) or
  9475. { LEA doesn't support 8-bit operands }
  9476. (taicpu(next).oper[1]^.typ <> top_reg) or
  9477. { Must write to a register }
  9478. (taicpu(next).oper[0]^.typ = top_ref) then
  9479. { Require a constant or a register }
  9480. Exit;
  9481. PotentialModified := True;
  9482. end;
  9483. A_SUB:
  9484. begin
  9485. if (taicpu(next).opsize = S_B) or
  9486. { LEA doesn't support 8-bit operands }
  9487. (taicpu(next).oper[1]^.typ <> top_reg) or
  9488. { Must write to a register }
  9489. (taicpu(next).oper[0]^.typ <> top_const) or
  9490. (taicpu(next).oper[0]^.val = $80000000) then
  9491. { Can't subtract a register with LEA - also
  9492. check that the value isn't -2^31, as this
  9493. can't be negated }
  9494. Exit;
  9495. PotentialModified := True;
  9496. end;
  9497. A_SAL,
  9498. A_SHL:
  9499. begin
  9500. if (taicpu(next).opsize = S_B) or
  9501. { LEA doesn't support 8-bit operands }
  9502. (taicpu(next).oper[1]^.typ <> top_reg) or
  9503. { Must write to a register }
  9504. (taicpu(next).oper[0]^.typ <> top_const) or
  9505. (taicpu(next).oper[0]^.val < 0) or
  9506. (taicpu(next).oper[0]^.val > 3) then
  9507. Exit;
  9508. PotentialModified := True;
  9509. end;
  9510. A_IMUL:
  9511. begin
  9512. if (taicpu(next).ops <> 3) or
  9513. (taicpu(next).oper[1]^.typ <> top_reg) or
  9514. { Must write to a register }
  9515. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  9516. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  9517. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  9518. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  9519. Exit
  9520. else
  9521. PotentialModified := True;
  9522. end;
  9523. else
  9524. { Don't know how to change this, so abort }
  9525. Exit;
  9526. end;
  9527. { Contains highest index (so instruction count - 1) }
  9528. Inc(InstrMax);
  9529. if InstrMax > High(InstrList) then
  9530. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  9531. InstrList[InstrMax] := taicpu(next);
  9532. end;
  9533. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  9534. end;
  9535. if not Assigned(next) or (next <> hp1) then
  9536. { It should be equal to hp1 }
  9537. InternalError(2021051702);
  9538. { Cycle through each instruction and check to see if we can
  9539. change them to versions that don't modify the flags }
  9540. if (InstrMax >= 0) then
  9541. begin
  9542. for Index := 0 to InstrMax do
  9543. case InstrList[Index].opcode of
  9544. A_ADD:
  9545. begin
  9546. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  9547. InstrList[Index].opcode := A_LEA;
  9548. reference_reset(NewRef, 1, []);
  9549. NewRef.base := InstrList[Index].oper[1]^.reg;
  9550. if InstrList[Index].oper[0]^.typ = top_reg then
  9551. begin
  9552. NewRef.index := InstrList[Index].oper[0]^.reg;
  9553. NewRef.scalefactor := 1;
  9554. end
  9555. else
  9556. NewRef.offset := InstrList[Index].oper[0]^.val;
  9557. InstrList[Index].loadref(0, NewRef);
  9558. end;
  9559. A_SUB:
  9560. begin
  9561. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  9562. InstrList[Index].opcode := A_LEA;
  9563. reference_reset(NewRef, 1, []);
  9564. NewRef.base := InstrList[Index].oper[1]^.reg;
  9565. NewRef.offset := -InstrList[Index].oper[0]^.val;
  9566. InstrList[Index].loadref(0, NewRef);
  9567. end;
  9568. A_SHL,
  9569. A_SAL:
  9570. begin
  9571. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  9572. InstrList[Index].opcode := A_LEA;
  9573. reference_reset(NewRef, 1, []);
  9574. NewRef.index := InstrList[Index].oper[1]^.reg;
  9575. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  9576. InstrList[Index].loadref(0, NewRef);
  9577. end;
  9578. A_IMUL:
  9579. begin
  9580. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  9581. InstrList[Index].opcode := A_LEA;
  9582. reference_reset(NewRef, 1, []);
  9583. NewRef.index := InstrList[Index].oper[1]^.reg;
  9584. case InstrList[Index].oper[0]^.val of
  9585. 2, 4, 8:
  9586. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  9587. else {3, 5 and 9}
  9588. begin
  9589. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  9590. NewRef.base := InstrList[Index].oper[1]^.reg;
  9591. end;
  9592. end;
  9593. InstrList[Index].loadref(0, NewRef);
  9594. end;
  9595. else
  9596. InternalError(2021051710);
  9597. end;
  9598. end;
  9599. { Mark the FLAGS register as used across this whole block }
  9600. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  9601. end;
  9602. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  9603. JumpC := taicpu(hp2).condition;
  9604. Unconditional := False;
  9605. if conditions_equal(JumpC, C_E) then
  9606. SetC := inverse_cond(taicpu(p).condition)
  9607. else if conditions_equal(JumpC, C_NE) then
  9608. SetC := taicpu(p).condition
  9609. else
  9610. { We've got something weird here (and inefficent) }
  9611. begin
  9612. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  9613. SetC := C_NONE;
  9614. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  9615. if condition_in(C_AE, JumpC) then
  9616. Unconditional := True
  9617. else
  9618. { Not sure what to do with this jump - drop out }
  9619. Exit;
  9620. end;
  9621. RemoveInstruction(hp1);
  9622. if Unconditional then
  9623. MakeUnconditional(taicpu(hp2))
  9624. else
  9625. begin
  9626. if SetC = C_NONE then
  9627. InternalError(2018061402);
  9628. taicpu(hp2).SetCondition(SetC);
  9629. end;
  9630. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  9631. TmpUsedRegs }
  9632. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  9633. begin
  9634. RemoveCurrentp(p, hp2);
  9635. if taicpu(hp2).opcode = A_SETcc then
  9636. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  9637. else
  9638. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  9639. end
  9640. else
  9641. if taicpu(hp2).opcode = A_SETcc then
  9642. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  9643. else
  9644. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  9645. Result := True;
  9646. end
  9647. else if
  9648. { Make sure the instructions are adjacent }
  9649. (
  9650. not (cs_opt_level3 in current_settings.optimizerswitches) or
  9651. GetNextInstruction(p, hp1)
  9652. ) and
  9653. MatchInstruction(hp1, A_MOV, [S_B]) and
  9654. { Writing to memory is allowed }
  9655. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  9656. begin
  9657. {
  9658. Watch out for sequences such as:
  9659. set(c)b %regb
  9660. movb %regb,(ref)
  9661. movb $0,1(ref)
  9662. movb $0,2(ref)
  9663. movb $0,3(ref)
  9664. Much more efficient to turn it into:
  9665. movl $0,%regl
  9666. set(c)b %regb
  9667. movl %regl,(ref)
  9668. Or:
  9669. set(c)b %regb
  9670. movzbl %regb,%regl
  9671. movl %regl,(ref)
  9672. }
  9673. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  9674. GetNextInstruction(hp1, hp2) and
  9675. MatchInstruction(hp2, A_MOV, [S_B]) and
  9676. (taicpu(hp2).oper[1]^.typ = top_ref) and
  9677. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  9678. begin
  9679. { Don't do anything else except set Result to True }
  9680. end
  9681. else
  9682. begin
  9683. if taicpu(p).oper[0]^.typ = top_reg then
  9684. begin
  9685. TransferUsedRegs(TmpUsedRegs);
  9686. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9687. end;
  9688. { If it's not a register, it's a memory address }
  9689. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  9690. begin
  9691. { Even if the register is still in use, we can minimise the
  9692. pipeline stall by changing the MOV into another SETcc. }
  9693. taicpu(hp1).opcode := A_SETcc;
  9694. taicpu(hp1).condition := taicpu(p).condition;
  9695. if taicpu(hp1).oper[1]^.typ = top_ref then
  9696. begin
  9697. { Swapping the operand pointers like this is probably a
  9698. bit naughty, but it is far faster than using loadoper
  9699. to transfer the reference from oper[1] to oper[0] if
  9700. you take into account the extra procedure calls and
  9701. the memory allocation and deallocation required }
  9702. OperPtr := taicpu(hp1).oper[1];
  9703. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  9704. taicpu(hp1).oper[0] := OperPtr;
  9705. end
  9706. else
  9707. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  9708. taicpu(hp1).clearop(1);
  9709. taicpu(hp1).ops := 1;
  9710. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  9711. end
  9712. else
  9713. begin
  9714. if taicpu(hp1).oper[1]^.typ = top_reg then
  9715. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  9716. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  9717. RemoveInstruction(hp1);
  9718. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  9719. end
  9720. end;
  9721. Result := True;
  9722. end;
  9723. end;
  9724. end;
  9725. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  9726. var
  9727. hp1: tai;
  9728. Count: Integer;
  9729. OrigLabel: TAsmLabel;
  9730. begin
  9731. result := False;
  9732. { Sometimes, the optimisations below can permit this }
  9733. RemoveDeadCodeAfterJump(p);
  9734. 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
  9735. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  9736. begin
  9737. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9738. { Also a side-effect of optimisations }
  9739. if CollapseZeroDistJump(p, OrigLabel) then
  9740. begin
  9741. Result := True;
  9742. Exit;
  9743. end;
  9744. hp1 := GetLabelWithSym(OrigLabel);
  9745. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  9746. begin
  9747. if taicpu(hp1).opcode = A_RET then
  9748. begin
  9749. {
  9750. change
  9751. jmp .L1
  9752. ...
  9753. .L1:
  9754. ret
  9755. into
  9756. ret
  9757. }
  9758. begin
  9759. ConvertJumpToRET(p, hp1);
  9760. result:=true;
  9761. end;
  9762. end
  9763. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  9764. not (cs_opt_size in current_settings.optimizerswitches) and
  9765. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  9766. begin
  9767. Result := True;
  9768. Exit;
  9769. end;
  9770. end;
  9771. end;
  9772. end;
  9773. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  9774. begin
  9775. CanBeCMOV:=assigned(p) and
  9776. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  9777. { we can't use cmov ref,reg because
  9778. ref could be nil and cmov still throws an exception
  9779. if ref=nil but the mov isn't done (FK)
  9780. or ((taicpu(p).oper[0]^.typ = top_ref) and
  9781. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  9782. }
  9783. (taicpu(p).oper[1]^.typ = top_reg) and
  9784. (
  9785. (taicpu(p).oper[0]^.typ = top_reg) or
  9786. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  9787. it is not expected that this can cause a seg. violation }
  9788. (
  9789. (taicpu(p).oper[0]^.typ = top_ref) and
  9790. IsRefSafe(taicpu(p).oper[0]^.ref)
  9791. )
  9792. );
  9793. end;
  9794. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  9795. var
  9796. hp1,hp2: tai;
  9797. {$ifndef i8086}
  9798. hp3,hp4,hpmov2, hp5: tai;
  9799. l : Longint;
  9800. condition : TAsmCond;
  9801. {$endif i8086}
  9802. carryadd_opcode : TAsmOp;
  9803. symbol: TAsmSymbol;
  9804. increg, tmpreg: TRegister;
  9805. begin
  9806. result:=false;
  9807. if GetNextInstruction(p,hp1) then
  9808. begin
  9809. if (hp1.typ=ait_label) then
  9810. begin
  9811. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  9812. Exit;
  9813. end
  9814. else if (hp1.typ<>ait_instruction) then
  9815. Exit;
  9816. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9817. if (
  9818. (
  9819. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  9820. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  9821. (Taicpu(hp1).oper[0]^.val=1)
  9822. ) or
  9823. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  9824. ) and
  9825. GetNextInstruction(hp1,hp2) and
  9826. SkipAligns(hp2, hp2) and
  9827. (hp2.typ = ait_label) and
  9828. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  9829. { jb @@1 cmc
  9830. inc/dec operand --> adc/sbb operand,0
  9831. @@1:
  9832. ... and ...
  9833. jnb @@1
  9834. inc/dec operand --> adc/sbb operand,0
  9835. @@1: }
  9836. begin
  9837. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  9838. begin
  9839. case taicpu(hp1).opcode of
  9840. A_INC,
  9841. A_ADD:
  9842. carryadd_opcode:=A_ADC;
  9843. A_DEC,
  9844. A_SUB:
  9845. carryadd_opcode:=A_SBB;
  9846. else
  9847. InternalError(2021011001);
  9848. end;
  9849. Taicpu(p).clearop(0);
  9850. Taicpu(p).ops:=0;
  9851. Taicpu(p).is_jmp:=false;
  9852. Taicpu(p).opcode:=A_CMC;
  9853. Taicpu(p).condition:=C_NONE;
  9854. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  9855. Taicpu(hp1).ops:=2;
  9856. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  9857. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  9858. else
  9859. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  9860. Taicpu(hp1).loadconst(0,0);
  9861. Taicpu(hp1).opcode:=carryadd_opcode;
  9862. result:=true;
  9863. exit;
  9864. end
  9865. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  9866. begin
  9867. case taicpu(hp1).opcode of
  9868. A_INC,
  9869. A_ADD:
  9870. carryadd_opcode:=A_ADC;
  9871. A_DEC,
  9872. A_SUB:
  9873. carryadd_opcode:=A_SBB;
  9874. else
  9875. InternalError(2021011002);
  9876. end;
  9877. Taicpu(hp1).ops:=2;
  9878. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  9879. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  9880. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  9881. else
  9882. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  9883. Taicpu(hp1).loadconst(0,0);
  9884. Taicpu(hp1).opcode:=carryadd_opcode;
  9885. RemoveCurrentP(p, hp1);
  9886. result:=true;
  9887. exit;
  9888. end
  9889. {
  9890. jcc @@1 setcc tmpreg
  9891. inc/dec/add/sub operand -> (movzx tmpreg)
  9892. @@1: add/sub tmpreg,operand
  9893. While this increases code size slightly, it makes the code much faster if the
  9894. jump is unpredictable
  9895. }
  9896. else if not(cs_opt_size in current_settings.optimizerswitches) then
  9897. begin
  9898. { search for an available register which is volatile }
  9899. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  9900. if increg <> NR_NO then
  9901. begin
  9902. { We don't need to check if tmpreg is in hp1 or not, because
  9903. it will be marked as in use at p (if not, this is
  9904. indictive of a compiler bug). }
  9905. TAsmLabel(symbol).decrefs;
  9906. Taicpu(p).clearop(0);
  9907. Taicpu(p).ops:=1;
  9908. Taicpu(p).is_jmp:=false;
  9909. Taicpu(p).opcode:=A_SETcc;
  9910. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  9911. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  9912. Taicpu(p).loadreg(0,increg);
  9913. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  9914. begin
  9915. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  9916. R_SUBW:
  9917. begin
  9918. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  9919. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  9920. end;
  9921. R_SUBD:
  9922. begin
  9923. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  9924. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  9925. end;
  9926. {$ifdef x86_64}
  9927. R_SUBQ:
  9928. begin
  9929. { MOVZX doesn't have a 64-bit variant, because
  9930. the 32-bit version implicitly zeroes the
  9931. upper 32-bits of the destination register }
  9932. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  9933. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  9934. setsubreg(tmpreg, R_SUBQ);
  9935. end;
  9936. {$endif x86_64}
  9937. else
  9938. Internalerror(2020030601);
  9939. end;
  9940. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  9941. asml.InsertAfter(hp2,p);
  9942. end
  9943. else
  9944. tmpreg := increg;
  9945. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  9946. begin
  9947. Taicpu(hp1).ops:=2;
  9948. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  9949. end;
  9950. Taicpu(hp1).loadreg(0,tmpreg);
  9951. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  9952. Result := True;
  9953. { p is no longer a Jcc instruction, so exit }
  9954. Exit;
  9955. end;
  9956. end;
  9957. end;
  9958. { Detect the following:
  9959. jmp<cond> @Lbl1
  9960. jmp @Lbl2
  9961. ...
  9962. @Lbl1:
  9963. ret
  9964. Change to:
  9965. jmp<inv_cond> @Lbl2
  9966. ret
  9967. }
  9968. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  9969. begin
  9970. hp2:=getlabelwithsym(TAsmLabel(symbol));
  9971. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  9972. MatchInstruction(hp2,A_RET,[S_NO]) then
  9973. begin
  9974. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  9975. { Change label address to that of the unconditional jump }
  9976. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  9977. TAsmLabel(symbol).DecRefs;
  9978. taicpu(hp1).opcode := A_RET;
  9979. taicpu(hp1).is_jmp := false;
  9980. taicpu(hp1).ops := taicpu(hp2).ops;
  9981. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  9982. case taicpu(hp2).ops of
  9983. 0:
  9984. taicpu(hp1).clearop(0);
  9985. 1:
  9986. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  9987. else
  9988. internalerror(2016041302);
  9989. end;
  9990. end;
  9991. {$ifndef i8086}
  9992. end
  9993. {
  9994. convert
  9995. j<c> .L1
  9996. mov 1,reg
  9997. jmp .L2
  9998. .L1
  9999. mov 0,reg
  10000. .L2
  10001. into
  10002. mov 0,reg
  10003. set<not(c)> reg
  10004. take care of alignment and that the mov 0,reg is not converted into a xor as this
  10005. would destroy the flag contents
  10006. }
  10007. else if MatchInstruction(hp1,A_MOV,[]) and
  10008. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10009. {$ifdef i386}
  10010. (
  10011. { Under i386, ESI, EDI, EBP and ESP
  10012. don't have an 8-bit representation }
  10013. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  10014. ) and
  10015. {$endif i386}
  10016. (taicpu(hp1).oper[0]^.val=1) and
  10017. GetNextInstruction(hp1,hp2) and
  10018. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  10019. GetNextInstruction(hp2,hp3) and
  10020. { skip align }
  10021. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  10022. (hp3.typ=ait_label) and
  10023. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  10024. (tai_label(hp3).labsym.getrefs=1) and
  10025. GetNextInstruction(hp3,hp4) and
  10026. MatchInstruction(hp4,A_MOV,[]) and
  10027. MatchOpType(taicpu(hp4),top_const,top_reg) and
  10028. (taicpu(hp4).oper[0]^.val=0) and
  10029. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  10030. GetNextInstruction(hp4,hp5) and
  10031. (hp5.typ=ait_label) and
  10032. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  10033. (tai_label(hp5).labsym.getrefs=1) then
  10034. begin
  10035. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  10036. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  10037. { remove last label }
  10038. RemoveInstruction(hp5);
  10039. { remove second label }
  10040. RemoveInstruction(hp3);
  10041. { if align is present remove it }
  10042. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  10043. RemoveInstruction(hp3);
  10044. { remove jmp }
  10045. RemoveInstruction(hp2);
  10046. if taicpu(hp1).opsize=S_B then
  10047. RemoveInstruction(hp1)
  10048. else
  10049. taicpu(hp1).loadconst(0,0);
  10050. taicpu(hp4).opcode:=A_SETcc;
  10051. taicpu(hp4).opsize:=S_B;
  10052. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  10053. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  10054. taicpu(hp4).opercnt:=1;
  10055. taicpu(hp4).ops:=1;
  10056. taicpu(hp4).freeop(1);
  10057. RemoveCurrentP(p);
  10058. Result:=true;
  10059. exit;
  10060. end
  10061. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  10062. begin
  10063. { check for
  10064. jCC xxx
  10065. <several movs>
  10066. xxx:
  10067. Also spot:
  10068. Jcc xxx
  10069. <several movs>
  10070. jmp xxx
  10071. Change to:
  10072. <several cmovs with inverted condition>
  10073. jmp xxx
  10074. }
  10075. l:=0;
  10076. while assigned(hp1) and
  10077. CanBeCMOV(hp1) and
  10078. { stop on labels }
  10079. not(hp1.typ=ait_label) do
  10080. begin
  10081. inc(l);
  10082. hp5 := hp1;
  10083. GetNextInstruction(hp1,hp1);
  10084. end;
  10085. if assigned(hp1) then
  10086. begin
  10087. TransferUsedRegs(TmpUsedRegs);
  10088. if (
  10089. MatchInstruction(hp1, A_JMP, []) and
  10090. (JumpTargetOp(taicpu(hp1))^.typ=top_ref) and
  10091. (JumpTargetOp(taicpu(hp1))^.ref^.symbol=symbol)
  10092. ) or
  10093. FindLabel(tasmlabel(symbol),hp1) then
  10094. begin
  10095. if (l<=4) and (l>0) then
  10096. begin
  10097. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  10098. condition:=inverse_cond(taicpu(p).condition);
  10099. UpdateUsedRegs(tai(p.next));
  10100. GetNextInstruction(p,hp1);
  10101. repeat
  10102. if not Assigned(hp1) then
  10103. InternalError(2018062900);
  10104. taicpu(hp1).opcode:=A_CMOVcc;
  10105. taicpu(hp1).condition:=condition;
  10106. UpdateUsedRegs(tai(hp1.next));
  10107. GetNextInstruction(hp1,hp1);
  10108. until not(CanBeCMOV(hp1));
  10109. { Remember what hp1 is in case there's multiple aligns to get rid of }
  10110. hp2 := hp1;
  10111. repeat
  10112. if not Assigned(hp2) then
  10113. InternalError(2018062910);
  10114. case hp2.typ of
  10115. ait_label:
  10116. { What we expected - break out of the loop (it won't be a dead label at the top of
  10117. a cluster because that was optimised at an earlier stage) }
  10118. Break;
  10119. ait_align:
  10120. { Go to the next entry until a label is found (may be multiple aligns before it) }
  10121. begin
  10122. hp2 := tai(hp2.Next);
  10123. Continue;
  10124. end;
  10125. ait_instruction:
  10126. begin
  10127. if taicpu(hp2).opcode<>A_JMP then
  10128. InternalError(2018062912);
  10129. { This is the Jcc @Lbl; <several movs>; JMP @Lbl variant }
  10130. Break;
  10131. end
  10132. else
  10133. begin
  10134. { Might be a comment or temporary allocation entry }
  10135. if not (hp2.typ in SkipInstr) then
  10136. InternalError(2018062911);
  10137. hp2 := tai(hp2.Next);
  10138. Continue;
  10139. end;
  10140. end;
  10141. until False;
  10142. { Now we can safely decrement the reference count }
  10143. tasmlabel(symbol).decrefs;
  10144. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  10145. { Remove the original jump }
  10146. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  10147. if hp2.typ=ait_instruction then
  10148. begin
  10149. p:=hp2;
  10150. Result:=True;
  10151. end
  10152. else
  10153. begin
  10154. UpdateUsedRegs(tai(hp2.next));
  10155. Result:=GetNextInstruction(hp2, p); { Instruction after the label }
  10156. { Remove the label if this is its final reference }
  10157. if (tasmlabel(symbol).getrefs=0) then
  10158. StripLabelFast(hp1);
  10159. end;
  10160. exit;
  10161. end;
  10162. end
  10163. else
  10164. begin
  10165. { check further for
  10166. jCC xxx
  10167. <several movs 1>
  10168. jmp yyy
  10169. xxx:
  10170. <several movs 2>
  10171. yyy:
  10172. }
  10173. { hp2 points to jmp yyy }
  10174. hp2:=hp1;
  10175. { skip hp1 to xxx (or an align right before it) }
  10176. GetNextInstruction(hp1, hp1);
  10177. if assigned(hp2) and
  10178. assigned(hp1) and
  10179. (l<=3) and
  10180. (hp2.typ=ait_instruction) and
  10181. (taicpu(hp2).is_jmp) and
  10182. (taicpu(hp2).condition=C_None) and
  10183. { real label and jump, no further references to the
  10184. label are allowed }
  10185. (tasmlabel(symbol).getrefs=1) and
  10186. FindLabel(tasmlabel(symbol),hp1) then
  10187. begin
  10188. l:=0;
  10189. { skip hp1 to <several moves 2> }
  10190. if (hp1.typ = ait_align) then
  10191. GetNextInstruction(hp1, hp1);
  10192. GetNextInstruction(hp1, hpmov2);
  10193. hp1 := hpmov2;
  10194. while assigned(hp1) and
  10195. CanBeCMOV(hp1) do
  10196. begin
  10197. inc(l);
  10198. hp5 := hp1;
  10199. GetNextInstruction(hp1, hp1);
  10200. end;
  10201. { hp1 points to yyy (or an align right before it) }
  10202. hp3 := hp1;
  10203. if assigned(hp1) and
  10204. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  10205. begin
  10206. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  10207. condition:=inverse_cond(taicpu(p).condition);
  10208. UpdateUsedRegs(tai(p.next));
  10209. GetNextInstruction(p,hp1);
  10210. repeat
  10211. taicpu(hp1).opcode:=A_CMOVcc;
  10212. taicpu(hp1).condition:=condition;
  10213. UpdateUsedRegs(tai(hp1.next));
  10214. GetNextInstruction(hp1,hp1);
  10215. until not(assigned(hp1)) or
  10216. not(CanBeCMOV(hp1));
  10217. condition:=inverse_cond(condition);
  10218. if GetLastInstruction(hpmov2,hp1) then
  10219. UpdateUsedRegs(tai(hp1.next));
  10220. hp1 := hpmov2;
  10221. { hp1 is now at <several movs 2> }
  10222. while Assigned(hp1) and CanBeCMOV(hp1) do
  10223. begin
  10224. taicpu(hp1).opcode:=A_CMOVcc;
  10225. taicpu(hp1).condition:=condition;
  10226. UpdateUsedRegs(tai(hp1.next));
  10227. GetNextInstruction(hp1,hp1);
  10228. end;
  10229. hp1 := p;
  10230. { Get first instruction after label }
  10231. UpdateUsedRegs(tai(hp3.next));
  10232. GetNextInstruction(hp3, p);
  10233. if assigned(p) and (hp3.typ = ait_align) then
  10234. GetNextInstruction(p, p);
  10235. { Don't dereference yet, as doing so will cause
  10236. GetNextInstruction to skip the label and
  10237. optional align marker. [Kit] }
  10238. GetNextInstruction(hp2, hp4);
  10239. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  10240. { remove jCC }
  10241. RemoveInstruction(hp1);
  10242. { Now we can safely decrement it }
  10243. tasmlabel(symbol).decrefs;
  10244. { Remove label xxx (it will have a ref of zero due to the initial check }
  10245. StripLabelFast(hp4);
  10246. { remove jmp }
  10247. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  10248. RemoveInstruction(hp2);
  10249. { As before, now we can safely decrement it }
  10250. tasmlabel(symbol).decrefs;
  10251. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  10252. if tasmlabel(symbol).getrefs = 0 then
  10253. StripLabelFast(hp3);
  10254. if Assigned(p) then
  10255. result:=true;
  10256. exit;
  10257. end;
  10258. end;
  10259. end;
  10260. end;
  10261. {$endif i8086}
  10262. end;
  10263. end;
  10264. end;
  10265. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  10266. var
  10267. hp1,hp2,hp3: tai;
  10268. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  10269. NewSize: TOpSize;
  10270. NewRegSize: TSubRegister;
  10271. Limit: TCgInt;
  10272. SwapOper: POper;
  10273. begin
  10274. result:=false;
  10275. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  10276. GetNextInstruction(p,hp1) and
  10277. (hp1.typ = ait_instruction);
  10278. if reg_and_hp1_is_instr and
  10279. (
  10280. (taicpu(hp1).opcode <> A_LEA) or
  10281. { If the LEA instruction can be converted into an arithmetic instruction,
  10282. it may be possible to then fold it. }
  10283. (
  10284. { If the flags register is in use, don't change the instruction
  10285. to an ADD otherwise this will scramble the flags. [Kit] }
  10286. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  10287. ConvertLEA(taicpu(hp1))
  10288. )
  10289. ) and
  10290. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  10291. GetNextInstruction(hp1,hp2) and
  10292. MatchInstruction(hp2,A_MOV,[]) and
  10293. (taicpu(hp2).oper[0]^.typ = top_reg) and
  10294. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  10295. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  10296. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  10297. {$ifdef i386}
  10298. { not all registers have byte size sub registers on i386 }
  10299. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  10300. {$endif i386}
  10301. (((taicpu(hp1).ops=2) and
  10302. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  10303. ((taicpu(hp1).ops=1) and
  10304. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  10305. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  10306. begin
  10307. { change movsX/movzX reg/ref, reg2
  10308. add/sub/or/... reg3/$const, reg2
  10309. mov reg2 reg/ref
  10310. to add/sub/or/... reg3/$const, reg/ref }
  10311. { by example:
  10312. movswl %si,%eax movswl %si,%eax p
  10313. decl %eax addl %edx,%eax hp1
  10314. movw %ax,%si movw %ax,%si hp2
  10315. ->
  10316. movswl %si,%eax movswl %si,%eax p
  10317. decw %eax addw %edx,%eax hp1
  10318. movw %ax,%si movw %ax,%si hp2
  10319. }
  10320. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  10321. {
  10322. ->
  10323. movswl %si,%eax movswl %si,%eax p
  10324. decw %si addw %dx,%si hp1
  10325. movw %ax,%si movw %ax,%si hp2
  10326. }
  10327. case taicpu(hp1).ops of
  10328. 1:
  10329. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  10330. 2:
  10331. begin
  10332. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  10333. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10334. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  10335. end;
  10336. else
  10337. internalerror(2008042702);
  10338. end;
  10339. {
  10340. ->
  10341. decw %si addw %dx,%si p
  10342. }
  10343. DebugMsg(SPeepholeOptimization + 'var3',p);
  10344. RemoveCurrentP(p, hp1);
  10345. RemoveInstruction(hp2);
  10346. Result := True;
  10347. Exit;
  10348. end;
  10349. if reg_and_hp1_is_instr and
  10350. (taicpu(hp1).opcode = A_MOV) and
  10351. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10352. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  10353. {$ifdef x86_64}
  10354. { check for implicit extension to 64 bit }
  10355. or
  10356. ((taicpu(p).opsize in [S_BL,S_WL]) and
  10357. (taicpu(hp1).opsize=S_Q) and
  10358. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  10359. )
  10360. {$endif x86_64}
  10361. )
  10362. then
  10363. begin
  10364. { change
  10365. movx %reg1,%reg2
  10366. mov %reg2,%reg3
  10367. dealloc %reg2
  10368. into
  10369. movx %reg,%reg3
  10370. }
  10371. TransferUsedRegs(TmpUsedRegs);
  10372. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10373. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  10374. begin
  10375. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  10376. {$ifdef x86_64}
  10377. if (taicpu(p).opsize in [S_BL,S_WL]) and
  10378. (taicpu(hp1).opsize=S_Q) then
  10379. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  10380. else
  10381. {$endif x86_64}
  10382. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  10383. RemoveInstruction(hp1);
  10384. Result := True;
  10385. Exit;
  10386. end;
  10387. end;
  10388. if reg_and_hp1_is_instr and
  10389. ((taicpu(hp1).opcode=A_MOV) or
  10390. (taicpu(hp1).opcode=A_ADD) or
  10391. (taicpu(hp1).opcode=A_SUB) or
  10392. (taicpu(hp1).opcode=A_CMP) or
  10393. (taicpu(hp1).opcode=A_OR) or
  10394. (taicpu(hp1).opcode=A_XOR) or
  10395. (taicpu(hp1).opcode=A_AND)
  10396. ) and
  10397. (taicpu(hp1).oper[1]^.typ = top_reg) then
  10398. begin
  10399. AndTest := (taicpu(hp1).opcode=A_AND) and
  10400. GetNextInstruction(hp1, hp2) and
  10401. (hp2.typ = ait_instruction) and
  10402. (
  10403. (
  10404. (taicpu(hp2).opcode=A_TEST) and
  10405. (
  10406. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  10407. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  10408. (
  10409. { If the AND and TEST instructions share a constant, this is also valid }
  10410. (taicpu(hp1).oper[0]^.typ = top_const) and
  10411. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  10412. )
  10413. ) and
  10414. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  10415. ) or
  10416. (
  10417. (taicpu(hp2).opcode=A_CMP) and
  10418. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  10419. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  10420. )
  10421. );
  10422. { change
  10423. movx (oper),%reg2
  10424. and $x,%reg2
  10425. test %reg2,%reg2
  10426. dealloc %reg2
  10427. into
  10428. op %reg1,%reg3
  10429. if the second op accesses only the bits stored in reg1
  10430. }
  10431. if ((taicpu(p).oper[0]^.typ=top_reg) or
  10432. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  10433. (taicpu(hp1).oper[0]^.typ = top_const) and
  10434. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  10435. AndTest then
  10436. begin
  10437. { Check if the AND constant is in range }
  10438. case taicpu(p).opsize of
  10439. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10440. begin
  10441. NewSize := S_B;
  10442. Limit := $FF;
  10443. end;
  10444. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10445. begin
  10446. NewSize := S_W;
  10447. Limit := $FFFF;
  10448. end;
  10449. {$ifdef x86_64}
  10450. S_LQ:
  10451. begin
  10452. NewSize := S_L;
  10453. Limit := $FFFFFFFF;
  10454. end;
  10455. {$endif x86_64}
  10456. else
  10457. InternalError(2021120303);
  10458. end;
  10459. if (
  10460. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  10461. { Check for negative operands }
  10462. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  10463. ) and
  10464. GetNextInstruction(hp2,hp3) and
  10465. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  10466. (taicpu(hp3).condition in [C_E,C_NE]) then
  10467. begin
  10468. TransferUsedRegs(TmpUsedRegs);
  10469. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10470. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  10471. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  10472. begin
  10473. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  10474. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  10475. taicpu(hp1).opcode := A_TEST;
  10476. taicpu(hp1).opsize := NewSize;
  10477. RemoveInstruction(hp2);
  10478. RemoveCurrentP(p, hp1);
  10479. Result:=true;
  10480. exit;
  10481. end;
  10482. end;
  10483. end;
  10484. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  10485. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  10486. (taicpu(hp1).opsize=S_B)) or
  10487. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  10488. (taicpu(hp1).opsize=S_W))
  10489. {$ifdef x86_64}
  10490. or ((taicpu(p).opsize=S_LQ) and
  10491. (taicpu(hp1).opsize=S_L))
  10492. {$endif x86_64}
  10493. ) and
  10494. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  10495. begin
  10496. { change
  10497. movx %reg1,%reg2
  10498. op %reg2,%reg3
  10499. dealloc %reg2
  10500. into
  10501. op %reg1,%reg3
  10502. if the second op accesses only the bits stored in reg1
  10503. }
  10504. TransferUsedRegs(TmpUsedRegs);
  10505. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10506. if AndTest then
  10507. begin
  10508. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10509. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  10510. end
  10511. else
  10512. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  10513. if not RegUsed then
  10514. begin
  10515. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  10516. if taicpu(p).oper[0]^.typ=top_reg then
  10517. begin
  10518. case taicpu(hp1).opsize of
  10519. S_B:
  10520. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  10521. S_W:
  10522. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  10523. S_L:
  10524. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  10525. else
  10526. Internalerror(2020102301);
  10527. end;
  10528. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  10529. end
  10530. else
  10531. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  10532. RemoveCurrentP(p);
  10533. if AndTest then
  10534. RemoveInstruction(hp2);
  10535. result:=true;
  10536. exit;
  10537. end;
  10538. end
  10539. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  10540. (
  10541. { Bitwise operations only }
  10542. (taicpu(hp1).opcode=A_AND) or
  10543. (taicpu(hp1).opcode=A_TEST) or
  10544. (
  10545. (taicpu(hp1).oper[0]^.typ = top_const) and
  10546. (
  10547. (taicpu(hp1).opcode=A_OR) or
  10548. (taicpu(hp1).opcode=A_XOR)
  10549. )
  10550. )
  10551. ) and
  10552. (
  10553. (taicpu(hp1).oper[0]^.typ = top_const) or
  10554. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  10555. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  10556. ) then
  10557. begin
  10558. { change
  10559. movx %reg2,%reg2
  10560. op const,%reg2
  10561. into
  10562. op const,%reg2 (smaller version)
  10563. movx %reg2,%reg2
  10564. also change
  10565. movx %reg1,%reg2
  10566. and/test (oper),%reg2
  10567. dealloc %reg2
  10568. into
  10569. and/test (oper),%reg1
  10570. }
  10571. case taicpu(p).opsize of
  10572. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10573. begin
  10574. NewSize := S_B;
  10575. NewRegSize := R_SUBL;
  10576. Limit := $FF;
  10577. end;
  10578. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10579. begin
  10580. NewSize := S_W;
  10581. NewRegSize := R_SUBW;
  10582. Limit := $FFFF;
  10583. end;
  10584. {$ifdef x86_64}
  10585. S_LQ:
  10586. begin
  10587. NewSize := S_L;
  10588. NewRegSize := R_SUBD;
  10589. Limit := $FFFFFFFF;
  10590. end;
  10591. {$endif x86_64}
  10592. else
  10593. Internalerror(2021120302);
  10594. end;
  10595. TransferUsedRegs(TmpUsedRegs);
  10596. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10597. if AndTest then
  10598. begin
  10599. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10600. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  10601. end
  10602. else
  10603. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  10604. if
  10605. (
  10606. (taicpu(p).opcode = A_MOVZX) and
  10607. (
  10608. (taicpu(hp1).opcode=A_AND) or
  10609. (taicpu(hp1).opcode=A_TEST)
  10610. ) and
  10611. not (
  10612. { If both are references, then the final instruction will have
  10613. both operands as references, which is not allowed }
  10614. (taicpu(p).oper[0]^.typ = top_ref) and
  10615. (taicpu(hp1).oper[0]^.typ = top_ref)
  10616. ) and
  10617. not RegUsed
  10618. ) or
  10619. (
  10620. (
  10621. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  10622. not RegUsed
  10623. ) and
  10624. (taicpu(p).oper[0]^.typ = top_reg) and
  10625. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10626. (taicpu(hp1).oper[0]^.typ = top_const) and
  10627. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  10628. ) then
  10629. begin
  10630. {$if defined(i386) or defined(i8086)}
  10631. { If the target size is 8-bit, make sure we can actually encode it }
  10632. if (NewRegSize = R_SUBL) and (taicpu(hp1).oper[0]^.typ = top_reg) and not (GetSupReg(taicpu(hp1).oper[0]^.reg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  10633. Exit;
  10634. {$endif i386 or i8086}
  10635. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  10636. taicpu(hp1).opsize := NewSize;
  10637. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  10638. if AndTest then
  10639. begin
  10640. RemoveInstruction(hp2);
  10641. if not RegUsed then
  10642. begin
  10643. taicpu(hp1).opcode := A_TEST;
  10644. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  10645. begin
  10646. { Make sure the reference is the second operand }
  10647. SwapOper := taicpu(hp1).oper[0];
  10648. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  10649. taicpu(hp1).oper[1] := SwapOper;
  10650. end;
  10651. end;
  10652. end;
  10653. case taicpu(hp1).oper[0]^.typ of
  10654. top_reg:
  10655. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  10656. top_const:
  10657. { For the AND/TEST case }
  10658. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  10659. else
  10660. ;
  10661. end;
  10662. if RegUsed then
  10663. begin
  10664. AsmL.Remove(p);
  10665. AsmL.InsertAfter(p, hp1);
  10666. p := hp1;
  10667. end
  10668. else
  10669. RemoveCurrentP(p, hp1);
  10670. result:=true;
  10671. exit;
  10672. end;
  10673. end;
  10674. end;
  10675. if reg_and_hp1_is_instr and
  10676. (taicpu(p).oper[0]^.typ = top_reg) and
  10677. (
  10678. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  10679. ) and
  10680. (taicpu(hp1).oper[0]^.typ = top_const) and
  10681. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10682. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10683. { Minimum shift value allowed is the bit difference between the sizes }
  10684. (taicpu(hp1).oper[0]^.val >=
  10685. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10686. 8 * (
  10687. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  10688. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10689. )
  10690. ) then
  10691. begin
  10692. { For:
  10693. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  10694. shl/sal ##, %reg1
  10695. Remove the movsx/movzx instruction if the shift overwrites the
  10696. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  10697. }
  10698. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  10699. RemoveCurrentP(p, hp1);
  10700. Result := True;
  10701. Exit;
  10702. end
  10703. else if reg_and_hp1_is_instr and
  10704. (taicpu(p).oper[0]^.typ = top_reg) and
  10705. (
  10706. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  10707. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  10708. ) and
  10709. (taicpu(hp1).oper[0]^.typ = top_const) and
  10710. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10711. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10712. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  10713. (taicpu(hp1).oper[0]^.val <
  10714. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10715. 8 * (
  10716. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10717. )
  10718. ) then
  10719. begin
  10720. { For:
  10721. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  10722. sar ##, %reg1 shr ##, %reg1
  10723. Move the shift to before the movx instruction if the shift value
  10724. is not too large.
  10725. }
  10726. asml.Remove(hp1);
  10727. asml.InsertBefore(hp1, p);
  10728. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  10729. case taicpu(p).opsize of
  10730. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  10731. taicpu(hp1).opsize := S_B;
  10732. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  10733. taicpu(hp1).opsize := S_W;
  10734. {$ifdef x86_64}
  10735. S_LQ:
  10736. taicpu(hp1).opsize := S_L;
  10737. {$endif}
  10738. else
  10739. InternalError(2020112401);
  10740. end;
  10741. if (taicpu(hp1).opcode = A_SHR) then
  10742. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  10743. else
  10744. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  10745. Result := True;
  10746. end;
  10747. if reg_and_hp1_is_instr and
  10748. (taicpu(p).oper[0]^.typ = top_reg) and
  10749. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10750. (
  10751. (taicpu(hp1).opcode = taicpu(p).opcode)
  10752. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  10753. {$ifdef x86_64}
  10754. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  10755. {$endif x86_64}
  10756. ) then
  10757. begin
  10758. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  10759. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  10760. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10761. begin
  10762. {
  10763. For example:
  10764. movzbw %al,%ax
  10765. movzwl %ax,%eax
  10766. Compress into:
  10767. movzbl %al,%eax
  10768. }
  10769. RegUsed := False;
  10770. case taicpu(p).opsize of
  10771. S_BW:
  10772. case taicpu(hp1).opsize of
  10773. S_WL:
  10774. begin
  10775. taicpu(p).opsize := S_BL;
  10776. RegUsed := True;
  10777. end;
  10778. {$ifdef x86_64}
  10779. S_WQ:
  10780. begin
  10781. if taicpu(p).opcode = A_MOVZX then
  10782. begin
  10783. taicpu(p).opsize := S_BL;
  10784. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10785. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10786. end
  10787. else
  10788. taicpu(p).opsize := S_BQ;
  10789. RegUsed := True;
  10790. end;
  10791. {$endif x86_64}
  10792. else
  10793. ;
  10794. end;
  10795. {$ifdef x86_64}
  10796. S_BL:
  10797. case taicpu(hp1).opsize of
  10798. S_LQ:
  10799. begin
  10800. if taicpu(p).opcode = A_MOVZX then
  10801. begin
  10802. taicpu(p).opsize := S_BL;
  10803. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10804. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10805. end
  10806. else
  10807. taicpu(p).opsize := S_BQ;
  10808. RegUsed := True;
  10809. end;
  10810. else
  10811. ;
  10812. end;
  10813. S_WL:
  10814. case taicpu(hp1).opsize of
  10815. S_LQ:
  10816. begin
  10817. if taicpu(p).opcode = A_MOVZX then
  10818. begin
  10819. taicpu(p).opsize := S_WL;
  10820. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10821. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10822. end
  10823. else
  10824. taicpu(p).opsize := S_WQ;
  10825. RegUsed := True;
  10826. end;
  10827. else
  10828. ;
  10829. end;
  10830. {$endif x86_64}
  10831. else
  10832. ;
  10833. end;
  10834. if RegUsed then
  10835. begin
  10836. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  10837. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  10838. RemoveInstruction(hp1);
  10839. Result := True;
  10840. Exit;
  10841. end;
  10842. end;
  10843. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  10844. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  10845. GetNextInstruction(hp1, hp2) and
  10846. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  10847. (
  10848. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  10849. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  10850. {$ifdef x86_64}
  10851. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  10852. {$endif x86_64}
  10853. ) and
  10854. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  10855. (
  10856. (
  10857. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10858. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  10859. ) or
  10860. (
  10861. { Only allow the operands in reverse order for TEST instructions }
  10862. (taicpu(hp2).opcode = A_TEST) and
  10863. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  10864. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  10865. )
  10866. ) then
  10867. begin
  10868. {
  10869. For example:
  10870. movzbl %al,%eax
  10871. movzbl (ref),%edx
  10872. andl %edx,%eax
  10873. (%edx deallocated)
  10874. Change to:
  10875. andb (ref),%al
  10876. movzbl %al,%eax
  10877. Rules are:
  10878. - First two instructions have the same opcode and opsize
  10879. - First instruction's operands are the same super-register
  10880. - Second instruction operates on a different register
  10881. - Third instruction is AND, OR, XOR or TEST
  10882. - Third instruction's operands are the destination registers of the first two instructions
  10883. - Third instruction writes to the destination register of the first instruction (except with TEST)
  10884. - Second instruction's destination register is deallocated afterwards
  10885. }
  10886. TransferUsedRegs(TmpUsedRegs);
  10887. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10888. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  10889. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  10890. begin
  10891. case taicpu(p).opsize of
  10892. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10893. NewSize := S_B;
  10894. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10895. NewSize := S_W;
  10896. {$ifdef x86_64}
  10897. S_LQ:
  10898. NewSize := S_L;
  10899. {$endif x86_64}
  10900. else
  10901. InternalError(2021120301);
  10902. end;
  10903. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  10904. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  10905. taicpu(hp2).opsize := NewSize;
  10906. RemoveInstruction(hp1);
  10907. { With TEST, it's best to keep the MOVX instruction at the top }
  10908. if (taicpu(hp2).opcode <> A_TEST) then
  10909. begin
  10910. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  10911. asml.Remove(p);
  10912. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  10913. asml.InsertAfter(p, hp2);
  10914. p := hp2;
  10915. end
  10916. else
  10917. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  10918. Result := True;
  10919. Exit;
  10920. end;
  10921. end;
  10922. end;
  10923. if taicpu(p).opcode=A_MOVZX then
  10924. begin
  10925. { removes superfluous And's after movzx's }
  10926. if reg_and_hp1_is_instr and
  10927. (taicpu(hp1).opcode = A_AND) and
  10928. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10929. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  10930. {$ifdef x86_64}
  10931. { check for implicit extension to 64 bit }
  10932. or
  10933. ((taicpu(p).opsize in [S_BL,S_WL]) and
  10934. (taicpu(hp1).opsize=S_Q) and
  10935. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  10936. )
  10937. {$endif x86_64}
  10938. )
  10939. then
  10940. begin
  10941. case taicpu(p).opsize Of
  10942. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10943. if (taicpu(hp1).oper[0]^.val = $ff) then
  10944. begin
  10945. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  10946. RemoveInstruction(hp1);
  10947. Result:=true;
  10948. exit;
  10949. end;
  10950. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10951. if (taicpu(hp1).oper[0]^.val = $ffff) then
  10952. begin
  10953. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  10954. RemoveInstruction(hp1);
  10955. Result:=true;
  10956. exit;
  10957. end;
  10958. {$ifdef x86_64}
  10959. S_LQ:
  10960. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  10961. begin
  10962. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  10963. RemoveInstruction(hp1);
  10964. Result:=true;
  10965. exit;
  10966. end;
  10967. {$endif x86_64}
  10968. else
  10969. ;
  10970. end;
  10971. { we cannot get rid of the and, but can we get rid of the movz ?}
  10972. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  10973. begin
  10974. case taicpu(p).opsize Of
  10975. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10976. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  10977. begin
  10978. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  10979. RemoveCurrentP(p,hp1);
  10980. Result:=true;
  10981. exit;
  10982. end;
  10983. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10984. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  10985. begin
  10986. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  10987. RemoveCurrentP(p,hp1);
  10988. Result:=true;
  10989. exit;
  10990. end;
  10991. {$ifdef x86_64}
  10992. S_LQ:
  10993. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  10994. begin
  10995. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  10996. RemoveCurrentP(p,hp1);
  10997. Result:=true;
  10998. exit;
  10999. end;
  11000. {$endif x86_64}
  11001. else
  11002. ;
  11003. end;
  11004. end;
  11005. end;
  11006. { changes some movzx constructs to faster synonyms (all examples
  11007. are given with eax/ax, but are also valid for other registers)}
  11008. if MatchOpType(taicpu(p),top_reg,top_reg) then
  11009. begin
  11010. case taicpu(p).opsize of
  11011. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  11012. (the machine code is equivalent to movzbl %al,%eax), but the
  11013. code generator still generates that assembler instruction and
  11014. it is silently converted. This should probably be checked.
  11015. [Kit] }
  11016. S_BW:
  11017. begin
  11018. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  11019. (
  11020. not IsMOVZXAcceptable
  11021. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  11022. or (
  11023. (cs_opt_size in current_settings.optimizerswitches) and
  11024. (taicpu(p).oper[1]^.reg = NR_AX)
  11025. )
  11026. ) then
  11027. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  11028. begin
  11029. DebugMsg(SPeepholeOptimization + 'var7',p);
  11030. taicpu(p).opcode := A_AND;
  11031. taicpu(p).changeopsize(S_W);
  11032. taicpu(p).loadConst(0,$ff);
  11033. Result := True;
  11034. end
  11035. else if not IsMOVZXAcceptable and
  11036. GetNextInstruction(p, hp1) and
  11037. (tai(hp1).typ = ait_instruction) and
  11038. (taicpu(hp1).opcode = A_AND) and
  11039. MatchOpType(taicpu(hp1),top_const,top_reg) and
  11040. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  11041. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  11042. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  11043. begin
  11044. DebugMsg(SPeepholeOptimization + 'var8',p);
  11045. taicpu(p).opcode := A_MOV;
  11046. taicpu(p).changeopsize(S_W);
  11047. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  11048. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  11049. Result := True;
  11050. end;
  11051. end;
  11052. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  11053. S_BL:
  11054. begin
  11055. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  11056. (
  11057. not IsMOVZXAcceptable
  11058. { and $0xff,%eax has a smaller encoding but risks a partial write penalty }
  11059. or (
  11060. (cs_opt_size in current_settings.optimizerswitches) and
  11061. (taicpu(p).oper[1]^.reg = NR_EAX)
  11062. )
  11063. ) then
  11064. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  11065. begin
  11066. DebugMsg(SPeepholeOptimization + 'var9',p);
  11067. taicpu(p).opcode := A_AND;
  11068. taicpu(p).changeopsize(S_L);
  11069. taicpu(p).loadConst(0,$ff);
  11070. Result := True;
  11071. end
  11072. else if not IsMOVZXAcceptable and
  11073. GetNextInstruction(p, hp1) and
  11074. (tai(hp1).typ = ait_instruction) and
  11075. (taicpu(hp1).opcode = A_AND) and
  11076. MatchOpType(taicpu(hp1),top_const,top_reg) and
  11077. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  11078. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  11079. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  11080. begin
  11081. DebugMsg(SPeepholeOptimization + 'var10',p);
  11082. taicpu(p).opcode := A_MOV;
  11083. taicpu(p).changeopsize(S_L);
  11084. { do not use R_SUBWHOLE
  11085. as movl %rdx,%eax
  11086. is invalid in assembler PM }
  11087. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  11088. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  11089. Result := True;
  11090. end;
  11091. end;
  11092. {$endif i8086}
  11093. S_WL:
  11094. if not IsMOVZXAcceptable then
  11095. begin
  11096. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  11097. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  11098. begin
  11099. DebugMsg(SPeepholeOptimization + 'var11',p);
  11100. taicpu(p).opcode := A_AND;
  11101. taicpu(p).changeopsize(S_L);
  11102. taicpu(p).loadConst(0,$ffff);
  11103. Result := True;
  11104. end
  11105. else if GetNextInstruction(p, hp1) and
  11106. (tai(hp1).typ = ait_instruction) and
  11107. (taicpu(hp1).opcode = A_AND) and
  11108. (taicpu(hp1).oper[0]^.typ = top_const) and
  11109. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11110. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  11111. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  11112. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  11113. begin
  11114. DebugMsg(SPeepholeOptimization + 'var12',p);
  11115. taicpu(p).opcode := A_MOV;
  11116. taicpu(p).changeopsize(S_L);
  11117. { do not use R_SUBWHOLE
  11118. as movl %rdx,%eax
  11119. is invalid in assembler PM }
  11120. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  11121. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  11122. Result := True;
  11123. end;
  11124. end;
  11125. else
  11126. InternalError(2017050705);
  11127. end;
  11128. end
  11129. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  11130. begin
  11131. if GetNextInstruction(p, hp1) and
  11132. (tai(hp1).typ = ait_instruction) and
  11133. (taicpu(hp1).opcode = A_AND) and
  11134. MatchOpType(taicpu(hp1),top_const,top_reg) and
  11135. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  11136. begin
  11137. //taicpu(p).opcode := A_MOV;
  11138. case taicpu(p).opsize Of
  11139. S_BL:
  11140. begin
  11141. DebugMsg(SPeepholeOptimization + 'var13',p);
  11142. taicpu(hp1).changeopsize(S_L);
  11143. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  11144. end;
  11145. S_WL:
  11146. begin
  11147. DebugMsg(SPeepholeOptimization + 'var14',p);
  11148. taicpu(hp1).changeopsize(S_L);
  11149. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  11150. end;
  11151. S_BW:
  11152. begin
  11153. DebugMsg(SPeepholeOptimization + 'var15',p);
  11154. taicpu(hp1).changeopsize(S_W);
  11155. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  11156. end;
  11157. else
  11158. Internalerror(2017050704)
  11159. end;
  11160. Result := True;
  11161. end;
  11162. end;
  11163. end;
  11164. end;
  11165. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  11166. var
  11167. hp1, hp2 : tai;
  11168. MaskLength : Cardinal;
  11169. MaskedBits : TCgInt;
  11170. ActiveReg : TRegister;
  11171. begin
  11172. Result:=false;
  11173. { There are no optimisations for reference targets }
  11174. if (taicpu(p).oper[1]^.typ <> top_reg) then
  11175. Exit;
  11176. while GetNextInstruction(p, hp1) and
  11177. (hp1.typ = ait_instruction) do
  11178. begin
  11179. if (taicpu(p).oper[0]^.typ = top_const) then
  11180. begin
  11181. case taicpu(hp1).opcode of
  11182. A_AND:
  11183. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  11184. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  11185. { the second register must contain the first one, so compare their subreg types }
  11186. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  11187. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  11188. { change
  11189. and const1, reg
  11190. and const2, reg
  11191. to
  11192. and (const1 and const2), reg
  11193. }
  11194. begin
  11195. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  11196. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  11197. RemoveCurrentP(p, hp1);
  11198. Result:=true;
  11199. exit;
  11200. end;
  11201. A_CMP:
  11202. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  11203. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  11204. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  11205. { Just check that the condition on the next instruction is compatible }
  11206. GetNextInstruction(hp1, hp2) and
  11207. (hp2.typ = ait_instruction) and
  11208. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  11209. then
  11210. { change
  11211. and 2^n, reg
  11212. cmp 2^n, reg
  11213. j(c) / set(c) / cmov(c) (c is equal or not equal)
  11214. to
  11215. and 2^n, reg
  11216. test reg, reg
  11217. j(~c) / set(~c) / cmov(~c)
  11218. }
  11219. begin
  11220. { Keep TEST instruction in, rather than remove it, because
  11221. it may trigger other optimisations such as MovAndTest2Test }
  11222. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  11223. taicpu(hp1).opcode := A_TEST;
  11224. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  11225. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  11226. Result := True;
  11227. Exit;
  11228. end;
  11229. A_MOVZX:
  11230. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11231. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  11232. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  11233. (
  11234. (
  11235. (taicpu(p).opsize=S_W) and
  11236. (taicpu(hp1).opsize=S_BW)
  11237. ) or
  11238. (
  11239. (taicpu(p).opsize=S_L) and
  11240. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  11241. )
  11242. {$ifdef x86_64}
  11243. or
  11244. (
  11245. (taicpu(p).opsize=S_Q) and
  11246. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  11247. )
  11248. {$endif x86_64}
  11249. ) then
  11250. begin
  11251. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  11252. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  11253. ) or
  11254. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  11255. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  11256. then
  11257. begin
  11258. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  11259. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  11260. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  11261. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  11262. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  11263. }
  11264. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  11265. RemoveInstruction(hp1);
  11266. { See if there are other optimisations possible }
  11267. Continue;
  11268. end;
  11269. end;
  11270. A_SHL:
  11271. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  11272. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  11273. begin
  11274. {$ifopt R+}
  11275. {$define RANGE_WAS_ON}
  11276. {$R-}
  11277. {$endif}
  11278. { get length of potential and mask }
  11279. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  11280. { really a mask? }
  11281. {$ifdef RANGE_WAS_ON}
  11282. {$R+}
  11283. {$endif}
  11284. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  11285. { unmasked part shifted out? }
  11286. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  11287. begin
  11288. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  11289. RemoveCurrentP(p, hp1);
  11290. Result:=true;
  11291. exit;
  11292. end;
  11293. end;
  11294. A_SHR:
  11295. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  11296. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  11297. (taicpu(hp1).oper[0]^.val <= 63) then
  11298. begin
  11299. { Does SHR combined with the AND cover all the bits?
  11300. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  11301. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  11302. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  11303. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  11304. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  11305. begin
  11306. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  11307. RemoveCurrentP(p, hp1);
  11308. Result := True;
  11309. Exit;
  11310. end;
  11311. end;
  11312. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  11313. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  11314. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  11315. begin
  11316. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  11317. (
  11318. (
  11319. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  11320. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  11321. ) or (
  11322. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  11323. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  11324. {$ifdef x86_64}
  11325. ) or (
  11326. (taicpu(hp1).opsize = S_LQ) and
  11327. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  11328. {$endif x86_64}
  11329. )
  11330. ) then
  11331. begin
  11332. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  11333. begin
  11334. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  11335. RemoveInstruction(hp1);
  11336. { See if there are other optimisations possible }
  11337. Continue;
  11338. end;
  11339. { The super-registers are the same though.
  11340. Note that this change by itself doesn't improve
  11341. code speed, but it opens up other optimisations. }
  11342. {$ifdef x86_64}
  11343. { Convert 64-bit register to 32-bit }
  11344. case taicpu(hp1).opsize of
  11345. S_BQ:
  11346. begin
  11347. taicpu(hp1).opsize := S_BL;
  11348. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  11349. end;
  11350. S_WQ:
  11351. begin
  11352. taicpu(hp1).opsize := S_WL;
  11353. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  11354. end
  11355. else
  11356. ;
  11357. end;
  11358. {$endif x86_64}
  11359. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  11360. taicpu(hp1).opcode := A_MOVZX;
  11361. { See if there are other optimisations possible }
  11362. Continue;
  11363. end;
  11364. end;
  11365. else
  11366. ;
  11367. end;
  11368. end
  11369. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  11370. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  11371. begin
  11372. {$ifdef x86_64}
  11373. if (taicpu(p).opsize = S_Q) then
  11374. begin
  11375. { Never necessary }
  11376. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  11377. RemoveCurrentP(p, hp1);
  11378. Result := True;
  11379. Exit;
  11380. end;
  11381. {$endif x86_64}
  11382. { Forward check to determine necessity of and %reg,%reg }
  11383. TransferUsedRegs(TmpUsedRegs);
  11384. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11385. { Saves on a bunch of dereferences }
  11386. ActiveReg := taicpu(p).oper[1]^.reg;
  11387. case taicpu(hp1).opcode of
  11388. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  11389. if (
  11390. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11391. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11392. ) and
  11393. (
  11394. (taicpu(hp1).opcode <> A_MOV) or
  11395. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  11396. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  11397. ) and
  11398. not (
  11399. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  11400. (taicpu(hp1).opcode = A_MOV) and
  11401. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  11402. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  11403. ) and
  11404. (
  11405. (
  11406. (taicpu(hp1).oper[0]^.typ = top_reg) and
  11407. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  11408. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  11409. ) or
  11410. (
  11411. {$ifdef x86_64}
  11412. (
  11413. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  11414. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  11415. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  11416. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  11417. ) and
  11418. {$endif x86_64}
  11419. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  11420. )
  11421. ) then
  11422. begin
  11423. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  11424. RemoveCurrentP(p, hp1);
  11425. Result := True;
  11426. Exit;
  11427. end;
  11428. A_ADD,
  11429. A_AND,
  11430. A_BSF,
  11431. A_BSR,
  11432. A_BTC,
  11433. A_BTR,
  11434. A_BTS,
  11435. A_OR,
  11436. A_SUB,
  11437. A_XOR:
  11438. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  11439. if (
  11440. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11441. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11442. ) and
  11443. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  11444. begin
  11445. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  11446. RemoveCurrentP(p, hp1);
  11447. Result := True;
  11448. Exit;
  11449. end;
  11450. A_CMP,
  11451. A_TEST:
  11452. if (
  11453. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11454. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11455. ) and
  11456. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  11457. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  11458. begin
  11459. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  11460. RemoveCurrentP(p, hp1);
  11461. Result := True;
  11462. Exit;
  11463. end;
  11464. A_BSWAP,
  11465. A_NEG,
  11466. A_NOT:
  11467. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  11468. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  11469. begin
  11470. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  11471. RemoveCurrentP(p, hp1);
  11472. Result := True;
  11473. Exit;
  11474. end;
  11475. else
  11476. ;
  11477. end;
  11478. end;
  11479. if (taicpu(hp1).is_jmp) and
  11480. (taicpu(hp1).opcode<>A_JMP) and
  11481. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  11482. begin
  11483. { change
  11484. and x, reg
  11485. jxx
  11486. to
  11487. test x, reg
  11488. jxx
  11489. if reg is deallocated before the
  11490. jump, but only if it's a conditional jump (PFV)
  11491. }
  11492. taicpu(p).opcode := A_TEST;
  11493. Exit;
  11494. end;
  11495. Break;
  11496. end;
  11497. { Lone AND tests }
  11498. if (taicpu(p).oper[0]^.typ = top_const) then
  11499. begin
  11500. {
  11501. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  11502. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  11503. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  11504. }
  11505. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  11506. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  11507. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  11508. begin
  11509. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  11510. if taicpu(p).opsize = S_L then
  11511. begin
  11512. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  11513. Result := True;
  11514. end;
  11515. end;
  11516. end;
  11517. { Backward check to determine necessity of and %reg,%reg }
  11518. if (taicpu(p).oper[0]^.typ = top_reg) and
  11519. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  11520. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11521. GetLastInstruction(p, hp2) and
  11522. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  11523. { Check size of adjacent instruction to determine if the AND is
  11524. effectively a null operation }
  11525. (
  11526. (taicpu(p).opsize = taicpu(hp2).opsize) or
  11527. { Note: Don't include S_Q }
  11528. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  11529. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  11530. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  11531. ) then
  11532. begin
  11533. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  11534. { If GetNextInstruction returned False, hp1 will be nil }
  11535. RemoveCurrentP(p, hp1);
  11536. Result := True;
  11537. Exit;
  11538. end;
  11539. end;
  11540. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  11541. var
  11542. hp1, hp2: tai;
  11543. NewRef: TReference;
  11544. Distance: Cardinal;
  11545. TempTracking: TAllUsedRegs;
  11546. { This entire nested function is used in an if-statement below, but we
  11547. want to avoid all the used reg transfers and GetNextInstruction calls
  11548. until we really have to check }
  11549. function MemRegisterNotUsedLater: Boolean; inline;
  11550. var
  11551. hp2: tai;
  11552. begin
  11553. TransferUsedRegs(TmpUsedRegs);
  11554. hp2 := p;
  11555. repeat
  11556. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  11557. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  11558. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  11559. end;
  11560. begin
  11561. Result := False;
  11562. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  11563. (taicpu(p).oper[1]^.typ = top_reg) then
  11564. begin
  11565. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  11566. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  11567. (hp1.typ <> ait_instruction) or
  11568. not
  11569. (
  11570. (cs_opt_level3 in current_settings.optimizerswitches) or
  11571. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  11572. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  11573. ) then
  11574. Exit;
  11575. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  11576. addq $x, %rax
  11577. movq %rax, %rdx
  11578. sarq $63, %rdx
  11579. (%rax still in use)
  11580. ...letting OptPass2ADD run its course (and without -Os) will produce:
  11581. leaq $x(%rax),%rdx
  11582. addq $x, %rax
  11583. sarq $63, %rdx
  11584. ...which is okay since it breaks the dependency chain between
  11585. addq and movq, but if OptPass2MOV is called first:
  11586. addq $x, %rax
  11587. cqto
  11588. ...which is better in all ways, taking only 2 cycles to execute
  11589. and much smaller in code size.
  11590. }
  11591. { The extra register tracking is quite strenuous }
  11592. if (cs_opt_level2 in current_settings.optimizerswitches) and
  11593. MatchInstruction(hp1, A_MOV, []) then
  11594. begin
  11595. { Update the register tracking to the MOV instruction }
  11596. CopyUsedRegs(TempTracking);
  11597. hp2 := p;
  11598. repeat
  11599. UpdateUsedRegs(tai(hp2.Next));
  11600. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  11601. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  11602. OptPass2ADD get called again }
  11603. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  11604. begin
  11605. { Reset the tracking to the current instruction }
  11606. RestoreUsedRegs(TempTracking);
  11607. ReleaseUsedRegs(TempTracking);
  11608. Result := True;
  11609. Exit;
  11610. end;
  11611. { Reset the tracking to the current instruction }
  11612. RestoreUsedRegs(TempTracking);
  11613. ReleaseUsedRegs(TempTracking);
  11614. { If OptPass2MOV returned True, we don't need to set Result to
  11615. True if hp1 didn't change because the ADD instruction didn't
  11616. get modified and we'll be evaluating hp1 again when the
  11617. peephole optimizer reaches it }
  11618. end;
  11619. { Change:
  11620. add %reg2,%reg1
  11621. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  11622. To:
  11623. mov/s/z #(%reg1,%reg2),%reg1
  11624. }
  11625. if (taicpu(p).oper[0]^.typ = top_reg) and
  11626. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  11627. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  11628. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  11629. (
  11630. (
  11631. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  11632. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  11633. { r/esp cannot be an index }
  11634. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  11635. ) or (
  11636. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  11637. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  11638. )
  11639. ) and (
  11640. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  11641. (
  11642. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  11643. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  11644. MemRegisterNotUsedLater
  11645. )
  11646. ) then
  11647. begin
  11648. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  11649. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  11650. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  11651. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  11652. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11653. { hp1 may not be the immediate next instruction under -O3 }
  11654. RemoveCurrentp(p)
  11655. else
  11656. RemoveCurrentp(p, hp1);
  11657. Result := True;
  11658. Exit;
  11659. end;
  11660. { Change:
  11661. addl/q $x,%reg1
  11662. movl/q %reg1,%reg2
  11663. To:
  11664. leal/q $x(%reg1),%reg2
  11665. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  11666. Breaks the dependency chain.
  11667. }
  11668. if (taicpu(p).oper[0]^.typ = top_const) and
  11669. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  11670. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11671. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  11672. (
  11673. { Instructions are guaranteed to be adjacent on -O2 and under }
  11674. not (cs_opt_level3 in current_settings.optimizerswitches) or
  11675. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  11676. ) then
  11677. begin
  11678. TransferUsedRegs(TmpUsedRegs);
  11679. hp2 := p;
  11680. repeat
  11681. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  11682. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  11683. if (
  11684. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  11685. not (cs_opt_size in current_settings.optimizerswitches) or
  11686. (
  11687. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  11688. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  11689. )
  11690. ) then
  11691. begin
  11692. { Change the MOV instruction to a LEA instruction, and update the
  11693. first operand }
  11694. reference_reset(NewRef, 1, []);
  11695. NewRef.base := taicpu(p).oper[1]^.reg;
  11696. NewRef.scalefactor := 1;
  11697. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  11698. taicpu(hp1).opcode := A_LEA;
  11699. taicpu(hp1).loadref(0, NewRef);
  11700. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  11701. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  11702. begin
  11703. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  11704. { Move what is now the LEA instruction to before the ADD instruction }
  11705. Asml.Remove(hp1);
  11706. Asml.InsertBefore(hp1, p);
  11707. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  11708. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  11709. p := hp1;
  11710. end
  11711. else
  11712. begin
  11713. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  11714. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  11715. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11716. { hp1 may not be the immediate next instruction under -O3 }
  11717. RemoveCurrentp(p)
  11718. else
  11719. RemoveCurrentp(p, hp1);
  11720. end;
  11721. Result := True;
  11722. end;
  11723. end;
  11724. end;
  11725. end;
  11726. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  11727. var
  11728. SubReg: TSubRegister;
  11729. begin
  11730. Result:=false;
  11731. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  11732. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11733. with taicpu(p).oper[0]^.ref^ do
  11734. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  11735. begin
  11736. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  11737. begin
  11738. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  11739. taicpu(p).opcode := A_ADD;
  11740. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  11741. Result := True;
  11742. end
  11743. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  11744. begin
  11745. if (base <> NR_NO) then
  11746. begin
  11747. if (scalefactor <= 1) then
  11748. begin
  11749. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  11750. taicpu(p).opcode := A_ADD;
  11751. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  11752. Result := True;
  11753. end;
  11754. end
  11755. else
  11756. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  11757. if (scalefactor in [2, 4, 8]) then
  11758. begin
  11759. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  11760. taicpu(p).loadconst(0, BsrByte(scalefactor));
  11761. taicpu(p).opcode := A_SHL;
  11762. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  11763. Result := True;
  11764. end;
  11765. end;
  11766. end;
  11767. end;
  11768. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  11769. var
  11770. hp1, hp2: tai;
  11771. NewRef: TReference;
  11772. Distance: Cardinal;
  11773. TempTracking: TAllUsedRegs;
  11774. begin
  11775. Result := False;
  11776. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  11777. MatchOpType(taicpu(p),top_const,top_reg) then
  11778. begin
  11779. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  11780. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  11781. (hp1.typ <> ait_instruction) or
  11782. not
  11783. (
  11784. (cs_opt_level3 in current_settings.optimizerswitches) or
  11785. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  11786. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  11787. ) then
  11788. Exit;
  11789. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  11790. subq $x, %rax
  11791. movq %rax, %rdx
  11792. sarq $63, %rdx
  11793. (%rax still in use)
  11794. ...letting OptPass2SUB run its course (and without -Os) will produce:
  11795. leaq $-x(%rax),%rdx
  11796. movq $x, %rax
  11797. sarq $63, %rdx
  11798. ...which is okay since it breaks the dependency chain between
  11799. subq and movq, but if OptPass2MOV is called first:
  11800. subq $x, %rax
  11801. cqto
  11802. ...which is better in all ways, taking only 2 cycles to execute
  11803. and much smaller in code size.
  11804. }
  11805. { The extra register tracking is quite strenuous }
  11806. if (cs_opt_level2 in current_settings.optimizerswitches) and
  11807. MatchInstruction(hp1, A_MOV, []) then
  11808. begin
  11809. { Update the register tracking to the MOV instruction }
  11810. CopyUsedRegs(TempTracking);
  11811. hp2 := p;
  11812. repeat
  11813. UpdateUsedRegs(tai(hp2.Next));
  11814. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  11815. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  11816. OptPass2SUB get called again }
  11817. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  11818. begin
  11819. { Reset the tracking to the current instruction }
  11820. RestoreUsedRegs(TempTracking);
  11821. ReleaseUsedRegs(TempTracking);
  11822. Result := True;
  11823. Exit;
  11824. end;
  11825. { Reset the tracking to the current instruction }
  11826. RestoreUsedRegs(TempTracking);
  11827. ReleaseUsedRegs(TempTracking);
  11828. { If OptPass2MOV returned True, we don't need to set Result to
  11829. True if hp1 didn't change because the SUB instruction didn't
  11830. get modified and we'll be evaluating hp1 again when the
  11831. peephole optimizer reaches it }
  11832. end;
  11833. { Change:
  11834. subl/q $x,%reg1
  11835. movl/q %reg1,%reg2
  11836. To:
  11837. leal/q $-x(%reg1),%reg2
  11838. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  11839. Breaks the dependency chain and potentially permits the removal of
  11840. a CMP instruction if one follows.
  11841. }
  11842. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  11843. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11844. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  11845. (
  11846. { Instructions are guaranteed to be adjacent on -O2 and under }
  11847. not (cs_opt_level3 in current_settings.optimizerswitches) or
  11848. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  11849. ) then
  11850. begin
  11851. TransferUsedRegs(TmpUsedRegs);
  11852. hp2 := p;
  11853. repeat
  11854. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  11855. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  11856. if (
  11857. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  11858. not (cs_opt_size in current_settings.optimizerswitches) or
  11859. (
  11860. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  11861. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  11862. )
  11863. ) then
  11864. begin
  11865. { Change the MOV instruction to a LEA instruction, and update the
  11866. first operand }
  11867. reference_reset(NewRef, 1, []);
  11868. NewRef.base := taicpu(p).oper[1]^.reg;
  11869. NewRef.scalefactor := 1;
  11870. NewRef.offset := -taicpu(p).oper[0]^.val;
  11871. taicpu(hp1).opcode := A_LEA;
  11872. taicpu(hp1).loadref(0, NewRef);
  11873. TransferUsedRegs(TmpUsedRegs);
  11874. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11875. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  11876. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  11877. begin
  11878. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  11879. { Move what is now the LEA instruction to before the SUB instruction }
  11880. Asml.Remove(hp1);
  11881. Asml.InsertBefore(hp1, p);
  11882. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  11883. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  11884. p := hp1;
  11885. end
  11886. else
  11887. begin
  11888. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  11889. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  11890. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11891. { hp1 may not be the immediate next instruction under -O3 }
  11892. RemoveCurrentp(p)
  11893. else
  11894. RemoveCurrentp(p, hp1);
  11895. end;
  11896. Result := True;
  11897. end;
  11898. end;
  11899. end;
  11900. end;
  11901. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  11902. begin
  11903. { we can skip all instructions not messing with the stack pointer }
  11904. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  11905. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  11906. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  11907. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  11908. ({(taicpu(hp1).ops=0) or }
  11909. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  11910. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  11911. ) and }
  11912. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  11913. )
  11914. ) do
  11915. GetNextInstruction(hp1,hp1);
  11916. Result:=assigned(hp1);
  11917. end;
  11918. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  11919. var
  11920. hp1, hp2, hp3, hp4, hp5: tai;
  11921. begin
  11922. Result:=false;
  11923. hp5:=nil;
  11924. { replace
  11925. leal(q) x(<stackpointer>),<stackpointer>
  11926. call procname
  11927. leal(q) -x(<stackpointer>),<stackpointer>
  11928. ret
  11929. by
  11930. jmp procname
  11931. but do it only on level 4 because it destroys stack back traces
  11932. }
  11933. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11934. MatchOpType(taicpu(p),top_ref,top_reg) and
  11935. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  11936. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  11937. { the -8 or -24 are not required, but bail out early if possible,
  11938. higher values are unlikely }
  11939. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  11940. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  11941. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  11942. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  11943. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  11944. GetNextInstruction(p, hp1) and
  11945. { Take a copy of hp1 }
  11946. SetAndTest(hp1, hp4) and
  11947. { trick to skip label }
  11948. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  11949. SkipSimpleInstructions(hp1) and
  11950. MatchInstruction(hp1,A_CALL,[S_NO]) and
  11951. GetNextInstruction(hp1, hp2) and
  11952. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  11953. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  11954. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  11955. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  11956. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  11957. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  11958. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  11959. { Segment register will be NR_NO }
  11960. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  11961. GetNextInstruction(hp2, hp3) and
  11962. { trick to skip label }
  11963. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  11964. (MatchInstruction(hp3,A_RET,[S_NO]) or
  11965. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  11966. SetAndTest(hp3,hp5) and
  11967. GetNextInstruction(hp3,hp3) and
  11968. MatchInstruction(hp3,A_RET,[S_NO])
  11969. )
  11970. ) and
  11971. (taicpu(hp3).ops=0) then
  11972. begin
  11973. taicpu(hp1).opcode := A_JMP;
  11974. taicpu(hp1).is_jmp := true;
  11975. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  11976. RemoveCurrentP(p, hp4);
  11977. RemoveInstruction(hp2);
  11978. RemoveInstruction(hp3);
  11979. if Assigned(hp5) then
  11980. begin
  11981. AsmL.Remove(hp5);
  11982. ASmL.InsertBefore(hp5,hp1)
  11983. end;
  11984. Result:=true;
  11985. end;
  11986. end;
  11987. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  11988. {$ifdef x86_64}
  11989. var
  11990. hp1, hp2, hp3, hp4, hp5: tai;
  11991. {$endif x86_64}
  11992. begin
  11993. Result:=false;
  11994. {$ifdef x86_64}
  11995. hp5:=nil;
  11996. { replace
  11997. push %rax
  11998. call procname
  11999. pop %rcx
  12000. ret
  12001. by
  12002. jmp procname
  12003. but do it only on level 4 because it destroys stack back traces
  12004. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  12005. for all supported calling conventions
  12006. }
  12007. if (cs_opt_level4 in current_settings.optimizerswitches) and
  12008. MatchOpType(taicpu(p),top_reg) and
  12009. (taicpu(p).oper[0]^.reg=NR_RAX) and
  12010. GetNextInstruction(p, hp1) and
  12011. { Take a copy of hp1 }
  12012. SetAndTest(hp1, hp4) and
  12013. { trick to skip label }
  12014. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  12015. SkipSimpleInstructions(hp1) and
  12016. MatchInstruction(hp1,A_CALL,[S_NO]) and
  12017. GetNextInstruction(hp1, hp2) and
  12018. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  12019. MatchOpType(taicpu(hp2),top_reg) and
  12020. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  12021. GetNextInstruction(hp2, hp3) and
  12022. { trick to skip label }
  12023. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  12024. (MatchInstruction(hp3,A_RET,[S_NO]) or
  12025. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  12026. SetAndTest(hp3,hp5) and
  12027. GetNextInstruction(hp3,hp3) and
  12028. MatchInstruction(hp3,A_RET,[S_NO])
  12029. )
  12030. ) and
  12031. (taicpu(hp3).ops=0) then
  12032. begin
  12033. taicpu(hp1).opcode := A_JMP;
  12034. taicpu(hp1).is_jmp := true;
  12035. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  12036. RemoveCurrentP(p, hp4);
  12037. RemoveInstruction(hp2);
  12038. RemoveInstruction(hp3);
  12039. if Assigned(hp5) then
  12040. begin
  12041. AsmL.Remove(hp5);
  12042. ASmL.InsertBefore(hp5,hp1)
  12043. end;
  12044. Result:=true;
  12045. end;
  12046. {$endif x86_64}
  12047. end;
  12048. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  12049. var
  12050. Value, RegName: string;
  12051. begin
  12052. Result:=false;
  12053. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  12054. begin
  12055. case taicpu(p).oper[0]^.val of
  12056. 0:
  12057. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  12058. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  12059. begin
  12060. { change "mov $0,%reg" into "xor %reg,%reg" }
  12061. taicpu(p).opcode := A_XOR;
  12062. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  12063. Result := True;
  12064. {$ifdef x86_64}
  12065. end
  12066. else if (taicpu(p).opsize = S_Q) then
  12067. begin
  12068. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  12069. { The actual optimization }
  12070. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  12071. taicpu(p).changeopsize(S_L);
  12072. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  12073. Result := True;
  12074. end;
  12075. $1..$FFFFFFFF:
  12076. begin
  12077. { Code size reduction by J. Gareth "Kit" Moreton }
  12078. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  12079. case taicpu(p).opsize of
  12080. S_Q:
  12081. begin
  12082. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  12083. Value := debug_tostr(taicpu(p).oper[0]^.val);
  12084. { The actual optimization }
  12085. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  12086. taicpu(p).changeopsize(S_L);
  12087. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  12088. Result := True;
  12089. end;
  12090. else
  12091. { Do nothing };
  12092. end;
  12093. {$endif x86_64}
  12094. end;
  12095. -1:
  12096. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  12097. if (cs_opt_size in current_settings.optimizerswitches) and
  12098. (taicpu(p).opsize <> S_B) and
  12099. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  12100. begin
  12101. { change "mov $-1,%reg" into "or $-1,%reg" }
  12102. { NOTES:
  12103. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  12104. - This operation creates a false dependency on the register, so only do it when optimising for size
  12105. - 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
  12106. }
  12107. taicpu(p).opcode := A_OR;
  12108. Result := True;
  12109. end;
  12110. else
  12111. { Do nothing };
  12112. end;
  12113. end;
  12114. end;
  12115. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  12116. var
  12117. hp1: tai;
  12118. begin
  12119. { Detect:
  12120. andw x, %ax (0 <= x < $8000)
  12121. ...
  12122. movzwl %ax,%eax
  12123. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  12124. }
  12125. Result := False; if MatchOpType(taicpu(p), top_const, top_reg) and
  12126. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  12127. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  12128. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  12129. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  12130. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  12131. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  12132. begin
  12133. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  12134. taicpu(hp1).opcode := A_CWDE;
  12135. taicpu(hp1).clearop(0);
  12136. taicpu(hp1).clearop(1);
  12137. taicpu(hp1).ops := 0;
  12138. { A change was made, but not with p, so move forward 1 }
  12139. p := tai(p.Next);
  12140. Result := True;
  12141. end;
  12142. end;
  12143. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  12144. begin
  12145. Result := False;
  12146. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  12147. Exit;
  12148. { Convert:
  12149. movswl %ax,%eax -> cwtl
  12150. movslq %eax,%rax -> cdqe
  12151. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  12152. refer to the same opcode and depends only on the assembler's
  12153. current operand-size attribute. [Kit]
  12154. }
  12155. with taicpu(p) do
  12156. case opsize of
  12157. S_WL:
  12158. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  12159. begin
  12160. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  12161. opcode := A_CWDE;
  12162. clearop(0);
  12163. clearop(1);
  12164. ops := 0;
  12165. Result := True;
  12166. end;
  12167. {$ifdef x86_64}
  12168. S_LQ:
  12169. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  12170. begin
  12171. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  12172. opcode := A_CDQE;
  12173. clearop(0);
  12174. clearop(1);
  12175. ops := 0;
  12176. Result := True;
  12177. end;
  12178. {$endif x86_64}
  12179. else
  12180. ;
  12181. end;
  12182. end;
  12183. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  12184. var
  12185. hp1, hp2: tai;
  12186. IdentityMask, Shift: TCGInt;
  12187. LimitSize: Topsize;
  12188. DoNotMerge: Boolean;
  12189. begin
  12190. Result := False;
  12191. { All these optimisations work on "shr const,%reg" }
  12192. if not MatchOpType(taicpu(p), top_const, top_reg) then
  12193. Exit;
  12194. DoNotMerge := False;
  12195. Shift := taicpu(p).oper[0]^.val;
  12196. LimitSize := taicpu(p).opsize;
  12197. hp1 := p;
  12198. repeat
  12199. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  12200. Break;
  12201. { Detect:
  12202. shr x, %reg
  12203. and y, %reg
  12204. If and y, %reg doesn't actually change the value of %reg (e.g. with
  12205. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  12206. }
  12207. case taicpu(hp1).opcode of
  12208. A_AND:
  12209. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  12210. MatchOpType(taicpu(hp1), top_const, top_reg) and
  12211. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12212. begin
  12213. { Make sure the FLAGS register isn't in use }
  12214. TransferUsedRegs(TmpUsedRegs);
  12215. hp2 := p;
  12216. repeat
  12217. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  12218. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12219. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  12220. begin
  12221. { Generate the identity mask }
  12222. case taicpu(p).opsize of
  12223. S_B:
  12224. IdentityMask := $FF shr Shift;
  12225. S_W:
  12226. IdentityMask := $FFFF shr Shift;
  12227. S_L:
  12228. IdentityMask := $FFFFFFFF shr Shift;
  12229. {$ifdef x86_64}
  12230. S_Q:
  12231. { We need to force the operands to be unsigned 64-bit
  12232. integers otherwise the wrong value is generated }
  12233. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  12234. {$endif x86_64}
  12235. else
  12236. InternalError(2022081501);
  12237. end;
  12238. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  12239. begin
  12240. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  12241. { All the possible 1 bits are covered, so we can remove the AND }
  12242. hp2 := tai(hp1.Previous);
  12243. RemoveInstruction(hp1);
  12244. { p wasn't actually changed, so don't set Result to True,
  12245. but a change was nonetheless made elsewhere }
  12246. Include(OptsToCheck, aoc_ForceNewIteration);
  12247. { Do another pass in case other AND or MOVZX instructions
  12248. follow }
  12249. hp1 := hp2;
  12250. Continue;
  12251. end;
  12252. end;
  12253. end;
  12254. A_TEST, A_CMP, A_Jcc:
  12255. { Skip over conditional jumps and relevant comparisons }
  12256. Continue;
  12257. A_MOVZX:
  12258. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  12259. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  12260. begin
  12261. { Since the original register is being read as is, subsequent
  12262. SHRs must not be merged at this point }
  12263. DoNotMerge := True;
  12264. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  12265. begin
  12266. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12267. begin
  12268. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  12269. { All the possible 1 bits are covered, so we can remove the AND }
  12270. hp2 := tai(hp1.Previous);
  12271. RemoveInstruction(hp1);
  12272. hp1 := hp2;
  12273. end
  12274. else { Different register target }
  12275. begin
  12276. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  12277. taicpu(hp1).opcode := A_MOV;
  12278. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  12279. case taicpu(hp1).opsize of
  12280. S_BW:
  12281. taicpu(hp1).opsize := S_W;
  12282. S_BL, S_WL:
  12283. taicpu(hp1).opsize := S_L;
  12284. else
  12285. InternalError(2022081503);
  12286. end;
  12287. end;
  12288. end
  12289. else if (Shift > 0) and
  12290. (taicpu(p).opsize = S_W) and
  12291. (taicpu(hp1).opsize = S_WL) and
  12292. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  12293. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  12294. begin
  12295. { Detect:
  12296. shr x, %ax (x > 0)
  12297. ...
  12298. movzwl %ax,%eax
  12299. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  12300. }
  12301. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  12302. taicpu(hp1).opcode := A_CWDE;
  12303. taicpu(hp1).clearop(0);
  12304. taicpu(hp1).clearop(1);
  12305. taicpu(hp1).ops := 0;
  12306. end;
  12307. { Move onto the next instruction }
  12308. Continue;
  12309. end;
  12310. A_SHL, A_SAL, A_SHR:
  12311. if (taicpu(hp1).opsize <= LimitSize) and
  12312. MatchOpType(taicpu(hp1), top_const, top_reg) and
  12313. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  12314. begin
  12315. { Make sure the sizes don't exceed the register size limit
  12316. (measured by the shift value falling below the limit) }
  12317. if taicpu(hp1).opsize < LimitSize then
  12318. LimitSize := taicpu(hp1).opsize;
  12319. if taicpu(hp1).opcode = A_SHR then
  12320. Inc(Shift, taicpu(hp1).oper[0]^.val)
  12321. else
  12322. begin
  12323. Dec(Shift, taicpu(hp1).oper[0]^.val);
  12324. DoNotMerge := True;
  12325. end;
  12326. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  12327. Break;
  12328. { Since we've established that the combined shift is within
  12329. limits, we can actually combine the adjacent SHR
  12330. instructions even if they're different sizes }
  12331. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  12332. begin
  12333. hp2 := tai(hp1.Previous);
  12334. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  12335. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  12336. RemoveInstruction(hp1);
  12337. hp1 := hp2;
  12338. end;
  12339. { Move onto the next instruction }
  12340. Continue;
  12341. end;
  12342. else
  12343. ;
  12344. end;
  12345. Break;
  12346. until False;
  12347. { Detect the following (looking backwards):
  12348. shr %cl,%reg
  12349. shr x, %reg
  12350. Swap the two SHR instructions to minimise a pipeline stall.
  12351. }
  12352. if GetLastInstruction(p, hp1) and
  12353. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  12354. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  12355. { First operand will be %cl }
  12356. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  12357. { Just to be sure }
  12358. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  12359. begin
  12360. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  12361. { Moving the entries this way ensures the register tracking remains correct }
  12362. Asml.Remove(p);
  12363. Asml.InsertBefore(p, hp1);
  12364. p := hp1;
  12365. { Don't set Result to True because the current instruction is now
  12366. "shr %cl,%reg" and there's nothing more we can do with it }
  12367. end;
  12368. end;
  12369. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  12370. var
  12371. hp1, hp2: tai;
  12372. Opposite, SecondOpposite: TAsmOp;
  12373. NewCond: TAsmCond;
  12374. begin
  12375. Result := False;
  12376. { Change:
  12377. add/sub 128,(dest)
  12378. To:
  12379. sub/add -128,(dest)
  12380. This generaally takes fewer bytes to encode because -128 can be stored
  12381. in a signed byte, whereas +128 cannot.
  12382. }
  12383. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  12384. begin
  12385. if taicpu(p).opcode = A_ADD then
  12386. Opposite := A_SUB
  12387. else
  12388. Opposite := A_ADD;
  12389. { Be careful if the flags are in use, because the CF flag inverts
  12390. when changing from ADD to SUB and vice versa }
  12391. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12392. GetNextInstruction(p, hp1) then
  12393. begin
  12394. TransferUsedRegs(TmpUsedRegs);
  12395. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  12396. hp2 := hp1;
  12397. { Scan ahead to check if everything's safe }
  12398. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  12399. begin
  12400. if (hp1.typ <> ait_instruction) then
  12401. { Probably unsafe since the flags are still in use }
  12402. Exit;
  12403. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  12404. { Stop searching at an unconditional jump }
  12405. Break;
  12406. if not
  12407. (
  12408. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  12409. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  12410. ) and
  12411. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  12412. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  12413. Exit;
  12414. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12415. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  12416. { Move to the next instruction }
  12417. GetNextInstruction(hp1, hp1);
  12418. end;
  12419. while Assigned(hp2) and (hp2 <> hp1) do
  12420. begin
  12421. NewCond := C_None;
  12422. case taicpu(hp2).condition of
  12423. C_A, C_NBE:
  12424. NewCond := C_BE;
  12425. C_B, C_C, C_NAE:
  12426. NewCond := C_AE;
  12427. C_AE, C_NB, C_NC:
  12428. NewCond := C_B;
  12429. C_BE, C_NA:
  12430. NewCond := C_A;
  12431. else
  12432. { No change needed };
  12433. end;
  12434. if NewCond <> C_None then
  12435. begin
  12436. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  12437. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  12438. taicpu(hp2).condition := NewCond;
  12439. end
  12440. else
  12441. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  12442. begin
  12443. { Because of the flipping of the carry bit, to ensure
  12444. the operation remains equivalent, ADC becomes SBB
  12445. and vice versa, and the constant is not-inverted.
  12446. If multiple ADCs or SBBs appear in a row, each one
  12447. changed causes the carry bit to invert, so they all
  12448. need to be flipped }
  12449. if taicpu(hp2).opcode = A_ADC then
  12450. SecondOpposite := A_SBB
  12451. else
  12452. SecondOpposite := A_ADC;
  12453. if taicpu(hp2).oper[0]^.typ <> top_const then
  12454. { Should have broken out of this optimisation already }
  12455. InternalError(2021112901);
  12456. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(hp2).opcode) + debug_opsize2str(taicpu(hp2).opsize) + ' $' + debug_tostr(taicpu(hp2).oper[0]^.val) + ',' + debug_operstr(taicpu(hp2).oper[1]^) + ' -> ' +
  12457. debug_op2str(SecondOpposite) + debug_opsize2str(taicpu(hp2).opsize) + ' $' + debug_tostr(not taicpu(hp2).oper[0]^.val) + ',' + debug_operstr(taicpu(hp2).oper[1]^) + ' to accommodate inverted carry bit', hp2);
  12458. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  12459. taicpu(hp2).opcode := SecondOpposite;
  12460. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  12461. end;
  12462. { Move to the next instruction }
  12463. GetNextInstruction(hp2, hp2);
  12464. end;
  12465. if (hp2 <> hp1) then
  12466. InternalError(2021111501);
  12467. end;
  12468. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  12469. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  12470. taicpu(p).opcode := Opposite;
  12471. taicpu(p).oper[0]^.val := -128;
  12472. { No further optimisations can be made on this instruction, so move
  12473. onto the next one to save time }
  12474. p := tai(p.Next);
  12475. UpdateUsedRegs(p);
  12476. Result := True;
  12477. Exit;
  12478. end;
  12479. { Detect:
  12480. add/sub %reg2,(dest)
  12481. add/sub x, (dest)
  12482. (dest can be a register or a reference)
  12483. Swap the instructions to minimise a pipeline stall. This reverses the
  12484. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  12485. optimisations could be made.
  12486. }
  12487. if (taicpu(p).oper[0]^.typ = top_reg) and
  12488. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  12489. (
  12490. (
  12491. (taicpu(p).oper[1]^.typ = top_reg) and
  12492. { We can try searching further ahead if we're writing to a register }
  12493. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  12494. ) or
  12495. (
  12496. (taicpu(p).oper[1]^.typ = top_ref) and
  12497. GetNextInstruction(p, hp1)
  12498. )
  12499. ) and
  12500. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  12501. (taicpu(hp1).oper[0]^.typ = top_const) and
  12502. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  12503. begin
  12504. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  12505. TransferUsedRegs(TmpUsedRegs);
  12506. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12507. hp2 := p;
  12508. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  12509. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  12510. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  12511. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  12512. begin
  12513. asml.remove(hp1);
  12514. asml.InsertBefore(hp1, p);
  12515. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  12516. Result := True;
  12517. end;
  12518. end;
  12519. end;
  12520. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  12521. begin
  12522. Result:=false;
  12523. { change "cmp $0, %reg" to "test %reg, %reg" }
  12524. if MatchOpType(taicpu(p),top_const,top_reg) and
  12525. (taicpu(p).oper[0]^.val = 0) then
  12526. begin
  12527. taicpu(p).opcode := A_TEST;
  12528. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  12529. Result:=true;
  12530. end;
  12531. end;
  12532. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  12533. var
  12534. IsTestConstX : Boolean;
  12535. hp1,hp2 : tai;
  12536. begin
  12537. Result:=false;
  12538. { removes the line marked with (x) from the sequence
  12539. and/or/xor/add/sub/... $x, %y
  12540. test/or %y, %y | test $-1, %y (x)
  12541. j(n)z _Label
  12542. as the first instruction already adjusts the ZF
  12543. %y operand may also be a reference }
  12544. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  12545. MatchOperand(taicpu(p).oper[0]^,-1);
  12546. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  12547. GetLastInstruction(p, hp1) and
  12548. (tai(hp1).typ = ait_instruction) and
  12549. GetNextInstruction(p,hp2) and
  12550. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  12551. case taicpu(hp1).opcode Of
  12552. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  12553. { These two instructions set the zero flag if the result is zero }
  12554. A_POPCNT, A_LZCNT:
  12555. begin
  12556. if (
  12557. { With POPCNT, an input of zero will set the zero flag
  12558. because the population count of zero is zero }
  12559. (taicpu(hp1).opcode = A_POPCNT) and
  12560. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  12561. (
  12562. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  12563. { Faster than going through the second half of the 'or'
  12564. condition below }
  12565. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  12566. )
  12567. ) or (
  12568. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  12569. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  12570. { and in case of carry for A(E)/B(E)/C/NC }
  12571. (
  12572. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  12573. (
  12574. (taicpu(hp1).opcode <> A_ADD) and
  12575. (taicpu(hp1).opcode <> A_SUB) and
  12576. (taicpu(hp1).opcode <> A_LZCNT)
  12577. )
  12578. )
  12579. ) then
  12580. begin
  12581. RemoveCurrentP(p, hp2);
  12582. Result:=true;
  12583. Exit;
  12584. end;
  12585. end;
  12586. A_SHL, A_SAL, A_SHR, A_SAR:
  12587. begin
  12588. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  12589. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  12590. { therefore, it's only safe to do this optimization for }
  12591. { shifts by a (nonzero) constant }
  12592. (taicpu(hp1).oper[0]^.typ = top_const) and
  12593. (taicpu(hp1).oper[0]^.val <> 0) and
  12594. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  12595. { and in case of carry for A(E)/B(E)/C/NC }
  12596. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  12597. begin
  12598. RemoveCurrentP(p, hp2);
  12599. Result:=true;
  12600. Exit;
  12601. end;
  12602. end;
  12603. A_DEC, A_INC, A_NEG:
  12604. begin
  12605. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  12606. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  12607. { and in case of carry for A(E)/B(E)/C/NC }
  12608. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  12609. begin
  12610. RemoveCurrentP(p, hp2);
  12611. Result:=true;
  12612. Exit;
  12613. end;
  12614. end
  12615. else
  12616. ;
  12617. end; { case }
  12618. { change "test $-1,%reg" into "test %reg,%reg" }
  12619. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  12620. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  12621. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  12622. if MatchInstruction(p, A_OR, []) and
  12623. { Can only match if they're both registers }
  12624. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  12625. begin
  12626. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  12627. taicpu(p).opcode := A_TEST;
  12628. { No need to set Result to True, as we've done all the optimisations we can }
  12629. end;
  12630. end;
  12631. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  12632. var
  12633. hp1,hp3 : tai;
  12634. {$ifndef x86_64}
  12635. hp2 : taicpu;
  12636. {$endif x86_64}
  12637. begin
  12638. Result:=false;
  12639. hp3:=nil;
  12640. {$ifndef x86_64}
  12641. { don't do this on modern CPUs, this really hurts them due to
  12642. broken call/ret pairing }
  12643. if (current_settings.optimizecputype < cpu_Pentium2) and
  12644. not(cs_create_pic in current_settings.moduleswitches) and
  12645. GetNextInstruction(p, hp1) and
  12646. MatchInstruction(hp1,A_JMP,[S_NO]) and
  12647. MatchOpType(taicpu(hp1),top_ref) and
  12648. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  12649. begin
  12650. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  12651. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  12652. InsertLLItem(p.previous, p, hp2);
  12653. taicpu(p).opcode := A_JMP;
  12654. taicpu(p).is_jmp := true;
  12655. RemoveInstruction(hp1);
  12656. Result:=true;
  12657. end
  12658. else
  12659. {$endif x86_64}
  12660. { replace
  12661. call procname
  12662. ret
  12663. by
  12664. jmp procname
  12665. but do it only on level 4 because it destroys stack back traces
  12666. else if the subroutine is marked as no return, remove the ret
  12667. }
  12668. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  12669. (po_noreturn in current_procinfo.procdef.procoptions)) and
  12670. GetNextInstruction(p, hp1) and
  12671. (MatchInstruction(hp1,A_RET,[S_NO]) or
  12672. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  12673. SetAndTest(hp1,hp3) and
  12674. GetNextInstruction(hp1,hp1) and
  12675. MatchInstruction(hp1,A_RET,[S_NO])
  12676. )
  12677. ) and
  12678. (taicpu(hp1).ops=0) then
  12679. begin
  12680. if (cs_opt_level4 in current_settings.optimizerswitches) and
  12681. { we might destroy stack alignment here if we do not do a call }
  12682. (target_info.stackalign<=sizeof(SizeUInt)) then
  12683. begin
  12684. taicpu(p).opcode := A_JMP;
  12685. taicpu(p).is_jmp := true;
  12686. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  12687. end
  12688. else
  12689. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  12690. RemoveInstruction(hp1);
  12691. if Assigned(hp3) then
  12692. begin
  12693. AsmL.Remove(hp3);
  12694. AsmL.InsertBefore(hp3,p)
  12695. end;
  12696. Result:=true;
  12697. end;
  12698. end;
  12699. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  12700. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  12701. begin
  12702. case OpSize of
  12703. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12704. Result := (Val <= $FF) and (Val >= -128);
  12705. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12706. Result := (Val <= $FFFF) and (Val >= -32768);
  12707. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  12708. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  12709. else
  12710. Result := True;
  12711. end;
  12712. end;
  12713. var
  12714. hp1, hp2 : tai;
  12715. SizeChange: Boolean;
  12716. PreMessage: string;
  12717. begin
  12718. Result := False;
  12719. if (taicpu(p).oper[0]^.typ = top_reg) and
  12720. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12721. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  12722. begin
  12723. { Change (using movzbl %al,%eax as an example):
  12724. movzbl %al, %eax movzbl %al, %eax
  12725. cmpl x, %eax testl %eax,%eax
  12726. To:
  12727. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  12728. movzbl %al, %eax movzbl %al, %eax
  12729. Smaller instruction and minimises pipeline stall as the CPU
  12730. doesn't have to wait for the register to get zero-extended. [Kit]
  12731. Also allow if the smaller of the two registers is being checked,
  12732. as this still removes the false dependency.
  12733. }
  12734. if
  12735. (
  12736. (
  12737. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  12738. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  12739. ) or (
  12740. { If MatchOperand returns True, they must both be registers }
  12741. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  12742. )
  12743. ) and
  12744. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  12745. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  12746. begin
  12747. PreMessage := debug_op2str(taicpu(hp1).opcode) + debug_opsize2str(taicpu(hp1).opsize) + ' ' + debug_operstr(taicpu(hp1).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' -> ' + debug_op2str(taicpu(hp1).opcode);
  12748. asml.Remove(hp1);
  12749. asml.InsertBefore(hp1, p);
  12750. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  12751. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  12752. begin
  12753. taicpu(hp1).opcode := A_TEST;
  12754. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  12755. end;
  12756. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  12757. case taicpu(p).opsize of
  12758. S_BW, S_BL:
  12759. begin
  12760. SizeChange := taicpu(hp1).opsize <> S_B;
  12761. taicpu(hp1).changeopsize(S_B);
  12762. end;
  12763. S_WL:
  12764. begin
  12765. SizeChange := taicpu(hp1).opsize <> S_W;
  12766. taicpu(hp1).changeopsize(S_W);
  12767. end
  12768. else
  12769. InternalError(2020112701);
  12770. end;
  12771. UpdateUsedRegs(tai(p.Next));
  12772. { Check if the register is used aferwards - if not, we can
  12773. remove the movzx instruction completely }
  12774. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  12775. begin
  12776. { Hp1 is a better position than p for debugging purposes }
  12777. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  12778. RemoveCurrentp(p, hp1);
  12779. Result := True;
  12780. end;
  12781. if SizeChange then
  12782. DebugMsg(SPeepholeOptimization + PreMessage +
  12783. debug_opsize2str(taicpu(hp1).opsize) + ' ' + debug_operstr(taicpu(hp1).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (smaller and minimises pipeline stall - MovzxCmp2CmpMovzx)', hp1)
  12784. else
  12785. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  12786. Exit;
  12787. end;
  12788. { Change (using movzwl %ax,%eax as an example):
  12789. movzwl %ax, %eax
  12790. movb %al, (dest) (Register is smaller than read register in movz)
  12791. To:
  12792. movb %al, (dest) (Move one back to avoid a false dependency)
  12793. movzwl %ax, %eax
  12794. }
  12795. if (taicpu(hp1).opcode = A_MOV) and
  12796. (taicpu(hp1).oper[0]^.typ = top_reg) and
  12797. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  12798. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  12799. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  12800. begin
  12801. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  12802. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  12803. asml.Remove(hp1);
  12804. asml.InsertBefore(hp1, p);
  12805. if taicpu(hp1).oper[1]^.typ = top_reg then
  12806. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  12807. { Check if the register is used aferwards - if not, we can
  12808. remove the movzx instruction completely }
  12809. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  12810. begin
  12811. { Hp1 is a better position than p for debugging purposes }
  12812. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  12813. RemoveCurrentp(p, hp1);
  12814. Result := True;
  12815. end;
  12816. Exit;
  12817. end;
  12818. end;
  12819. end;
  12820. {$ifdef x86_64}
  12821. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  12822. var
  12823. PreMessage, RegName: string;
  12824. begin
  12825. { Code size reduction by J. Gareth "Kit" Moreton }
  12826. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  12827. as this removes the REX prefix }
  12828. Result := False;
  12829. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  12830. Exit;
  12831. if taicpu(p).oper[0]^.typ <> top_reg then
  12832. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  12833. InternalError(2018011500);
  12834. case taicpu(p).opsize of
  12835. S_Q:
  12836. begin
  12837. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  12838. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  12839. { The actual optimization }
  12840. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12841. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  12842. taicpu(p).changeopsize(S_L);
  12843. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  12844. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  12845. end;
  12846. else
  12847. ;
  12848. end;
  12849. end;
  12850. {$endif}
  12851. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  12852. var
  12853. XReg: TRegister;
  12854. begin
  12855. Result := False;
  12856. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  12857. Smaller encoding and slightly faster on some platforms (also works for
  12858. ZMM-sized registers) }
  12859. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  12860. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  12861. begin
  12862. XReg := taicpu(p).oper[0]^.reg;
  12863. if (taicpu(p).oper[1]^.reg = XReg) then
  12864. begin
  12865. taicpu(p).changeopsize(S_XMM);
  12866. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  12867. if (cs_opt_size in current_settings.optimizerswitches) then
  12868. begin
  12869. { Change input registers to %xmm0 to reduce size. Note that
  12870. there's a risk of a false dependency doing this, so only
  12871. optimise for size here }
  12872. XReg := NR_XMM0;
  12873. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  12874. end
  12875. else
  12876. begin
  12877. setsubreg(XReg, R_SUBMMX);
  12878. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  12879. end;
  12880. taicpu(p).oper[0]^.reg := XReg;
  12881. taicpu(p).oper[1]^.reg := XReg;
  12882. Result := True;
  12883. end;
  12884. end;
  12885. end;
  12886. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  12887. var
  12888. OperIdx: Integer;
  12889. begin
  12890. for OperIdx := 0 to p.ops - 1 do
  12891. if p.oper[OperIdx]^.typ = top_ref then
  12892. optimize_ref(p.oper[OperIdx]^.ref^, False);
  12893. end;
  12894. end.