aoptx86.pas 414 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. {$define DEBUG_AOPTCPU}
  20. interface
  21. uses
  22. globtype,
  23. cpubase,
  24. aasmtai,aasmcpu,
  25. cgbase,cgutils,
  26. aopt,aoptobj;
  27. type
  28. TOptsToCheck = (
  29. aoc_MovAnd2Mov_3
  30. );
  31. TX86AsmOptimizer = class(TAsmOptimizer)
  32. { some optimizations are very expensive to check, so the
  33. pre opt pass can be used to set some flags, depending on the found
  34. instructions if it is worth to check a certain optimization }
  35. OptsToCheck : set of TOptsToCheck;
  36. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  37. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  38. function RegReadByInstruction(reg : TRegister; hp : tai) : boolean;
  39. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  40. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  41. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  42. potentially allowing further optimisation (although it might need to know if
  43. it crossed a conditional jump. }
  44. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  45. {
  46. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  47. the use of a register by allocs/dealloc, so it can ignore calls.
  48. In the following example, GetNextInstructionUsingReg will return the second movq,
  49. GetNextInstructionUsingRegTrackingUse won't.
  50. movq %rdi,%rax
  51. # Register rdi released
  52. # Register rdi allocated
  53. movq %rax,%rdi
  54. While in this example:
  55. movq %rdi,%rax
  56. call proc
  57. movq %rdi,%rax
  58. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  59. won't.
  60. }
  61. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  62. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  63. private
  64. function SkipSimpleInstructions(var hp1: tai): Boolean;
  65. protected
  66. class function IsMOVZXAcceptable: Boolean; static; inline;
  67. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  68. function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  69. { checks whether reading the value in reg1 depends on the value of reg2. This
  70. is very similar to SuperRegisterEquals, except it takes into account that
  71. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  72. depend on the value in AH). }
  73. function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  74. { Replaces all references to AOldReg in a memory reference to ANewReg }
  75. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  76. { Replaces all references to AOldReg in an operand to ANewReg }
  77. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  78. { Replaces all references to AOldReg in an instruction to ANewReg,
  79. except where the register is being written }
  80. function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  81. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  82. or writes to a global symbol }
  83. class function IsRefSafe(const ref: PReference): Boolean; static; inline;
  84. { Returns true if the given MOV instruction can be safely converted to CMOV }
  85. class function CanBeCMOV(p : tai) : boolean; static;
  86. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  87. conversion was successful }
  88. function ConvertLEA(const p : taicpu): Boolean;
  89. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  90. procedure DebugMsg(const s : string; p : tai);inline;
  91. class function IsExitCode(p : tai) : boolean; static;
  92. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  93. procedure RemoveLastDeallocForFuncRes(p : tai);
  94. function DoSubAddOpt(var p : tai) : Boolean;
  95. function PrePeepholeOptSxx(var p : tai) : boolean;
  96. function PrePeepholeOptIMUL(var p : tai) : boolean;
  97. function OptPass1Test(var p: tai): boolean;
  98. function OptPass1Add(var p: tai): boolean;
  99. function OptPass1AND(var p : tai) : boolean;
  100. function OptPass1_V_MOVAP(var p : tai) : boolean;
  101. function OptPass1VOP(var p : tai) : boolean;
  102. function OptPass1MOV(var p : tai) : boolean;
  103. function OptPass1Movx(var p : tai) : boolean;
  104. function OptPass1MOVXX(var p : tai) : boolean;
  105. function OptPass1OP(var p : tai) : boolean;
  106. function OptPass1LEA(var p : tai) : boolean;
  107. function OptPass1Sub(var p : tai) : boolean;
  108. function OptPass1SHLSAL(var p : tai) : boolean;
  109. function OptPass1FSTP(var p : tai) : boolean;
  110. function OptPass1FLD(var p : tai) : boolean;
  111. function OptPass1Cmp(var p : tai) : boolean;
  112. function OptPass1PXor(var p : tai) : boolean;
  113. function OptPass1VPXor(var p: tai): boolean;
  114. function OptPass1Imul(var p : tai) : boolean;
  115. function OptPass1Jcc(var p : tai) : boolean;
  116. function OptPass1SHXX(var p: tai): boolean;
  117. function OptPass2Movx(var p : tai): Boolean;
  118. function OptPass2MOV(var p : tai) : boolean;
  119. function OptPass2Imul(var p : tai) : boolean;
  120. function OptPass2Jmp(var p : tai) : boolean;
  121. function OptPass2Jcc(var p : tai) : boolean;
  122. function OptPass2Lea(var p: tai): Boolean;
  123. function OptPass2SUB(var p: tai): Boolean;
  124. function OptPass2ADD(var p : tai): Boolean;
  125. function OptPass2SETcc(var p : tai) : boolean;
  126. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  127. function PostPeepholeOptMov(var p : tai) : Boolean;
  128. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  129. {$ifdef x86_64} { These post-peephole optimisations only affect 64-bit registers. [Kit] }
  130. function PostPeepholeOptXor(var p : tai) : Boolean;
  131. {$endif}
  132. function PostPeepholeOptAnd(var p : tai) : boolean;
  133. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  134. function PostPeepholeOptCmp(var p : tai) : Boolean;
  135. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  136. function PostPeepholeOptCall(var p : tai) : Boolean;
  137. function PostPeepholeOptLea(var p : tai) : Boolean;
  138. function PostPeepholeOptPush(var p: tai): Boolean;
  139. function PostPeepholeOptShr(var p : tai) : boolean;
  140. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  141. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  142. procedure SwapMovCmp(var p, hp1: tai);
  143. { Processor-dependent reference optimisation }
  144. class procedure OptimizeRefs(var p: taicpu); static;
  145. end;
  146. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  147. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  148. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  149. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  150. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  151. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  152. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  153. {$if max_operands>2}
  154. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  155. {$endif max_operands>2}
  156. function RefsEqual(const r1, r2: treference): boolean;
  157. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  158. { returns true, if ref is a reference using only the registers passed as base and index
  159. and having an offset }
  160. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  161. implementation
  162. uses
  163. cutils,verbose,
  164. systems,
  165. globals,
  166. cpuinfo,
  167. procinfo,
  168. paramgr,
  169. aasmbase,
  170. aoptbase,aoptutils,
  171. symconst,symsym,
  172. cgx86,
  173. itcpugas;
  174. {$ifdef DEBUG_AOPTCPU}
  175. const
  176. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  177. {$else DEBUG_AOPTCPU}
  178. { Empty strings help the optimizer to remove string concatenations that won't
  179. ever appear to the user on release builds. [Kit] }
  180. const
  181. SPeepholeOptimization = '';
  182. {$endif DEBUG_AOPTCPU}
  183. LIST_STEP_SIZE = 4;
  184. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  185. begin
  186. result :=
  187. (instr.typ = ait_instruction) and
  188. (taicpu(instr).opcode = op) and
  189. ((opsize = []) or (taicpu(instr).opsize in opsize));
  190. end;
  191. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  192. begin
  193. result :=
  194. (instr.typ = ait_instruction) and
  195. ((taicpu(instr).opcode = op1) or
  196. (taicpu(instr).opcode = op2)
  197. ) and
  198. ((opsize = []) or (taicpu(instr).opsize in opsize));
  199. end;
  200. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  201. begin
  202. result :=
  203. (instr.typ = ait_instruction) and
  204. ((taicpu(instr).opcode = op1) or
  205. (taicpu(instr).opcode = op2) or
  206. (taicpu(instr).opcode = op3)
  207. ) and
  208. ((opsize = []) or (taicpu(instr).opsize in opsize));
  209. end;
  210. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  211. const opsize : topsizes) : boolean;
  212. var
  213. op : TAsmOp;
  214. begin
  215. result:=false;
  216. for op in ops do
  217. begin
  218. if (instr.typ = ait_instruction) and
  219. (taicpu(instr).opcode = op) and
  220. ((opsize = []) or (taicpu(instr).opsize in opsize)) then
  221. begin
  222. result:=true;
  223. exit;
  224. end;
  225. end;
  226. end;
  227. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  228. begin
  229. result := (oper.typ = top_reg) and (oper.reg = reg);
  230. end;
  231. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  232. begin
  233. result := (oper.typ = top_const) and (oper.val = a);
  234. end;
  235. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  236. begin
  237. result := oper1.typ = oper2.typ;
  238. if result then
  239. case oper1.typ of
  240. top_const:
  241. Result:=oper1.val = oper2.val;
  242. top_reg:
  243. Result:=oper1.reg = oper2.reg;
  244. top_ref:
  245. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  246. else
  247. internalerror(2013102801);
  248. end
  249. end;
  250. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  251. begin
  252. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  253. if result then
  254. case oper1.typ of
  255. top_const:
  256. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  257. top_reg:
  258. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  259. top_ref:
  260. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  261. else
  262. internalerror(2020052401);
  263. end
  264. end;
  265. function RefsEqual(const r1, r2: treference): boolean;
  266. begin
  267. RefsEqual :=
  268. (r1.offset = r2.offset) and
  269. (r1.segment = r2.segment) and (r1.base = r2.base) and
  270. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  271. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  272. (r1.relsymbol = r2.relsymbol) and
  273. (r1.volatility=[]) and
  274. (r2.volatility=[]);
  275. end;
  276. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  277. begin
  278. Result:=(ref.offset=0) and
  279. (ref.scalefactor in [0,1]) and
  280. (ref.segment=NR_NO) and
  281. (ref.symbol=nil) and
  282. (ref.relsymbol=nil) and
  283. ((base=NR_INVALID) or
  284. (ref.base=base)) and
  285. ((index=NR_INVALID) or
  286. (ref.index=index)) and
  287. (ref.volatility=[]);
  288. end;
  289. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  290. begin
  291. Result:=(ref.scalefactor in [0,1]) and
  292. (ref.segment=NR_NO) and
  293. (ref.symbol=nil) and
  294. (ref.relsymbol=nil) and
  295. ((base=NR_INVALID) or
  296. (ref.base=base)) and
  297. ((index=NR_INVALID) or
  298. (ref.index=index)) and
  299. (ref.volatility=[]);
  300. end;
  301. function InstrReadsFlags(p: tai): boolean;
  302. begin
  303. InstrReadsFlags := true;
  304. case p.typ of
  305. ait_instruction:
  306. if InsProp[taicpu(p).opcode].Ch*
  307. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  308. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  309. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  310. exit;
  311. ait_label:
  312. exit;
  313. else
  314. ;
  315. end;
  316. InstrReadsFlags := false;
  317. end;
  318. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  319. begin
  320. Next:=Current;
  321. repeat
  322. Result:=GetNextInstruction(Next,Next);
  323. until not (Result) or
  324. not(cs_opt_level3 in current_settings.optimizerswitches) or
  325. (Next.typ<>ait_instruction) or
  326. RegInInstruction(reg,Next) or
  327. is_calljmp(taicpu(Next).opcode);
  328. end;
  329. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  330. begin
  331. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  332. Next := Current;
  333. repeat
  334. Result := GetNextInstruction(Next,Next);
  335. if Result and (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  336. if is_calljmpuncond(taicpu(Next).opcode) then
  337. begin
  338. Result := False;
  339. Exit;
  340. end
  341. else
  342. CrossJump := True;
  343. until not Result or
  344. not (cs_opt_level3 in current_settings.optimizerswitches) or
  345. (Next.typ <> ait_instruction) or
  346. RegInInstruction(reg,Next);
  347. end;
  348. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  349. begin
  350. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  351. begin
  352. Result:=GetNextInstruction(Current,Next);
  353. exit;
  354. end;
  355. Next:=tai(Current.Next);
  356. Result:=false;
  357. while assigned(Next) do
  358. begin
  359. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  360. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  361. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  362. exit
  363. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  364. begin
  365. Result:=true;
  366. exit;
  367. end;
  368. Next:=tai(Next.Next);
  369. end;
  370. end;
  371. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  372. begin
  373. Result:=RegReadByInstruction(reg,hp);
  374. end;
  375. function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  376. var
  377. p: taicpu;
  378. opcount: longint;
  379. begin
  380. RegReadByInstruction := false;
  381. if hp.typ <> ait_instruction then
  382. exit;
  383. p := taicpu(hp);
  384. case p.opcode of
  385. A_CALL:
  386. regreadbyinstruction := true;
  387. A_IMUL:
  388. case p.ops of
  389. 1:
  390. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  391. (
  392. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  393. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  394. );
  395. 2,3:
  396. regReadByInstruction :=
  397. reginop(reg,p.oper[0]^) or
  398. reginop(reg,p.oper[1]^);
  399. else
  400. InternalError(2019112801);
  401. end;
  402. A_MUL:
  403. begin
  404. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  405. (
  406. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  407. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  408. );
  409. end;
  410. A_IDIV,A_DIV:
  411. begin
  412. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  413. (
  414. (getregtype(reg)=R_INTREGISTER) and
  415. (
  416. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  417. )
  418. );
  419. end;
  420. else
  421. begin
  422. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  423. begin
  424. RegReadByInstruction := false;
  425. exit;
  426. end;
  427. for opcount := 0 to p.ops-1 do
  428. if (p.oper[opCount]^.typ = top_ref) and
  429. RegInRef(reg,p.oper[opcount]^.ref^) then
  430. begin
  431. RegReadByInstruction := true;
  432. exit
  433. end;
  434. { special handling for SSE MOVSD }
  435. if (p.opcode=A_MOVSD) and (p.ops>0) then
  436. begin
  437. if p.ops<>2 then
  438. internalerror(2017042702);
  439. regReadByInstruction := reginop(reg,p.oper[0]^) or
  440. (
  441. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  442. );
  443. exit;
  444. end;
  445. with insprop[p.opcode] do
  446. begin
  447. if getregtype(reg)=R_INTREGISTER then
  448. begin
  449. case getsupreg(reg) of
  450. RS_EAX:
  451. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  452. begin
  453. RegReadByInstruction := true;
  454. exit
  455. end;
  456. RS_ECX:
  457. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  458. begin
  459. RegReadByInstruction := true;
  460. exit
  461. end;
  462. RS_EDX:
  463. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  464. begin
  465. RegReadByInstruction := true;
  466. exit
  467. end;
  468. RS_EBX:
  469. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  470. begin
  471. RegReadByInstruction := true;
  472. exit
  473. end;
  474. RS_ESP:
  475. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  476. begin
  477. RegReadByInstruction := true;
  478. exit
  479. end;
  480. RS_EBP:
  481. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  482. begin
  483. RegReadByInstruction := true;
  484. exit
  485. end;
  486. RS_ESI:
  487. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  488. begin
  489. RegReadByInstruction := true;
  490. exit
  491. end;
  492. RS_EDI:
  493. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  494. begin
  495. RegReadByInstruction := true;
  496. exit
  497. end;
  498. end;
  499. end;
  500. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  501. begin
  502. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  503. begin
  504. case p.condition of
  505. C_A,C_NBE, { CF=0 and ZF=0 }
  506. C_BE,C_NA: { CF=1 or ZF=1 }
  507. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  508. C_AE,C_NB,C_NC, { CF=0 }
  509. C_B,C_NAE,C_C: { CF=1 }
  510. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  511. C_NE,C_NZ, { ZF=0 }
  512. C_E,C_Z: { ZF=1 }
  513. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  514. C_G,C_NLE, { ZF=0 and SF=OF }
  515. C_LE,C_NG: { ZF=1 or SF<>OF }
  516. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  517. C_GE,C_NL, { SF=OF }
  518. C_L,C_NGE: { SF<>OF }
  519. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  520. C_NO, { OF=0 }
  521. C_O: { OF=1 }
  522. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  523. C_NP,C_PO, { PF=0 }
  524. C_P,C_PE: { PF=1 }
  525. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  526. C_NS, { SF=0 }
  527. C_S: { SF=1 }
  528. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  529. else
  530. internalerror(2017042701);
  531. end;
  532. if RegReadByInstruction then
  533. exit;
  534. end;
  535. case getsubreg(reg) of
  536. R_SUBW,R_SUBD,R_SUBQ:
  537. RegReadByInstruction :=
  538. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  539. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  540. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  541. R_SUBFLAGCARRY:
  542. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  543. R_SUBFLAGPARITY:
  544. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  545. R_SUBFLAGAUXILIARY:
  546. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  547. R_SUBFLAGZERO:
  548. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  549. R_SUBFLAGSIGN:
  550. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  551. R_SUBFLAGOVERFLOW:
  552. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  553. R_SUBFLAGINTERRUPT:
  554. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  555. R_SUBFLAGDIRECTION:
  556. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  557. else
  558. internalerror(2017042601);
  559. end;
  560. exit;
  561. end;
  562. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  563. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  564. (p.oper[0]^.reg=p.oper[1]^.reg) then
  565. exit;
  566. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  567. begin
  568. RegReadByInstruction := true;
  569. exit
  570. end;
  571. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  572. begin
  573. RegReadByInstruction := true;
  574. exit
  575. end;
  576. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  577. begin
  578. RegReadByInstruction := true;
  579. exit
  580. end;
  581. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  582. begin
  583. RegReadByInstruction := true;
  584. exit
  585. end;
  586. end;
  587. end;
  588. end;
  589. end;
  590. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  591. begin
  592. result:=false;
  593. if p1.typ<>ait_instruction then
  594. exit;
  595. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  596. exit(true);
  597. if (getregtype(reg)=R_INTREGISTER) and
  598. { change information for xmm movsd are not correct }
  599. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  600. begin
  601. case getsupreg(reg) of
  602. { RS_EAX = RS_RAX on x86-64 }
  603. RS_EAX:
  604. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  605. RS_ECX:
  606. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  607. RS_EDX:
  608. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  609. RS_EBX:
  610. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  611. RS_ESP:
  612. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  613. RS_EBP:
  614. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  615. RS_ESI:
  616. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  617. RS_EDI:
  618. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  619. else
  620. ;
  621. end;
  622. if result then
  623. exit;
  624. end
  625. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  626. begin
  627. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  628. exit(true);
  629. case getsubreg(reg) of
  630. R_SUBFLAGCARRY:
  631. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  632. R_SUBFLAGPARITY:
  633. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  634. R_SUBFLAGAUXILIARY:
  635. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  636. R_SUBFLAGZERO:
  637. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  638. R_SUBFLAGSIGN:
  639. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  640. R_SUBFLAGOVERFLOW:
  641. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  642. R_SUBFLAGINTERRUPT:
  643. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  644. R_SUBFLAGDIRECTION:
  645. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  646. else
  647. ;
  648. end;
  649. if result then
  650. exit;
  651. end
  652. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  653. exit(true);
  654. Result:=inherited RegInInstruction(Reg, p1);
  655. end;
  656. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  657. begin
  658. Result := False;
  659. if p1.typ <> ait_instruction then
  660. exit;
  661. with insprop[taicpu(p1).opcode] do
  662. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  663. begin
  664. case getsubreg(reg) of
  665. R_SUBW,R_SUBD,R_SUBQ:
  666. Result :=
  667. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  668. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  669. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  670. R_SUBFLAGCARRY:
  671. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  672. R_SUBFLAGPARITY:
  673. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  674. R_SUBFLAGAUXILIARY:
  675. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  676. R_SUBFLAGZERO:
  677. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  678. R_SUBFLAGSIGN:
  679. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  680. R_SUBFLAGOVERFLOW:
  681. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  682. R_SUBFLAGINTERRUPT:
  683. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  684. R_SUBFLAGDIRECTION:
  685. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  686. else
  687. internalerror(2017042602);
  688. end;
  689. exit;
  690. end;
  691. case taicpu(p1).opcode of
  692. A_CALL:
  693. { We could potentially set Result to False if the register in
  694. question is non-volatile for the subroutine's calling convention,
  695. but this would require detecting the calling convention in use and
  696. also assuming that the routine doesn't contain malformed assembly
  697. language, for example... so it could only be done under -O4 as it
  698. would be considered a side-effect. [Kit] }
  699. Result := True;
  700. A_MOVSD:
  701. { special handling for SSE MOVSD }
  702. if (taicpu(p1).ops>0) then
  703. begin
  704. if taicpu(p1).ops<>2 then
  705. internalerror(2017042703);
  706. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  707. end;
  708. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  709. so fix it here (FK)
  710. }
  711. A_VMOVSS,
  712. A_VMOVSD:
  713. begin
  714. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  715. exit;
  716. end;
  717. A_IMUL:
  718. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  719. else
  720. ;
  721. end;
  722. if Result then
  723. exit;
  724. with insprop[taicpu(p1).opcode] do
  725. begin
  726. if getregtype(reg)=R_INTREGISTER then
  727. begin
  728. case getsupreg(reg) of
  729. RS_EAX:
  730. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  731. begin
  732. Result := True;
  733. exit
  734. end;
  735. RS_ECX:
  736. if [Ch_WECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  737. begin
  738. Result := True;
  739. exit
  740. end;
  741. RS_EDX:
  742. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  743. begin
  744. Result := True;
  745. exit
  746. end;
  747. RS_EBX:
  748. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  749. begin
  750. Result := True;
  751. exit
  752. end;
  753. RS_ESP:
  754. if [Ch_WESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  755. begin
  756. Result := True;
  757. exit
  758. end;
  759. RS_EBP:
  760. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  761. begin
  762. Result := True;
  763. exit
  764. end;
  765. RS_ESI:
  766. if [Ch_WESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  767. begin
  768. Result := True;
  769. exit
  770. end;
  771. RS_EDI:
  772. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  773. begin
  774. Result := True;
  775. exit
  776. end;
  777. end;
  778. end;
  779. if ([CH_RWOP1,CH_WOP1,CH_MOP1]*Ch<>[]) and reginop(reg,taicpu(p1).oper[0]^) then
  780. begin
  781. Result := true;
  782. exit
  783. end;
  784. if ([Ch_RWOP2,Ch_WOP2,Ch_MOP2]*Ch<>[]) and reginop(reg,taicpu(p1).oper[1]^) then
  785. begin
  786. Result := true;
  787. exit
  788. end;
  789. if ([Ch_RWOP3,Ch_WOP3,Ch_MOP3]*Ch<>[]) and reginop(reg,taicpu(p1).oper[2]^) then
  790. begin
  791. Result := true;
  792. exit
  793. end;
  794. if ([Ch_RWOP4,Ch_WOP4,Ch_MOP4]*Ch<>[]) and reginop(reg,taicpu(p1).oper[3]^) then
  795. begin
  796. Result := true;
  797. exit
  798. end;
  799. end;
  800. end;
  801. {$ifdef DEBUG_AOPTCPU}
  802. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  803. begin
  804. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  805. end;
  806. function debug_tostr(i: tcgint): string; inline;
  807. begin
  808. Result := tostr(i);
  809. end;
  810. function debug_regname(r: TRegister): string; inline;
  811. begin
  812. Result := '%' + std_regname(r);
  813. end;
  814. { Debug output function - creates a string representation of an operator }
  815. function debug_operstr(oper: TOper): string;
  816. begin
  817. case oper.typ of
  818. top_const:
  819. Result := '$' + debug_tostr(oper.val);
  820. top_reg:
  821. Result := debug_regname(oper.reg);
  822. top_ref:
  823. begin
  824. if oper.ref^.offset <> 0 then
  825. Result := debug_tostr(oper.ref^.offset) + '('
  826. else
  827. Result := '(';
  828. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  829. begin
  830. Result := Result + debug_regname(oper.ref^.base);
  831. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  832. Result := Result + ',' + debug_regname(oper.ref^.index);
  833. end
  834. else
  835. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  836. Result := Result + debug_regname(oper.ref^.index);
  837. if (oper.ref^.scalefactor > 1) then
  838. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  839. else
  840. Result := Result + ')';
  841. end;
  842. else
  843. Result := '[UNKNOWN]';
  844. end;
  845. end;
  846. function debug_op2str(opcode: tasmop): string; inline;
  847. begin
  848. Result := std_op2str[opcode];
  849. end;
  850. function debug_opsize2str(opsize: topsize): string; inline;
  851. begin
  852. Result := gas_opsize2str[opsize];
  853. end;
  854. {$else DEBUG_AOPTCPU}
  855. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  856. begin
  857. end;
  858. function debug_tostr(i: tcgint): string; inline;
  859. begin
  860. Result := '';
  861. end;
  862. function debug_regname(r: TRegister): string; inline;
  863. begin
  864. Result := '';
  865. end;
  866. function debug_operstr(oper: TOper): string; inline;
  867. begin
  868. Result := '';
  869. end;
  870. function debug_op2str(opcode: tasmop): string; inline;
  871. begin
  872. Result := '';
  873. end;
  874. function debug_opsize2str(opsize: topsize): string; inline;
  875. begin
  876. Result := '';
  877. end;
  878. {$endif DEBUG_AOPTCPU}
  879. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  880. begin
  881. {$ifdef x86_64}
  882. { Always fine on x86-64 }
  883. Result := True;
  884. {$else x86_64}
  885. Result :=
  886. {$ifdef i8086}
  887. (current_settings.cputype >= cpu_386) and
  888. {$endif i8086}
  889. (
  890. { Always accept if optimising for size }
  891. (cs_opt_size in current_settings.optimizerswitches) or
  892. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  893. (current_settings.optimizecputype >= cpu_Pentium2)
  894. );
  895. {$endif x86_64}
  896. end;
  897. function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  898. begin
  899. if not SuperRegistersEqual(reg1,reg2) then
  900. exit(false);
  901. if getregtype(reg1)<>R_INTREGISTER then
  902. exit(true); {because SuperRegisterEqual is true}
  903. case getsubreg(reg1) of
  904. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  905. higher, it preserves the high bits, so the new value depends on
  906. reg2's previous value. In other words, it is equivalent to doing:
  907. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  908. R_SUBL:
  909. exit(getsubreg(reg2)=R_SUBL);
  910. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  911. higher, it actually does a:
  912. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  913. R_SUBH:
  914. exit(getsubreg(reg2)=R_SUBH);
  915. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  916. bits of reg2:
  917. reg2 := (reg2 and $ffff0000) or word(reg1); }
  918. R_SUBW:
  919. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  920. { a write to R_SUBD always overwrites every other subregister,
  921. because it clears the high 32 bits of R_SUBQ on x86_64 }
  922. R_SUBD,
  923. R_SUBQ:
  924. exit(true);
  925. else
  926. internalerror(2017042801);
  927. end;
  928. end;
  929. function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  930. begin
  931. if not SuperRegistersEqual(reg1,reg2) then
  932. exit(false);
  933. if getregtype(reg1)<>R_INTREGISTER then
  934. exit(true); {because SuperRegisterEqual is true}
  935. case getsubreg(reg1) of
  936. R_SUBL:
  937. exit(getsubreg(reg2)<>R_SUBH);
  938. R_SUBH:
  939. exit(getsubreg(reg2)<>R_SUBL);
  940. R_SUBW,
  941. R_SUBD,
  942. R_SUBQ:
  943. exit(true);
  944. else
  945. internalerror(2017042802);
  946. end;
  947. end;
  948. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  949. var
  950. hp1 : tai;
  951. l : TCGInt;
  952. begin
  953. result:=false;
  954. { changes the code sequence
  955. shr/sar const1, x
  956. shl const2, x
  957. to
  958. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  959. if GetNextInstruction(p, hp1) and
  960. MatchInstruction(hp1,A_SHL,[]) and
  961. (taicpu(p).oper[0]^.typ = top_const) and
  962. (taicpu(hp1).oper[0]^.typ = top_const) and
  963. (taicpu(hp1).opsize = taicpu(p).opsize) and
  964. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  965. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  966. begin
  967. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  968. not(cs_opt_size in current_settings.optimizerswitches) then
  969. begin
  970. { shr/sar const1, %reg
  971. shl const2, %reg
  972. with const1 > const2 }
  973. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  974. taicpu(hp1).opcode := A_AND;
  975. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  976. case taicpu(p).opsize Of
  977. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  978. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  979. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  980. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  981. else
  982. Internalerror(2017050703)
  983. end;
  984. end
  985. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  986. not(cs_opt_size in current_settings.optimizerswitches) then
  987. begin
  988. { shr/sar const1, %reg
  989. shl const2, %reg
  990. with const1 < const2 }
  991. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  992. taicpu(p).opcode := A_AND;
  993. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  994. case taicpu(p).opsize Of
  995. S_B: taicpu(p).loadConst(0,l Xor $ff);
  996. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  997. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  998. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  999. else
  1000. Internalerror(2017050702)
  1001. end;
  1002. end
  1003. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1004. begin
  1005. { shr/sar const1, %reg
  1006. shl const2, %reg
  1007. with const1 = const2 }
  1008. taicpu(p).opcode := A_AND;
  1009. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1010. case taicpu(p).opsize Of
  1011. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1012. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1013. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1014. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1015. else
  1016. Internalerror(2017050701)
  1017. end;
  1018. RemoveInstruction(hp1);
  1019. end;
  1020. end;
  1021. end;
  1022. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1023. var
  1024. opsize : topsize;
  1025. hp1 : tai;
  1026. tmpref : treference;
  1027. ShiftValue : Cardinal;
  1028. BaseValue : TCGInt;
  1029. begin
  1030. result:=false;
  1031. opsize:=taicpu(p).opsize;
  1032. { changes certain "imul const, %reg"'s to lea sequences }
  1033. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1034. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1035. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1036. if (taicpu(p).oper[0]^.val = 1) then
  1037. if (taicpu(p).ops = 2) then
  1038. { remove "imul $1, reg" }
  1039. begin
  1040. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1041. Result := RemoveCurrentP(p);
  1042. end
  1043. else
  1044. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1045. begin
  1046. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1047. InsertLLItem(p.previous, p.next, hp1);
  1048. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1049. p.free;
  1050. p := hp1;
  1051. end
  1052. else if ((taicpu(p).ops <= 2) or
  1053. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1054. not(cs_opt_size in current_settings.optimizerswitches) and
  1055. (not(GetNextInstruction(p, hp1)) or
  1056. not((tai(hp1).typ = ait_instruction) and
  1057. ((taicpu(hp1).opcode=A_Jcc) and
  1058. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1059. begin
  1060. {
  1061. imul X, reg1, reg2 to
  1062. lea (reg1,reg1,Y), reg2
  1063. shl ZZ,reg2
  1064. imul XX, reg1 to
  1065. lea (reg1,reg1,YY), reg1
  1066. shl ZZ,reg2
  1067. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1068. it does not exist as a separate optimization target in FPC though.
  1069. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1070. at most two zeros
  1071. }
  1072. reference_reset(tmpref,1,[]);
  1073. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1074. begin
  1075. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1076. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1077. TmpRef.base := taicpu(p).oper[1]^.reg;
  1078. TmpRef.index := taicpu(p).oper[1]^.reg;
  1079. if not(BaseValue in [3,5,9]) then
  1080. Internalerror(2018110101);
  1081. TmpRef.ScaleFactor := BaseValue-1;
  1082. if (taicpu(p).ops = 2) then
  1083. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1084. else
  1085. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1086. AsmL.InsertAfter(hp1,p);
  1087. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1088. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1089. RemoveCurrentP(p, hp1);
  1090. if ShiftValue>0 then
  1091. AsmL.InsertAfter(taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg),hp1);
  1092. end;
  1093. end;
  1094. end;
  1095. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1096. var
  1097. p: taicpu absolute hp;
  1098. i: Integer;
  1099. begin
  1100. Result := False;
  1101. if not assigned(hp) or
  1102. (hp.typ <> ait_instruction) then
  1103. Exit;
  1104. // p := taicpu(hp);
  1105. Prefetch(insprop[p.opcode]);
  1106. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1107. with insprop[p.opcode] do
  1108. begin
  1109. case getsubreg(reg) of
  1110. R_SUBW,R_SUBD,R_SUBQ:
  1111. Result:=
  1112. RegLoadedWithNewValue(NR_CARRYFLAG,hp) and
  1113. RegLoadedWithNewValue(NR_PARITYFLAG,hp) and
  1114. RegLoadedWithNewValue(NR_AUXILIARYFLAG,hp) and
  1115. RegLoadedWithNewValue(NR_ZEROFLAG,hp) and
  1116. RegLoadedWithNewValue(NR_SIGNFLAG,hp) and
  1117. RegLoadedWithNewValue(NR_OVERFLOWFLAG,hp);
  1118. R_SUBFLAGCARRY:
  1119. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1120. R_SUBFLAGPARITY:
  1121. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1122. R_SUBFLAGAUXILIARY:
  1123. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1124. R_SUBFLAGZERO:
  1125. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1126. R_SUBFLAGSIGN:
  1127. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1128. R_SUBFLAGOVERFLOW:
  1129. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1130. R_SUBFLAGINTERRUPT:
  1131. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1132. R_SUBFLAGDIRECTION:
  1133. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1134. else
  1135. begin
  1136. writeln(getsubreg(reg));
  1137. internalerror(2017050501);
  1138. end;
  1139. end;
  1140. exit;
  1141. end;
  1142. { Handle special cases first }
  1143. case p.opcode of
  1144. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1145. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1146. begin
  1147. Result :=
  1148. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1149. (p.oper[1]^.typ = top_reg) and
  1150. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1151. (
  1152. (p.oper[0]^.typ = top_const) or
  1153. (
  1154. (p.oper[0]^.typ = top_reg) and
  1155. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1156. ) or (
  1157. (p.oper[0]^.typ = top_ref) and
  1158. not RegInRef(reg,p.oper[0]^.ref^)
  1159. )
  1160. );
  1161. end;
  1162. A_MUL, A_IMUL:
  1163. Result :=
  1164. (
  1165. (p.ops=3) and { IMUL only }
  1166. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1167. (
  1168. (
  1169. (p.oper[1]^.typ=top_reg) and
  1170. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1171. ) or (
  1172. (p.oper[1]^.typ=top_ref) and
  1173. not RegInRef(reg,p.oper[1]^.ref^)
  1174. )
  1175. )
  1176. ) or (
  1177. (
  1178. (p.ops=1) and
  1179. (
  1180. (
  1181. (
  1182. (p.oper[0]^.typ=top_reg) and
  1183. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1184. )
  1185. ) or (
  1186. (p.oper[0]^.typ=top_ref) and
  1187. not RegInRef(reg,p.oper[0]^.ref^)
  1188. )
  1189. ) and (
  1190. (
  1191. (p.opsize=S_B) and
  1192. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1193. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1194. ) or (
  1195. (p.opsize=S_W) and
  1196. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1197. ) or (
  1198. (p.opsize=S_L) and
  1199. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1200. {$ifdef x86_64}
  1201. ) or (
  1202. (p.opsize=S_Q) and
  1203. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1204. {$endif x86_64}
  1205. )
  1206. )
  1207. )
  1208. );
  1209. A_CBW:
  1210. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1211. {$ifndef x86_64}
  1212. A_LDS:
  1213. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1214. A_LES:
  1215. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1216. {$endif not x86_64}
  1217. A_LFS:
  1218. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1219. A_LGS:
  1220. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1221. A_LSS:
  1222. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1223. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1224. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1225. A_LODSB:
  1226. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1227. A_LODSW:
  1228. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1229. {$ifdef x86_64}
  1230. A_LODSQ:
  1231. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1232. {$endif x86_64}
  1233. A_LODSD:
  1234. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1235. A_FSTSW, A_FNSTSW:
  1236. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1237. else
  1238. begin
  1239. with insprop[p.opcode] do
  1240. begin
  1241. if (
  1242. { xor %reg,%reg etc. is classed as a new value }
  1243. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1244. MatchOpType(p, top_reg, top_reg) and
  1245. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1246. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1247. ) then
  1248. begin
  1249. Result := True;
  1250. Exit;
  1251. end;
  1252. { Make sure the entire register is overwritten }
  1253. if (getregtype(reg) = R_INTREGISTER) then
  1254. begin
  1255. if (p.ops > 0) then
  1256. begin
  1257. if RegInOp(reg, p.oper[0]^) then
  1258. begin
  1259. if (p.oper[0]^.typ = top_ref) then
  1260. begin
  1261. if RegInRef(reg, p.oper[0]^.ref^) then
  1262. begin
  1263. Result := False;
  1264. Exit;
  1265. end;
  1266. end
  1267. else if (p.oper[0]^.typ = top_reg) then
  1268. begin
  1269. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1270. begin
  1271. Result := False;
  1272. Exit;
  1273. end
  1274. else if ([Ch_WOp1]*Ch<>[]) then
  1275. begin
  1276. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1277. Result := True
  1278. else
  1279. begin
  1280. Result := False;
  1281. Exit;
  1282. end;
  1283. end;
  1284. end;
  1285. end;
  1286. if (p.ops > 1) then
  1287. begin
  1288. if RegInOp(reg, p.oper[1]^) then
  1289. begin
  1290. if (p.oper[1]^.typ = top_ref) then
  1291. begin
  1292. if RegInRef(reg, p.oper[1]^.ref^) then
  1293. begin
  1294. Result := False;
  1295. Exit;
  1296. end;
  1297. end
  1298. else if (p.oper[1]^.typ = top_reg) then
  1299. begin
  1300. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1301. begin
  1302. Result := False;
  1303. Exit;
  1304. end
  1305. else if ([Ch_WOp2]*Ch<>[]) then
  1306. begin
  1307. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1308. Result := True
  1309. else
  1310. begin
  1311. Result := False;
  1312. Exit;
  1313. end;
  1314. end;
  1315. end;
  1316. end;
  1317. if (p.ops > 2) then
  1318. begin
  1319. if RegInOp(reg, p.oper[2]^) then
  1320. begin
  1321. if (p.oper[2]^.typ = top_ref) then
  1322. begin
  1323. if RegInRef(reg, p.oper[2]^.ref^) then
  1324. begin
  1325. Result := False;
  1326. Exit;
  1327. end;
  1328. end
  1329. else if (p.oper[2]^.typ = top_reg) then
  1330. begin
  1331. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1332. begin
  1333. Result := False;
  1334. Exit;
  1335. end
  1336. else if ([Ch_WOp3]*Ch<>[]) then
  1337. begin
  1338. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1339. Result := True
  1340. else
  1341. begin
  1342. Result := False;
  1343. Exit;
  1344. end;
  1345. end;
  1346. end;
  1347. end;
  1348. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1349. begin
  1350. if (p.oper[3]^.typ = top_ref) then
  1351. begin
  1352. if RegInRef(reg, p.oper[3]^.ref^) then
  1353. begin
  1354. Result := False;
  1355. Exit;
  1356. end;
  1357. end
  1358. else if (p.oper[3]^.typ = top_reg) then
  1359. begin
  1360. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1361. begin
  1362. Result := False;
  1363. Exit;
  1364. end
  1365. else if ([Ch_WOp4]*Ch<>[]) then
  1366. begin
  1367. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1368. Result := True
  1369. else
  1370. begin
  1371. Result := False;
  1372. Exit;
  1373. end;
  1374. end;
  1375. end;
  1376. end;
  1377. end;
  1378. end;
  1379. end;
  1380. { Don't do these ones first in case an input operand is equal to an explicit output registers }
  1381. case getsupreg(reg) of
  1382. RS_EAX:
  1383. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1384. begin
  1385. Result := True;
  1386. Exit;
  1387. end;
  1388. RS_ECX:
  1389. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1390. begin
  1391. Result := True;
  1392. Exit;
  1393. end;
  1394. RS_EDX:
  1395. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1396. begin
  1397. Result := True;
  1398. Exit;
  1399. end;
  1400. RS_EBX:
  1401. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1402. begin
  1403. Result := True;
  1404. Exit;
  1405. end;
  1406. RS_ESP:
  1407. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1408. begin
  1409. Result := True;
  1410. Exit;
  1411. end;
  1412. RS_EBP:
  1413. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1414. begin
  1415. Result := True;
  1416. Exit;
  1417. end;
  1418. RS_ESI:
  1419. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1420. begin
  1421. Result := True;
  1422. Exit;
  1423. end;
  1424. RS_EDI:
  1425. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1426. begin
  1427. Result := True;
  1428. Exit;
  1429. end;
  1430. else
  1431. ;
  1432. end;
  1433. end;
  1434. end;
  1435. end;
  1436. end;
  1437. end;
  1438. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1439. var
  1440. hp2,hp3 : tai;
  1441. begin
  1442. { some x86-64 issue a NOP before the real exit code }
  1443. if MatchInstruction(p,A_NOP,[]) then
  1444. GetNextInstruction(p,p);
  1445. result:=assigned(p) and (p.typ=ait_instruction) and
  1446. ((taicpu(p).opcode = A_RET) or
  1447. ((taicpu(p).opcode=A_LEAVE) and
  1448. GetNextInstruction(p,hp2) and
  1449. MatchInstruction(hp2,A_RET,[S_NO])
  1450. ) or
  1451. (((taicpu(p).opcode=A_LEA) and
  1452. MatchOpType(taicpu(p),top_ref,top_reg) and
  1453. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1454. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1455. ) and
  1456. GetNextInstruction(p,hp2) and
  1457. MatchInstruction(hp2,A_RET,[S_NO])
  1458. ) or
  1459. ((((taicpu(p).opcode=A_MOV) and
  1460. MatchOpType(taicpu(p),top_reg,top_reg) and
  1461. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1462. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1463. ((taicpu(p).opcode=A_LEA) and
  1464. MatchOpType(taicpu(p),top_ref,top_reg) and
  1465. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1466. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1467. )
  1468. ) and
  1469. GetNextInstruction(p,hp2) and
  1470. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1471. MatchOpType(taicpu(hp2),top_reg) and
  1472. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1473. GetNextInstruction(hp2,hp3) and
  1474. MatchInstruction(hp3,A_RET,[S_NO])
  1475. )
  1476. );
  1477. end;
  1478. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1479. begin
  1480. isFoldableArithOp := False;
  1481. case hp1.opcode of
  1482. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1483. isFoldableArithOp :=
  1484. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1485. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1486. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1487. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1488. (taicpu(hp1).oper[1]^.reg = reg);
  1489. A_INC,A_DEC,A_NEG,A_NOT:
  1490. isFoldableArithOp :=
  1491. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1492. (taicpu(hp1).oper[0]^.reg = reg);
  1493. else
  1494. ;
  1495. end;
  1496. end;
  1497. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1498. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1499. var
  1500. hp2: tai;
  1501. begin
  1502. hp2 := p;
  1503. repeat
  1504. hp2 := tai(hp2.previous);
  1505. if assigned(hp2) and
  1506. (hp2.typ = ait_regalloc) and
  1507. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1508. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1509. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1510. begin
  1511. RemoveInstruction(hp2);
  1512. break;
  1513. end;
  1514. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1515. end;
  1516. begin
  1517. case current_procinfo.procdef.returndef.typ of
  1518. arraydef,recorddef,pointerdef,
  1519. stringdef,enumdef,procdef,objectdef,errordef,
  1520. filedef,setdef,procvardef,
  1521. classrefdef,forwarddef:
  1522. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1523. orddef:
  1524. if current_procinfo.procdef.returndef.size <> 0 then
  1525. begin
  1526. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1527. { for int64/qword }
  1528. if current_procinfo.procdef.returndef.size = 8 then
  1529. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1530. end;
  1531. else
  1532. ;
  1533. end;
  1534. end;
  1535. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1536. var
  1537. hp1,hp2 : tai;
  1538. begin
  1539. result:=false;
  1540. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1541. begin
  1542. { vmova* reg1,reg1
  1543. =>
  1544. <nop> }
  1545. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1546. begin
  1547. RemoveCurrentP(p);
  1548. result:=true;
  1549. exit;
  1550. end
  1551. else if GetNextInstruction(p,hp1) then
  1552. begin
  1553. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1554. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1555. begin
  1556. { vmova* reg1,reg2
  1557. vmova* reg2,reg3
  1558. dealloc reg2
  1559. =>
  1560. vmova* reg1,reg3 }
  1561. TransferUsedRegs(TmpUsedRegs);
  1562. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1563. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1564. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1565. begin
  1566. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1567. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1568. RemoveInstruction(hp1);
  1569. result:=true;
  1570. exit;
  1571. end
  1572. { special case:
  1573. vmova* reg1,<op>
  1574. vmova* <op>,reg1
  1575. =>
  1576. vmova* reg1,<op> }
  1577. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1578. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1579. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1580. ) then
  1581. begin
  1582. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1583. RemoveInstruction(hp1);
  1584. result:=true;
  1585. exit;
  1586. end
  1587. end
  1588. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  1589. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  1590. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  1591. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  1592. ) and
  1593. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1594. begin
  1595. { vmova* reg1,reg2
  1596. vmovs* reg2,<op>
  1597. dealloc reg2
  1598. =>
  1599. vmovs* reg1,reg3 }
  1600. TransferUsedRegs(TmpUsedRegs);
  1601. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1602. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1603. begin
  1604. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  1605. taicpu(p).opcode:=taicpu(hp1).opcode;
  1606. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1607. RemoveInstruction(hp1);
  1608. result:=true;
  1609. exit;
  1610. end
  1611. end;
  1612. end;
  1613. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  1614. begin
  1615. if MatchInstruction(hp1,[A_VFMADDPD,
  1616. A_VFMADD132PD,
  1617. A_VFMADD132PS,
  1618. A_VFMADD132SD,
  1619. A_VFMADD132SS,
  1620. A_VFMADD213PD,
  1621. A_VFMADD213PS,
  1622. A_VFMADD213SD,
  1623. A_VFMADD213SS,
  1624. A_VFMADD231PD,
  1625. A_VFMADD231PS,
  1626. A_VFMADD231SD,
  1627. A_VFMADD231SS,
  1628. A_VFMADDSUB132PD,
  1629. A_VFMADDSUB132PS,
  1630. A_VFMADDSUB213PD,
  1631. A_VFMADDSUB213PS,
  1632. A_VFMADDSUB231PD,
  1633. A_VFMADDSUB231PS,
  1634. A_VFMSUB132PD,
  1635. A_VFMSUB132PS,
  1636. A_VFMSUB132SD,
  1637. A_VFMSUB132SS,
  1638. A_VFMSUB213PD,
  1639. A_VFMSUB213PS,
  1640. A_VFMSUB213SD,
  1641. A_VFMSUB213SS,
  1642. A_VFMSUB231PD,
  1643. A_VFMSUB231PS,
  1644. A_VFMSUB231SD,
  1645. A_VFMSUB231SS,
  1646. A_VFMSUBADD132PD,
  1647. A_VFMSUBADD132PS,
  1648. A_VFMSUBADD213PD,
  1649. A_VFMSUBADD213PS,
  1650. A_VFMSUBADD231PD,
  1651. A_VFMSUBADD231PS,
  1652. A_VFNMADD132PD,
  1653. A_VFNMADD132PS,
  1654. A_VFNMADD132SD,
  1655. A_VFNMADD132SS,
  1656. A_VFNMADD213PD,
  1657. A_VFNMADD213PS,
  1658. A_VFNMADD213SD,
  1659. A_VFNMADD213SS,
  1660. A_VFNMADD231PD,
  1661. A_VFNMADD231PS,
  1662. A_VFNMADD231SD,
  1663. A_VFNMADD231SS,
  1664. A_VFNMSUB132PD,
  1665. A_VFNMSUB132PS,
  1666. A_VFNMSUB132SD,
  1667. A_VFNMSUB132SS,
  1668. A_VFNMSUB213PD,
  1669. A_VFNMSUB213PS,
  1670. A_VFNMSUB213SD,
  1671. A_VFNMSUB213SS,
  1672. A_VFNMSUB231PD,
  1673. A_VFNMSUB231PS,
  1674. A_VFNMSUB231SD,
  1675. A_VFNMSUB231SS],[S_NO]) and
  1676. { we mix single and double opperations here because we assume that the compiler
  1677. generates vmovapd only after double operations and vmovaps only after single operations }
  1678. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  1679. GetNextInstruction(hp1,hp2) and
  1680. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  1681. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  1682. begin
  1683. TransferUsedRegs(TmpUsedRegs);
  1684. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1685. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1686. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1687. begin
  1688. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  1689. RemoveCurrentP(p, hp1); // <-- Is this actually safe? hp1 is not necessarily the next instruction. [Kit]
  1690. RemoveInstruction(hp2);
  1691. end;
  1692. end
  1693. else if (hp1.typ = ait_instruction) and
  1694. GetNextInstruction(hp1, hp2) and
  1695. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  1696. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  1697. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  1698. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  1699. (((taicpu(p).opcode=A_MOVAPS) and
  1700. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  1701. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  1702. ((taicpu(p).opcode=A_MOVAPD) and
  1703. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  1704. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  1705. ) then
  1706. { change
  1707. movapX reg,reg2
  1708. addsX/subsX/... reg3, reg2
  1709. movapX reg2,reg
  1710. to
  1711. addsX/subsX/... reg3,reg
  1712. }
  1713. begin
  1714. TransferUsedRegs(TmpUsedRegs);
  1715. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1716. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1717. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1718. begin
  1719. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  1720. debug_op2str(taicpu(p).opcode)+' '+
  1721. debug_op2str(taicpu(hp1).opcode)+' '+
  1722. debug_op2str(taicpu(hp2).opcode)+') done',p);
  1723. { we cannot eliminate the first move if
  1724. the operations uses the same register for source and dest }
  1725. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  1726. RemoveCurrentP(p, nil);
  1727. p:=hp1;
  1728. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  1729. RemoveInstruction(hp2);
  1730. result:=true;
  1731. end;
  1732. end;
  1733. end;
  1734. end;
  1735. end;
  1736. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  1737. var
  1738. hp1 : tai;
  1739. begin
  1740. result:=false;
  1741. { replace
  1742. V<Op>X %mreg1,%mreg2,%mreg3
  1743. VMovX %mreg3,%mreg4
  1744. dealloc %mreg3
  1745. by
  1746. V<Op>X %mreg1,%mreg2,%mreg4
  1747. ?
  1748. }
  1749. if GetNextInstruction(p,hp1) and
  1750. { we mix single and double operations here because we assume that the compiler
  1751. generates vmovapd only after double operations and vmovaps only after single operations }
  1752. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  1753. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  1754. (taicpu(hp1).oper[1]^.typ=top_reg) then
  1755. begin
  1756. TransferUsedRegs(TmpUsedRegs);
  1757. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1758. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  1759. begin
  1760. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  1761. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  1762. RemoveInstruction(hp1);
  1763. result:=true;
  1764. end;
  1765. end;
  1766. end;
  1767. { Replaces all references to AOldReg in a memory reference to ANewReg }
  1768. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  1769. begin
  1770. Result := False;
  1771. { For safety reasons, only check for exact register matches }
  1772. { Check base register }
  1773. if (ref.base = AOldReg) then
  1774. begin
  1775. ref.base := ANewReg;
  1776. Result := True;
  1777. end;
  1778. { Check index register }
  1779. if (ref.index = AOldReg) then
  1780. begin
  1781. ref.index := ANewReg;
  1782. Result := True;
  1783. end;
  1784. end;
  1785. { Replaces all references to AOldReg in an operand to ANewReg }
  1786. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  1787. var
  1788. OldSupReg, NewSupReg: TSuperRegister;
  1789. OldSubReg, NewSubReg: TSubRegister;
  1790. OldRegType: TRegisterType;
  1791. ThisOper: POper;
  1792. begin
  1793. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  1794. Result := False;
  1795. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  1796. InternalError(2020011801);
  1797. OldSupReg := getsupreg(AOldReg);
  1798. OldSubReg := getsubreg(AOldReg);
  1799. OldRegType := getregtype(AOldReg);
  1800. NewSupReg := getsupreg(ANewReg);
  1801. NewSubReg := getsubreg(ANewReg);
  1802. if OldRegType <> getregtype(ANewReg) then
  1803. InternalError(2020011802);
  1804. if OldSubReg <> NewSubReg then
  1805. InternalError(2020011803);
  1806. case ThisOper^.typ of
  1807. top_reg:
  1808. if (
  1809. (ThisOper^.reg = AOldReg) or
  1810. (
  1811. (OldRegType = R_INTREGISTER) and
  1812. (getsupreg(ThisOper^.reg) = OldSupReg) and
  1813. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  1814. (
  1815. (getsubreg(ThisOper^.reg) <= OldSubReg)
  1816. {$ifndef x86_64}
  1817. and (
  1818. { Under i386 and i8086, ESI, EDI, EBP and ESP
  1819. don't have an 8-bit representation }
  1820. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  1821. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  1822. )
  1823. {$endif x86_64}
  1824. )
  1825. )
  1826. ) then
  1827. begin
  1828. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  1829. Result := True;
  1830. end;
  1831. top_ref:
  1832. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  1833. Result := True;
  1834. else
  1835. ;
  1836. end;
  1837. end;
  1838. { Replaces all references to AOldReg in an instruction to ANewReg }
  1839. function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  1840. const
  1841. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  1842. var
  1843. OperIdx: Integer;
  1844. begin
  1845. Result := False;
  1846. for OperIdx := 0 to p.ops - 1 do
  1847. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) and
  1848. { The shift and rotate instructions can only use CL }
  1849. not (
  1850. (OperIdx = 0) and
  1851. { This second condition just helps to avoid unnecessarily
  1852. calling MatchInstruction for 10 different opcodes }
  1853. (p.oper[0]^.reg = NR_CL) and
  1854. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  1855. ) then
  1856. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  1857. end;
  1858. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean; inline;
  1859. begin
  1860. Result :=
  1861. (ref^.index = NR_NO) and
  1862. (
  1863. {$ifdef x86_64}
  1864. (
  1865. (ref^.base = NR_RIP) and
  1866. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  1867. ) or
  1868. {$endif x86_64}
  1869. (ref^.base = NR_STACK_POINTER_REG) or
  1870. (ref^.base = current_procinfo.framepointer)
  1871. );
  1872. end;
  1873. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  1874. var
  1875. l: asizeint;
  1876. begin
  1877. Result := False;
  1878. { Should have been checked previously }
  1879. if p.opcode <> A_LEA then
  1880. InternalError(2020072501);
  1881. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  1882. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  1883. not(cs_opt_size in current_settings.optimizerswitches) then
  1884. exit;
  1885. with p.oper[0]^.ref^ do
  1886. begin
  1887. if (base <> p.oper[1]^.reg) or
  1888. (index <> NR_NO) or
  1889. assigned(symbol) then
  1890. exit;
  1891. l:=offset;
  1892. if (l=1) and UseIncDec then
  1893. begin
  1894. p.opcode:=A_INC;
  1895. p.loadreg(0,p.oper[1]^.reg);
  1896. p.ops:=1;
  1897. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  1898. end
  1899. else if (l=-1) and UseIncDec then
  1900. begin
  1901. p.opcode:=A_DEC;
  1902. p.loadreg(0,p.oper[1]^.reg);
  1903. p.ops:=1;
  1904. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  1905. end
  1906. else
  1907. begin
  1908. if (l<0) and (l<>-2147483648) then
  1909. begin
  1910. p.opcode:=A_SUB;
  1911. p.loadConst(0,-l);
  1912. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  1913. end
  1914. else
  1915. begin
  1916. p.opcode:=A_ADD;
  1917. p.loadConst(0,l);
  1918. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  1919. end;
  1920. end;
  1921. end;
  1922. Result := True;
  1923. end;
  1924. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  1925. var
  1926. CurrentReg, ReplaceReg: TRegister;
  1927. begin
  1928. Result := False;
  1929. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  1930. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  1931. case hp.opcode of
  1932. A_FSTSW, A_FNSTSW,
  1933. A_IN, A_INS, A_OUT, A_OUTS,
  1934. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  1935. { These routines have explicit operands, but they are restricted in
  1936. what they can be (e.g. IN and OUT can only read from AL, AX or
  1937. EAX. }
  1938. Exit;
  1939. A_IMUL:
  1940. begin
  1941. { The 1-operand version writes to implicit registers
  1942. The 2-operand version reads from the first operator, and reads
  1943. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  1944. the 3-operand version reads from a register that it doesn't write to
  1945. }
  1946. case hp.ops of
  1947. 1:
  1948. if (
  1949. (
  1950. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  1951. ) or
  1952. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  1953. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  1954. begin
  1955. Result := True;
  1956. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  1957. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  1958. end;
  1959. 2:
  1960. { Only modify the first parameter }
  1961. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  1962. begin
  1963. Result := True;
  1964. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  1965. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  1966. end;
  1967. 3:
  1968. { Only modify the second parameter }
  1969. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  1970. begin
  1971. Result := True;
  1972. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  1973. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  1974. end;
  1975. else
  1976. InternalError(2020012901);
  1977. end;
  1978. end;
  1979. else
  1980. if (hp.ops > 0) and
  1981. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  1982. begin
  1983. Result := True;
  1984. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  1985. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  1986. end;
  1987. end;
  1988. end;
  1989. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  1990. var
  1991. hp1, hp2, hp3: tai;
  1992. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  1993. begin
  1994. if taicpu(hp1).opcode = signed_movop then
  1995. begin
  1996. if taicpu(p).oper[0]^.val > max_value shr 1 then
  1997. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  1998. end
  1999. else
  2000. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2001. end;
  2002. var
  2003. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2004. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2005. NewSize: topsize;
  2006. CurrentReg: TRegister;
  2007. begin
  2008. Result:=false;
  2009. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2010. { remove mov reg1,reg1? }
  2011. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2012. then
  2013. begin
  2014. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2015. { take care of the register (de)allocs following p }
  2016. RemoveCurrentP(p, hp1);
  2017. Result:=true;
  2018. exit;
  2019. end;
  2020. { All the next optimisations require a next instruction }
  2021. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2022. Exit;
  2023. { Look for:
  2024. mov %reg1,%reg2
  2025. ??? %reg2,r/m
  2026. Change to:
  2027. mov %reg1,%reg2
  2028. ??? %reg1,r/m
  2029. }
  2030. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2031. begin
  2032. CurrentReg := taicpu(p).oper[1]^.reg;
  2033. if RegReadByInstruction(CurrentReg, hp1) and
  2034. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2035. begin
  2036. TransferUsedRegs(TmpUsedRegs);
  2037. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2038. if not RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs) and
  2039. { Just in case something didn't get modified (e.g. an
  2040. implicit register) }
  2041. not RegReadByInstruction(CurrentReg, hp1) then
  2042. begin
  2043. { We can remove the original MOV }
  2044. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2045. RemoveCurrentp(p, hp1);
  2046. { UsedRegs got updated by RemoveCurrentp }
  2047. Result := True;
  2048. Exit;
  2049. end;
  2050. { If we know a MOV instruction has become a null operation, we might as well
  2051. get rid of it now to save time. }
  2052. if (taicpu(hp1).opcode = A_MOV) and
  2053. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2054. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2055. { Just being a register is enough to confirm it's a null operation }
  2056. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2057. begin
  2058. Result := True;
  2059. { Speed-up to reduce a pipeline stall... if we had something like...
  2060. movl %eax,%edx
  2061. movw %dx,%ax
  2062. ... the second instruction would change to movw %ax,%ax, but
  2063. given that it is now %ax that's active rather than %eax,
  2064. penalties might occur due to a partial register write, so instead,
  2065. change it to a MOVZX instruction when optimising for speed.
  2066. }
  2067. if not (cs_opt_size in current_settings.optimizerswitches) and
  2068. IsMOVZXAcceptable and
  2069. (taicpu(hp1).opsize < taicpu(p).opsize)
  2070. {$ifdef x86_64}
  2071. { operations already implicitly set the upper 64 bits to zero }
  2072. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2073. {$endif x86_64}
  2074. then
  2075. begin
  2076. CurrentReg := taicpu(hp1).oper[1]^.reg;
  2077. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2078. case taicpu(p).opsize of
  2079. S_W:
  2080. if taicpu(hp1).opsize = S_B then
  2081. taicpu(hp1).opsize := S_BL
  2082. else
  2083. InternalError(2020012911);
  2084. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2085. case taicpu(hp1).opsize of
  2086. S_B:
  2087. taicpu(hp1).opsize := S_BL;
  2088. S_W:
  2089. taicpu(hp1).opsize := S_WL;
  2090. else
  2091. InternalError(2020012912);
  2092. end;
  2093. else
  2094. InternalError(2020012910);
  2095. end;
  2096. taicpu(hp1).opcode := A_MOVZX;
  2097. taicpu(hp1).oper[1]^.reg := newreg(getregtype(CurrentReg), getsupreg(CurrentReg), R_SUBD)
  2098. end
  2099. else
  2100. begin
  2101. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2102. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2103. RemoveInstruction(hp1);
  2104. { The instruction after what was hp1 is now the immediate next instruction,
  2105. so we can continue to make optimisations if it's present }
  2106. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2107. Exit;
  2108. hp1 := hp2;
  2109. end;
  2110. end;
  2111. end;
  2112. end;
  2113. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2114. overwrites the original destination register. e.g.
  2115. movl ###,%reg2d
  2116. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2117. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2118. }
  2119. if (taicpu(p).oper[1]^.typ = top_reg) and
  2120. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2121. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2122. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2123. begin
  2124. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2125. begin
  2126. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2127. case taicpu(p).oper[0]^.typ of
  2128. top_const:
  2129. { We have something like:
  2130. movb $x, %regb
  2131. movzbl %regb,%regd
  2132. Change to:
  2133. movl $x, %regd
  2134. }
  2135. begin
  2136. case taicpu(hp1).opsize of
  2137. S_BW:
  2138. begin
  2139. convert_mov_value(A_MOVSX, $FF);
  2140. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2141. taicpu(p).opsize := S_W;
  2142. end;
  2143. S_BL:
  2144. begin
  2145. convert_mov_value(A_MOVSX, $FF);
  2146. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2147. taicpu(p).opsize := S_L;
  2148. end;
  2149. S_WL:
  2150. begin
  2151. convert_mov_value(A_MOVSX, $FFFF);
  2152. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2153. taicpu(p).opsize := S_L;
  2154. end;
  2155. {$ifdef x86_64}
  2156. S_BQ:
  2157. begin
  2158. convert_mov_value(A_MOVSX, $FF);
  2159. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2160. taicpu(p).opsize := S_Q;
  2161. end;
  2162. S_WQ:
  2163. begin
  2164. convert_mov_value(A_MOVSX, $FFFF);
  2165. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2166. taicpu(p).opsize := S_Q;
  2167. end;
  2168. S_LQ:
  2169. begin
  2170. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2171. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2172. taicpu(p).opsize := S_Q;
  2173. end;
  2174. {$endif x86_64}
  2175. else
  2176. { If hp1 was a MOV instruction, it should have been
  2177. optimised already }
  2178. InternalError(2020021001);
  2179. end;
  2180. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2181. RemoveInstruction(hp1);
  2182. Result := True;
  2183. Exit;
  2184. end;
  2185. top_ref:
  2186. { We have something like:
  2187. movb mem, %regb
  2188. movzbl %regb,%regd
  2189. Change to:
  2190. movzbl mem, %regd
  2191. }
  2192. if (taicpu(p).oper[0]^.ref^.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2193. begin
  2194. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2195. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  2196. RemoveCurrentP(p, hp1);
  2197. Result:=True;
  2198. Exit;
  2199. end;
  2200. else
  2201. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2202. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2203. Exit;
  2204. end;
  2205. end
  2206. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2207. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2208. optimised }
  2209. else
  2210. begin
  2211. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2212. RemoveCurrentP(p, hp1);
  2213. Result := True;
  2214. Exit;
  2215. end;
  2216. end;
  2217. if (taicpu(hp1).opcode = A_AND) and
  2218. (taicpu(p).oper[1]^.typ = top_reg) and
  2219. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2220. begin
  2221. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2222. begin
  2223. case taicpu(p).opsize of
  2224. S_L:
  2225. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2226. begin
  2227. { Optimize out:
  2228. mov x, %reg
  2229. and ffffffffh, %reg
  2230. }
  2231. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2232. RemoveInstruction(hp1);
  2233. Result:=true;
  2234. exit;
  2235. end;
  2236. S_Q: { TODO: Confirm if this is even possible }
  2237. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2238. begin
  2239. { Optimize out:
  2240. mov x, %reg
  2241. and ffffffffffffffffh, %reg
  2242. }
  2243. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2244. RemoveInstruction(hp1);
  2245. Result:=true;
  2246. exit;
  2247. end;
  2248. else
  2249. ;
  2250. end;
  2251. if ((taicpu(p).oper[0]^.typ=top_reg) or
  2252. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  2253. GetNextInstruction(hp1,hp2) and
  2254. MatchInstruction(hp2,A_TEST,[taicpu(p).opsize]) and
  2255. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) and
  2256. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) and
  2257. GetNextInstruction(hp2,hp3) and
  2258. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2259. (taicpu(hp3).condition in [C_E,C_NE]) then
  2260. begin
  2261. TransferUsedRegs(TmpUsedRegs);
  2262. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2263. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2264. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2265. begin
  2266. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2267. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2268. taicpu(hp1).opcode:=A_TEST;
  2269. RemoveInstruction(hp2);
  2270. RemoveCurrentP(p, hp1);
  2271. Result:=true;
  2272. exit;
  2273. end;
  2274. end;
  2275. end
  2276. else if IsMOVZXAcceptable and
  2277. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  2278. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  2279. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  2280. then
  2281. begin
  2282. InputVal := debug_operstr(taicpu(p).oper[0]^);
  2283. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  2284. case taicpu(p).opsize of
  2285. S_B:
  2286. if (taicpu(hp1).oper[0]^.val = $ff) then
  2287. begin
  2288. { Convert:
  2289. movb x, %regl movb x, %regl
  2290. andw ffh, %regw andl ffh, %regd
  2291. To:
  2292. movzbw x, %regd movzbl x, %regd
  2293. (Identical registers, just different sizes)
  2294. }
  2295. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  2296. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  2297. case taicpu(hp1).opsize of
  2298. S_W: NewSize := S_BW;
  2299. S_L: NewSize := S_BL;
  2300. {$ifdef x86_64}
  2301. S_Q: NewSize := S_BQ;
  2302. {$endif x86_64}
  2303. else
  2304. InternalError(2018011510);
  2305. end;
  2306. end
  2307. else
  2308. NewSize := S_NO;
  2309. S_W:
  2310. if (taicpu(hp1).oper[0]^.val = $ffff) then
  2311. begin
  2312. { Convert:
  2313. movw x, %regw
  2314. andl ffffh, %regd
  2315. To:
  2316. movzwl x, %regd
  2317. (Identical registers, just different sizes)
  2318. }
  2319. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  2320. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  2321. case taicpu(hp1).opsize of
  2322. S_L: NewSize := S_WL;
  2323. {$ifdef x86_64}
  2324. S_Q: NewSize := S_WQ;
  2325. {$endif x86_64}
  2326. else
  2327. InternalError(2018011511);
  2328. end;
  2329. end
  2330. else
  2331. NewSize := S_NO;
  2332. else
  2333. NewSize := S_NO;
  2334. end;
  2335. if NewSize <> S_NO then
  2336. begin
  2337. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  2338. { The actual optimization }
  2339. taicpu(p).opcode := A_MOVZX;
  2340. taicpu(p).changeopsize(NewSize);
  2341. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  2342. { Safeguard if "and" is followed by a conditional command }
  2343. TransferUsedRegs(TmpUsedRegs);
  2344. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  2345. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  2346. begin
  2347. { At this point, the "and" command is effectively equivalent to
  2348. "test %reg,%reg". This will be handled separately by the
  2349. Peephole Optimizer. [Kit] }
  2350. DebugMsg(SPeepholeOptimization + PreMessage +
  2351. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2352. end
  2353. else
  2354. begin
  2355. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  2356. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2357. RemoveInstruction(hp1);
  2358. end;
  2359. Result := True;
  2360. Exit;
  2361. end;
  2362. end;
  2363. end;
  2364. { Next instruction is also a MOV ? }
  2365. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  2366. begin
  2367. if (taicpu(p).oper[1]^.typ = top_reg) and
  2368. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2369. begin
  2370. CurrentReg := taicpu(p).oper[1]^.reg;
  2371. TransferUsedRegs(TmpUsedRegs);
  2372. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2373. { we have
  2374. mov x, %treg
  2375. mov %treg, y
  2376. }
  2377. if not(RegInOp(CurrentReg, taicpu(hp1).oper[1]^)) then
  2378. if not(RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs)) then
  2379. { we've got
  2380. mov x, %treg
  2381. mov %treg, y
  2382. with %treg is not used after }
  2383. case taicpu(p).oper[0]^.typ Of
  2384. { top_reg is covered by DeepMOVOpt }
  2385. top_const:
  2386. begin
  2387. { change
  2388. mov const, %treg
  2389. mov %treg, y
  2390. to
  2391. mov const, y
  2392. }
  2393. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  2394. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  2395. begin
  2396. if taicpu(hp1).oper[1]^.typ=top_reg then
  2397. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2398. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  2399. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  2400. RemoveInstruction(hp1);
  2401. Result:=true;
  2402. Exit;
  2403. end;
  2404. end;
  2405. top_ref:
  2406. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  2407. begin
  2408. { change
  2409. mov mem, %treg
  2410. mov %treg, %reg
  2411. to
  2412. mov mem, %reg"
  2413. }
  2414. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2415. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  2416. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  2417. RemoveInstruction(hp1);
  2418. Result:=true;
  2419. Exit;
  2420. end;
  2421. else
  2422. ;
  2423. end
  2424. else
  2425. { %treg is used afterwards, but all eventualities
  2426. other than the first MOV instruction being a constant
  2427. are covered by DeepMOVOpt, so only check for that }
  2428. if (taicpu(p).oper[0]^.typ = top_const) and
  2429. (
  2430. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  2431. not (cs_opt_size in current_settings.optimizerswitches) or
  2432. (taicpu(hp1).opsize = S_B)
  2433. ) and
  2434. (
  2435. (taicpu(hp1).oper[1]^.typ = top_reg) or
  2436. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  2437. ) then
  2438. begin
  2439. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  2440. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  2441. end;
  2442. end;
  2443. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  2444. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  2445. { mov reg1, mem1 or mov mem1, reg1
  2446. mov mem2, reg2 mov reg2, mem2}
  2447. begin
  2448. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  2449. { mov reg1, mem1 or mov mem1, reg1
  2450. mov mem2, reg1 mov reg2, mem1}
  2451. begin
  2452. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  2453. { Removes the second statement from
  2454. mov reg1, mem1/reg2
  2455. mov mem1/reg2, reg1 }
  2456. begin
  2457. if taicpu(p).oper[0]^.typ=top_reg then
  2458. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  2459. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  2460. RemoveInstruction(hp1);
  2461. Result:=true;
  2462. exit;
  2463. end
  2464. else
  2465. begin
  2466. TransferUsedRegs(TmpUsedRegs);
  2467. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2468. if (taicpu(p).oper[1]^.typ = top_ref) and
  2469. { mov reg1, mem1
  2470. mov mem2, reg1 }
  2471. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  2472. GetNextInstruction(hp1, hp2) and
  2473. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  2474. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  2475. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  2476. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  2477. { change to
  2478. mov reg1, mem1 mov reg1, mem1
  2479. mov mem2, reg1 cmp reg1, mem2
  2480. cmp mem1, reg1
  2481. }
  2482. begin
  2483. RemoveInstruction(hp2);
  2484. taicpu(hp1).opcode := A_CMP;
  2485. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  2486. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  2487. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  2488. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  2489. end;
  2490. end;
  2491. end
  2492. else if (taicpu(p).oper[1]^.typ=top_ref) and
  2493. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  2494. begin
  2495. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  2496. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  2497. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  2498. end
  2499. else
  2500. begin
  2501. TransferUsedRegs(TmpUsedRegs);
  2502. if GetNextInstruction(hp1, hp2) and
  2503. MatchOpType(taicpu(p),top_ref,top_reg) and
  2504. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  2505. (taicpu(hp1).oper[1]^.typ = top_ref) and
  2506. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  2507. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  2508. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  2509. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  2510. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  2511. { mov mem1, %reg1
  2512. mov %reg1, mem2
  2513. mov mem2, reg2
  2514. to:
  2515. mov mem1, reg2
  2516. mov reg2, mem2}
  2517. begin
  2518. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  2519. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  2520. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  2521. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  2522. RemoveInstruction(hp2);
  2523. end
  2524. {$ifdef i386}
  2525. { this is enabled for i386 only, as the rules to create the reg sets below
  2526. are too complicated for x86-64, so this makes this code too error prone
  2527. on x86-64
  2528. }
  2529. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  2530. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  2531. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  2532. { mov mem1, reg1 mov mem1, reg1
  2533. mov reg1, mem2 mov reg1, mem2
  2534. mov mem2, reg2 mov mem2, reg1
  2535. to: to:
  2536. mov mem1, reg1 mov mem1, reg1
  2537. mov mem1, reg2 mov reg1, mem2
  2538. mov reg1, mem2
  2539. or (if mem1 depends on reg1
  2540. and/or if mem2 depends on reg2)
  2541. to:
  2542. mov mem1, reg1
  2543. mov reg1, mem2
  2544. mov reg1, reg2
  2545. }
  2546. begin
  2547. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  2548. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  2549. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  2550. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  2551. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  2552. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  2553. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  2554. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  2555. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  2556. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  2557. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  2558. end
  2559. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  2560. begin
  2561. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  2562. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  2563. end
  2564. else
  2565. begin
  2566. RemoveInstruction(hp2);
  2567. end
  2568. {$endif i386}
  2569. ;
  2570. end;
  2571. end
  2572. { movl [mem1],reg1
  2573. movl [mem1],reg2
  2574. to
  2575. movl [mem1],reg1
  2576. movl reg1,reg2
  2577. }
  2578. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  2579. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2580. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2581. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2582. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2583. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2584. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2585. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2586. begin
  2587. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2588. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2589. end;
  2590. { movl const1,[mem1]
  2591. movl [mem1],reg1
  2592. to
  2593. movl const1,reg1
  2594. movl reg1,[mem1]
  2595. }
  2596. if MatchOpType(Taicpu(p),top_const,top_ref) and
  2597. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  2598. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2599. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  2600. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  2601. begin
  2602. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2603. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  2604. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  2605. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  2606. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  2607. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  2608. Result:=true;
  2609. exit;
  2610. end;
  2611. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  2612. end;
  2613. { search further than the next instruction for a mov }
  2614. if
  2615. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  2616. (taicpu(p).oper[1]^.typ = top_reg) and
  2617. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  2618. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  2619. begin
  2620. { we work with hp2 here, so hp1 can be still used later on when
  2621. checking for GetNextInstruction_p }
  2622. hp3 := hp1;
  2623. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  2624. CrossJump := False;
  2625. while GetNextInstructionUsingRegCond(hp3,hp2,taicpu(p).oper[1]^.reg,CrossJump) and
  2626. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  2627. (hp2.typ=ait_instruction) do
  2628. begin
  2629. case taicpu(hp2).opcode of
  2630. A_MOV:
  2631. if MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^.reg) and
  2632. ((taicpu(p).oper[0]^.typ=top_const) or
  2633. ((taicpu(p).oper[0]^.typ=top_reg) and
  2634. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  2635. )
  2636. ) then
  2637. begin
  2638. { we have
  2639. mov x, %treg
  2640. mov %treg, y
  2641. }
  2642. TransferUsedRegs(TmpUsedRegs);
  2643. TmpUsedRegs[R_INTREGISTER].Update(tai(p.Next));
  2644. { We don't need to call UpdateUsedRegs for every instruction between
  2645. p and hp2 because the register we're concerned about will not
  2646. become deallocated (otherwise GetNextInstructionUsingReg would
  2647. have stopped at an earlier instruction). [Kit] }
  2648. TempRegUsed :=
  2649. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  2650. RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) or
  2651. RegReadByInstruction(taicpu(p).oper[1]^.reg, hp1);
  2652. case taicpu(p).oper[0]^.typ Of
  2653. top_reg:
  2654. begin
  2655. { change
  2656. mov %reg, %treg
  2657. mov %treg, y
  2658. to
  2659. mov %reg, y
  2660. }
  2661. CurrentReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  2662. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  2663. if taicpu(hp2).oper[1]^.reg = CurrentReg then
  2664. begin
  2665. { %reg = y - remove hp2 completely (doing it here instead of relying on
  2666. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  2667. if TempRegUsed then
  2668. begin
  2669. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  2670. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  2671. { Set the start of the next GetNextInstructionUsingRegCond search
  2672. to start at the entry right before hp2 (which is about to be removed) }
  2673. hp3 := tai(hp2.Previous);
  2674. RemoveInstruction(hp2);
  2675. { See if there's more we can optimise }
  2676. Continue;
  2677. end
  2678. else
  2679. begin
  2680. RemoveInstruction(hp2);
  2681. { We can remove the original MOV too }
  2682. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  2683. RemoveCurrentP(p, hp1);
  2684. Result:=true;
  2685. Exit;
  2686. end;
  2687. end
  2688. else
  2689. begin
  2690. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  2691. taicpu(hp2).loadReg(0, CurrentReg);
  2692. if TempRegUsed then
  2693. begin
  2694. { Don't remove the first instruction if the temporary register is in use }
  2695. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(CurrentReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  2696. { No need to set Result to True. If there's another instruction later on
  2697. that can be optimised, it will be detected when the main Pass 1 loop
  2698. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  2699. end
  2700. else
  2701. begin
  2702. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  2703. RemoveCurrentP(p, hp1);
  2704. Result:=true;
  2705. Exit;
  2706. end;
  2707. end;
  2708. end;
  2709. top_const:
  2710. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  2711. begin
  2712. { change
  2713. mov const, %treg
  2714. mov %treg, y
  2715. to
  2716. mov const, y
  2717. }
  2718. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  2719. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  2720. begin
  2721. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  2722. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  2723. if TempRegUsed then
  2724. begin
  2725. { Don't remove the first instruction if the temporary register is in use }
  2726. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  2727. { No need to set Result to True. If there's another instruction later on
  2728. that can be optimised, it will be detected when the main Pass 1 loop
  2729. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  2730. end
  2731. else
  2732. begin
  2733. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  2734. RemoveCurrentP(p, hp1);
  2735. Result:=true;
  2736. Exit;
  2737. end;
  2738. end;
  2739. end;
  2740. else
  2741. Internalerror(2019103001);
  2742. end;
  2743. end;
  2744. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  2745. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  2746. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  2747. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2748. begin
  2749. {
  2750. Change from:
  2751. mov ###, %reg
  2752. ...
  2753. movs/z %reg,%reg (Same register, just different sizes)
  2754. To:
  2755. movs/z ###, %reg (Longer version)
  2756. ...
  2757. (remove)
  2758. }
  2759. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  2760. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  2761. { Keep the first instruction as mov if ### is a constant }
  2762. if taicpu(p).oper[0]^.typ = top_const then
  2763. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  2764. else
  2765. begin
  2766. taicpu(p).opcode := taicpu(hp2).opcode;
  2767. taicpu(p).opsize := taicpu(hp2).opsize;
  2768. end;
  2769. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  2770. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  2771. RemoveInstruction(hp2);
  2772. Result := True;
  2773. Exit;
  2774. end;
  2775. else
  2776. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2777. begin
  2778. CurrentReg := taicpu(p).oper[1]^.reg;
  2779. TransferUsedRegs(TmpUsedRegs);
  2780. TmpUsedRegs[R_INTREGISTER].Update(tai(p.Next));
  2781. if
  2782. not RegModifiedByInstruction(taicpu(p).oper[0]^.reg, hp1) and
  2783. not RegModifiedBetween(taicpu(p).oper[0]^.reg, hp1, hp2) and
  2784. DeepMovOpt(taicpu(p), taicpu(hp2)) then
  2785. begin
  2786. { Just in case something didn't get modified (e.g. an
  2787. implicit register) }
  2788. if not RegReadByInstruction(CurrentReg, hp2) and
  2789. { If a conditional jump was crossed, do not delete
  2790. the original MOV no matter what }
  2791. not CrossJump then
  2792. begin
  2793. TransferUsedRegs(TmpUsedRegs);
  2794. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2795. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2796. if
  2797. { Make sure the original register isn't still present
  2798. and has been written to (e.g. with SHRX) }
  2799. RegLoadedWithNewValue(CurrentReg, hp2) or
  2800. not RegUsedAfterInstruction(CurrentReg, hp2, TmpUsedRegs) then
  2801. begin
  2802. { We can remove the original MOV }
  2803. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  2804. RemoveCurrentp(p, hp1);
  2805. Result := True;
  2806. Exit;
  2807. end
  2808. else
  2809. begin
  2810. { See if there's more we can optimise }
  2811. hp3 := hp2;
  2812. Continue;
  2813. end;
  2814. end;
  2815. end;
  2816. end;
  2817. end;
  2818. { Break out of the while loop under normal circumstances }
  2819. Break;
  2820. end;
  2821. end;
  2822. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  2823. (taicpu(p).oper[1]^.typ = top_reg) and
  2824. (taicpu(p).opsize = S_L) and
  2825. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  2826. (taicpu(hp2).opcode = A_AND) and
  2827. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  2828. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2829. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  2830. ) then
  2831. begin
  2832. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  2833. begin
  2834. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  2835. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  2836. begin
  2837. { Optimize out:
  2838. mov x, %reg
  2839. and ffffffffh, %reg
  2840. }
  2841. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  2842. RemoveInstruction(hp2);
  2843. Result:=true;
  2844. exit;
  2845. end;
  2846. end;
  2847. end;
  2848. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  2849. x >= RetOffset) as it doesn't do anything (it writes either to a
  2850. parameter or to the temporary storage room for the function
  2851. result)
  2852. }
  2853. if IsExitCode(hp1) and
  2854. (taicpu(p).oper[1]^.typ = top_ref) and
  2855. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  2856. (
  2857. (
  2858. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  2859. not (
  2860. assigned(current_procinfo.procdef.funcretsym) and
  2861. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  2862. )
  2863. ) or
  2864. { Also discard writes to the stack that are below the base pointer,
  2865. as this is temporary storage rather than a function result on the
  2866. stack, say. }
  2867. (
  2868. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  2869. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  2870. )
  2871. ) then
  2872. begin
  2873. RemoveCurrentp(p, hp1);
  2874. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  2875. RemoveLastDeallocForFuncRes(p);
  2876. Result:=true;
  2877. exit;
  2878. end;
  2879. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  2880. begin
  2881. if MatchOpType(taicpu(p),top_reg,top_ref) and
  2882. (taicpu(hp1).oper[1]^.typ = top_ref) and
  2883. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  2884. begin
  2885. { change
  2886. mov reg1, mem1
  2887. test/cmp x, mem1
  2888. to
  2889. mov reg1, mem1
  2890. test/cmp x, reg1
  2891. }
  2892. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  2893. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  2894. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  2895. Result := True;
  2896. Exit;
  2897. end;
  2898. if MatchOpType(taicpu(p),top_ref,top_reg) and
  2899. { The x86 assemblers have difficulty comparing values against absolute addresses }
  2900. (taicpu(p).oper[0]^.ref^.refaddr in [addr_no, addr_pic, addr_pic_no_got]) and
  2901. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  2902. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  2903. (
  2904. (
  2905. (taicpu(hp1).opcode = A_TEST)
  2906. ) or (
  2907. (taicpu(hp1).opcode = A_CMP) and
  2908. { A sanity check more than anything }
  2909. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  2910. )
  2911. ) then
  2912. begin
  2913. { change
  2914. mov mem, %reg
  2915. cmp/test x, %reg / test %reg,%reg
  2916. (reg deallocated)
  2917. to
  2918. cmp/test x, mem / cmp 0, mem
  2919. }
  2920. TransferUsedRegs(TmpUsedRegs);
  2921. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2922. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  2923. begin
  2924. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  2925. if (taicpu(hp1).opcode = A_TEST) and
  2926. (
  2927. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  2928. MatchOperand(taicpu(hp1).oper[0]^, -1)
  2929. ) then
  2930. begin
  2931. taicpu(hp1).opcode := A_CMP;
  2932. taicpu(hp1).loadconst(0, 0);
  2933. end;
  2934. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  2935. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  2936. RemoveCurrentP(p, hp1);
  2937. Result := True;
  2938. Exit;
  2939. end;
  2940. end;
  2941. end;
  2942. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  2943. { If the flags register is in use, don't change the instruction to an
  2944. ADD otherwise this will scramble the flags. [Kit] }
  2945. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  2946. begin
  2947. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  2948. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  2949. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  2950. ) or
  2951. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  2952. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  2953. )
  2954. ) then
  2955. { mov reg1,ref
  2956. lea reg2,[reg1,reg2]
  2957. to
  2958. add reg2,ref}
  2959. begin
  2960. TransferUsedRegs(TmpUsedRegs);
  2961. { reg1 may not be used afterwards }
  2962. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  2963. begin
  2964. Taicpu(hp1).opcode:=A_ADD;
  2965. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  2966. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  2967. RemoveCurrentp(p, hp1);
  2968. result:=true;
  2969. exit;
  2970. end;
  2971. end;
  2972. { If the LEA instruction can be converted into an arithmetic instruction,
  2973. it may be possible to then fold it in the next optimisation, otherwise
  2974. there's nothing more that can be optimised here. }
  2975. if not ConvertLEA(taicpu(hp1)) then
  2976. Exit;
  2977. end;
  2978. if (taicpu(p).oper[1]^.typ = top_reg) and
  2979. (hp1.typ = ait_instruction) and
  2980. GetNextInstruction(hp1, hp2) and
  2981. MatchInstruction(hp2,A_MOV,[]) and
  2982. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  2983. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  2984. (
  2985. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  2986. {$ifdef x86_64}
  2987. or
  2988. (
  2989. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  2990. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  2991. )
  2992. {$endif x86_64}
  2993. ) then
  2994. begin
  2995. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2996. (taicpu(hp2).oper[0]^.typ=top_reg) then
  2997. { change movsX/movzX reg/ref, reg2
  2998. add/sub/or/... reg3/$const, reg2
  2999. mov reg2 reg/ref
  3000. dealloc reg2
  3001. to
  3002. add/sub/or/... reg3/$const, reg/ref }
  3003. begin
  3004. TransferUsedRegs(TmpUsedRegs);
  3005. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3006. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3007. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3008. begin
  3009. { by example:
  3010. movswl %si,%eax movswl %si,%eax p
  3011. decl %eax addl %edx,%eax hp1
  3012. movw %ax,%si movw %ax,%si hp2
  3013. ->
  3014. movswl %si,%eax movswl %si,%eax p
  3015. decw %eax addw %edx,%eax hp1
  3016. movw %ax,%si movw %ax,%si hp2
  3017. }
  3018. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  3019. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3020. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3021. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3022. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3023. {
  3024. ->
  3025. movswl %si,%eax movswl %si,%eax p
  3026. decw %si addw %dx,%si hp1
  3027. movw %ax,%si movw %ax,%si hp2
  3028. }
  3029. case taicpu(hp1).ops of
  3030. 1:
  3031. begin
  3032. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3033. if taicpu(hp1).oper[0]^.typ=top_reg then
  3034. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3035. end;
  3036. 2:
  3037. begin
  3038. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3039. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3040. (taicpu(hp1).opcode<>A_SHL) and
  3041. (taicpu(hp1).opcode<>A_SHR) and
  3042. (taicpu(hp1).opcode<>A_SAR) then
  3043. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3044. end;
  3045. else
  3046. internalerror(2008042701);
  3047. end;
  3048. {
  3049. ->
  3050. decw %si addw %dx,%si p
  3051. }
  3052. RemoveInstruction(hp2);
  3053. RemoveCurrentP(p, hp1);
  3054. Result:=True;
  3055. Exit;
  3056. end;
  3057. end;
  3058. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3059. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  3060. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  3061. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  3062. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  3063. )
  3064. {$ifdef i386}
  3065. { byte registers of esi, edi, ebp, esp are not available on i386 }
  3066. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3067. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3068. {$endif i386}
  3069. then
  3070. { change movsX/movzX reg/ref, reg2
  3071. add/sub/or/... regX/$const, reg2
  3072. mov reg2, reg3
  3073. dealloc reg2
  3074. to
  3075. movsX/movzX reg/ref, reg3
  3076. add/sub/or/... reg3/$const, reg3
  3077. }
  3078. begin
  3079. TransferUsedRegs(TmpUsedRegs);
  3080. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3081. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3082. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3083. begin
  3084. { by example:
  3085. movswl %si,%eax movswl %si,%eax p
  3086. decl %eax addl %edx,%eax hp1
  3087. movw %ax,%si movw %ax,%si hp2
  3088. ->
  3089. movswl %si,%eax movswl %si,%eax p
  3090. decw %eax addw %edx,%eax hp1
  3091. movw %ax,%si movw %ax,%si hp2
  3092. }
  3093. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  3094. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3095. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3096. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3097. { limit size of constants as well to avoid assembler errors, but
  3098. check opsize to avoid overflow when left shifting the 1 }
  3099. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  3100. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  3101. {$ifdef x86_64}
  3102. { Be careful of, for example:
  3103. movl %reg1,%reg2
  3104. addl %reg3,%reg2
  3105. movq %reg2,%reg4
  3106. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  3107. }
  3108. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  3109. begin
  3110. taicpu(hp2).changeopsize(S_L);
  3111. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  3112. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  3113. end;
  3114. {$endif x86_64}
  3115. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3116. taicpu(p).changeopsize(taicpu(hp2).opsize);
  3117. if taicpu(p).oper[0]^.typ=top_reg then
  3118. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3119. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  3120. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  3121. {
  3122. ->
  3123. movswl %si,%eax movswl %si,%eax p
  3124. decw %si addw %dx,%si hp1
  3125. movw %ax,%si movw %ax,%si hp2
  3126. }
  3127. case taicpu(hp1).ops of
  3128. 1:
  3129. begin
  3130. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3131. if taicpu(hp1).oper[0]^.typ=top_reg then
  3132. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3133. end;
  3134. 2:
  3135. begin
  3136. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3137. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3138. (taicpu(hp1).opcode<>A_SHL) and
  3139. (taicpu(hp1).opcode<>A_SHR) and
  3140. (taicpu(hp1).opcode<>A_SAR) then
  3141. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3142. end;
  3143. else
  3144. internalerror(2018111801);
  3145. end;
  3146. {
  3147. ->
  3148. decw %si addw %dx,%si p
  3149. }
  3150. RemoveInstruction(hp2);
  3151. end;
  3152. end;
  3153. end;
  3154. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  3155. GetNextInstruction(hp1, hp2) and
  3156. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  3157. MatchOperand(Taicpu(p).oper[0]^,0) and
  3158. (Taicpu(p).oper[1]^.typ = top_reg) and
  3159. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  3160. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  3161. { mov reg1,0
  3162. bts reg1,operand1 --> mov reg1,operand2
  3163. or reg1,operand2 bts reg1,operand1}
  3164. begin
  3165. Taicpu(hp2).opcode:=A_MOV;
  3166. asml.remove(hp1);
  3167. insertllitem(hp2,hp2.next,hp1);
  3168. RemoveCurrentp(p, hp1);
  3169. Result:=true;
  3170. exit;
  3171. end;
  3172. {$ifdef x86_64}
  3173. { Convert:
  3174. movq x(ref),%reg64
  3175. shrq y,%reg64
  3176. To:
  3177. movq x+4(ref),%reg32
  3178. shrq y-32,%reg32 (Remove if y = 32)
  3179. }
  3180. if (taicpu(p).opsize = S_Q) and
  3181. (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  3182. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFB) and
  3183. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  3184. MatchOpType(taicpu(hp1), top_const, top_reg) and
  3185. (taicpu(hp1).oper[0]^.val >= 32) and
  3186. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  3187. begin
  3188. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  3189. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  3190. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  3191. { Convert to 32-bit }
  3192. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3193. taicpu(p).opsize := S_L;
  3194. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  3195. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  3196. if (taicpu(hp1).oper[0]^.val = 32) then
  3197. begin
  3198. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  3199. RemoveInstruction(hp1);
  3200. end
  3201. else
  3202. begin
  3203. { This will potentially open up more arithmetic operations since
  3204. the peephole optimizer now has a big hint that only the lower
  3205. 32 bits are currently in use (and opcodes are smaller in size) }
  3206. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3207. taicpu(hp1).opsize := S_L;
  3208. Dec(taicpu(hp1).oper[0]^.val, 32);
  3209. DebugMsg(SPeepholeOptimization + PreMessage +
  3210. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  3211. end;
  3212. Result := True;
  3213. Exit;
  3214. end;
  3215. {$endif x86_64}
  3216. end;
  3217. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  3218. var
  3219. hp1 : tai;
  3220. begin
  3221. Result:=false;
  3222. if taicpu(p).ops <> 2 then
  3223. exit;
  3224. if GetNextInstruction(p,hp1) and
  3225. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  3226. (taicpu(hp1).ops = 2) then
  3227. begin
  3228. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3229. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3230. { movXX reg1, mem1 or movXX mem1, reg1
  3231. movXX mem2, reg2 movXX reg2, mem2}
  3232. begin
  3233. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3234. { movXX reg1, mem1 or movXX mem1, reg1
  3235. movXX mem2, reg1 movXX reg2, mem1}
  3236. begin
  3237. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3238. begin
  3239. { Removes the second statement from
  3240. movXX reg1, mem1/reg2
  3241. movXX mem1/reg2, reg1
  3242. }
  3243. if taicpu(p).oper[0]^.typ=top_reg then
  3244. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3245. { Removes the second statement from
  3246. movXX mem1/reg1, reg2
  3247. movXX reg2, mem1/reg1
  3248. }
  3249. if (taicpu(p).oper[1]^.typ=top_reg) and
  3250. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  3251. begin
  3252. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  3253. RemoveInstruction(hp1);
  3254. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  3255. end
  3256. else
  3257. begin
  3258. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  3259. RemoveInstruction(hp1);
  3260. end;
  3261. Result:=true;
  3262. exit;
  3263. end
  3264. end;
  3265. end;
  3266. end;
  3267. end;
  3268. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  3269. var
  3270. hp1 : tai;
  3271. begin
  3272. result:=false;
  3273. { replace
  3274. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  3275. MovX %mreg2,%mreg1
  3276. dealloc %mreg2
  3277. by
  3278. <Op>X %mreg2,%mreg1
  3279. ?
  3280. }
  3281. if GetNextInstruction(p,hp1) and
  3282. { we mix single and double opperations here because we assume that the compiler
  3283. generates vmovapd only after double operations and vmovaps only after single operations }
  3284. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  3285. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3286. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  3287. (taicpu(p).oper[0]^.typ=top_reg) then
  3288. begin
  3289. TransferUsedRegs(TmpUsedRegs);
  3290. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3291. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3292. begin
  3293. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  3294. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  3295. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  3296. RemoveInstruction(hp1);
  3297. result:=true;
  3298. end;
  3299. end;
  3300. end;
  3301. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  3302. var
  3303. hp1, p_label, p_dist, hp1_dist: tai;
  3304. JumpLabel, JumpLabel_dist: TAsmLabel;
  3305. begin
  3306. Result := False;
  3307. if (taicpu(p).oper[1]^.typ = top_reg) then
  3308. begin
  3309. if GetNextInstruction(p, hp1) and
  3310. MatchInstruction(hp1,A_MOV,[]) and
  3311. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  3312. (
  3313. (taicpu(p).oper[0]^.typ <> top_reg) or
  3314. not RegInInstruction(taicpu(p).oper[0]^.reg, hp1)
  3315. ) then
  3316. begin
  3317. { If we have something like:
  3318. test %reg1,%reg1
  3319. mov 0,%reg2
  3320. And no registers are shared (the two %reg1's can be different, as
  3321. long as neither of them are also %reg2), move the MOV command to
  3322. before the comparison as this means it can be optimised without
  3323. worrying about the FLAGS register. (This combination is generated
  3324. by "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  3325. }
  3326. SwapMovCmp(p, hp1);
  3327. Result := True;
  3328. Exit;
  3329. end;
  3330. { Search for:
  3331. test %reg,%reg
  3332. j(c1) @lbl1
  3333. ...
  3334. @lbl:
  3335. test %reg,%reg (same register)
  3336. j(c2) @lbl2
  3337. If c2 is a subset of c1, change to:
  3338. test %reg,%reg
  3339. j(c1) @lbl2
  3340. (@lbl1 may become a dead label as a result)
  3341. }
  3342. if (taicpu(p).oper[0]^.typ = top_reg) and
  3343. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  3344. MatchInstruction(hp1, A_JCC, []) and
  3345. IsJumpToLabel(taicpu(hp1)) then
  3346. begin
  3347. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  3348. p_label := nil;
  3349. if Assigned(JumpLabel) then
  3350. p_label := getlabelwithsym(JumpLabel);
  3351. if Assigned(p_label) and
  3352. GetNextInstruction(p_label, p_dist) and
  3353. MatchInstruction(p_dist, A_TEST, []) and
  3354. { It's fine if the second test uses smaller sub-registers }
  3355. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  3356. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  3357. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  3358. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  3359. GetNextInstruction(p_dist, hp1_dist) and
  3360. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  3361. begin
  3362. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  3363. if JumpLabel = JumpLabel_dist then
  3364. { This is an infinite loop }
  3365. Exit;
  3366. { Best optimisation when the first condition is a subset (or equal) of the second }
  3367. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  3368. begin
  3369. { Any registers used here will already be allocated }
  3370. if Assigned(JumpLabel_dist) then
  3371. JumpLabel_dist.IncRefs;
  3372. if Assigned(JumpLabel) then
  3373. JumpLabel.DecRefs;
  3374. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  3375. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  3376. Result := True;
  3377. Exit;
  3378. end;
  3379. end;
  3380. end;
  3381. end;
  3382. end;
  3383. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  3384. var
  3385. hp1 : tai;
  3386. begin
  3387. result:=false;
  3388. { replace
  3389. addX const,%reg1
  3390. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  3391. dealloc %reg1
  3392. by
  3393. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  3394. }
  3395. if MatchOpType(taicpu(p),top_const,top_reg) and
  3396. GetNextInstruction(p,hp1) and
  3397. MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  3398. ((taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.base) or
  3399. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index)) then
  3400. begin
  3401. TransferUsedRegs(TmpUsedRegs);
  3402. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3403. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3404. begin
  3405. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  3406. if taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.base then
  3407. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  3408. if taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index then
  3409. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  3410. RemoveCurrentP(p);
  3411. result:=true;
  3412. end;
  3413. end;
  3414. end;
  3415. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  3416. var
  3417. hp1: tai;
  3418. ref: Integer;
  3419. saveref: treference;
  3420. TempReg: TRegister;
  3421. Multiple: TCGInt;
  3422. begin
  3423. Result:=false;
  3424. { removes seg register prefixes from LEA operations, as they
  3425. don't do anything}
  3426. taicpu(p).oper[0]^.ref^.Segment:=NR_NO;
  3427. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  3428. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3429. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  3430. (
  3431. { do not mess with leas accessing the stack pointer
  3432. unless it's a null operation }
  3433. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  3434. (
  3435. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  3436. (taicpu(p).oper[0]^.ref^.offset = 0)
  3437. )
  3438. ) and
  3439. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  3440. begin
  3441. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  3442. begin
  3443. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  3444. begin
  3445. hp1:=taicpu.op_reg_reg(A_MOV,taicpu(p).opsize,taicpu(p).oper[0]^.ref^.base,
  3446. taicpu(p).oper[1]^.reg);
  3447. InsertLLItem(p.previous,p.next, hp1);
  3448. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',hp1);
  3449. p.free;
  3450. p:=hp1;
  3451. end
  3452. else
  3453. begin
  3454. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  3455. RemoveCurrentP(p);
  3456. end;
  3457. Result:=true;
  3458. exit;
  3459. end
  3460. else if (
  3461. { continue to use lea to adjust the stack pointer,
  3462. it is the recommended way, but only if not optimizing for size }
  3463. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  3464. (cs_opt_size in current_settings.optimizerswitches)
  3465. ) and
  3466. { If the flags register is in use, don't change the instruction
  3467. to an ADD otherwise this will scramble the flags. [Kit] }
  3468. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  3469. ConvertLEA(taicpu(p)) then
  3470. begin
  3471. Result:=true;
  3472. exit;
  3473. end;
  3474. end;
  3475. if GetNextInstruction(p,hp1) and
  3476. (hp1.typ=ait_instruction) then
  3477. begin
  3478. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  3479. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3480. MatchOpType(Taicpu(hp1),top_reg,top_reg) and
  3481. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) then
  3482. begin
  3483. TransferUsedRegs(TmpUsedRegs);
  3484. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3485. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3486. begin
  3487. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  3488. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  3489. RemoveInstruction(hp1);
  3490. result:=true;
  3491. exit;
  3492. end;
  3493. end;
  3494. { changes
  3495. lea <ref1>, reg1
  3496. <op> ...,<ref. with reg1>,...
  3497. to
  3498. <op> ...,<ref1>,... }
  3499. if (taicpu(p).oper[1]^.reg<>current_procinfo.framepointer) and
  3500. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) and
  3501. not(MatchInstruction(hp1,A_LEA,[])) then
  3502. begin
  3503. { find a reference which uses reg1 }
  3504. 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
  3505. ref:=0
  3506. 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
  3507. ref:=1
  3508. else
  3509. ref:=-1;
  3510. if (ref<>-1) and
  3511. { reg1 must be either the base or the index }
  3512. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  3513. begin
  3514. { reg1 can be removed from the reference }
  3515. saveref:=taicpu(hp1).oper[ref]^.ref^;
  3516. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  3517. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  3518. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  3519. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  3520. else
  3521. Internalerror(2019111201);
  3522. { check if the can insert all data of the lea into the second instruction }
  3523. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  3524. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  3525. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  3526. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  3527. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  3528. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  3529. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  3530. {$ifdef x86_64}
  3531. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  3532. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  3533. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  3534. )
  3535. {$endif x86_64}
  3536. then
  3537. begin
  3538. { reg1 might not used by the second instruction after it is remove from the reference }
  3539. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  3540. begin
  3541. TransferUsedRegs(TmpUsedRegs);
  3542. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3543. { reg1 is not updated so it might not be used afterwards }
  3544. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3545. begin
  3546. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  3547. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  3548. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  3549. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  3550. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  3551. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  3552. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  3553. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  3554. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  3555. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  3556. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  3557. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  3558. RemoveCurrentP(p, hp1);
  3559. result:=true;
  3560. exit;
  3561. end
  3562. end;
  3563. end;
  3564. { recover }
  3565. taicpu(hp1).oper[ref]^.ref^:=saveref;
  3566. end;
  3567. end;
  3568. end;
  3569. { for now, we do not mess with the stack pointer, thought it might be usefull to remove
  3570. unneeded lea sequences on the stack pointer, it needs to be tested in detail }
  3571. if (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) and
  3572. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  3573. begin
  3574. { Check common LEA/LEA conditions }
  3575. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  3576. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  3577. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  3578. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  3579. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  3580. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  3581. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  3582. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  3583. (
  3584. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  3585. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  3586. ) and (
  3587. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  3588. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  3589. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  3590. ) then
  3591. begin
  3592. { changes
  3593. lea (regX,scale), reg1
  3594. lea offset(reg1,reg1), reg1
  3595. to
  3596. lea offset(regX,scale*2), reg1
  3597. and
  3598. lea (regX,scale1), reg1
  3599. lea offset(reg1,scale2), reg1
  3600. to
  3601. lea offset(regX,scale1*scale2), reg1
  3602. ... so long as the final scale does not exceed 8
  3603. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  3604. }
  3605. if (taicpu(p).oper[0]^.ref^.offset = 0) and
  3606. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  3607. (
  3608. (
  3609. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  3610. ) or (
  3611. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  3612. (
  3613. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  3614. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  3615. )
  3616. )
  3617. ) and (
  3618. (
  3619. { lea (reg1,scale2), reg1 variant }
  3620. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  3621. (
  3622. (
  3623. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  3624. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  3625. ) or (
  3626. { lea (regX,regX), reg1 variant }
  3627. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3628. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  3629. )
  3630. )
  3631. ) or (
  3632. { lea (reg1,reg1), reg1 variant }
  3633. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  3634. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  3635. )
  3636. ) then
  3637. begin
  3638. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  3639. { Make everything homogeneous to make calculations easier }
  3640. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  3641. begin
  3642. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  3643. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  3644. taicpu(p).oper[0]^.ref^.scalefactor := 2
  3645. else
  3646. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  3647. taicpu(p).oper[0]^.ref^.base := NR_NO;
  3648. end;
  3649. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  3650. begin
  3651. { Just to prevent miscalculations }
  3652. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  3653. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  3654. else
  3655. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  3656. end
  3657. else
  3658. begin
  3659. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  3660. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  3661. end;
  3662. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  3663. RemoveCurrentP(p);
  3664. result:=true;
  3665. exit;
  3666. end
  3667. { changes
  3668. lea offset1(regX), reg1
  3669. lea offset2(reg1), reg1
  3670. to
  3671. lea offset1+offset2(regX), reg1 }
  3672. else if
  3673. (
  3674. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  3675. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  3676. ) or (
  3677. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  3678. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  3679. (
  3680. (
  3681. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  3682. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  3683. ) or (
  3684. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  3685. (
  3686. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  3687. (
  3688. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  3689. (
  3690. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  3691. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  3692. )
  3693. )
  3694. )
  3695. )
  3696. )
  3697. ) then
  3698. begin
  3699. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  3700. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  3701. begin
  3702. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  3703. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  3704. { if the register is used as index and base, we have to increase for base as well
  3705. and adapt base }
  3706. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  3707. begin
  3708. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  3709. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  3710. end;
  3711. end
  3712. else
  3713. begin
  3714. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  3715. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  3716. end;
  3717. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  3718. begin
  3719. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  3720. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  3721. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  3722. end;
  3723. RemoveCurrentP(p);
  3724. result:=true;
  3725. exit;
  3726. end;
  3727. end;
  3728. { Change:
  3729. leal/q $x(%reg1),%reg2
  3730. ...
  3731. shll/q $y,%reg2
  3732. To:
  3733. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  3734. }
  3735. if MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  3736. MatchOpType(taicpu(hp1), top_const, top_reg) and
  3737. (taicpu(hp1).oper[0]^.val <= 3) then
  3738. begin
  3739. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  3740. TransferUsedRegs(TmpUsedRegs);
  3741. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3742. TempReg := taicpu(hp1).oper[1]^.reg; { Store locally to reduce the number of dereferences }
  3743. if
  3744. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  3745. (this works even if scalefactor is zero) }
  3746. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  3747. { Ensure offset doesn't go out of bounds }
  3748. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  3749. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  3750. MatchOperand(taicpu(p).oper[1]^, TempReg) and
  3751. (
  3752. (
  3753. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, TempReg) and
  3754. (
  3755. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  3756. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  3757. (
  3758. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  3759. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  3760. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  3761. )
  3762. )
  3763. ) or (
  3764. (
  3765. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  3766. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  3767. ) and
  3768. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, TempReg)
  3769. )
  3770. ) then
  3771. begin
  3772. repeat
  3773. with taicpu(p).oper[0]^.ref^ do
  3774. begin
  3775. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  3776. if index = base then
  3777. begin
  3778. if Multiple > 4 then
  3779. { Optimisation will no longer work because resultant
  3780. scale factor will exceed 8 }
  3781. Break;
  3782. base := NR_NO;
  3783. scalefactor := 2;
  3784. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  3785. end
  3786. else if (base <> NR_NO) and (base <> NR_INVALID) then
  3787. begin
  3788. { Scale factor only works on the index register }
  3789. index := base;
  3790. base := NR_NO;
  3791. end;
  3792. { For safety }
  3793. if scalefactor <= 1 then
  3794. begin
  3795. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  3796. scalefactor := Multiple;
  3797. end
  3798. else
  3799. begin
  3800. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  3801. scalefactor := scalefactor * Multiple;
  3802. end;
  3803. offset := offset * Multiple;
  3804. end;
  3805. RemoveInstruction(hp1);
  3806. Result := True;
  3807. Exit;
  3808. { This repeat..until loop exists for the benefit of Break }
  3809. until True;
  3810. end;
  3811. end;
  3812. end;
  3813. end;
  3814. function TX86AsmOptimizer.DoSubAddOpt(var p: tai): Boolean;
  3815. var
  3816. hp1 : tai;
  3817. begin
  3818. DoSubAddOpt := False;
  3819. if GetLastInstruction(p, hp1) and
  3820. (hp1.typ = ait_instruction) and
  3821. (taicpu(hp1).opsize = taicpu(p).opsize) then
  3822. case taicpu(hp1).opcode Of
  3823. A_DEC:
  3824. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  3825. MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3826. begin
  3827. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+1);
  3828. RemoveInstruction(hp1);
  3829. end;
  3830. A_SUB:
  3831. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  3832. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  3833. begin
  3834. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val);
  3835. RemoveInstruction(hp1);
  3836. end;
  3837. A_ADD:
  3838. begin
  3839. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  3840. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  3841. begin
  3842. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  3843. RemoveInstruction(hp1);
  3844. if (taicpu(p).oper[0]^.val = 0) then
  3845. begin
  3846. hp1 := tai(p.next);
  3847. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  3848. if not GetLastInstruction(hp1, p) then
  3849. p := hp1;
  3850. DoSubAddOpt := True;
  3851. end
  3852. end;
  3853. end;
  3854. else
  3855. ;
  3856. end;
  3857. end;
  3858. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  3859. {$ifdef i386}
  3860. var
  3861. hp1 : tai;
  3862. {$endif i386}
  3863. begin
  3864. Result:=false;
  3865. { * change "subl $2, %esp; pushw x" to "pushl x"}
  3866. { * change "sub/add const1, reg" or "dec reg" followed by
  3867. "sub const2, reg" to one "sub ..., reg" }
  3868. if MatchOpType(taicpu(p),top_const,top_reg) then
  3869. begin
  3870. {$ifdef i386}
  3871. if (taicpu(p).oper[0]^.val = 2) and
  3872. (taicpu(p).oper[1]^.reg = NR_ESP) and
  3873. { Don't do the sub/push optimization if the sub }
  3874. { comes from setting up the stack frame (JM) }
  3875. (not(GetLastInstruction(p,hp1)) or
  3876. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  3877. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  3878. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  3879. begin
  3880. hp1 := tai(p.next);
  3881. while Assigned(hp1) and
  3882. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  3883. not RegReadByInstruction(NR_ESP,hp1) and
  3884. not RegModifiedByInstruction(NR_ESP,hp1) do
  3885. hp1 := tai(hp1.next);
  3886. if Assigned(hp1) and
  3887. MatchInstruction(hp1,A_PUSH,[S_W]) then
  3888. begin
  3889. taicpu(hp1).changeopsize(S_L);
  3890. if taicpu(hp1).oper[0]^.typ=top_reg then
  3891. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  3892. hp1 := tai(p.next);
  3893. RemoveCurrentp(p, hp1);
  3894. Result:=true;
  3895. exit;
  3896. end;
  3897. end;
  3898. {$endif i386}
  3899. if DoSubAddOpt(p) then
  3900. Result:=true;
  3901. end;
  3902. end;
  3903. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  3904. var
  3905. TmpBool1,TmpBool2 : Boolean;
  3906. tmpref : treference;
  3907. hp1,hp2: tai;
  3908. mask: tcgint;
  3909. begin
  3910. Result:=false;
  3911. { All these optimisations work on "shl/sal const,%reg" }
  3912. if not MatchOpType(taicpu(p),top_const,top_reg) then
  3913. Exit;
  3914. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  3915. (taicpu(p).oper[0]^.val <= 3) then
  3916. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  3917. begin
  3918. { should we check the next instruction? }
  3919. TmpBool1 := True;
  3920. { have we found an add/sub which could be
  3921. integrated in the lea? }
  3922. TmpBool2 := False;
  3923. reference_reset(tmpref,2,[]);
  3924. TmpRef.index := taicpu(p).oper[1]^.reg;
  3925. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  3926. while TmpBool1 and
  3927. GetNextInstruction(p, hp1) and
  3928. (tai(hp1).typ = ait_instruction) and
  3929. ((((taicpu(hp1).opcode = A_ADD) or
  3930. (taicpu(hp1).opcode = A_SUB)) and
  3931. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  3932. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  3933. (((taicpu(hp1).opcode = A_INC) or
  3934. (taicpu(hp1).opcode = A_DEC)) and
  3935. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  3936. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  3937. ((taicpu(hp1).opcode = A_LEA) and
  3938. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  3939. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  3940. (not GetNextInstruction(hp1,hp2) or
  3941. not instrReadsFlags(hp2)) Do
  3942. begin
  3943. TmpBool1 := False;
  3944. if taicpu(hp1).opcode=A_LEA then
  3945. begin
  3946. if (TmpRef.base = NR_NO) and
  3947. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  3948. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  3949. (taicpu(hp1).oper[0]^.ref^.segment=NR_NO) and
  3950. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  3951. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  3952. begin
  3953. TmpBool1 := True;
  3954. TmpBool2 := True;
  3955. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  3956. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  3957. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  3958. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  3959. RemoveInstruction(hp1);
  3960. end
  3961. end
  3962. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  3963. begin
  3964. TmpBool1 := True;
  3965. TmpBool2 := True;
  3966. case taicpu(hp1).opcode of
  3967. A_ADD:
  3968. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  3969. A_SUB:
  3970. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  3971. else
  3972. internalerror(2019050536);
  3973. end;
  3974. RemoveInstruction(hp1);
  3975. end
  3976. else
  3977. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  3978. (((taicpu(hp1).opcode = A_ADD) and
  3979. (TmpRef.base = NR_NO)) or
  3980. (taicpu(hp1).opcode = A_INC) or
  3981. (taicpu(hp1).opcode = A_DEC)) then
  3982. begin
  3983. TmpBool1 := True;
  3984. TmpBool2 := True;
  3985. case taicpu(hp1).opcode of
  3986. A_ADD:
  3987. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  3988. A_INC:
  3989. inc(TmpRef.offset);
  3990. A_DEC:
  3991. dec(TmpRef.offset);
  3992. else
  3993. internalerror(2019050535);
  3994. end;
  3995. RemoveInstruction(hp1);
  3996. end;
  3997. end;
  3998. if TmpBool2
  3999. {$ifndef x86_64}
  4000. or
  4001. ((current_settings.optimizecputype < cpu_Pentium2) and
  4002. (taicpu(p).oper[0]^.val <= 3) and
  4003. not(cs_opt_size in current_settings.optimizerswitches))
  4004. {$endif x86_64}
  4005. then
  4006. begin
  4007. if not(TmpBool2) and
  4008. (taicpu(p).oper[0]^.val=1) then
  4009. begin
  4010. hp1:=taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  4011. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  4012. end
  4013. else
  4014. hp1:=taicpu.op_ref_reg(A_LEA, taicpu(p).opsize, TmpRef,
  4015. taicpu(p).oper[1]^.reg);
  4016. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  4017. InsertLLItem(p.previous, p.next, hp1);
  4018. p.free;
  4019. p := hp1;
  4020. end;
  4021. end
  4022. {$ifndef x86_64}
  4023. else if (current_settings.optimizecputype < cpu_Pentium2) then
  4024. begin
  4025. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  4026. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  4027. (unlike shl, which is only Tairable in the U pipe) }
  4028. if taicpu(p).oper[0]^.val=1 then
  4029. begin
  4030. hp1 := taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  4031. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg);
  4032. InsertLLItem(p.previous, p.next, hp1);
  4033. p.free;
  4034. p := hp1;
  4035. end
  4036. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  4037. "shl $3, %reg" to "lea (,%reg,8), %reg }
  4038. else if (taicpu(p).opsize = S_L) and
  4039. (taicpu(p).oper[0]^.val<= 3) then
  4040. begin
  4041. reference_reset(tmpref,2,[]);
  4042. TmpRef.index := taicpu(p).oper[1]^.reg;
  4043. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  4044. hp1 := taicpu.Op_ref_reg(A_LEA,S_L,TmpRef, taicpu(p).oper[1]^.reg);
  4045. InsertLLItem(p.previous, p.next, hp1);
  4046. p.free;
  4047. p := hp1;
  4048. end;
  4049. end
  4050. {$endif x86_64}
  4051. else if
  4052. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  4053. (
  4054. (
  4055. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  4056. SetAndTest(hp1, hp2)
  4057. {$ifdef x86_64}
  4058. ) or
  4059. (
  4060. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  4061. GetNextInstruction(hp1, hp2) and
  4062. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  4063. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4064. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  4065. {$endif x86_64}
  4066. )
  4067. ) and
  4068. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  4069. begin
  4070. { Change:
  4071. shl x, %reg1
  4072. mov -(1<<x), %reg2
  4073. and %reg2, %reg1
  4074. Or:
  4075. shl x, %reg1
  4076. and -(1<<x), %reg1
  4077. To just:
  4078. shl x, %reg1
  4079. Since the and operation only zeroes bits that are already zero from the shl operation
  4080. }
  4081. case taicpu(p).oper[0]^.val of
  4082. 8:
  4083. mask:=$FFFFFFFFFFFFFF00;
  4084. 16:
  4085. mask:=$FFFFFFFFFFFF0000;
  4086. 32:
  4087. mask:=$FFFFFFFF00000000;
  4088. 63:
  4089. { Constant pre-calculated to prevent overflow errors with Int64 }
  4090. mask:=$8000000000000000;
  4091. else
  4092. begin
  4093. if taicpu(p).oper[0]^.val >= 64 then
  4094. { Shouldn't happen realistically, since the register
  4095. is guaranteed to be set to zero at this point }
  4096. mask := 0
  4097. else
  4098. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  4099. end;
  4100. end;
  4101. if taicpu(hp1).oper[0]^.val = mask then
  4102. begin
  4103. { Everything checks out, perform the optimisation, as long as
  4104. the FLAGS register isn't being used}
  4105. TransferUsedRegs(TmpUsedRegs);
  4106. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4107. {$ifdef x86_64}
  4108. if (hp1 <> hp2) then
  4109. begin
  4110. { "shl/mov/and" version }
  4111. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4112. { Don't do the optimisation if the FLAGS register is in use }
  4113. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  4114. begin
  4115. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  4116. { Don't remove the 'mov' instruction if its register is used elsewhere }
  4117. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  4118. begin
  4119. RemoveInstruction(hp1);
  4120. Result := True;
  4121. end;
  4122. { Only set Result to True if the 'mov' instruction was removed }
  4123. RemoveInstruction(hp2);
  4124. end;
  4125. end
  4126. else
  4127. {$endif x86_64}
  4128. begin
  4129. { "shl/and" version }
  4130. { Don't do the optimisation if the FLAGS register is in use }
  4131. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  4132. begin
  4133. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  4134. RemoveInstruction(hp1);
  4135. Result := True;
  4136. end;
  4137. end;
  4138. Exit;
  4139. end
  4140. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  4141. begin
  4142. { Even if the mask doesn't allow for its removal, we might be
  4143. able to optimise the mask for the "shl/and" version, which
  4144. may permit other peephole optimisations }
  4145. {$ifdef DEBUG_AOPTCPU}
  4146. mask := taicpu(hp1).oper[0]^.val and mask;
  4147. if taicpu(hp1).oper[0]^.val <> mask then
  4148. begin
  4149. DebugMsg(
  4150. SPeepholeOptimization +
  4151. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  4152. ' to $' + debug_tostr(mask) +
  4153. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  4154. taicpu(hp1).oper[0]^.val := mask;
  4155. end;
  4156. {$else DEBUG_AOPTCPU}
  4157. { If debugging is off, just set the operand even if it's the same }
  4158. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  4159. {$endif DEBUG_AOPTCPU}
  4160. end;
  4161. end;
  4162. end;
  4163. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  4164. var
  4165. CurrentRef: TReference;
  4166. FullReg: TRegister;
  4167. hp1, hp2: tai;
  4168. begin
  4169. Result := False;
  4170. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  4171. Exit;
  4172. { We assume you've checked if the operand is actually a reference by
  4173. this point. If it isn't, you'll most likely get an access violation }
  4174. CurrentRef := first_mov.oper[1]^.ref^;
  4175. { Memory must be aligned }
  4176. if (CurrentRef.offset mod 4) <> 0 then
  4177. Exit;
  4178. Inc(CurrentRef.offset);
  4179. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  4180. if MatchOperand(second_mov.oper[0]^, 0) and
  4181. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  4182. GetNextInstruction(second_mov, hp1) and
  4183. (hp1.typ = ait_instruction) and
  4184. (taicpu(hp1).opcode = A_MOV) and
  4185. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4186. (taicpu(hp1).oper[0]^.val = 0) then
  4187. begin
  4188. Inc(CurrentRef.offset);
  4189. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  4190. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  4191. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  4192. begin
  4193. case taicpu(hp1).opsize of
  4194. S_B:
  4195. if GetNextInstruction(hp1, hp2) and
  4196. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  4197. MatchOpType(taicpu(hp2), top_const, top_ref) and
  4198. (taicpu(hp2).oper[0]^.val = 0) then
  4199. begin
  4200. Inc(CurrentRef.offset);
  4201. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  4202. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  4203. (taicpu(hp2).opsize = S_B) then
  4204. begin
  4205. RemoveInstruction(hp1);
  4206. RemoveInstruction(hp2);
  4207. first_mov.opsize := S_L;
  4208. if first_mov.oper[0]^.typ = top_reg then
  4209. begin
  4210. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  4211. { Reuse second_mov as a MOVZX instruction }
  4212. second_mov.opcode := A_MOVZX;
  4213. second_mov.opsize := S_BL;
  4214. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  4215. second_mov.loadreg(1, FullReg);
  4216. first_mov.oper[0]^.reg := FullReg;
  4217. asml.Remove(second_mov);
  4218. asml.InsertBefore(second_mov, first_mov);
  4219. end
  4220. else
  4221. { It's a value }
  4222. begin
  4223. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  4224. RemoveInstruction(second_mov);
  4225. end;
  4226. Result := True;
  4227. Exit;
  4228. end;
  4229. end;
  4230. S_W:
  4231. begin
  4232. RemoveInstruction(hp1);
  4233. first_mov.opsize := S_L;
  4234. if first_mov.oper[0]^.typ = top_reg then
  4235. begin
  4236. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  4237. { Reuse second_mov as a MOVZX instruction }
  4238. second_mov.opcode := A_MOVZX;
  4239. second_mov.opsize := S_BL;
  4240. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  4241. second_mov.loadreg(1, FullReg);
  4242. first_mov.oper[0]^.reg := FullReg;
  4243. asml.Remove(second_mov);
  4244. asml.InsertBefore(second_mov, first_mov);
  4245. end
  4246. else
  4247. { It's a value }
  4248. begin
  4249. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  4250. RemoveInstruction(second_mov);
  4251. end;
  4252. Result := True;
  4253. Exit;
  4254. end;
  4255. else
  4256. ;
  4257. end;
  4258. end;
  4259. end;
  4260. end;
  4261. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  4262. { returns true if a "continue" should be done after this optimization }
  4263. var
  4264. hp1, hp2: tai;
  4265. begin
  4266. Result := false;
  4267. if MatchOpType(taicpu(p),top_ref) and
  4268. GetNextInstruction(p, hp1) and
  4269. (hp1.typ = ait_instruction) and
  4270. (((taicpu(hp1).opcode = A_FLD) and
  4271. (taicpu(p).opcode = A_FSTP)) or
  4272. ((taicpu(p).opcode = A_FISTP) and
  4273. (taicpu(hp1).opcode = A_FILD))) and
  4274. MatchOpType(taicpu(hp1),top_ref) and
  4275. (taicpu(hp1).opsize = taicpu(p).opsize) and
  4276. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  4277. begin
  4278. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  4279. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  4280. GetNextInstruction(hp1, hp2) and
  4281. (hp2.typ = ait_instruction) and
  4282. IsExitCode(hp2) and
  4283. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  4284. not(assigned(current_procinfo.procdef.funcretsym) and
  4285. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  4286. (taicpu(p).oper[0]^.ref^.index = NR_NO) then
  4287. begin
  4288. RemoveInstruction(hp1);
  4289. RemoveCurrentP(p, hp2);
  4290. RemoveLastDeallocForFuncRes(p);
  4291. Result := true;
  4292. end
  4293. else
  4294. { we can do this only in fast math mode as fstp is rounding ...
  4295. ... still disabled as it breaks the compiler and/or rtl }
  4296. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  4297. { ... or if another fstp equal to the first one follows }
  4298. (GetNextInstruction(hp1,hp2) and
  4299. (hp2.typ = ait_instruction) and
  4300. (taicpu(p).opcode=taicpu(hp2).opcode) and
  4301. (taicpu(p).opsize=taicpu(hp2).opsize))
  4302. ) and
  4303. { fst can't store an extended/comp value }
  4304. (taicpu(p).opsize <> S_FX) and
  4305. (taicpu(p).opsize <> S_IQ) then
  4306. begin
  4307. if (taicpu(p).opcode = A_FSTP) then
  4308. taicpu(p).opcode := A_FST
  4309. else
  4310. taicpu(p).opcode := A_FIST;
  4311. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  4312. RemoveInstruction(hp1);
  4313. end;
  4314. end;
  4315. end;
  4316. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  4317. var
  4318. hp1, hp2: tai;
  4319. begin
  4320. result:=false;
  4321. if MatchOpType(taicpu(p),top_reg) and
  4322. GetNextInstruction(p, hp1) and
  4323. (hp1.typ = Ait_Instruction) and
  4324. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4325. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  4326. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  4327. { change to
  4328. fld reg fxxx reg,st
  4329. fxxxp st, st1 (hp1)
  4330. Remark: non commutative operations must be reversed!
  4331. }
  4332. begin
  4333. case taicpu(hp1).opcode Of
  4334. A_FMULP,A_FADDP,
  4335. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  4336. begin
  4337. case taicpu(hp1).opcode Of
  4338. A_FADDP: taicpu(hp1).opcode := A_FADD;
  4339. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  4340. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  4341. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  4342. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  4343. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  4344. else
  4345. internalerror(2019050534);
  4346. end;
  4347. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  4348. taicpu(hp1).oper[1]^.reg := NR_ST;
  4349. RemoveCurrentP(p, hp1);
  4350. Result:=true;
  4351. exit;
  4352. end;
  4353. else
  4354. ;
  4355. end;
  4356. end
  4357. else
  4358. if MatchOpType(taicpu(p),top_ref) and
  4359. GetNextInstruction(p, hp2) and
  4360. (hp2.typ = Ait_Instruction) and
  4361. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4362. (taicpu(p).opsize in [S_FS, S_FL]) and
  4363. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  4364. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  4365. if GetLastInstruction(p, hp1) and
  4366. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  4367. MatchOpType(taicpu(hp1),top_ref) and
  4368. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  4369. if ((taicpu(hp2).opcode = A_FMULP) or
  4370. (taicpu(hp2).opcode = A_FADDP)) then
  4371. { change to
  4372. fld/fst mem1 (hp1) fld/fst mem1
  4373. fld mem1 (p) fadd/
  4374. faddp/ fmul st, st
  4375. fmulp st, st1 (hp2) }
  4376. begin
  4377. RemoveCurrentP(p, hp1);
  4378. if (taicpu(hp2).opcode = A_FADDP) then
  4379. taicpu(hp2).opcode := A_FADD
  4380. else
  4381. taicpu(hp2).opcode := A_FMUL;
  4382. taicpu(hp2).oper[1]^.reg := NR_ST;
  4383. end
  4384. else
  4385. { change to
  4386. fld/fst mem1 (hp1) fld/fst mem1
  4387. fld mem1 (p) fld st}
  4388. begin
  4389. taicpu(p).changeopsize(S_FL);
  4390. taicpu(p).loadreg(0,NR_ST);
  4391. end
  4392. else
  4393. begin
  4394. case taicpu(hp2).opcode Of
  4395. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  4396. { change to
  4397. fld/fst mem1 (hp1) fld/fst mem1
  4398. fld mem2 (p) fxxx mem2
  4399. fxxxp st, st1 (hp2) }
  4400. begin
  4401. case taicpu(hp2).opcode Of
  4402. A_FADDP: taicpu(p).opcode := A_FADD;
  4403. A_FMULP: taicpu(p).opcode := A_FMUL;
  4404. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  4405. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  4406. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  4407. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  4408. else
  4409. internalerror(2019050533);
  4410. end;
  4411. RemoveInstruction(hp2);
  4412. end
  4413. else
  4414. ;
  4415. end
  4416. end
  4417. end;
  4418. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  4419. begin
  4420. Result := condition_in(cond1, cond2) or
  4421. { Not strictly subsets due to the actual flags checked, but because we're
  4422. comparing integers, E is a subset of AE and GE and their aliases }
  4423. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  4424. end;
  4425. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  4426. var
  4427. v: TCGInt;
  4428. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  4429. FirstMatch: Boolean;
  4430. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  4431. begin
  4432. Result:=false;
  4433. { All these optimisations need a next instruction }
  4434. if not GetNextInstruction(p, hp1) then
  4435. Exit;
  4436. { Search for:
  4437. cmp ###,###
  4438. j(c1) @lbl1
  4439. ...
  4440. @lbl:
  4441. cmp ###.### (same comparison as above)
  4442. j(c2) @lbl2
  4443. If c1 is a subset of c2, change to:
  4444. cmp ###,###
  4445. j(c2) @lbl2
  4446. (@lbl1 may become a dead label as a result)
  4447. }
  4448. { Also handle cases where there are multiple jumps in a row }
  4449. p_jump := hp1;
  4450. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  4451. begin
  4452. if IsJumpToLabel(taicpu(p_jump)) then
  4453. begin
  4454. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  4455. p_label := nil;
  4456. if Assigned(JumpLabel) then
  4457. p_label := getlabelwithsym(JumpLabel);
  4458. if Assigned(p_label) and
  4459. GetNextInstruction(p_label, p_dist) and
  4460. MatchInstruction(p_dist, A_CMP, []) and
  4461. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  4462. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4463. GetNextInstruction(p_dist, hp1_dist) and
  4464. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4465. begin
  4466. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4467. if JumpLabel = JumpLabel_dist then
  4468. { This is an infinite loop }
  4469. Exit;
  4470. { Best optimisation when the first condition is a subset (or equal) of the second }
  4471. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  4472. begin
  4473. { Any registers used here will already be allocated }
  4474. if Assigned(JumpLabel_dist) then
  4475. JumpLabel_dist.IncRefs;
  4476. if Assigned(JumpLabel) then
  4477. JumpLabel.DecRefs;
  4478. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  4479. taicpu(p_jump).condition := taicpu(hp1_dist).condition;
  4480. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  4481. Result := True;
  4482. { Don't exit yet. Since p and p_jump haven't actually been
  4483. removed, we can check for more on this iteration }
  4484. end
  4485. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  4486. GetNextInstruction(hp1_dist, hp1_label) and
  4487. SkipAligns(hp1_label, hp1_label) and
  4488. (hp1_label.typ = ait_label) then
  4489. begin
  4490. JumpLabel_far := tai_label(hp1_label).labsym;
  4491. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  4492. { This is an infinite loop }
  4493. Exit;
  4494. if Assigned(JumpLabel_far) then
  4495. begin
  4496. { In this situation, if the first jump branches, the second one will never,
  4497. branch so change the destination label to after the second jump }
  4498. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  4499. if Assigned(JumpLabel) then
  4500. JumpLabel.DecRefs;
  4501. JumpLabel_far.IncRefs;
  4502. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  4503. Result := True;
  4504. { Don't exit yet. Since p and p_jump haven't actually been
  4505. removed, we can check for more on this iteration }
  4506. Continue;
  4507. end;
  4508. end;
  4509. end;
  4510. end;
  4511. { Search for:
  4512. cmp ###,###
  4513. j(c1) @lbl1
  4514. cmp ###,### (same as first)
  4515. Remove second cmp
  4516. }
  4517. if GetNextInstruction(p_jump, hp2) and
  4518. (
  4519. (
  4520. MatchInstruction(hp2, A_CMP, []) and
  4521. (
  4522. (
  4523. MatchOpType(taicpu(p), top_const, top_reg) and
  4524. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  4525. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[1]^.reg)
  4526. ) or (
  4527. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  4528. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  4529. )
  4530. )
  4531. ) or (
  4532. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  4533. MatchOperand(taicpu(p).oper[0]^, 0) and
  4534. (taicpu(p).oper[1]^.typ = top_reg) and
  4535. MatchInstruction(hp2, A_TEST, []) and
  4536. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4537. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  4538. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[1]^.reg)
  4539. )
  4540. ) then
  4541. begin
  4542. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  4543. RemoveInstruction(hp2);
  4544. Result := True;
  4545. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  4546. end;
  4547. GetNextInstruction(p_jump, p_jump);
  4548. end;
  4549. if taicpu(p).oper[0]^.typ = top_const then
  4550. begin
  4551. if (taicpu(p).oper[0]^.val = 0) and
  4552. (taicpu(p).oper[1]^.typ = top_reg) and
  4553. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  4554. begin
  4555. hp2 := p;
  4556. FirstMatch := True;
  4557. { When dealing with "cmp $0,%reg", only ZF and SF contain
  4558. anything meaningful once it's converted to "test %reg,%reg";
  4559. additionally, some jumps will always (or never) branch, so
  4560. evaluate every jump immediately following the
  4561. comparison, optimising the conditions if possible.
  4562. Similarly with SETcc... those that are always set to 0 or 1
  4563. are changed to MOV instructions }
  4564. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  4565. (
  4566. GetNextInstruction(hp2, hp1) and
  4567. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  4568. ) do
  4569. begin
  4570. FirstMatch := False;
  4571. case taicpu(hp1).condition of
  4572. C_B, C_C, C_NAE, C_O:
  4573. { For B/NAE:
  4574. Will never branch since an unsigned integer can never be below zero
  4575. For C/O:
  4576. Result cannot overflow because 0 is being subtracted
  4577. }
  4578. begin
  4579. if taicpu(hp1).opcode = A_Jcc then
  4580. begin
  4581. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  4582. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  4583. RemoveInstruction(hp1);
  4584. { Since hp1 was deleted, hp2 must not be updated }
  4585. Continue;
  4586. end
  4587. else
  4588. begin
  4589. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  4590. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  4591. taicpu(hp1).opcode := A_MOV;
  4592. taicpu(hp1).ops := 2;
  4593. taicpu(hp1).condition := C_None;
  4594. taicpu(hp1).opsize := S_B;
  4595. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  4596. taicpu(hp1).loadconst(0, 0);
  4597. end;
  4598. end;
  4599. C_BE, C_NA:
  4600. begin
  4601. { Will only branch if equal to zero }
  4602. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  4603. taicpu(hp1).condition := C_E;
  4604. end;
  4605. C_A, C_NBE:
  4606. begin
  4607. { Will only branch if not equal to zero }
  4608. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  4609. taicpu(hp1).condition := C_NE;
  4610. end;
  4611. C_AE, C_NB, C_NC, C_NO:
  4612. begin
  4613. { Will always branch }
  4614. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  4615. if taicpu(hp1).opcode = A_Jcc then
  4616. begin
  4617. MakeUnconditional(taicpu(hp1));
  4618. { Any jumps/set that follow will now be dead code }
  4619. RemoveDeadCodeAfterJump(taicpu(hp1));
  4620. Break;
  4621. end
  4622. else
  4623. begin
  4624. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  4625. taicpu(hp1).opcode := A_MOV;
  4626. taicpu(hp1).ops := 2;
  4627. taicpu(hp1).condition := C_None;
  4628. taicpu(hp1).opsize := S_B;
  4629. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  4630. taicpu(hp1).loadconst(0, 1);
  4631. end;
  4632. end;
  4633. C_None:
  4634. InternalError(2020012201);
  4635. C_P, C_PE, C_NP, C_PO:
  4636. { We can't handle parity checks and they should never be generated
  4637. after a general-purpose CMP (it's used in some floating-point
  4638. comparisons that don't use CMP) }
  4639. InternalError(2020012202);
  4640. else
  4641. { Zero/Equality, Sign, their complements and all of the
  4642. signed comparisons do not need to be converted };
  4643. end;
  4644. hp2 := hp1;
  4645. end;
  4646. { Convert the instruction to a TEST }
  4647. taicpu(p).opcode := A_TEST;
  4648. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  4649. Result := True;
  4650. Exit;
  4651. end
  4652. else if (taicpu(p).oper[0]^.val = 1) and
  4653. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  4654. (taicpu(hp1).condition in [C_L, C_NGE]) then
  4655. begin
  4656. { Convert; To:
  4657. cmp $1,r/m cmp $0,r/m
  4658. jl @lbl jle @lbl
  4659. }
  4660. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  4661. taicpu(p).oper[0]^.val := 0;
  4662. taicpu(hp1).condition := C_LE;
  4663. { If the instruction is now "cmp $0,%reg", convert it to a
  4664. TEST (and effectively do the work of the "cmp $0,%reg" in
  4665. the block above)
  4666. If it's a reference, we can get away with not setting
  4667. Result to True because he haven't evaluated the jump
  4668. in this pass yet.
  4669. }
  4670. if (taicpu(p).oper[1]^.typ = top_reg) then
  4671. begin
  4672. taicpu(p).opcode := A_TEST;
  4673. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  4674. Result := True;
  4675. end;
  4676. Exit;
  4677. end
  4678. else if (taicpu(p).oper[1]^.typ = top_reg) then
  4679. begin
  4680. { cmp register,$8000 neg register
  4681. je target --> jo target
  4682. .... only if register is deallocated before jump.}
  4683. case Taicpu(p).opsize of
  4684. S_B: v:=$80;
  4685. S_W: v:=$8000;
  4686. S_L: v:=qword($80000000);
  4687. { S_Q will never happen: cmp with 64 bit constants is not possible }
  4688. S_Q:
  4689. Exit;
  4690. else
  4691. internalerror(2013112905);
  4692. end;
  4693. if (taicpu(p).oper[0]^.val=v) and
  4694. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  4695. (Taicpu(hp1).condition in [C_E,C_NE]) then
  4696. begin
  4697. TransferUsedRegs(TmpUsedRegs);
  4698. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  4699. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  4700. begin
  4701. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  4702. Taicpu(p).opcode:=A_NEG;
  4703. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  4704. Taicpu(p).clearop(1);
  4705. Taicpu(p).ops:=1;
  4706. if Taicpu(hp1).condition=C_E then
  4707. Taicpu(hp1).condition:=C_O
  4708. else
  4709. Taicpu(hp1).condition:=C_NO;
  4710. Result:=true;
  4711. exit;
  4712. end;
  4713. end;
  4714. end;
  4715. end;
  4716. if (taicpu(p).oper[1]^.typ = top_reg) and
  4717. MatchInstruction(hp1,A_MOV,[]) and
  4718. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  4719. (
  4720. (taicpu(p).oper[0]^.typ <> top_reg) or
  4721. not RegInInstruction(taicpu(p).oper[0]^.reg, hp1)
  4722. ) then
  4723. begin
  4724. { If we have something like:
  4725. cmp ###,%reg1
  4726. mov 0,%reg2
  4727. And no registers are shared, move the MOV command to before the
  4728. comparison as this means it can be optimised without worrying
  4729. about the FLAGS register. (This combination is generated by
  4730. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  4731. }
  4732. SwapMovCmp(p, hp1);
  4733. Result := True;
  4734. Exit;
  4735. end;
  4736. end;
  4737. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  4738. var
  4739. hp1: tai;
  4740. begin
  4741. {
  4742. remove the second (v)pxor from
  4743. pxor reg,reg
  4744. ...
  4745. pxor reg,reg
  4746. }
  4747. Result:=false;
  4748. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  4749. MatchOpType(taicpu(p),top_reg,top_reg) and
  4750. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  4751. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4752. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  4753. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  4754. begin
  4755. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  4756. RemoveInstruction(hp1);
  4757. Result:=true;
  4758. Exit;
  4759. end
  4760. {
  4761. replace
  4762. pxor reg1,reg1
  4763. movapd/s reg1,reg2
  4764. dealloc reg1
  4765. by
  4766. pxor reg2,reg2
  4767. }
  4768. else if GetNextInstruction(p,hp1) and
  4769. { we mix single and double opperations here because we assume that the compiler
  4770. generates vmovapd only after double operations and vmovaps only after single operations }
  4771. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4772. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  4773. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4774. (taicpu(p).oper[0]^.typ=top_reg) then
  4775. begin
  4776. TransferUsedRegs(TmpUsedRegs);
  4777. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4778. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4779. begin
  4780. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  4781. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4782. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  4783. RemoveInstruction(hp1);
  4784. result:=true;
  4785. end;
  4786. end;
  4787. end;
  4788. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  4789. var
  4790. hp1: tai;
  4791. begin
  4792. {
  4793. remove the second (v)pxor from
  4794. (v)pxor reg,reg
  4795. ...
  4796. (v)pxor reg,reg
  4797. }
  4798. Result:=false;
  4799. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  4800. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  4801. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  4802. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4803. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  4804. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  4805. begin
  4806. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2PXor done',hp1);
  4807. RemoveInstruction(hp1);
  4808. Result:=true;
  4809. Exit;
  4810. end
  4811. else
  4812. Result:=OptPass1VOP(p);
  4813. end;
  4814. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  4815. var
  4816. hp1 : tai;
  4817. begin
  4818. result:=false;
  4819. { replace
  4820. IMul const,%mreg1,%mreg2
  4821. Mov %reg2,%mreg3
  4822. dealloc %mreg3
  4823. by
  4824. Imul const,%mreg1,%mreg23
  4825. }
  4826. if (taicpu(p).ops=3) and
  4827. GetNextInstruction(p,hp1) and
  4828. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  4829. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  4830. (taicpu(hp1).oper[1]^.typ=top_reg) then
  4831. begin
  4832. TransferUsedRegs(TmpUsedRegs);
  4833. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4834. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  4835. begin
  4836. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  4837. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  4838. RemoveInstruction(hp1);
  4839. result:=true;
  4840. end;
  4841. end;
  4842. end;
  4843. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  4844. var
  4845. hp1 : tai;
  4846. begin
  4847. result:=false;
  4848. { replace
  4849. IMul %reg0,%reg1,%reg2
  4850. Mov %reg2,%reg3
  4851. dealloc %reg2
  4852. by
  4853. Imul %reg0,%reg1,%reg3
  4854. }
  4855. if GetNextInstruction(p,hp1) and
  4856. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  4857. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  4858. (taicpu(hp1).oper[1]^.typ=top_reg) then
  4859. begin
  4860. TransferUsedRegs(TmpUsedRegs);
  4861. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4862. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  4863. begin
  4864. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  4865. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  4866. RemoveInstruction(hp1);
  4867. result:=true;
  4868. end;
  4869. end;
  4870. end;
  4871. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  4872. var
  4873. hp1, hp2, hp3, hp4, hp5: tai;
  4874. ThisReg: TRegister;
  4875. begin
  4876. Result := False;
  4877. if not GetNextInstruction(p,hp1) or (hp1.typ <> ait_instruction) then
  4878. Exit;
  4879. {
  4880. convert
  4881. j<c> .L1
  4882. mov 1,reg
  4883. jmp .L2
  4884. .L1
  4885. mov 0,reg
  4886. .L2
  4887. into
  4888. mov 0,reg
  4889. set<not(c)> reg
  4890. take care of alignment and that the mov 0,reg is not converted into a xor as this
  4891. would destroy the flag contents
  4892. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  4893. executed at the same time as a previous comparison.
  4894. set<not(c)> reg
  4895. movzx reg, reg
  4896. }
  4897. if MatchInstruction(hp1,A_MOV,[]) and
  4898. (taicpu(hp1).oper[0]^.typ = top_const) and
  4899. (
  4900. (
  4901. (taicpu(hp1).oper[1]^.typ = top_reg)
  4902. {$ifdef i386}
  4903. { Under i386, ESI, EDI, EBP and ESP
  4904. don't have an 8-bit representation }
  4905. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  4906. {$endif i386}
  4907. ) or (
  4908. {$ifdef i386}
  4909. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  4910. {$endif i386}
  4911. (taicpu(hp1).opsize = S_B)
  4912. )
  4913. ) and
  4914. GetNextInstruction(hp1,hp2) and
  4915. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  4916. GetNextInstruction(hp2,hp3) and
  4917. SkipAligns(hp3, hp3) and
  4918. (hp3.typ=ait_label) and
  4919. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  4920. GetNextInstruction(hp3,hp4) and
  4921. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  4922. (taicpu(hp4).oper[0]^.typ = top_const) and
  4923. (
  4924. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  4925. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  4926. ) and
  4927. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  4928. GetNextInstruction(hp4,hp5) and
  4929. SkipAligns(hp5, hp5) and
  4930. (hp5.typ=ait_label) and
  4931. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  4932. begin
  4933. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  4934. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  4935. tai_label(hp3).labsym.DecRefs;
  4936. { If this isn't the only reference to the middle label, we can
  4937. still make a saving - only that the first jump and everything
  4938. that follows will remain. }
  4939. if (tai_label(hp3).labsym.getrefs = 0) then
  4940. begin
  4941. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  4942. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  4943. else
  4944. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  4945. { remove jump, first label and second MOV (also catching any aligns) }
  4946. repeat
  4947. if not GetNextInstruction(hp2, hp3) then
  4948. InternalError(2021040810);
  4949. RemoveInstruction(hp2);
  4950. hp2 := hp3;
  4951. until hp2 = hp5;
  4952. { Don't decrement reference count before the removal loop
  4953. above, otherwise GetNextInstruction won't stop on the
  4954. the label }
  4955. tai_label(hp5).labsym.DecRefs;
  4956. end
  4957. else
  4958. begin
  4959. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  4960. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  4961. else
  4962. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  4963. end;
  4964. taicpu(p).opcode:=A_SETcc;
  4965. taicpu(p).opsize:=S_B;
  4966. taicpu(p).is_jmp:=False;
  4967. if taicpu(hp1).opsize=S_B then
  4968. begin
  4969. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  4970. RemoveInstruction(hp1);
  4971. end
  4972. else
  4973. begin
  4974. { Will be a register because the size can't be S_B otherwise }
  4975. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  4976. taicpu(p).loadreg(0, ThisReg);
  4977. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  4978. begin
  4979. case taicpu(hp1).opsize of
  4980. S_W:
  4981. taicpu(hp1).opsize := S_BW;
  4982. S_L:
  4983. taicpu(hp1).opsize := S_BL;
  4984. {$ifdef x86_64}
  4985. S_Q:
  4986. begin
  4987. taicpu(hp1).opsize := S_BL;
  4988. { Change the destination register to 32-bit }
  4989. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  4990. end;
  4991. {$endif x86_64}
  4992. else
  4993. InternalError(2021040820);
  4994. end;
  4995. taicpu(hp1).opcode := A_MOVZX;
  4996. taicpu(hp1).loadreg(0, ThisReg);
  4997. end
  4998. else
  4999. begin
  5000. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  5001. { hp1 is already a MOV instruction with the correct register }
  5002. taicpu(hp1).loadconst(0, 0);
  5003. { Inserting it right before p will guarantee that the flags are also tracked }
  5004. asml.Remove(hp1);
  5005. asml.InsertBefore(hp1, p);
  5006. end;
  5007. end;
  5008. Result:=true;
  5009. exit;
  5010. end
  5011. end;
  5012. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  5013. var
  5014. hp2, hp3, first_assignment: tai;
  5015. IncCount, OperIdx: Integer;
  5016. OrigLabel: TAsmLabel;
  5017. begin
  5018. Count := 0;
  5019. Result := False;
  5020. first_assignment := nil;
  5021. if (LoopCount >= 20) then
  5022. begin
  5023. { Guard against infinite loops }
  5024. Exit;
  5025. end;
  5026. if (taicpu(p).oper[0]^.typ <> top_ref) or
  5027. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  5028. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  5029. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  5030. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  5031. Exit;
  5032. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  5033. {
  5034. change
  5035. jmp .L1
  5036. ...
  5037. .L1:
  5038. mov ##, ## ( multiple movs possible )
  5039. jmp/ret
  5040. into
  5041. mov ##, ##
  5042. jmp/ret
  5043. }
  5044. if not Assigned(hp1) then
  5045. begin
  5046. hp1 := GetLabelWithSym(OrigLabel);
  5047. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  5048. Exit;
  5049. end;
  5050. hp2 := hp1;
  5051. while Assigned(hp2) do
  5052. begin
  5053. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  5054. SkipLabels(hp2,hp2);
  5055. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  5056. Break;
  5057. case taicpu(hp2).opcode of
  5058. A_MOVSS:
  5059. begin
  5060. if taicpu(hp2).ops = 0 then
  5061. { Wrong MOVSS }
  5062. Break;
  5063. Inc(Count);
  5064. if Count >= 5 then
  5065. { Too many to be worthwhile }
  5066. Break;
  5067. GetNextInstruction(hp2, hp2);
  5068. Continue;
  5069. end;
  5070. A_MOV,
  5071. A_MOVD,
  5072. A_MOVQ,
  5073. A_MOVSX,
  5074. {$ifdef x86_64}
  5075. A_MOVSXD,
  5076. {$endif x86_64}
  5077. A_MOVZX,
  5078. A_MOVAPS,
  5079. A_MOVUPS,
  5080. A_MOVSD,
  5081. A_MOVAPD,
  5082. A_MOVUPD,
  5083. A_MOVDQA,
  5084. A_MOVDQU,
  5085. A_VMOVSS,
  5086. A_VMOVAPS,
  5087. A_VMOVUPS,
  5088. A_VMOVSD,
  5089. A_VMOVAPD,
  5090. A_VMOVUPD,
  5091. A_VMOVDQA,
  5092. A_VMOVDQU:
  5093. begin
  5094. Inc(Count);
  5095. if Count >= 5 then
  5096. { Too many to be worthwhile }
  5097. Break;
  5098. GetNextInstruction(hp2, hp2);
  5099. Continue;
  5100. end;
  5101. A_JMP:
  5102. begin
  5103. { Guard against infinite loops }
  5104. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  5105. Exit;
  5106. { Analyse this jump first in case it also duplicates assignments }
  5107. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  5108. begin
  5109. { Something did change! }
  5110. Result := True;
  5111. Inc(Count, IncCount);
  5112. if Count >= 5 then
  5113. begin
  5114. { Too many to be worthwhile }
  5115. Exit;
  5116. end;
  5117. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  5118. Break;
  5119. end;
  5120. Result := True;
  5121. Break;
  5122. end;
  5123. A_RET:
  5124. begin
  5125. Result := True;
  5126. Break;
  5127. end;
  5128. else
  5129. Break;
  5130. end;
  5131. end;
  5132. if Result then
  5133. begin
  5134. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  5135. if Count = 0 then
  5136. begin
  5137. Result := False;
  5138. Exit;
  5139. end;
  5140. hp3 := p;
  5141. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  5142. while True do
  5143. begin
  5144. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  5145. SkipLabels(hp1,hp1);
  5146. if (hp1.typ <> ait_instruction) then
  5147. InternalError(2021040720);
  5148. case taicpu(hp1).opcode of
  5149. A_JMP:
  5150. begin
  5151. { Change the original jump to the new destination }
  5152. OrigLabel.decrefs;
  5153. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  5154. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  5155. { Set p to the first duplicated assignment so it can get optimised if needs be }
  5156. if not Assigned(first_assignment) then
  5157. InternalError(2021040810)
  5158. else
  5159. p := first_assignment;
  5160. Exit;
  5161. end;
  5162. A_RET:
  5163. begin
  5164. { Now change the jump into a RET instruction }
  5165. ConvertJumpToRET(p, hp1);
  5166. { Set p to the first duplicated assignment so it can get optimised if needs be }
  5167. if not Assigned(first_assignment) then
  5168. InternalError(2021040811)
  5169. else
  5170. p := first_assignment;
  5171. Exit;
  5172. end;
  5173. else
  5174. begin
  5175. { Duplicate the MOV instruction }
  5176. hp3:=tai(hp1.getcopy);
  5177. if first_assignment = nil then
  5178. first_assignment := hp3;
  5179. asml.InsertBefore(hp3, p);
  5180. { Make sure the compiler knows about any final registers written here }
  5181. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  5182. with taicpu(hp3).oper[OperIdx]^ do
  5183. begin
  5184. case typ of
  5185. top_ref:
  5186. begin
  5187. if (ref^.base <> NR_NO) and
  5188. (getsupreg(ref^.base) <> RS_ESP) and
  5189. (getsupreg(ref^.base) <> RS_EBP)
  5190. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  5191. then
  5192. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  5193. if (ref^.index <> NR_NO) and
  5194. (getsupreg(ref^.index) <> RS_ESP) and
  5195. (getsupreg(ref^.index) <> RS_EBP)
  5196. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  5197. (ref^.index <> ref^.base) then
  5198. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  5199. end;
  5200. top_reg:
  5201. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  5202. else
  5203. ;
  5204. end;
  5205. end;
  5206. end;
  5207. end;
  5208. if not GetNextInstruction(hp1, hp1) then
  5209. { Should have dropped out earlier }
  5210. InternalError(2021040710);
  5211. end;
  5212. end;
  5213. end;
  5214. procedure TX86AsmOptimizer.SwapMovCmp(var p, hp1: tai);
  5215. var
  5216. hp2: tai;
  5217. X: Integer;
  5218. begin
  5219. asml.Remove(hp1);
  5220. { Try to insert after the last instructions where the FLAGS register is not yet in use }
  5221. if not GetLastInstruction(p, hp2) then
  5222. asml.InsertBefore(hp1, p)
  5223. else
  5224. asml.InsertAfter(hp1, hp2);
  5225. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and mov instructions to improve optimisation potential', hp1);
  5226. for X := 0 to 1 do
  5227. case taicpu(hp1).oper[X]^.typ of
  5228. top_reg:
  5229. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  5230. top_ref:
  5231. begin
  5232. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  5233. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  5234. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  5235. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  5236. end;
  5237. else
  5238. ;
  5239. end;
  5240. end;
  5241. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  5242. function IsXCHGAcceptable: Boolean; inline;
  5243. begin
  5244. { Always accept if optimising for size }
  5245. Result := (cs_opt_size in current_settings.optimizerswitches) or
  5246. (
  5247. {$ifdef x86_64}
  5248. { XCHG takes 3 cycles on AMD Athlon64 }
  5249. (current_settings.optimizecputype >= cpu_core_i)
  5250. {$else x86_64}
  5251. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  5252. than 3, so it becomes a saving compared to three MOVs with two of
  5253. them able to execute simultaneously. [Kit] }
  5254. (current_settings.optimizecputype >= cpu_PentiumM)
  5255. {$endif x86_64}
  5256. );
  5257. end;
  5258. var
  5259. NewRef: TReference;
  5260. hp1, hp2, hp3, hp4: Tai;
  5261. {$ifndef x86_64}
  5262. OperIdx: Integer;
  5263. {$endif x86_64}
  5264. NewInstr : Taicpu;
  5265. NewAligh : Tai_align;
  5266. DestLabel: TAsmLabel;
  5267. begin
  5268. Result:=false;
  5269. { This optimisation adds an instruction, so only do it for speed }
  5270. if not (cs_opt_size in current_settings.optimizerswitches) and
  5271. MatchOpType(taicpu(p), top_const, top_reg) and
  5272. (taicpu(p).oper[0]^.val = 0) then
  5273. begin
  5274. { To avoid compiler warning }
  5275. DestLabel := nil;
  5276. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  5277. InternalError(2021040750);
  5278. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  5279. Exit;
  5280. case hp1.typ of
  5281. ait_label:
  5282. begin
  5283. { Change:
  5284. mov $0,%reg mov $0,%reg
  5285. @Lbl1: @Lbl1:
  5286. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  5287. je @Lbl2 jne @Lbl2
  5288. To: To:
  5289. mov $0,%reg mov $0,%reg
  5290. jmp @Lbl2 jmp @Lbl3
  5291. (align) (align)
  5292. @Lbl1: @Lbl1:
  5293. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  5294. je @Lbl2 je @Lbl2
  5295. @Lbl3: <-- Only if label exists
  5296. (Not if it's optimised for size)
  5297. }
  5298. if not GetNextInstruction(hp1, hp2) then
  5299. Exit;
  5300. if not (cs_opt_size in current_settings.optimizerswitches) and
  5301. (hp2.typ = ait_instruction) and
  5302. (
  5303. { Register sizes must exactly match }
  5304. (
  5305. (taicpu(hp2).opcode = A_CMP) and
  5306. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  5307. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  5308. ) or (
  5309. (taicpu(hp2).opcode = A_TEST) and
  5310. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  5311. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  5312. )
  5313. ) and GetNextInstruction(hp2, hp3) and
  5314. (hp3.typ = ait_instruction) and
  5315. (taicpu(hp3).opcode = A_JCC) and
  5316. (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
  5317. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  5318. begin
  5319. { Check condition of jump }
  5320. { Always true? }
  5321. if condition_in(C_E, taicpu(hp3).condition) then
  5322. begin
  5323. { Copy label symbol and obtain matching label entry for the
  5324. conditional jump, as this will be our destination}
  5325. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  5326. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  5327. Result := True;
  5328. end
  5329. { Always false? }
  5330. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  5331. begin
  5332. { This is only worth it if there's a jump to take }
  5333. case hp2.typ of
  5334. ait_instruction:
  5335. begin
  5336. if taicpu(hp2).opcode = A_JMP then
  5337. begin
  5338. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  5339. { An unconditional jump follows the conditional jump which will always be false,
  5340. so use this jump's destination for the new jump }
  5341. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  5342. Result := True;
  5343. end
  5344. else if taicpu(hp2).opcode = A_JCC then
  5345. begin
  5346. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  5347. if condition_in(C_E, taicpu(hp2).condition) then
  5348. begin
  5349. { A second conditional jump follows the conditional jump which will always be false,
  5350. while the second jump is always True, so use this jump's destination for the new jump }
  5351. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  5352. Result := True;
  5353. end;
  5354. { Don't risk it if the jump isn't always true (Result remains False) }
  5355. end;
  5356. end;
  5357. else
  5358. { If anything else don't optimise };
  5359. end;
  5360. end;
  5361. if Result then
  5362. begin
  5363. { Just so we have something to insert as a paremeter}
  5364. reference_reset(NewRef, 1, []);
  5365. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  5366. { Now actually load the correct parameter }
  5367. NewInstr.loadsymbol(0, DestLabel, 0);
  5368. { Get instruction before original label (may not be p under -O3) }
  5369. if not GetLastInstruction(hp1, hp2) then
  5370. { Shouldn't fail here }
  5371. InternalError(2021040701);
  5372. DestLabel.increfs;
  5373. AsmL.InsertAfter(NewInstr, hp2);
  5374. { Add new alignment field }
  5375. (* AsmL.InsertAfter(
  5376. cai_align.create_max(
  5377. current_settings.alignment.jumpalign,
  5378. current_settings.alignment.jumpalignskipmax
  5379. ),
  5380. NewInstr
  5381. ); *)
  5382. end;
  5383. Exit;
  5384. end;
  5385. end;
  5386. else
  5387. ;
  5388. end;
  5389. end;
  5390. if not GetNextInstruction(p, hp1) then
  5391. Exit;
  5392. if MatchInstruction(hp1, A_JMP, [S_NO]) then
  5393. begin
  5394. { Sometimes the MOVs that OptPass2JMP produces can be improved
  5395. further, but we can't just put this jump optimisation in pass 1
  5396. because it tends to perform worse when conditional jumps are
  5397. nearby (e.g. when converting CMOV instructions). [Kit] }
  5398. if OptPass2JMP(hp1) then
  5399. { call OptPass1MOV once to potentially merge any MOVs that were created }
  5400. Result := OptPass1MOV(p)
  5401. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  5402. returned True and the instruction is still a MOV, thus checking
  5403. the optimisations below }
  5404. { If OptPass2JMP returned False, no optimisations were done to
  5405. the jump and there are no further optimisations that can be done
  5406. to the MOV instruction on this pass }
  5407. end
  5408. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  5409. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  5410. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5411. MatchOpType(taicpu(hp1),top_const,top_reg) and
  5412. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5413. { be lazy, checking separately for sub would be slightly better }
  5414. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  5415. begin
  5416. { Change:
  5417. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  5418. addl/q $x,%reg2 subl/q $x,%reg2
  5419. To:
  5420. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  5421. }
  5422. TransferUsedRegs(TmpUsedRegs);
  5423. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5424. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5425. if not GetNextInstruction(hp1, hp2) or
  5426. (
  5427. { The FLAGS register isn't always tracked properly, so do not
  5428. perform this optimisation if a conditional statement follows }
  5429. not RegReadByInstruction(NR_DEFAULTFLAGS, hp2) and
  5430. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)
  5431. ) then
  5432. begin
  5433. reference_reset(NewRef, 1, []);
  5434. NewRef.base := taicpu(p).oper[0]^.reg;
  5435. NewRef.scalefactor := 1;
  5436. if taicpu(hp1).opcode = A_ADD then
  5437. begin
  5438. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  5439. NewRef.offset := taicpu(hp1).oper[0]^.val;
  5440. end
  5441. else
  5442. begin
  5443. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  5444. NewRef.offset := -taicpu(hp1).oper[0]^.val;
  5445. end;
  5446. taicpu(p).opcode := A_LEA;
  5447. taicpu(p).loadref(0, NewRef);
  5448. RemoveInstruction(hp1);
  5449. Result := True;
  5450. Exit;
  5451. end;
  5452. end
  5453. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  5454. {$ifdef x86_64}
  5455. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  5456. {$else x86_64}
  5457. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  5458. {$endif x86_64}
  5459. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5460. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  5461. { mov reg1, reg2 mov reg1, reg2
  5462. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  5463. begin
  5464. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  5465. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  5466. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  5467. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  5468. TransferUsedRegs(TmpUsedRegs);
  5469. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5470. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  5471. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  5472. then
  5473. begin
  5474. RemoveCurrentP(p, hp1);
  5475. Result:=true;
  5476. end;
  5477. exit;
  5478. end
  5479. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  5480. IsXCHGAcceptable and
  5481. { XCHG doesn't support 8-byte registers }
  5482. (taicpu(p).opsize <> S_B) and
  5483. MatchInstruction(hp1, A_MOV, []) and
  5484. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5485. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  5486. GetNextInstruction(hp1, hp2) and
  5487. MatchInstruction(hp2, A_MOV, []) and
  5488. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  5489. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  5490. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  5491. begin
  5492. { mov %reg1,%reg2
  5493. mov %reg3,%reg1 -> xchg %reg3,%reg1
  5494. mov %reg2,%reg3
  5495. (%reg2 not used afterwards)
  5496. Note that xchg takes 3 cycles to execute, and generally mov's take
  5497. only one cycle apiece, but the first two mov's can be executed in
  5498. parallel, only taking 2 cycles overall. Older processors should
  5499. therefore only optimise for size. [Kit]
  5500. }
  5501. TransferUsedRegs(TmpUsedRegs);
  5502. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5503. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5504. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  5505. begin
  5506. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  5507. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  5508. taicpu(hp1).opcode := A_XCHG;
  5509. RemoveCurrentP(p, hp1);
  5510. RemoveInstruction(hp2);
  5511. Result := True;
  5512. Exit;
  5513. end;
  5514. end
  5515. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  5516. MatchInstruction(hp1, A_SAR, []) then
  5517. begin
  5518. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  5519. begin
  5520. { the use of %edx also covers the opsize being S_L }
  5521. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  5522. begin
  5523. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  5524. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  5525. (taicpu(p).oper[1]^.reg = NR_EDX) then
  5526. begin
  5527. { Change:
  5528. movl %eax,%edx
  5529. sarl $31,%edx
  5530. To:
  5531. cltd
  5532. }
  5533. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  5534. RemoveInstruction(hp1);
  5535. taicpu(p).opcode := A_CDQ;
  5536. taicpu(p).opsize := S_NO;
  5537. taicpu(p).clearop(1);
  5538. taicpu(p).clearop(0);
  5539. taicpu(p).ops:=0;
  5540. Result := True;
  5541. end
  5542. else if (cs_opt_size in current_settings.optimizerswitches) and
  5543. (taicpu(p).oper[0]^.reg = NR_EDX) and
  5544. (taicpu(p).oper[1]^.reg = NR_EAX) then
  5545. begin
  5546. { Change:
  5547. movl %edx,%eax
  5548. sarl $31,%edx
  5549. To:
  5550. movl %edx,%eax
  5551. cltd
  5552. Note that this creates a dependency between the two instructions,
  5553. so only perform if optimising for size.
  5554. }
  5555. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  5556. taicpu(hp1).opcode := A_CDQ;
  5557. taicpu(hp1).opsize := S_NO;
  5558. taicpu(hp1).clearop(1);
  5559. taicpu(hp1).clearop(0);
  5560. taicpu(hp1).ops:=0;
  5561. end;
  5562. {$ifndef x86_64}
  5563. end
  5564. { Don't bother if CMOV is supported, because a more optimal
  5565. sequence would have been generated for the Abs() intrinsic }
  5566. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  5567. { the use of %eax also covers the opsize being S_L }
  5568. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  5569. (taicpu(p).oper[0]^.reg = NR_EAX) and
  5570. (taicpu(p).oper[1]^.reg = NR_EDX) and
  5571. GetNextInstruction(hp1, hp2) and
  5572. MatchInstruction(hp2, A_XOR, [S_L]) and
  5573. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  5574. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  5575. GetNextInstruction(hp2, hp3) and
  5576. MatchInstruction(hp3, A_SUB, [S_L]) and
  5577. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  5578. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  5579. begin
  5580. { Change:
  5581. movl %eax,%edx
  5582. sarl $31,%eax
  5583. xorl %eax,%edx
  5584. subl %eax,%edx
  5585. (Instruction that uses %edx)
  5586. (%eax deallocated)
  5587. (%edx deallocated)
  5588. To:
  5589. cltd
  5590. xorl %edx,%eax <-- Note the registers have swapped
  5591. subl %edx,%eax
  5592. (Instruction that uses %eax) <-- %eax rather than %edx
  5593. }
  5594. TransferUsedRegs(TmpUsedRegs);
  5595. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5596. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5597. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5598. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  5599. begin
  5600. if GetNextInstruction(hp3, hp4) and
  5601. not RegModifiedByInstruction(NR_EDX, hp4) and
  5602. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  5603. begin
  5604. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  5605. taicpu(p).opcode := A_CDQ;
  5606. taicpu(p).clearop(1);
  5607. taicpu(p).clearop(0);
  5608. taicpu(p).ops:=0;
  5609. RemoveInstruction(hp1);
  5610. taicpu(hp2).loadreg(0, NR_EDX);
  5611. taicpu(hp2).loadreg(1, NR_EAX);
  5612. taicpu(hp3).loadreg(0, NR_EDX);
  5613. taicpu(hp3).loadreg(1, NR_EAX);
  5614. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  5615. { Convert references in the following instruction (hp4) from %edx to %eax }
  5616. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  5617. with taicpu(hp4).oper[OperIdx]^ do
  5618. case typ of
  5619. top_reg:
  5620. if getsupreg(reg) = RS_EDX then
  5621. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  5622. top_ref:
  5623. begin
  5624. if getsupreg(reg) = RS_EDX then
  5625. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  5626. if getsupreg(reg) = RS_EDX then
  5627. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  5628. end;
  5629. else
  5630. ;
  5631. end;
  5632. end;
  5633. end;
  5634. {$else x86_64}
  5635. end;
  5636. end
  5637. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  5638. { the use of %rdx also covers the opsize being S_Q }
  5639. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  5640. begin
  5641. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  5642. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  5643. (taicpu(p).oper[1]^.reg = NR_RDX) then
  5644. begin
  5645. { Change:
  5646. movq %rax,%rdx
  5647. sarq $63,%rdx
  5648. To:
  5649. cqto
  5650. }
  5651. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  5652. RemoveInstruction(hp1);
  5653. taicpu(p).opcode := A_CQO;
  5654. taicpu(p).opsize := S_NO;
  5655. taicpu(p).clearop(1);
  5656. taicpu(p).clearop(0);
  5657. taicpu(p).ops:=0;
  5658. Result := True;
  5659. end
  5660. else if (cs_opt_size in current_settings.optimizerswitches) and
  5661. (taicpu(p).oper[0]^.reg = NR_RDX) and
  5662. (taicpu(p).oper[1]^.reg = NR_RAX) then
  5663. begin
  5664. { Change:
  5665. movq %rdx,%rax
  5666. sarq $63,%rdx
  5667. To:
  5668. movq %rdx,%rax
  5669. cqto
  5670. Note that this creates a dependency between the two instructions,
  5671. so only perform if optimising for size.
  5672. }
  5673. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  5674. taicpu(hp1).opcode := A_CQO;
  5675. taicpu(hp1).opsize := S_NO;
  5676. taicpu(hp1).clearop(1);
  5677. taicpu(hp1).clearop(0);
  5678. taicpu(hp1).ops:=0;
  5679. {$endif x86_64}
  5680. end;
  5681. end;
  5682. end
  5683. else if MatchInstruction(hp1, A_MOV, []) and
  5684. (taicpu(hp1).oper[1]^.typ = top_reg) then
  5685. { Though "GetNextInstruction" could be factored out, along with
  5686. the instructions that depend on hp2, it is an expensive call that
  5687. should be delayed for as long as possible, hence we do cheaper
  5688. checks first that are likely to be False. [Kit] }
  5689. begin
  5690. if (
  5691. (
  5692. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  5693. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  5694. (
  5695. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  5696. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  5697. )
  5698. ) or
  5699. (
  5700. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  5701. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  5702. (
  5703. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  5704. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  5705. )
  5706. )
  5707. ) and
  5708. GetNextInstruction(hp1, hp2) and
  5709. MatchInstruction(hp2, A_SAR, []) and
  5710. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  5711. begin
  5712. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  5713. begin
  5714. { Change:
  5715. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  5716. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  5717. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  5718. To:
  5719. movl r/m,%eax <- Note the change in register
  5720. cltd
  5721. }
  5722. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  5723. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  5724. taicpu(p).loadreg(1, NR_EAX);
  5725. taicpu(hp1).opcode := A_CDQ;
  5726. taicpu(hp1).clearop(1);
  5727. taicpu(hp1).clearop(0);
  5728. taicpu(hp1).ops:=0;
  5729. RemoveInstruction(hp2);
  5730. (*
  5731. {$ifdef x86_64}
  5732. end
  5733. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  5734. { This code sequence does not get generated - however it might become useful
  5735. if and when 128-bit signed integer types make an appearance, so the code
  5736. is kept here for when it is eventually needed. [Kit] }
  5737. (
  5738. (
  5739. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  5740. (
  5741. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  5742. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  5743. )
  5744. ) or
  5745. (
  5746. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  5747. (
  5748. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  5749. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  5750. )
  5751. )
  5752. ) and
  5753. GetNextInstruction(hp1, hp2) and
  5754. MatchInstruction(hp2, A_SAR, [S_Q]) and
  5755. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  5756. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  5757. begin
  5758. { Change:
  5759. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  5760. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  5761. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  5762. To:
  5763. movq r/m,%rax <- Note the change in register
  5764. cqto
  5765. }
  5766. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  5767. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  5768. taicpu(p).loadreg(1, NR_RAX);
  5769. taicpu(hp1).opcode := A_CQO;
  5770. taicpu(hp1).clearop(1);
  5771. taicpu(hp1).clearop(0);
  5772. taicpu(hp1).ops:=0;
  5773. RemoveInstruction(hp2);
  5774. {$endif x86_64}
  5775. *)
  5776. end;
  5777. end;
  5778. {$ifdef x86_64}
  5779. end
  5780. else if (taicpu(p).opsize = S_L) and
  5781. (taicpu(p).oper[1]^.typ = top_reg) and
  5782. (
  5783. MatchInstruction(hp1, A_MOV,[]) and
  5784. (taicpu(hp1).opsize = S_L) and
  5785. (taicpu(hp1).oper[1]^.typ = top_reg)
  5786. ) and (
  5787. GetNextInstruction(hp1, hp2) and
  5788. (tai(hp2).typ=ait_instruction) and
  5789. (taicpu(hp2).opsize = S_Q) and
  5790. (
  5791. (
  5792. MatchInstruction(hp2, A_ADD,[]) and
  5793. (taicpu(hp2).opsize = S_Q) and
  5794. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  5795. (
  5796. (
  5797. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  5798. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  5799. ) or (
  5800. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  5801. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  5802. )
  5803. )
  5804. ) or (
  5805. MatchInstruction(hp2, A_LEA,[]) and
  5806. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  5807. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  5808. (
  5809. (
  5810. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  5811. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  5812. ) or (
  5813. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  5814. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  5815. )
  5816. ) and (
  5817. (
  5818. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  5819. ) or (
  5820. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  5821. )
  5822. )
  5823. )
  5824. )
  5825. ) and (
  5826. GetNextInstruction(hp2, hp3) and
  5827. MatchInstruction(hp3, A_SHR,[]) and
  5828. (taicpu(hp3).opsize = S_Q) and
  5829. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  5830. (taicpu(hp3).oper[0]^.val = 1) and
  5831. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  5832. ) then
  5833. begin
  5834. { Change movl x, reg1d movl x, reg1d
  5835. movl y, reg2d movl y, reg2d
  5836. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  5837. shrq $1, reg1q shrq $1, reg1q
  5838. ( reg1d and reg2d can be switched around in the first two instructions )
  5839. To movl x, reg1d
  5840. addl y, reg1d
  5841. rcrl $1, reg1d
  5842. This corresponds to the common expression (x + y) shr 1, where
  5843. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  5844. smaller code, but won't account for x + y causing an overflow). [Kit]
  5845. }
  5846. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  5847. { Change first MOV command to have the same register as the final output }
  5848. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  5849. else
  5850. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  5851. { Change second MOV command to an ADD command. This is easier than
  5852. converting the existing command because it means we don't have to
  5853. touch 'y', which might be a complicated reference, and also the
  5854. fact that the third command might either be ADD or LEA. [Kit] }
  5855. taicpu(hp1).opcode := A_ADD;
  5856. { Delete old ADD/LEA instruction }
  5857. RemoveInstruction(hp2);
  5858. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  5859. taicpu(hp3).opcode := A_RCR;
  5860. taicpu(hp3).changeopsize(S_L);
  5861. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  5862. {$endif x86_64}
  5863. end;
  5864. end;
  5865. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  5866. var
  5867. ThisReg: TRegister;
  5868. MinSize, MaxSize, TrySmaller, TargetSize: TOpSize;
  5869. TargetSubReg: TSubRegister;
  5870. hp1, hp2: tai;
  5871. RegInUse, RegChanged, p_removed: Boolean;
  5872. { Store list of found instructions so we don't have to call
  5873. GetNextInstructionUsingReg multiple times }
  5874. InstrList: array of taicpu;
  5875. InstrMax, Index: Integer;
  5876. UpperLimit, TrySmallerLimit: TCgInt;
  5877. PreMessage: string;
  5878. { Data flow analysis }
  5879. TestValMin, TestValMax: TCgInt;
  5880. SmallerOverflow: Boolean;
  5881. begin
  5882. Result := False;
  5883. p_removed := False;
  5884. { This is anything but quick! }
  5885. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  5886. Exit;
  5887. SetLength(InstrList, 0);
  5888. InstrMax := -1;
  5889. ThisReg := taicpu(p).oper[1]^.reg;
  5890. case taicpu(p).opsize of
  5891. S_BW, S_BL:
  5892. begin
  5893. {$if defined(i386) or defined(i8086)}
  5894. { If the target size is 8-bit, make sure we can actually encode it }
  5895. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  5896. Exit;
  5897. {$endif i386 or i8086}
  5898. UpperLimit := $FF;
  5899. MinSize := S_B;
  5900. if taicpu(p).opsize = S_BW then
  5901. MaxSize := S_W
  5902. else
  5903. MaxSize := S_L;
  5904. end;
  5905. S_WL:
  5906. begin
  5907. UpperLimit := $FFFF;
  5908. MinSize := S_W;
  5909. MaxSize := S_L;
  5910. end
  5911. else
  5912. InternalError(2020112301);
  5913. end;
  5914. TestValMin := 0;
  5915. TestValMax := UpperLimit;
  5916. TrySmallerLimit := UpperLimit;
  5917. TrySmaller := S_NO;
  5918. SmallerOverflow := False;
  5919. RegChanged := False;
  5920. hp1 := p;
  5921. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  5922. (hp1.typ = ait_instruction) and
  5923. (
  5924. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  5925. instruction that doesn't actually contain ThisReg }
  5926. (cs_opt_level3 in current_settings.optimizerswitches) or
  5927. RegInInstruction(ThisReg, hp1)
  5928. ) do
  5929. begin
  5930. case taicpu(hp1).opcode of
  5931. A_INC,A_DEC:
  5932. begin
  5933. { Has to be an exact match on the register }
  5934. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  5935. Break;
  5936. if taicpu(hp1).opcode = A_INC then
  5937. begin
  5938. Inc(TestValMin);
  5939. Inc(TestValMax);
  5940. end
  5941. else
  5942. begin
  5943. Dec(TestValMin);
  5944. Dec(TestValMax);
  5945. end;
  5946. end;
  5947. A_CMP:
  5948. begin
  5949. if (taicpu(hp1).oper[1]^.typ <> top_reg) or
  5950. { Has to be an exact match on the register }
  5951. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  5952. (taicpu(hp1).oper[0]^.typ <> top_const) or
  5953. { Make sure the comparison value is not smaller than the
  5954. smallest allowed signed value for the minimum size (e.g.
  5955. -128 for 8-bit) }
  5956. not (
  5957. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  5958. { Is it in the negative range? }
  5959. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  5960. ) then
  5961. Break;
  5962. TestValMin := TestValMin - taicpu(hp1).oper[0]^.val;
  5963. TestValMax := TestValMax - taicpu(hp1).oper[0]^.val;
  5964. if (TestValMin < TrySmallerLimit) or (TestValMax < TrySmallerLimit) or
  5965. (TestValMin > UpperLimit) or (TestValMax > UpperLimit) then
  5966. { Overflow }
  5967. Break;
  5968. { Check to see if the active register is used afterwards }
  5969. TransferUsedRegs(TmpUsedRegs);
  5970. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  5971. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  5972. begin
  5973. case MinSize of
  5974. S_B:
  5975. TargetSubReg := R_SUBL;
  5976. S_W:
  5977. TargetSubReg := R_SUBW;
  5978. else
  5979. InternalError(2021051002);
  5980. end;
  5981. { Update the register to its new size }
  5982. setsubreg(ThisReg, TargetSubReg);
  5983. taicpu(hp1).oper[1]^.reg := ThisReg;
  5984. taicpu(hp1).opsize := MinSize;
  5985. { Convert the input MOVZX to a MOV }
  5986. if (taicpu(p).oper[0]^.typ = top_reg) and
  5987. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  5988. begin
  5989. { Or remove it completely! }
  5990. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  5991. RemoveCurrentP(p);
  5992. p_removed := True;
  5993. end
  5994. else
  5995. begin
  5996. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  5997. taicpu(p).opcode := A_MOV;
  5998. taicpu(p).oper[1]^.reg := ThisReg;
  5999. taicpu(p).opsize := MinSize;
  6000. end;
  6001. if (InstrMax >= 0) then
  6002. begin
  6003. for Index := 0 to InstrMax do
  6004. begin
  6005. { If p_removed is true, then the original MOV/Z was removed
  6006. and removing the AND instruction may not be safe if it
  6007. appears first }
  6008. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  6009. InternalError(2020112311);
  6010. if InstrList[Index].oper[0]^.typ = top_reg then
  6011. InstrList[Index].oper[0]^.reg := ThisReg;
  6012. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  6013. InstrList[Index].opsize := MinSize;
  6014. end;
  6015. end;
  6016. Result := True;
  6017. Exit;
  6018. end;
  6019. end;
  6020. { OR and XOR are not included because they can too easily fool
  6021. the data flow analysis (they can cause non-linear behaviour) }
  6022. A_ADD,A_SUB,A_AND,A_SHL,A_SHR:
  6023. begin
  6024. if
  6025. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  6026. { Has to be an exact match on the register }
  6027. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  6028. (
  6029. (
  6030. (taicpu(hp1).oper[0]^.typ = top_const) and
  6031. (
  6032. (
  6033. (taicpu(hp1).opcode = A_SHL) and
  6034. (
  6035. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  6036. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  6037. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  6038. )
  6039. ) or (
  6040. (taicpu(hp1).opcode <> A_SHL) and
  6041. (
  6042. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  6043. { Is it in the negative range? }
  6044. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  6045. )
  6046. )
  6047. )
  6048. ) or (
  6049. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  6050. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  6051. )
  6052. ) then
  6053. Break;
  6054. case taicpu(hp1).opcode of
  6055. A_ADD:
  6056. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  6057. begin
  6058. TestValMin := TestValMin * 2;
  6059. TestValMax := TestValMax * 2;
  6060. end
  6061. else
  6062. begin
  6063. TestValMin := TestValMin + taicpu(hp1).oper[0]^.val;
  6064. TestValMax := TestValMax + taicpu(hp1).oper[0]^.val;
  6065. end;
  6066. A_SUB:
  6067. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  6068. begin
  6069. TestValMin := 0;
  6070. TestValMax := 0;
  6071. end
  6072. else
  6073. begin
  6074. TestValMin := TestValMin - taicpu(hp1).oper[0]^.val;
  6075. TestValMax := TestValMax - taicpu(hp1).oper[0]^.val;
  6076. end;
  6077. A_AND:
  6078. if (taicpu(hp1).oper[0]^.typ = top_const) then
  6079. begin
  6080. { we might be able to go smaller if AND appears first }
  6081. if InstrMax = -1 then
  6082. case MinSize of
  6083. S_B:
  6084. ;
  6085. S_W:
  6086. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  6087. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  6088. begin
  6089. TrySmaller := S_B;
  6090. TrySmallerLimit := $FF;
  6091. end;
  6092. S_L:
  6093. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  6094. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  6095. begin
  6096. TrySmaller := S_B;
  6097. TrySmallerLimit := $FF;
  6098. end
  6099. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  6100. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  6101. begin
  6102. TrySmaller := S_W;
  6103. TrySmallerLimit := $FFFF;
  6104. end;
  6105. else
  6106. InternalError(2020112320);
  6107. end;
  6108. TestValMin := TestValMin and taicpu(hp1).oper[0]^.val;
  6109. TestValMax := TestValMax and taicpu(hp1).oper[0]^.val;
  6110. end;
  6111. A_SHL:
  6112. begin
  6113. TestValMin := TestValMin shl taicpu(hp1).oper[0]^.val;
  6114. TestValMax := TestValMax shl taicpu(hp1).oper[0]^.val;
  6115. end;
  6116. A_SHR:
  6117. begin
  6118. { we might be able to go smaller if SHR appears first }
  6119. if InstrMax = -1 then
  6120. case MinSize of
  6121. S_B:
  6122. ;
  6123. S_W:
  6124. if (taicpu(hp1).oper[0]^.val >= 8) then
  6125. begin
  6126. TrySmaller := S_B;
  6127. TrySmallerLimit := $FF;
  6128. end;
  6129. S_L:
  6130. if (taicpu(hp1).oper[0]^.val >= 24) then
  6131. begin
  6132. TrySmaller := S_B;
  6133. TrySmallerLimit := $FF;
  6134. end
  6135. else if (taicpu(hp1).oper[0]^.val >= 16) then
  6136. begin
  6137. TrySmaller := S_W;
  6138. TrySmallerLimit := $FFFF;
  6139. end;
  6140. else
  6141. InternalError(2020112321);
  6142. end;
  6143. TestValMin := TestValMin shr taicpu(hp1).oper[0]^.val;
  6144. TestValMax := TestValMax shr taicpu(hp1).oper[0]^.val;
  6145. end;
  6146. else
  6147. InternalError(2020112303);
  6148. end;
  6149. end;
  6150. (*
  6151. A_IMUL:
  6152. case taicpu(hp1).ops of
  6153. 2:
  6154. begin
  6155. if not MatchOpType(hp1, top_reg, top_reg) or
  6156. { Has to be an exact match on the register }
  6157. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  6158. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  6159. Break;
  6160. TestValMin := TestValMin * TestValMin;
  6161. TestValMax := TestValMax * TestValMax;
  6162. end;
  6163. 3:
  6164. begin
  6165. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  6166. { Has to be an exact match on the register }
  6167. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  6168. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  6169. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  6170. { Is it in the negative range? }
  6171. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  6172. Break;
  6173. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  6174. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  6175. end;
  6176. else
  6177. Break;
  6178. end;
  6179. A_IDIV:
  6180. case taicpu(hp1).ops of
  6181. 3:
  6182. begin
  6183. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  6184. { Has to be an exact match on the register }
  6185. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  6186. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  6187. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  6188. { Is it in the negative range? }
  6189. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  6190. Break;
  6191. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  6192. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  6193. end;
  6194. else
  6195. Break;
  6196. end;
  6197. *)
  6198. A_MOVZX:
  6199. begin
  6200. if not MatchOpType(taicpu(hp1), top_reg, top_reg) then
  6201. Break;
  6202. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  6203. begin
  6204. { Because hp1 was obtained via GetNextInstructionUsingReg
  6205. and ThisReg doesn't appear in the first operand, it
  6206. must appear in the second operand and hence gets
  6207. overwritten }
  6208. if (InstrMax = -1) and
  6209. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  6210. begin
  6211. { The two MOVZX instructions are adjacent, so remove the first one }
  6212. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  6213. RemoveCurrentP(p);
  6214. Result := True;
  6215. Exit;
  6216. end;
  6217. Break;
  6218. end;
  6219. { The objective here is to try to find a combination that
  6220. removes one of the MOV/Z instructions. }
  6221. case taicpu(hp1).opsize of
  6222. S_WL:
  6223. if (MinSize in [S_B, S_W]) then
  6224. begin
  6225. TargetSize := S_L;
  6226. TargetSubReg := R_SUBD;
  6227. end
  6228. else if ((TrySmaller in [S_B, S_W]) and not SmallerOverflow) then
  6229. begin
  6230. TargetSize := TrySmaller;
  6231. if TrySmaller = S_B then
  6232. TargetSubReg := R_SUBL
  6233. else
  6234. TargetSubReg := R_SUBW;
  6235. end
  6236. else
  6237. Break;
  6238. S_BW:
  6239. if (MinSize in [S_B, S_W]) then
  6240. begin
  6241. TargetSize := S_W;
  6242. TargetSubReg := R_SUBW;
  6243. end
  6244. else if ((TrySmaller = S_B) and not SmallerOverflow) then
  6245. begin
  6246. TargetSize := S_B;
  6247. TargetSubReg := R_SUBL;
  6248. end
  6249. else
  6250. Break;
  6251. S_BL:
  6252. if (MinSize in [S_B, S_W]) then
  6253. begin
  6254. TargetSize := S_L;
  6255. TargetSubReg := R_SUBD;
  6256. end
  6257. else if ((TrySmaller = S_B) and not SmallerOverflow) then
  6258. begin
  6259. TargetSize := S_B;
  6260. TargetSubReg := R_SUBL;
  6261. end
  6262. else
  6263. Break;
  6264. else
  6265. InternalError(2020112302);
  6266. end;
  6267. { Update the register to its new size }
  6268. setsubreg(ThisReg, TargetSubReg);
  6269. if TargetSize = MinSize then
  6270. begin
  6271. { Convert the input MOVZX to a MOV }
  6272. if (taicpu(p).oper[0]^.typ = top_reg) and
  6273. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  6274. begin
  6275. { Or remove it completely! }
  6276. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  6277. RemoveCurrentP(p);
  6278. p_removed := True;
  6279. end
  6280. else
  6281. begin
  6282. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  6283. taicpu(p).opcode := A_MOV;
  6284. taicpu(p).oper[1]^.reg := ThisReg;
  6285. taicpu(p).opsize := TargetSize;
  6286. end;
  6287. Result := True;
  6288. end
  6289. else if TargetSize <> MaxSize then
  6290. begin
  6291. case MaxSize of
  6292. S_L:
  6293. if TargetSize = S_W then
  6294. begin
  6295. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  6296. taicpu(p).opsize := S_BW;
  6297. taicpu(p).oper[1]^.reg := ThisReg;
  6298. Result := True;
  6299. end
  6300. else
  6301. InternalError(2020112341);
  6302. S_W:
  6303. if TargetSize = S_L then
  6304. begin
  6305. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  6306. taicpu(p).opsize := S_BL;
  6307. taicpu(p).oper[1]^.reg := ThisReg;
  6308. Result := True;
  6309. end
  6310. else
  6311. InternalError(2020112342);
  6312. else
  6313. ;
  6314. end;
  6315. end;
  6316. if (MaxSize = TargetSize) or
  6317. ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  6318. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  6319. begin
  6320. { Convert the output MOVZX to a MOV }
  6321. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  6322. begin
  6323. { Or remove it completely! }
  6324. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  6325. { Be careful; if p = hp1 and p was also removed, p
  6326. will become a dangling pointer }
  6327. if p = hp1 then
  6328. RemoveCurrentp(p) { p = hp1 and will then become the next instruction }
  6329. else
  6330. RemoveInstruction(hp1);
  6331. end
  6332. else
  6333. begin
  6334. taicpu(hp1).opcode := A_MOV;
  6335. taicpu(hp1).oper[0]^.reg := ThisReg;
  6336. taicpu(hp1).opsize := TargetSize;
  6337. { Check to see if the active register is used afterwards;
  6338. if not, we can change it and make a saving. }
  6339. RegInUse := False;
  6340. TransferUsedRegs(TmpUsedRegs);
  6341. { The target register may be marked as in use to cross
  6342. a jump to a distant label, so exclude it }
  6343. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  6344. hp2 := p;
  6345. repeat
  6346. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6347. { Explicitly check for the excluded register (don't include the first
  6348. instruction as it may be reading from here }
  6349. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  6350. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  6351. begin
  6352. RegInUse := True;
  6353. Break;
  6354. end;
  6355. if not GetNextInstruction(hp2, hp2) then
  6356. InternalError(2020112340);
  6357. until (hp2 = hp1);
  6358. if not RegInUse and not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  6359. begin
  6360. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  6361. ThisReg := taicpu(hp1).oper[1]^.reg;
  6362. RegChanged := True;
  6363. TransferUsedRegs(TmpUsedRegs);
  6364. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  6365. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  6366. if p = hp1 then
  6367. RemoveCurrentp(p) { p = hp1 and will then become the next instruction }
  6368. else
  6369. RemoveInstruction(hp1);
  6370. { Instruction will become "mov %reg,%reg" }
  6371. if not p_removed and (taicpu(p).opcode = A_MOV) and
  6372. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  6373. begin
  6374. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  6375. RemoveCurrentP(p);
  6376. p_removed := True;
  6377. end
  6378. else
  6379. taicpu(p).oper[1]^.reg := ThisReg;
  6380. Result := True;
  6381. end
  6382. else
  6383. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  6384. end;
  6385. end
  6386. else
  6387. InternalError(2020112330);
  6388. { Now go through every instruction we found and change the
  6389. size. If TargetSize = MaxSize, then almost no changes are
  6390. needed and Result can remain False if it hasn't been set
  6391. yet.
  6392. If RegChanged is True, then the register requires changing
  6393. and so the point about TargetSize = MaxSize doesn't apply. }
  6394. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  6395. begin
  6396. for Index := 0 to InstrMax do
  6397. begin
  6398. { If p_removed is true, then the original MOV/Z was removed
  6399. and removing the AND instruction may not be safe if it
  6400. appears first }
  6401. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  6402. InternalError(2020112310);
  6403. if InstrList[Index].oper[0]^.typ = top_reg then
  6404. InstrList[Index].oper[0]^.reg := ThisReg;
  6405. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  6406. InstrList[Index].opsize := TargetSize;
  6407. end;
  6408. Result := True;
  6409. end;
  6410. Exit;
  6411. end;
  6412. else
  6413. { This includes ADC, SBB, IDIV and SAR }
  6414. Break;
  6415. end;
  6416. if (TestValMin < 0) or (TestValMax < 0) or
  6417. (TestValMin > UpperLimit) or (TestValMax > UpperLimit) then
  6418. { Overflow }
  6419. Break
  6420. else if not SmallerOverflow and (TrySmaller <> S_NO) and
  6421. ((TestValMin > TrySmallerLimit) or (TestValMax > TrySmallerLimit)) then
  6422. SmallerOverflow := True;
  6423. { Contains highest index (so instruction count - 1) }
  6424. Inc(InstrMax);
  6425. if InstrMax > High(InstrList) then
  6426. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  6427. InstrList[InstrMax] := taicpu(hp1);
  6428. end;
  6429. end;
  6430. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  6431. var
  6432. hp1 : tai;
  6433. begin
  6434. Result:=false;
  6435. if (taicpu(p).ops >= 2) and
  6436. ((taicpu(p).oper[0]^.typ = top_const) or
  6437. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  6438. (taicpu(p).oper[1]^.typ = top_reg) and
  6439. ((taicpu(p).ops = 2) or
  6440. ((taicpu(p).oper[2]^.typ = top_reg) and
  6441. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  6442. GetLastInstruction(p,hp1) and
  6443. MatchInstruction(hp1,A_MOV,[]) and
  6444. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6445. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  6446. begin
  6447. TransferUsedRegs(TmpUsedRegs);
  6448. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  6449. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  6450. { change
  6451. mov reg1,reg2
  6452. imul y,reg2 to imul y,reg1,reg2 }
  6453. begin
  6454. taicpu(p).ops := 3;
  6455. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  6456. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6457. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  6458. RemoveInstruction(hp1);
  6459. result:=true;
  6460. end;
  6461. end;
  6462. end;
  6463. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  6464. var
  6465. ThisLabel: TAsmLabel;
  6466. begin
  6467. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  6468. ThisLabel.decrefs;
  6469. taicpu(p).opcode := A_RET;
  6470. taicpu(p).is_jmp := false;
  6471. taicpu(p).ops := taicpu(ret_p).ops;
  6472. case taicpu(ret_p).ops of
  6473. 0:
  6474. taicpu(p).clearop(0);
  6475. 1:
  6476. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  6477. else
  6478. internalerror(2016041301);
  6479. end;
  6480. { If the original label is now dead, it might turn out that the label
  6481. immediately follows p. As a result, everything beyond it, which will
  6482. be just some final register configuration and a RET instruction, is
  6483. now dead code. [Kit] }
  6484. { NOTE: This is much faster than introducing a OptPass2RET routine and
  6485. running RemoveDeadCodeAfterJump for each RET instruction, because
  6486. this optimisation rarely happens and most RETs appear at the end of
  6487. routines where there is nothing that can be stripped. [Kit] }
  6488. if not ThisLabel.is_used then
  6489. RemoveDeadCodeAfterJump(p);
  6490. end;
  6491. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  6492. var
  6493. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  6494. Unconditional, PotentialModified: Boolean;
  6495. OperPtr: POper;
  6496. NewRef: TReference;
  6497. InstrList: array of taicpu;
  6498. InstrMax, Index: Integer;
  6499. const
  6500. {$ifdef DEBUG_AOPTCPU}
  6501. SNoFlags: shortstring = ' so the flags aren''t modified';
  6502. {$else DEBUG_AOPTCPU}
  6503. SNoFlags = '';
  6504. {$endif DEBUG_AOPTCPU}
  6505. begin
  6506. Result:=false;
  6507. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  6508. begin
  6509. if MatchInstruction(hp1, A_TEST, [S_B]) and
  6510. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6511. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  6512. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  6513. GetNextInstruction(hp1, hp2) and
  6514. MatchInstruction(hp2, A_Jcc, []) then
  6515. { Change from: To:
  6516. set(C) %reg j(~C) label
  6517. test %reg,%reg/cmp $0,%reg
  6518. je label
  6519. set(C) %reg j(C) label
  6520. test %reg,%reg/cmp $0,%reg
  6521. jne label
  6522. }
  6523. begin
  6524. { Before we do anything else, we need to check the instructions
  6525. in between SETcc and TEST to make sure they don't modify the
  6526. FLAGS register - if -O2 or under, there won't be any
  6527. instructions between SET and TEST }
  6528. TransferUsedRegs(TmpUsedRegs);
  6529. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6530. if (cs_opt_level3 in current_settings.optimizerswitches) then
  6531. begin
  6532. next := p;
  6533. SetLength(InstrList, 0);
  6534. InstrMax := -1;
  6535. PotentialModified := False;
  6536. { Make a note of every instruction that modifies the FLAGS
  6537. register }
  6538. while GetNextInstruction(next, next) and (next <> hp1) do
  6539. begin
  6540. if next.typ <> ait_instruction then
  6541. { GetNextInstructionUsingReg should have returned False }
  6542. InternalError(2021051701);
  6543. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  6544. begin
  6545. case taicpu(next).opcode of
  6546. A_SETcc,
  6547. A_CMOVcc,
  6548. A_Jcc:
  6549. begin
  6550. if PotentialModified then
  6551. { Not safe because the flags were modified earlier }
  6552. Exit
  6553. else
  6554. { Condition is the same as the initial SETcc, so this is safe
  6555. (don't add to instruction list though) }
  6556. Continue;
  6557. end;
  6558. A_ADD:
  6559. begin
  6560. if (taicpu(next).opsize = S_B) or
  6561. { LEA doesn't support 8-bit operands }
  6562. (taicpu(next).oper[1]^.typ <> top_reg) or
  6563. { Must write to a register }
  6564. (taicpu(next).oper[0]^.typ = top_ref) then
  6565. { Require a constant or a register }
  6566. Exit;
  6567. PotentialModified := True;
  6568. end;
  6569. A_SUB:
  6570. begin
  6571. if (taicpu(next).opsize = S_B) or
  6572. { LEA doesn't support 8-bit operands }
  6573. (taicpu(next).oper[1]^.typ <> top_reg) or
  6574. { Must write to a register }
  6575. (taicpu(next).oper[0]^.typ <> top_const) or
  6576. (taicpu(next).oper[0]^.val = $80000000) then
  6577. { Can't subtract a register with LEA - also
  6578. check that the value isn't -2^31, as this
  6579. can't be negated }
  6580. Exit;
  6581. PotentialModified := True;
  6582. end;
  6583. A_SAL,
  6584. A_SHL:
  6585. begin
  6586. if (taicpu(next).opsize = S_B) or
  6587. { LEA doesn't support 8-bit operands }
  6588. (taicpu(next).oper[1]^.typ <> top_reg) or
  6589. { Must write to a register }
  6590. (taicpu(next).oper[0]^.typ <> top_const) or
  6591. (taicpu(next).oper[0]^.val < 0) or
  6592. (taicpu(next).oper[0]^.val > 3) then
  6593. Exit;
  6594. PotentialModified := True;
  6595. end;
  6596. A_IMUL:
  6597. begin
  6598. if (taicpu(next).ops <> 3) or
  6599. (taicpu(next).oper[1]^.typ <> top_reg) or
  6600. { Must write to a register }
  6601. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  6602. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  6603. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  6604. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  6605. Exit
  6606. else
  6607. PotentialModified := True;
  6608. end;
  6609. else
  6610. { Don't know how to change this, so abort }
  6611. Exit;
  6612. end;
  6613. { Contains highest index (so instruction count - 1) }
  6614. Inc(InstrMax);
  6615. if InstrMax > High(InstrList) then
  6616. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  6617. InstrList[InstrMax] := taicpu(next);
  6618. end;
  6619. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  6620. end;
  6621. if not Assigned(next) or (next <> hp1) then
  6622. { It should be equal to hp1 }
  6623. InternalError(2021051702);
  6624. { Cycle through each instruction and check to see if we can
  6625. change them to versions that don't modify the flags }
  6626. if (InstrMax >= 0) then
  6627. begin
  6628. for Index := 0 to InstrMax do
  6629. case InstrList[Index].opcode of
  6630. A_ADD:
  6631. begin
  6632. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  6633. InstrList[Index].opcode := A_LEA;
  6634. reference_reset(NewRef, 1, []);
  6635. NewRef.base := InstrList[Index].oper[1]^.reg;
  6636. if InstrList[Index].oper[0]^.typ = top_reg then
  6637. begin
  6638. NewRef.index := InstrList[Index].oper[0]^.reg;
  6639. NewRef.scalefactor := 1;
  6640. end
  6641. else
  6642. NewRef.offset := InstrList[Index].oper[0]^.val;
  6643. InstrList[Index].loadref(0, NewRef);
  6644. end;
  6645. A_SUB:
  6646. begin
  6647. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  6648. InstrList[Index].opcode := A_LEA;
  6649. reference_reset(NewRef, 1, []);
  6650. NewRef.base := InstrList[Index].oper[1]^.reg;
  6651. NewRef.offset := -InstrList[Index].oper[0]^.val;
  6652. InstrList[Index].loadref(0, NewRef);
  6653. end;
  6654. A_SHL,
  6655. A_SAL:
  6656. begin
  6657. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  6658. InstrList[Index].opcode := A_LEA;
  6659. reference_reset(NewRef, 1, []);
  6660. NewRef.index := InstrList[Index].oper[1]^.reg;
  6661. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  6662. InstrList[Index].loadref(0, NewRef);
  6663. end;
  6664. A_IMUL:
  6665. begin
  6666. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  6667. InstrList[Index].opcode := A_LEA;
  6668. reference_reset(NewRef, 1, []);
  6669. NewRef.index := InstrList[Index].oper[1]^.reg;
  6670. case InstrList[Index].oper[0]^.val of
  6671. 2, 4, 8:
  6672. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  6673. else {3, 5 and 9}
  6674. begin
  6675. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  6676. NewRef.base := InstrList[Index].oper[1]^.reg;
  6677. end;
  6678. end;
  6679. InstrList[Index].loadref(0, NewRef);
  6680. end;
  6681. else
  6682. InternalError(2021051710);
  6683. end;
  6684. end;
  6685. { Mark the FLAGS register as used across this whole block }
  6686. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  6687. end;
  6688. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6689. JumpC := taicpu(hp2).condition;
  6690. Unconditional := False;
  6691. if conditions_equal(JumpC, C_E) then
  6692. SetC := inverse_cond(taicpu(p).condition)
  6693. else if conditions_equal(JumpC, C_NE) then
  6694. SetC := taicpu(p).condition
  6695. else
  6696. { We've got something weird here (and inefficent) }
  6697. begin
  6698. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  6699. SetC := C_NONE;
  6700. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  6701. if condition_in(C_AE, JumpC) then
  6702. Unconditional := True
  6703. else
  6704. { Not sure what to do with this jump - drop out }
  6705. Exit;
  6706. end;
  6707. RemoveInstruction(hp1);
  6708. if Unconditional then
  6709. MakeUnconditional(taicpu(hp2))
  6710. else
  6711. begin
  6712. if SetC = C_NONE then
  6713. InternalError(2018061402);
  6714. taicpu(hp2).SetCondition(SetC);
  6715. end;
  6716. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  6717. TmpUsedRegs }
  6718. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  6719. begin
  6720. RemoveCurrentp(p, hp2);
  6721. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  6722. end
  6723. else
  6724. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  6725. Result := True;
  6726. end
  6727. else if
  6728. { Make sure the instructions are adjacent }
  6729. (
  6730. not (cs_opt_level3 in current_settings.optimizerswitches) or
  6731. GetNextInstruction(p, hp1)
  6732. ) and
  6733. MatchInstruction(hp1, A_MOV, [S_B]) and
  6734. { Writing to memory is allowed }
  6735. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  6736. begin
  6737. {
  6738. Watch out for sequences such as:
  6739. set(c)b %regb
  6740. movb %regb,(ref)
  6741. movb $0,1(ref)
  6742. movb $0,2(ref)
  6743. movb $0,3(ref)
  6744. Much more efficient to turn it into:
  6745. movl $0,%regl
  6746. set(c)b %regb
  6747. movl %regl,(ref)
  6748. Or:
  6749. set(c)b %regb
  6750. movzbl %regb,%regl
  6751. movl %regl,(ref)
  6752. }
  6753. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  6754. GetNextInstruction(hp1, hp2) and
  6755. MatchInstruction(hp2, A_MOV, [S_B]) and
  6756. (taicpu(hp2).oper[1]^.typ = top_ref) and
  6757. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  6758. begin
  6759. { Don't do anything else except set Result to True }
  6760. end
  6761. else
  6762. begin
  6763. if taicpu(p).oper[0]^.typ = top_reg then
  6764. begin
  6765. TransferUsedRegs(TmpUsedRegs);
  6766. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6767. end;
  6768. { If it's not a register, it's a memory address }
  6769. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  6770. begin
  6771. { Even if the register is still in use, we can minimise the
  6772. pipeline stall by changing the MOV into another SETcc. }
  6773. taicpu(hp1).opcode := A_SETcc;
  6774. taicpu(hp1).condition := taicpu(p).condition;
  6775. if taicpu(hp1).oper[1]^.typ = top_ref then
  6776. begin
  6777. { Swapping the operand pointers like this is probably a
  6778. bit naughty, but it is far faster than using loadoper
  6779. to transfer the reference from oper[1] to oper[0] if
  6780. you take into account the extra procedure calls and
  6781. the memory allocation and deallocation required }
  6782. OperPtr := taicpu(hp1).oper[1];
  6783. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  6784. taicpu(hp1).oper[0] := OperPtr;
  6785. end
  6786. else
  6787. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  6788. taicpu(hp1).clearop(1);
  6789. taicpu(hp1).ops := 1;
  6790. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  6791. end
  6792. else
  6793. begin
  6794. if taicpu(hp1).oper[1]^.typ = top_reg then
  6795. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  6796. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  6797. RemoveInstruction(hp1);
  6798. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  6799. end
  6800. end;
  6801. Result := True;
  6802. end;
  6803. end;
  6804. end;
  6805. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  6806. var
  6807. hp1: tai;
  6808. Count: Integer;
  6809. OrigLabel: TAsmLabel;
  6810. begin
  6811. result := False;
  6812. { Sometimes, the optimisations below can permit this }
  6813. RemoveDeadCodeAfterJump(p);
  6814. 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
  6815. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  6816. begin
  6817. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  6818. { Also a side-effect of optimisations }
  6819. if CollapseZeroDistJump(p, OrigLabel) then
  6820. begin
  6821. Result := True;
  6822. Exit;
  6823. end;
  6824. hp1 := GetLabelWithSym(OrigLabel);
  6825. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  6826. begin
  6827. case taicpu(hp1).opcode of
  6828. A_RET:
  6829. {
  6830. change
  6831. jmp .L1
  6832. ...
  6833. .L1:
  6834. ret
  6835. into
  6836. ret
  6837. }
  6838. begin
  6839. ConvertJumpToRET(p, hp1);
  6840. result:=true;
  6841. end;
  6842. { Check any kind of direct assignment instruction }
  6843. A_MOV,
  6844. A_MOVD,
  6845. A_MOVQ,
  6846. A_MOVSX,
  6847. {$ifdef x86_64}
  6848. A_MOVSXD,
  6849. {$endif x86_64}
  6850. A_MOVZX,
  6851. A_MOVAPS,
  6852. A_MOVUPS,
  6853. A_MOVSD,
  6854. A_MOVAPD,
  6855. A_MOVUPD,
  6856. A_MOVDQA,
  6857. A_MOVDQU,
  6858. A_VMOVSS,
  6859. A_VMOVAPS,
  6860. A_VMOVUPS,
  6861. A_VMOVSD,
  6862. A_VMOVAPD,
  6863. A_VMOVUPD,
  6864. A_VMOVDQA,
  6865. A_VMOVDQU:
  6866. if ((current_settings.optimizerswitches * [cs_opt_level3, cs_opt_size]) <> [cs_opt_size]) and
  6867. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  6868. begin
  6869. Result := True;
  6870. Exit;
  6871. end;
  6872. else
  6873. ;
  6874. end;
  6875. end;
  6876. end;
  6877. end;
  6878. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  6879. begin
  6880. CanBeCMOV:=assigned(p) and
  6881. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  6882. { we can't use cmov ref,reg because
  6883. ref could be nil and cmov still throws an exception
  6884. if ref=nil but the mov isn't done (FK)
  6885. or ((taicpu(p).oper[0]^.typ = top_ref) and
  6886. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  6887. }
  6888. (taicpu(p).oper[1]^.typ = top_reg) and
  6889. (
  6890. (taicpu(p).oper[0]^.typ = top_reg) or
  6891. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  6892. it is not expected that this can cause a seg. violation }
  6893. (
  6894. (taicpu(p).oper[0]^.typ = top_ref) and
  6895. IsRefSafe(taicpu(p).oper[0]^.ref)
  6896. )
  6897. );
  6898. end;
  6899. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  6900. var
  6901. hp1,hp2: tai;
  6902. {$ifndef i8086}
  6903. hp3,hp4,hpmov2, hp5: tai;
  6904. l : Longint;
  6905. condition : TAsmCond;
  6906. {$endif i8086}
  6907. carryadd_opcode : TAsmOp;
  6908. symbol: TAsmSymbol;
  6909. reg: tsuperregister;
  6910. increg, tmpreg: TRegister;
  6911. begin
  6912. result:=false;
  6913. if GetNextInstruction(p,hp1) and (hp1.typ=ait_instruction) then
  6914. begin
  6915. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  6916. if (
  6917. (
  6918. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  6919. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  6920. (Taicpu(hp1).oper[0]^.val=1)
  6921. ) or
  6922. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  6923. ) and
  6924. GetNextInstruction(hp1,hp2) and
  6925. SkipAligns(hp2, hp2) and
  6926. (hp2.typ = ait_label) and
  6927. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  6928. { jb @@1 cmc
  6929. inc/dec operand --> adc/sbb operand,0
  6930. @@1:
  6931. ... and ...
  6932. jnb @@1
  6933. inc/dec operand --> adc/sbb operand,0
  6934. @@1: }
  6935. begin
  6936. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  6937. begin
  6938. case taicpu(hp1).opcode of
  6939. A_INC,
  6940. A_ADD:
  6941. carryadd_opcode:=A_ADC;
  6942. A_DEC,
  6943. A_SUB:
  6944. carryadd_opcode:=A_SBB;
  6945. else
  6946. InternalError(2021011001);
  6947. end;
  6948. Taicpu(p).clearop(0);
  6949. Taicpu(p).ops:=0;
  6950. Taicpu(p).is_jmp:=false;
  6951. Taicpu(p).opcode:=A_CMC;
  6952. Taicpu(p).condition:=C_NONE;
  6953. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  6954. Taicpu(hp1).ops:=2;
  6955. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  6956. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  6957. else
  6958. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  6959. Taicpu(hp1).loadconst(0,0);
  6960. Taicpu(hp1).opcode:=carryadd_opcode;
  6961. result:=true;
  6962. exit;
  6963. end
  6964. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  6965. begin
  6966. case taicpu(hp1).opcode of
  6967. A_INC,
  6968. A_ADD:
  6969. carryadd_opcode:=A_ADC;
  6970. A_DEC,
  6971. A_SUB:
  6972. carryadd_opcode:=A_SBB;
  6973. else
  6974. InternalError(2021011002);
  6975. end;
  6976. Taicpu(hp1).ops:=2;
  6977. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  6978. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  6979. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  6980. else
  6981. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  6982. Taicpu(hp1).loadconst(0,0);
  6983. Taicpu(hp1).opcode:=carryadd_opcode;
  6984. RemoveCurrentP(p, hp1);
  6985. result:=true;
  6986. exit;
  6987. end
  6988. {
  6989. jcc @@1 setcc tmpreg
  6990. inc/dec/add/sub operand -> (movzx tmpreg)
  6991. @@1: add/sub tmpreg,operand
  6992. While this increases code size slightly, it makes the code much faster if the
  6993. jump is unpredictable
  6994. }
  6995. else if not(cs_opt_size in current_settings.optimizerswitches) then
  6996. begin
  6997. { search for an available register which is volatile }
  6998. for reg in tcpuregisterset do
  6999. begin
  7000. if
  7001. {$if defined(i386) or defined(i8086)}
  7002. { Only use registers whose lowest 8-bits can Be accessed }
  7003. (reg in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) and
  7004. {$endif i386 or i8086}
  7005. (reg in paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption)) and
  7006. not(reg in UsedRegs[R_INTREGISTER].GetUsedRegs)
  7007. { We don't need to check if tmpreg is in hp1 or not, because
  7008. it will be marked as in use at p (if not, this is
  7009. indictive of a compiler bug). }
  7010. then
  7011. begin
  7012. TAsmLabel(symbol).decrefs;
  7013. increg := newreg(R_INTREGISTER,reg,R_SUBL);
  7014. Taicpu(p).clearop(0);
  7015. Taicpu(p).ops:=1;
  7016. Taicpu(p).is_jmp:=false;
  7017. Taicpu(p).opcode:=A_SETcc;
  7018. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  7019. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  7020. Taicpu(p).loadreg(0,increg);
  7021. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  7022. begin
  7023. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  7024. R_SUBW:
  7025. begin
  7026. tmpreg := newreg(R_INTREGISTER,reg,R_SUBW);
  7027. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  7028. end;
  7029. R_SUBD:
  7030. begin
  7031. tmpreg := newreg(R_INTREGISTER,reg,R_SUBD);
  7032. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  7033. end;
  7034. {$ifdef x86_64}
  7035. R_SUBQ:
  7036. begin
  7037. { MOVZX doesn't have a 64-bit variant, because
  7038. the 32-bit version implicitly zeroes the
  7039. upper 32-bits of the destination register }
  7040. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,
  7041. newreg(R_INTREGISTER,reg,R_SUBD));
  7042. tmpreg := newreg(R_INTREGISTER,reg,R_SUBQ);
  7043. end;
  7044. {$endif x86_64}
  7045. else
  7046. Internalerror(2020030601);
  7047. end;
  7048. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  7049. asml.InsertAfter(hp2,p);
  7050. end
  7051. else
  7052. tmpreg := increg;
  7053. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  7054. begin
  7055. Taicpu(hp1).ops:=2;
  7056. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  7057. end;
  7058. Taicpu(hp1).loadreg(0,tmpreg);
  7059. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  7060. Result := True;
  7061. { p is no longer a Jcc instruction, so exit }
  7062. Exit;
  7063. end;
  7064. end;
  7065. end;
  7066. end;
  7067. { Detect the following:
  7068. jmp<cond> @Lbl1
  7069. jmp @Lbl2
  7070. ...
  7071. @Lbl1:
  7072. ret
  7073. Change to:
  7074. jmp<inv_cond> @Lbl2
  7075. ret
  7076. }
  7077. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  7078. begin
  7079. hp2:=getlabelwithsym(TAsmLabel(symbol));
  7080. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  7081. MatchInstruction(hp2,A_RET,[S_NO]) then
  7082. begin
  7083. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7084. { Change label address to that of the unconditional jump }
  7085. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  7086. TAsmLabel(symbol).DecRefs;
  7087. taicpu(hp1).opcode := A_RET;
  7088. taicpu(hp1).is_jmp := false;
  7089. taicpu(hp1).ops := taicpu(hp2).ops;
  7090. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  7091. case taicpu(hp2).ops of
  7092. 0:
  7093. taicpu(hp1).clearop(0);
  7094. 1:
  7095. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  7096. else
  7097. internalerror(2016041302);
  7098. end;
  7099. end;
  7100. {$ifndef i8086}
  7101. end
  7102. {
  7103. convert
  7104. j<c> .L1
  7105. mov 1,reg
  7106. jmp .L2
  7107. .L1
  7108. mov 0,reg
  7109. .L2
  7110. into
  7111. mov 0,reg
  7112. set<not(c)> reg
  7113. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7114. would destroy the flag contents
  7115. }
  7116. else if MatchInstruction(hp1,A_MOV,[]) and
  7117. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7118. {$ifdef i386}
  7119. (
  7120. { Under i386, ESI, EDI, EBP and ESP
  7121. don't have an 8-bit representation }
  7122. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7123. ) and
  7124. {$endif i386}
  7125. (taicpu(hp1).oper[0]^.val=1) and
  7126. GetNextInstruction(hp1,hp2) and
  7127. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7128. GetNextInstruction(hp2,hp3) and
  7129. { skip align }
  7130. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  7131. (hp3.typ=ait_label) and
  7132. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7133. (tai_label(hp3).labsym.getrefs=1) and
  7134. GetNextInstruction(hp3,hp4) and
  7135. MatchInstruction(hp4,A_MOV,[]) and
  7136. MatchOpType(taicpu(hp4),top_const,top_reg) and
  7137. (taicpu(hp4).oper[0]^.val=0) and
  7138. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7139. GetNextInstruction(hp4,hp5) and
  7140. (hp5.typ=ait_label) and
  7141. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  7142. (tai_label(hp5).labsym.getrefs=1) then
  7143. begin
  7144. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  7145. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  7146. { remove last label }
  7147. RemoveInstruction(hp5);
  7148. { remove second label }
  7149. RemoveInstruction(hp3);
  7150. { if align is present remove it }
  7151. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  7152. RemoveInstruction(hp3);
  7153. { remove jmp }
  7154. RemoveInstruction(hp2);
  7155. if taicpu(hp1).opsize=S_B then
  7156. RemoveInstruction(hp1)
  7157. else
  7158. taicpu(hp1).loadconst(0,0);
  7159. taicpu(hp4).opcode:=A_SETcc;
  7160. taicpu(hp4).opsize:=S_B;
  7161. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  7162. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  7163. taicpu(hp4).opercnt:=1;
  7164. taicpu(hp4).ops:=1;
  7165. taicpu(hp4).freeop(1);
  7166. RemoveCurrentP(p);
  7167. Result:=true;
  7168. exit;
  7169. end
  7170. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  7171. begin
  7172. { check for
  7173. jCC xxx
  7174. <several movs>
  7175. xxx:
  7176. }
  7177. l:=0;
  7178. while assigned(hp1) and
  7179. CanBeCMOV(hp1) and
  7180. { stop on labels }
  7181. not(hp1.typ=ait_label) do
  7182. begin
  7183. inc(l);
  7184. GetNextInstruction(hp1,hp1);
  7185. end;
  7186. if assigned(hp1) then
  7187. begin
  7188. if FindLabel(tasmlabel(symbol),hp1) then
  7189. begin
  7190. if (l<=4) and (l>0) then
  7191. begin
  7192. condition:=inverse_cond(taicpu(p).condition);
  7193. GetNextInstruction(p,hp1);
  7194. repeat
  7195. if not Assigned(hp1) then
  7196. InternalError(2018062900);
  7197. taicpu(hp1).opcode:=A_CMOVcc;
  7198. taicpu(hp1).condition:=condition;
  7199. UpdateUsedRegs(hp1);
  7200. GetNextInstruction(hp1,hp1);
  7201. until not(CanBeCMOV(hp1));
  7202. { Remember what hp1 is in case there's multiple aligns to get rid of }
  7203. hp2 := hp1;
  7204. repeat
  7205. if not Assigned(hp2) then
  7206. InternalError(2018062910);
  7207. case hp2.typ of
  7208. ait_label:
  7209. { What we expected - break out of the loop (it won't be a dead label at the top of
  7210. a cluster because that was optimised at an earlier stage) }
  7211. Break;
  7212. ait_align:
  7213. { Go to the next entry until a label is found (may be multiple aligns before it) }
  7214. begin
  7215. hp2 := tai(hp2.Next);
  7216. Continue;
  7217. end;
  7218. else
  7219. begin
  7220. { Might be a comment or temporary allocation entry }
  7221. if not (hp2.typ in SkipInstr) then
  7222. InternalError(2018062911);
  7223. hp2 := tai(hp2.Next);
  7224. Continue;
  7225. end;
  7226. end;
  7227. until False;
  7228. { Now we can safely decrement the reference count }
  7229. tasmlabel(symbol).decrefs;
  7230. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  7231. { Remove the original jump }
  7232. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  7233. GetNextInstruction(hp2, p); { Instruction after the label }
  7234. { Remove the label if this is its final reference }
  7235. if (tasmlabel(symbol).getrefs=0) then
  7236. StripLabelFast(hp1);
  7237. if Assigned(p) then
  7238. begin
  7239. UpdateUsedRegs(p);
  7240. result:=true;
  7241. end;
  7242. exit;
  7243. end;
  7244. end
  7245. else
  7246. begin
  7247. { check further for
  7248. jCC xxx
  7249. <several movs 1>
  7250. jmp yyy
  7251. xxx:
  7252. <several movs 2>
  7253. yyy:
  7254. }
  7255. { hp2 points to jmp yyy }
  7256. hp2:=hp1;
  7257. { skip hp1 to xxx (or an align right before it) }
  7258. GetNextInstruction(hp1, hp1);
  7259. if assigned(hp2) and
  7260. assigned(hp1) and
  7261. (l<=3) and
  7262. (hp2.typ=ait_instruction) and
  7263. (taicpu(hp2).is_jmp) and
  7264. (taicpu(hp2).condition=C_None) and
  7265. { real label and jump, no further references to the
  7266. label are allowed }
  7267. (tasmlabel(symbol).getrefs=1) and
  7268. FindLabel(tasmlabel(symbol),hp1) then
  7269. begin
  7270. l:=0;
  7271. { skip hp1 to <several moves 2> }
  7272. if (hp1.typ = ait_align) then
  7273. GetNextInstruction(hp1, hp1);
  7274. GetNextInstruction(hp1, hpmov2);
  7275. hp1 := hpmov2;
  7276. while assigned(hp1) and
  7277. CanBeCMOV(hp1) do
  7278. begin
  7279. inc(l);
  7280. GetNextInstruction(hp1, hp1);
  7281. end;
  7282. { hp1 points to yyy (or an align right before it) }
  7283. hp3 := hp1;
  7284. if assigned(hp1) and
  7285. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  7286. begin
  7287. condition:=inverse_cond(taicpu(p).condition);
  7288. GetNextInstruction(p,hp1);
  7289. repeat
  7290. taicpu(hp1).opcode:=A_CMOVcc;
  7291. taicpu(hp1).condition:=condition;
  7292. UpdateUsedRegs(hp1);
  7293. GetNextInstruction(hp1,hp1);
  7294. until not(assigned(hp1)) or
  7295. not(CanBeCMOV(hp1));
  7296. condition:=inverse_cond(condition);
  7297. hp1 := hpmov2;
  7298. { hp1 is now at <several movs 2> }
  7299. while Assigned(hp1) and CanBeCMOV(hp1) do
  7300. begin
  7301. taicpu(hp1).opcode:=A_CMOVcc;
  7302. taicpu(hp1).condition:=condition;
  7303. UpdateUsedRegs(hp1);
  7304. GetNextInstruction(hp1,hp1);
  7305. end;
  7306. hp1 := p;
  7307. { Get first instruction after label }
  7308. GetNextInstruction(hp3, p);
  7309. if assigned(p) and (hp3.typ = ait_align) then
  7310. GetNextInstruction(p, p);
  7311. { Don't dereference yet, as doing so will cause
  7312. GetNextInstruction to skip the label and
  7313. optional align marker. [Kit] }
  7314. GetNextInstruction(hp2, hp4);
  7315. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  7316. { remove jCC }
  7317. RemoveInstruction(hp1);
  7318. { Now we can safely decrement it }
  7319. tasmlabel(symbol).decrefs;
  7320. { Remove label xxx (it will have a ref of zero due to the initial check }
  7321. StripLabelFast(hp4);
  7322. { remove jmp }
  7323. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  7324. RemoveInstruction(hp2);
  7325. { As before, now we can safely decrement it }
  7326. tasmlabel(symbol).decrefs;
  7327. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  7328. if tasmlabel(symbol).getrefs = 0 then
  7329. StripLabelFast(hp3);
  7330. if Assigned(p) then
  7331. begin
  7332. UpdateUsedRegs(p);
  7333. result:=true;
  7334. end;
  7335. exit;
  7336. end;
  7337. end;
  7338. end;
  7339. end;
  7340. {$endif i8086}
  7341. end;
  7342. end;
  7343. end;
  7344. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  7345. var
  7346. hp1,hp2: tai;
  7347. reg_and_hp1_is_instr: Boolean;
  7348. begin
  7349. result:=false;
  7350. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  7351. GetNextInstruction(p,hp1) and
  7352. (hp1.typ = ait_instruction);
  7353. if reg_and_hp1_is_instr and
  7354. (
  7355. (taicpu(hp1).opcode <> A_LEA) or
  7356. { If the LEA instruction can be converted into an arithmetic instruction,
  7357. it may be possible to then fold it. }
  7358. (
  7359. { If the flags register is in use, don't change the instruction
  7360. to an ADD otherwise this will scramble the flags. [Kit] }
  7361. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  7362. ConvertLEA(taicpu(hp1))
  7363. )
  7364. ) and
  7365. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  7366. GetNextInstruction(hp1,hp2) and
  7367. MatchInstruction(hp2,A_MOV,[]) and
  7368. (taicpu(hp2).oper[0]^.typ = top_reg) and
  7369. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  7370. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  7371. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  7372. {$ifdef i386}
  7373. { not all registers have byte size sub registers on i386 }
  7374. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  7375. {$endif i386}
  7376. (((taicpu(hp1).ops=2) and
  7377. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7378. ((taicpu(hp1).ops=1) and
  7379. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  7380. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  7381. begin
  7382. { change movsX/movzX reg/ref, reg2
  7383. add/sub/or/... reg3/$const, reg2
  7384. mov reg2 reg/ref
  7385. to add/sub/or/... reg3/$const, reg/ref }
  7386. { by example:
  7387. movswl %si,%eax movswl %si,%eax p
  7388. decl %eax addl %edx,%eax hp1
  7389. movw %ax,%si movw %ax,%si hp2
  7390. ->
  7391. movswl %si,%eax movswl %si,%eax p
  7392. decw %eax addw %edx,%eax hp1
  7393. movw %ax,%si movw %ax,%si hp2
  7394. }
  7395. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  7396. {
  7397. ->
  7398. movswl %si,%eax movswl %si,%eax p
  7399. decw %si addw %dx,%si hp1
  7400. movw %ax,%si movw %ax,%si hp2
  7401. }
  7402. case taicpu(hp1).ops of
  7403. 1:
  7404. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  7405. 2:
  7406. begin
  7407. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  7408. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  7409. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  7410. end;
  7411. else
  7412. internalerror(2008042702);
  7413. end;
  7414. {
  7415. ->
  7416. decw %si addw %dx,%si p
  7417. }
  7418. DebugMsg(SPeepholeOptimization + 'var3',p);
  7419. RemoveCurrentP(p, hp1);
  7420. RemoveInstruction(hp2);
  7421. end
  7422. else if reg_and_hp1_is_instr and
  7423. (taicpu(hp1).opcode = A_MOV) and
  7424. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7425. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  7426. {$ifdef x86_64}
  7427. { check for implicit extension to 64 bit }
  7428. or
  7429. ((taicpu(p).opsize in [S_BL,S_WL]) and
  7430. (taicpu(hp1).opsize=S_Q) and
  7431. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  7432. )
  7433. {$endif x86_64}
  7434. )
  7435. then
  7436. begin
  7437. { change
  7438. movx %reg1,%reg2
  7439. mov %reg2,%reg3
  7440. dealloc %reg2
  7441. into
  7442. movx %reg,%reg3
  7443. }
  7444. TransferUsedRegs(TmpUsedRegs);
  7445. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7446. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7447. begin
  7448. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  7449. {$ifdef x86_64}
  7450. if (taicpu(p).opsize in [S_BL,S_WL]) and
  7451. (taicpu(hp1).opsize=S_Q) then
  7452. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  7453. else
  7454. {$endif x86_64}
  7455. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7456. RemoveInstruction(hp1);
  7457. end;
  7458. end
  7459. else if reg_and_hp1_is_instr and
  7460. (taicpu(hp1).opcode = A_MOV) and
  7461. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7462. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  7463. (taicpu(hp1).opsize=S_B)) or
  7464. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  7465. (taicpu(hp1).opsize=S_W))
  7466. {$ifdef x86_64}
  7467. or ((taicpu(p).opsize=S_LQ) and
  7468. (taicpu(hp1).opsize=S_L))
  7469. {$endif x86_64}
  7470. ) and
  7471. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  7472. begin
  7473. { change
  7474. movx %reg1,%reg2
  7475. mov %reg2,%reg3
  7476. dealloc %reg2
  7477. into
  7478. mov %reg1,%reg3
  7479. if the second mov accesses only the bits stored in reg1
  7480. }
  7481. TransferUsedRegs(TmpUsedRegs);
  7482. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7483. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7484. begin
  7485. DebugMsg(SPeepholeOptimization + 'MovxMov2Mov',p);
  7486. if taicpu(p).oper[0]^.typ=top_reg then
  7487. begin
  7488. case taicpu(hp1).opsize of
  7489. S_B:
  7490. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  7491. S_W:
  7492. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  7493. S_L:
  7494. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  7495. else
  7496. Internalerror(2020102301);
  7497. end;
  7498. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  7499. end
  7500. else
  7501. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  7502. RemoveCurrentP(p);
  7503. result:=true;
  7504. exit;
  7505. end;
  7506. end
  7507. else if reg_and_hp1_is_instr and
  7508. (taicpu(p).oper[0]^.typ = top_reg) and
  7509. (
  7510. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  7511. ) and
  7512. (taicpu(hp1).oper[0]^.typ = top_const) and
  7513. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  7514. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  7515. { Minimum shift value allowed is the bit difference between the sizes }
  7516. (taicpu(hp1).oper[0]^.val >=
  7517. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  7518. 8 * (
  7519. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  7520. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  7521. )
  7522. ) then
  7523. begin
  7524. { For:
  7525. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  7526. shl/sal ##, %reg1
  7527. Remove the movsx/movzx instruction if the shift overwrites the
  7528. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  7529. }
  7530. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  7531. RemoveCurrentP(p, hp1);
  7532. Result := True;
  7533. Exit;
  7534. end
  7535. else if reg_and_hp1_is_instr and
  7536. (taicpu(p).oper[0]^.typ = top_reg) and
  7537. (
  7538. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  7539. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  7540. ) and
  7541. (taicpu(hp1).oper[0]^.typ = top_const) and
  7542. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  7543. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  7544. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  7545. (taicpu(hp1).oper[0]^.val <
  7546. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  7547. 8 * (
  7548. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  7549. )
  7550. ) then
  7551. begin
  7552. { For:
  7553. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  7554. sar ##, %reg1 shr ##, %reg1
  7555. Move the shift to before the movx instruction if the shift value
  7556. is not too large.
  7557. }
  7558. asml.Remove(hp1);
  7559. asml.InsertBefore(hp1, p);
  7560. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  7561. case taicpu(p).opsize of
  7562. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  7563. taicpu(hp1).opsize := S_B;
  7564. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  7565. taicpu(hp1).opsize := S_W;
  7566. {$ifdef x86_64}
  7567. S_LQ:
  7568. taicpu(hp1).opsize := S_L;
  7569. {$endif}
  7570. else
  7571. InternalError(2020112401);
  7572. end;
  7573. if (taicpu(hp1).opcode = A_SHR) then
  7574. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  7575. else
  7576. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  7577. Result := True;
  7578. end
  7579. else if taicpu(p).opcode=A_MOVZX then
  7580. begin
  7581. { removes superfluous And's after movzx's }
  7582. if reg_and_hp1_is_instr and
  7583. (taicpu(hp1).opcode = A_AND) and
  7584. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7585. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  7586. {$ifdef x86_64}
  7587. { check for implicit extension to 64 bit }
  7588. or
  7589. ((taicpu(p).opsize in [S_BL,S_WL]) and
  7590. (taicpu(hp1).opsize=S_Q) and
  7591. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  7592. )
  7593. {$endif x86_64}
  7594. )
  7595. then
  7596. begin
  7597. case taicpu(p).opsize Of
  7598. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  7599. if (taicpu(hp1).oper[0]^.val = $ff) then
  7600. begin
  7601. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  7602. RemoveInstruction(hp1);
  7603. Result:=true;
  7604. exit;
  7605. end;
  7606. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  7607. if (taicpu(hp1).oper[0]^.val = $ffff) then
  7608. begin
  7609. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  7610. RemoveInstruction(hp1);
  7611. Result:=true;
  7612. exit;
  7613. end;
  7614. {$ifdef x86_64}
  7615. S_LQ:
  7616. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  7617. begin
  7618. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  7619. RemoveInstruction(hp1);
  7620. Result:=true;
  7621. exit;
  7622. end;
  7623. {$endif x86_64}
  7624. else
  7625. ;
  7626. end;
  7627. { we cannot get rid of the and, but can we get rid of the movz ?}
  7628. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  7629. begin
  7630. case taicpu(p).opsize Of
  7631. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  7632. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  7633. begin
  7634. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  7635. RemoveCurrentP(p,hp1);
  7636. Result:=true;
  7637. exit;
  7638. end;
  7639. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  7640. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  7641. begin
  7642. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  7643. RemoveCurrentP(p,hp1);
  7644. Result:=true;
  7645. exit;
  7646. end;
  7647. {$ifdef x86_64}
  7648. S_LQ:
  7649. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  7650. begin
  7651. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  7652. RemoveCurrentP(p,hp1);
  7653. Result:=true;
  7654. exit;
  7655. end;
  7656. {$endif x86_64}
  7657. else
  7658. ;
  7659. end;
  7660. end;
  7661. end;
  7662. { changes some movzx constructs to faster synonyms (all examples
  7663. are given with eax/ax, but are also valid for other registers)}
  7664. if MatchOpType(taicpu(p),top_reg,top_reg) then
  7665. begin
  7666. case taicpu(p).opsize of
  7667. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  7668. (the machine code is equivalent to movzbl %al,%eax), but the
  7669. code generator still generates that assembler instruction and
  7670. it is silently converted. This should probably be checked.
  7671. [Kit] }
  7672. S_BW:
  7673. begin
  7674. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7675. (
  7676. not IsMOVZXAcceptable
  7677. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  7678. or (
  7679. (cs_opt_size in current_settings.optimizerswitches) and
  7680. (taicpu(p).oper[1]^.reg = NR_AX)
  7681. )
  7682. ) then
  7683. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  7684. begin
  7685. DebugMsg(SPeepholeOptimization + 'var7',p);
  7686. taicpu(p).opcode := A_AND;
  7687. taicpu(p).changeopsize(S_W);
  7688. taicpu(p).loadConst(0,$ff);
  7689. Result := True;
  7690. end
  7691. else if not IsMOVZXAcceptable and
  7692. GetNextInstruction(p, hp1) and
  7693. (tai(hp1).typ = ait_instruction) and
  7694. (taicpu(hp1).opcode = A_AND) and
  7695. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7696. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7697. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  7698. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  7699. begin
  7700. DebugMsg(SPeepholeOptimization + 'var8',p);
  7701. taicpu(p).opcode := A_MOV;
  7702. taicpu(p).changeopsize(S_W);
  7703. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  7704. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  7705. Result := True;
  7706. end;
  7707. end;
  7708. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  7709. S_BL:
  7710. begin
  7711. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7712. (
  7713. not IsMOVZXAcceptable
  7714. { and $0xff,%eax has a smaller encoding but risks a partial write penalty }
  7715. or (
  7716. (cs_opt_size in current_settings.optimizerswitches) and
  7717. (taicpu(p).oper[1]^.reg = NR_EAX)
  7718. )
  7719. ) then
  7720. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  7721. begin
  7722. DebugMsg(SPeepholeOptimization + 'var9',p);
  7723. taicpu(p).opcode := A_AND;
  7724. taicpu(p).changeopsize(S_L);
  7725. taicpu(p).loadConst(0,$ff);
  7726. Result := True;
  7727. end
  7728. else if not IsMOVZXAcceptable and
  7729. GetNextInstruction(p, hp1) and
  7730. (tai(hp1).typ = ait_instruction) and
  7731. (taicpu(hp1).opcode = A_AND) and
  7732. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7733. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7734. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  7735. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  7736. begin
  7737. DebugMsg(SPeepholeOptimization + 'var10',p);
  7738. taicpu(p).opcode := A_MOV;
  7739. taicpu(p).changeopsize(S_L);
  7740. { do not use R_SUBWHOLE
  7741. as movl %rdx,%eax
  7742. is invalid in assembler PM }
  7743. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  7744. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  7745. Result := True;
  7746. end;
  7747. end;
  7748. {$endif i8086}
  7749. S_WL:
  7750. if not IsMOVZXAcceptable then
  7751. begin
  7752. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  7753. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  7754. begin
  7755. DebugMsg(SPeepholeOptimization + 'var11',p);
  7756. taicpu(p).opcode := A_AND;
  7757. taicpu(p).changeopsize(S_L);
  7758. taicpu(p).loadConst(0,$ffff);
  7759. Result := True;
  7760. end
  7761. else if GetNextInstruction(p, hp1) and
  7762. (tai(hp1).typ = ait_instruction) and
  7763. (taicpu(hp1).opcode = A_AND) and
  7764. (taicpu(hp1).oper[0]^.typ = top_const) and
  7765. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7766. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7767. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  7768. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  7769. begin
  7770. DebugMsg(SPeepholeOptimization + 'var12',p);
  7771. taicpu(p).opcode := A_MOV;
  7772. taicpu(p).changeopsize(S_L);
  7773. { do not use R_SUBWHOLE
  7774. as movl %rdx,%eax
  7775. is invalid in assembler PM }
  7776. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  7777. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  7778. Result := True;
  7779. end;
  7780. end;
  7781. else
  7782. InternalError(2017050705);
  7783. end;
  7784. end
  7785. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  7786. begin
  7787. if GetNextInstruction(p, hp1) and
  7788. (tai(hp1).typ = ait_instruction) and
  7789. (taicpu(hp1).opcode = A_AND) and
  7790. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7791. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7792. begin
  7793. //taicpu(p).opcode := A_MOV;
  7794. case taicpu(p).opsize Of
  7795. S_BL:
  7796. begin
  7797. DebugMsg(SPeepholeOptimization + 'var13',p);
  7798. taicpu(hp1).changeopsize(S_L);
  7799. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  7800. end;
  7801. S_WL:
  7802. begin
  7803. DebugMsg(SPeepholeOptimization + 'var14',p);
  7804. taicpu(hp1).changeopsize(S_L);
  7805. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  7806. end;
  7807. S_BW:
  7808. begin
  7809. DebugMsg(SPeepholeOptimization + 'var15',p);
  7810. taicpu(hp1).changeopsize(S_W);
  7811. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  7812. end;
  7813. else
  7814. Internalerror(2017050704)
  7815. end;
  7816. Result := True;
  7817. end;
  7818. end;
  7819. end;
  7820. end;
  7821. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  7822. var
  7823. hp1, hp2 : tai;
  7824. MaskLength : Cardinal;
  7825. MaskedBits : TCgInt;
  7826. begin
  7827. Result:=false;
  7828. { There are no optimisations for reference targets }
  7829. if (taicpu(p).oper[1]^.typ <> top_reg) then
  7830. Exit;
  7831. while GetNextInstruction(p, hp1) and
  7832. (hp1.typ = ait_instruction) do
  7833. begin
  7834. if (taicpu(p).oper[0]^.typ = top_const) then
  7835. begin
  7836. if (taicpu(hp1).opcode = A_AND) and
  7837. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7838. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7839. { the second register must contain the first one, so compare their subreg types }
  7840. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  7841. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  7842. { change
  7843. and const1, reg
  7844. and const2, reg
  7845. to
  7846. and (const1 and const2), reg
  7847. }
  7848. begin
  7849. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  7850. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  7851. RemoveCurrentP(p, hp1);
  7852. Result:=true;
  7853. exit;
  7854. end
  7855. else if (taicpu(hp1).opcode = A_MOVZX) and
  7856. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7857. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  7858. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7859. (((taicpu(p).opsize=S_W) and
  7860. (taicpu(hp1).opsize=S_BW)) or
  7861. ((taicpu(p).opsize=S_L) and
  7862. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}]))
  7863. {$ifdef x86_64}
  7864. or
  7865. ((taicpu(p).opsize=S_Q) and
  7866. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL]))
  7867. {$endif x86_64}
  7868. ) then
  7869. begin
  7870. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  7871. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  7872. ) or
  7873. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  7874. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  7875. then
  7876. begin
  7877. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  7878. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  7879. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  7880. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  7881. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  7882. }
  7883. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  7884. RemoveInstruction(hp1);
  7885. { See if there are other optimisations possible }
  7886. Continue;
  7887. end;
  7888. end
  7889. else if (taicpu(hp1).opcode = A_SHL) and
  7890. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7891. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  7892. begin
  7893. {$ifopt R+}
  7894. {$define RANGE_WAS_ON}
  7895. {$R-}
  7896. {$endif}
  7897. { get length of potential and mask }
  7898. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  7899. { really a mask? }
  7900. {$ifdef RANGE_WAS_ON}
  7901. {$R+}
  7902. {$endif}
  7903. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  7904. { unmasked part shifted out? }
  7905. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  7906. begin
  7907. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  7908. RemoveCurrentP(p, hp1);
  7909. Result:=true;
  7910. exit;
  7911. end;
  7912. end
  7913. else if (taicpu(hp1).opcode = A_SHR) and
  7914. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7915. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  7916. (taicpu(hp1).oper[0]^.val <= 63) then
  7917. begin
  7918. { Does SHR combined with the AND cover all the bits?
  7919. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  7920. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  7921. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  7922. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  7923. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  7924. begin
  7925. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  7926. RemoveCurrentP(p, hp1);
  7927. Result := True;
  7928. Exit;
  7929. end;
  7930. end
  7931. else if ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}) and
  7932. (taicpu(hp1).oper[0]^.typ = top_reg) and
  7933. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  7934. begin
  7935. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  7936. (
  7937. (
  7938. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  7939. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  7940. ) or (
  7941. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  7942. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  7943. {$ifdef x86_64}
  7944. ) or (
  7945. (taicpu(hp1).opsize = S_LQ) and
  7946. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  7947. {$endif x86_64}
  7948. )
  7949. ) then
  7950. begin
  7951. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  7952. begin
  7953. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  7954. RemoveInstruction(hp1);
  7955. { See if there are other optimisations possible }
  7956. Continue;
  7957. end;
  7958. { The super-registers are the same though.
  7959. Note that this change by itself doesn't improve
  7960. code speed, but it opens up other optimisations. }
  7961. {$ifdef x86_64}
  7962. { Convert 64-bit register to 32-bit }
  7963. case taicpu(hp1).opsize of
  7964. S_BQ:
  7965. begin
  7966. taicpu(hp1).opsize := S_BL;
  7967. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  7968. end;
  7969. S_WQ:
  7970. begin
  7971. taicpu(hp1).opsize := S_WL;
  7972. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  7973. end
  7974. else
  7975. ;
  7976. end;
  7977. {$endif x86_64}
  7978. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  7979. taicpu(hp1).opcode := A_MOVZX;
  7980. { See if there are other optimisations possible }
  7981. Continue;
  7982. end;
  7983. end;
  7984. end;
  7985. if (taicpu(hp1).is_jmp) and
  7986. (taicpu(hp1).opcode<>A_JMP) and
  7987. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  7988. begin
  7989. { change
  7990. and x, reg
  7991. jxx
  7992. to
  7993. test x, reg
  7994. jxx
  7995. if reg is deallocated before the
  7996. jump, but only if it's a conditional jump (PFV)
  7997. }
  7998. taicpu(p).opcode := A_TEST;
  7999. Exit;
  8000. end;
  8001. Break;
  8002. end;
  8003. { Lone AND tests }
  8004. if (taicpu(p).oper[0]^.typ = top_const) then
  8005. begin
  8006. {
  8007. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  8008. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  8009. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  8010. }
  8011. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  8012. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  8013. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  8014. begin
  8015. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  8016. if taicpu(p).opsize = S_L then
  8017. begin
  8018. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  8019. Result := True;
  8020. end;
  8021. end;
  8022. end;
  8023. { Backward check to determine necessity of and %reg,%reg }
  8024. if (taicpu(p).oper[0]^.typ = top_reg) and
  8025. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  8026. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  8027. GetLastInstruction(p, hp2) and
  8028. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  8029. { Check size of adjacent instruction to determine if the AND is
  8030. effectively a null operation }
  8031. (
  8032. (taicpu(p).opsize = taicpu(hp2).opsize) or
  8033. { Note: Don't include S_Q }
  8034. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  8035. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  8036. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  8037. ) then
  8038. begin
  8039. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  8040. { If GetNextInstruction returned False, hp1 will be nil }
  8041. RemoveCurrentP(p, hp1);
  8042. Result := True;
  8043. Exit;
  8044. end;
  8045. end;
  8046. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  8047. var
  8048. hp1: tai; NewRef: TReference;
  8049. { This entire nested function is used in an if-statement below, but we
  8050. want to avoid all the used reg transfers and GetNextInstruction calls
  8051. until we really have to check }
  8052. function MemRegisterNotUsedLater: Boolean; inline;
  8053. var
  8054. hp2: tai;
  8055. begin
  8056. TransferUsedRegs(TmpUsedRegs);
  8057. hp2 := p;
  8058. repeat
  8059. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8060. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  8061. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  8062. end;
  8063. begin
  8064. Result := False;
  8065. if not GetNextInstruction(p, hp1) or (hp1.typ <> ait_instruction) then
  8066. Exit;
  8067. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) then
  8068. begin
  8069. { Change:
  8070. add %reg2,%reg1
  8071. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  8072. To:
  8073. mov/s/z #(%reg1,%reg2),%reg1
  8074. }
  8075. if MatchOpType(taicpu(p), top_reg, top_reg) and
  8076. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  8077. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  8078. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  8079. (
  8080. (
  8081. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  8082. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  8083. { r/esp cannot be an index }
  8084. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  8085. ) or (
  8086. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  8087. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  8088. )
  8089. ) and (
  8090. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  8091. (
  8092. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  8093. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  8094. MemRegisterNotUsedLater
  8095. )
  8096. ) then
  8097. begin
  8098. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  8099. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  8100. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  8101. RemoveCurrentp(p, hp1);
  8102. Result := True;
  8103. Exit;
  8104. end;
  8105. { Change:
  8106. addl/q $x,%reg1
  8107. movl/q %reg1,%reg2
  8108. To:
  8109. leal/q $x(%reg1),%reg2
  8110. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  8111. Breaks the dependency chain.
  8112. }
  8113. if MatchOpType(taicpu(p),top_const,top_reg) and
  8114. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  8115. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8116. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  8117. (
  8118. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  8119. not (cs_opt_size in current_settings.optimizerswitches) or
  8120. (
  8121. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  8122. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  8123. )
  8124. ) then
  8125. begin
  8126. { Change the MOV instruction to a LEA instruction, and update the
  8127. first operand }
  8128. reference_reset(NewRef, 1, []);
  8129. NewRef.base := taicpu(p).oper[1]^.reg;
  8130. NewRef.scalefactor := 1;
  8131. NewRef.offset := taicpu(p).oper[0]^.val;
  8132. taicpu(hp1).opcode := A_LEA;
  8133. taicpu(hp1).loadref(0, NewRef);
  8134. TransferUsedRegs(TmpUsedRegs);
  8135. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8136. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  8137. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  8138. begin
  8139. { Move what is now the LEA instruction to before the SUB instruction }
  8140. Asml.Remove(hp1);
  8141. Asml.InsertBefore(hp1, p);
  8142. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  8143. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  8144. p := hp1;
  8145. end
  8146. else
  8147. begin
  8148. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  8149. RemoveCurrentP(p, hp1);
  8150. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', p);
  8151. end;
  8152. Result := True;
  8153. end;
  8154. end;
  8155. end;
  8156. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  8157. begin
  8158. Result:=false;
  8159. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  8160. begin
  8161. if MatchReference(taicpu(p).oper[0]^.ref^,taicpu(p).oper[1]^.reg,NR_INVALID) and
  8162. (taicpu(p).oper[0]^.ref^.index<>NR_NO) then
  8163. begin
  8164. taicpu(p).loadreg(1,taicpu(p).oper[0]^.ref^.base);
  8165. taicpu(p).loadreg(0,taicpu(p).oper[0]^.ref^.index);
  8166. taicpu(p).opcode:=A_ADD;
  8167. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  8168. result:=true;
  8169. end
  8170. else if MatchReference(taicpu(p).oper[0]^.ref^,NR_INVALID,taicpu(p).oper[1]^.reg) and
  8171. (taicpu(p).oper[0]^.ref^.base<>NR_NO) then
  8172. begin
  8173. taicpu(p).loadreg(1,taicpu(p).oper[0]^.ref^.index);
  8174. taicpu(p).loadreg(0,taicpu(p).oper[0]^.ref^.base);
  8175. taicpu(p).opcode:=A_ADD;
  8176. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  8177. result:=true;
  8178. end;
  8179. end;
  8180. end;
  8181. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  8182. var
  8183. hp1: tai; NewRef: TReference;
  8184. begin
  8185. { Change:
  8186. subl/q $x,%reg1
  8187. movl/q %reg1,%reg2
  8188. To:
  8189. leal/q $-x(%reg1),%reg2
  8190. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  8191. Breaks the dependency chain and potentially permits the removal of
  8192. a CMP instruction if one follows.
  8193. }
  8194. Result := False;
  8195. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  8196. MatchOpType(taicpu(p),top_const,top_reg) and
  8197. GetNextInstruction(p, hp1) and
  8198. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  8199. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8200. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  8201. (
  8202. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  8203. not (cs_opt_size in current_settings.optimizerswitches) or
  8204. (
  8205. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  8206. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  8207. )
  8208. ) then
  8209. begin
  8210. { Change the MOV instruction to a LEA instruction, and update the
  8211. first operand }
  8212. reference_reset(NewRef, 1, []);
  8213. NewRef.base := taicpu(p).oper[1]^.reg;
  8214. NewRef.scalefactor := 1;
  8215. NewRef.offset := -taicpu(p).oper[0]^.val;
  8216. taicpu(hp1).opcode := A_LEA;
  8217. taicpu(hp1).loadref(0, NewRef);
  8218. TransferUsedRegs(TmpUsedRegs);
  8219. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8220. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  8221. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  8222. begin
  8223. { Move what is now the LEA instruction to before the SUB instruction }
  8224. Asml.Remove(hp1);
  8225. Asml.InsertBefore(hp1, p);
  8226. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  8227. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  8228. p := hp1;
  8229. end
  8230. else
  8231. begin
  8232. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  8233. RemoveCurrentP(p, hp1);
  8234. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', p);
  8235. end;
  8236. Result := True;
  8237. end;
  8238. end;
  8239. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  8240. begin
  8241. { we can skip all instructions not messing with the stack pointer }
  8242. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  8243. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  8244. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  8245. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  8246. ({(taicpu(hp1).ops=0) or }
  8247. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  8248. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  8249. ) and }
  8250. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  8251. )
  8252. ) do
  8253. GetNextInstruction(hp1,hp1);
  8254. Result:=assigned(hp1);
  8255. end;
  8256. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  8257. var
  8258. hp1, hp2, hp3, hp4, hp5: tai;
  8259. begin
  8260. Result:=false;
  8261. hp5:=nil;
  8262. { replace
  8263. leal(q) x(<stackpointer>),<stackpointer>
  8264. call procname
  8265. leal(q) -x(<stackpointer>),<stackpointer>
  8266. ret
  8267. by
  8268. jmp procname
  8269. but do it only on level 4 because it destroys stack back traces
  8270. }
  8271. if (cs_opt_level4 in current_settings.optimizerswitches) and
  8272. MatchOpType(taicpu(p),top_ref,top_reg) and
  8273. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  8274. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  8275. { the -8 or -24 are not required, but bail out early if possible,
  8276. higher values are unlikely }
  8277. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  8278. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  8279. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  8280. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  8281. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and
  8282. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  8283. GetNextInstruction(p, hp1) and
  8284. { Take a copy of hp1 }
  8285. SetAndTest(hp1, hp4) and
  8286. { trick to skip label }
  8287. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  8288. SkipSimpleInstructions(hp1) and
  8289. MatchInstruction(hp1,A_CALL,[S_NO]) and
  8290. GetNextInstruction(hp1, hp2) and
  8291. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  8292. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  8293. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  8294. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  8295. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  8296. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  8297. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  8298. (taicpu(hp2).oper[0]^.ref^.segment=NR_NO) and
  8299. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  8300. GetNextInstruction(hp2, hp3) and
  8301. { trick to skip label }
  8302. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  8303. (MatchInstruction(hp3,A_RET,[S_NO]) or
  8304. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  8305. SetAndTest(hp3,hp5) and
  8306. GetNextInstruction(hp3,hp3) and
  8307. MatchInstruction(hp3,A_RET,[S_NO])
  8308. )
  8309. ) and
  8310. (taicpu(hp3).ops=0) then
  8311. begin
  8312. taicpu(hp1).opcode := A_JMP;
  8313. taicpu(hp1).is_jmp := true;
  8314. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  8315. RemoveCurrentP(p, hp4);
  8316. RemoveInstruction(hp2);
  8317. RemoveInstruction(hp3);
  8318. if Assigned(hp5) then
  8319. begin
  8320. AsmL.Remove(hp5);
  8321. ASmL.InsertBefore(hp5,hp1)
  8322. end;
  8323. Result:=true;
  8324. end;
  8325. end;
  8326. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  8327. {$ifdef x86_64}
  8328. var
  8329. hp1, hp2, hp3, hp4, hp5: tai;
  8330. {$endif x86_64}
  8331. begin
  8332. Result:=false;
  8333. {$ifdef x86_64}
  8334. hp5:=nil;
  8335. { replace
  8336. push %rax
  8337. call procname
  8338. pop %rcx
  8339. ret
  8340. by
  8341. jmp procname
  8342. but do it only on level 4 because it destroys stack back traces
  8343. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  8344. for all supported calling conventions
  8345. }
  8346. if (cs_opt_level4 in current_settings.optimizerswitches) and
  8347. MatchOpType(taicpu(p),top_reg) and
  8348. (taicpu(p).oper[0]^.reg=NR_RAX) and
  8349. GetNextInstruction(p, hp1) and
  8350. { Take a copy of hp1 }
  8351. SetAndTest(hp1, hp4) and
  8352. { trick to skip label }
  8353. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  8354. SkipSimpleInstructions(hp1) and
  8355. MatchInstruction(hp1,A_CALL,[S_NO]) and
  8356. GetNextInstruction(hp1, hp2) and
  8357. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  8358. MatchOpType(taicpu(hp2),top_reg) and
  8359. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  8360. GetNextInstruction(hp2, hp3) and
  8361. { trick to skip label }
  8362. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  8363. (MatchInstruction(hp3,A_RET,[S_NO]) or
  8364. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  8365. SetAndTest(hp3,hp5) and
  8366. GetNextInstruction(hp3,hp3) and
  8367. MatchInstruction(hp3,A_RET,[S_NO])
  8368. )
  8369. ) and
  8370. (taicpu(hp3).ops=0) then
  8371. begin
  8372. taicpu(hp1).opcode := A_JMP;
  8373. taicpu(hp1).is_jmp := true;
  8374. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  8375. RemoveCurrentP(p, hp4);
  8376. RemoveInstruction(hp2);
  8377. RemoveInstruction(hp3);
  8378. if Assigned(hp5) then
  8379. begin
  8380. AsmL.Remove(hp5);
  8381. ASmL.InsertBefore(hp5,hp1)
  8382. end;
  8383. Result:=true;
  8384. end;
  8385. {$endif x86_64}
  8386. end;
  8387. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  8388. var
  8389. Value, RegName: string;
  8390. begin
  8391. Result:=false;
  8392. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  8393. begin
  8394. case taicpu(p).oper[0]^.val of
  8395. 0:
  8396. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  8397. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  8398. begin
  8399. { change "mov $0,%reg" into "xor %reg,%reg" }
  8400. taicpu(p).opcode := A_XOR;
  8401. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  8402. Result := True;
  8403. end;
  8404. $1..$FFFFFFFF:
  8405. begin
  8406. { Code size reduction by J. Gareth "Kit" Moreton }
  8407. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  8408. case taicpu(p).opsize of
  8409. S_Q:
  8410. begin
  8411. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  8412. Value := debug_tostr(taicpu(p).oper[0]^.val);
  8413. { The actual optimization }
  8414. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  8415. taicpu(p).changeopsize(S_L);
  8416. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  8417. Result := True;
  8418. end;
  8419. else
  8420. { Do nothing };
  8421. end;
  8422. end;
  8423. -1:
  8424. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  8425. if (cs_opt_size in current_settings.optimizerswitches) and
  8426. (taicpu(p).opsize <> S_B) and
  8427. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  8428. begin
  8429. { change "mov $-1,%reg" into "or $-1,%reg" }
  8430. { NOTES:
  8431. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  8432. - This operation creates a false dependency on the register, so only do it when optimising for size
  8433. - 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
  8434. }
  8435. taicpu(p).opcode := A_OR;
  8436. Result := True;
  8437. end;
  8438. end;
  8439. end;
  8440. end;
  8441. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  8442. var
  8443. hp1: tai;
  8444. begin
  8445. { Detect:
  8446. andw x, %ax (0 <= x < $8000)
  8447. ...
  8448. movzwl %ax,%eax
  8449. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  8450. }
  8451. Result := False; if MatchOpType(taicpu(p), top_const, top_reg) and
  8452. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  8453. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  8454. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  8455. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  8456. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  8457. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  8458. begin
  8459. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  8460. taicpu(hp1).opcode := A_CWDE;
  8461. taicpu(hp1).clearop(0);
  8462. taicpu(hp1).clearop(1);
  8463. taicpu(hp1).ops := 0;
  8464. { A change was made, but not with p, so move forward 1 }
  8465. p := tai(p.Next);
  8466. Result := True;
  8467. end;
  8468. end;
  8469. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  8470. begin
  8471. Result := False;
  8472. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  8473. Exit;
  8474. { Convert:
  8475. movswl %ax,%eax -> cwtl
  8476. movslq %eax,%rax -> cdqe
  8477. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  8478. refer to the same opcode and depends only on the assembler's
  8479. current operand-size attribute. [Kit]
  8480. }
  8481. with taicpu(p) do
  8482. case opsize of
  8483. S_WL:
  8484. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  8485. begin
  8486. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  8487. opcode := A_CWDE;
  8488. clearop(0);
  8489. clearop(1);
  8490. ops := 0;
  8491. Result := True;
  8492. end;
  8493. {$ifdef x86_64}
  8494. S_LQ:
  8495. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  8496. begin
  8497. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  8498. opcode := A_CDQE;
  8499. clearop(0);
  8500. clearop(1);
  8501. ops := 0;
  8502. Result := True;
  8503. end;
  8504. {$endif x86_64}
  8505. else
  8506. ;
  8507. end;
  8508. end;
  8509. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  8510. var
  8511. hp1: tai;
  8512. begin
  8513. { Detect:
  8514. shr x, %ax (x > 0)
  8515. ...
  8516. movzwl %ax,%eax
  8517. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  8518. }
  8519. Result := False;
  8520. if MatchOpType(taicpu(p), top_const, top_reg) and
  8521. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  8522. (taicpu(p).oper[0]^.val > 0) and
  8523. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  8524. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  8525. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  8526. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  8527. begin
  8528. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  8529. taicpu(hp1).opcode := A_CWDE;
  8530. taicpu(hp1).clearop(0);
  8531. taicpu(hp1).clearop(1);
  8532. taicpu(hp1).ops := 0;
  8533. { A change was made, but not with p, so move forward 1 }
  8534. p := tai(p.Next);
  8535. Result := True;
  8536. end;
  8537. end;
  8538. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  8539. begin
  8540. Result:=false;
  8541. { change "cmp $0, %reg" to "test %reg, %reg" }
  8542. if MatchOpType(taicpu(p),top_const,top_reg) and
  8543. (taicpu(p).oper[0]^.val = 0) then
  8544. begin
  8545. taicpu(p).opcode := A_TEST;
  8546. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  8547. Result:=true;
  8548. end;
  8549. end;
  8550. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  8551. var
  8552. IsTestConstX : Boolean;
  8553. hp1,hp2 : tai;
  8554. begin
  8555. Result:=false;
  8556. { removes the line marked with (x) from the sequence
  8557. and/or/xor/add/sub/... $x, %y
  8558. test/or %y, %y | test $-1, %y (x)
  8559. j(n)z _Label
  8560. as the first instruction already adjusts the ZF
  8561. %y operand may also be a reference }
  8562. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  8563. MatchOperand(taicpu(p).oper[0]^,-1);
  8564. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  8565. GetLastInstruction(p, hp1) and
  8566. (tai(hp1).typ = ait_instruction) and
  8567. GetNextInstruction(p,hp2) and
  8568. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  8569. case taicpu(hp1).opcode Of
  8570. A_ADD, A_SUB, A_OR, A_XOR, A_AND:
  8571. begin
  8572. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  8573. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  8574. { and in case of carry for A(E)/B(E)/C/NC }
  8575. ((taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  8576. ((taicpu(hp1).opcode <> A_ADD) and
  8577. (taicpu(hp1).opcode <> A_SUB))) then
  8578. begin
  8579. RemoveCurrentP(p, hp2);
  8580. Result:=true;
  8581. Exit;
  8582. end;
  8583. end;
  8584. A_SHL, A_SAL, A_SHR, A_SAR:
  8585. begin
  8586. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  8587. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  8588. { therefore, it's only safe to do this optimization for }
  8589. { shifts by a (nonzero) constant }
  8590. (taicpu(hp1).oper[0]^.typ = top_const) and
  8591. (taicpu(hp1).oper[0]^.val <> 0) and
  8592. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  8593. { and in case of carry for A(E)/B(E)/C/NC }
  8594. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  8595. begin
  8596. RemoveCurrentP(p, hp2);
  8597. Result:=true;
  8598. Exit;
  8599. end;
  8600. end;
  8601. A_DEC, A_INC, A_NEG:
  8602. begin
  8603. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  8604. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  8605. { and in case of carry for A(E)/B(E)/C/NC }
  8606. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  8607. begin
  8608. case taicpu(hp1).opcode of
  8609. A_DEC, A_INC:
  8610. { replace inc/dec with add/sub 1, because inc/dec doesn't set the carry flag }
  8611. begin
  8612. case taicpu(hp1).opcode Of
  8613. A_DEC: taicpu(hp1).opcode := A_SUB;
  8614. A_INC: taicpu(hp1).opcode := A_ADD;
  8615. else
  8616. ;
  8617. end;
  8618. taicpu(hp1).loadoper(1,taicpu(hp1).oper[0]^);
  8619. taicpu(hp1).loadConst(0,1);
  8620. taicpu(hp1).ops:=2;
  8621. end;
  8622. else
  8623. ;
  8624. end;
  8625. RemoveCurrentP(p, hp2);
  8626. Result:=true;
  8627. Exit;
  8628. end;
  8629. end
  8630. else
  8631. ;
  8632. end; { case }
  8633. { change "test $-1,%reg" into "test %reg,%reg" }
  8634. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  8635. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  8636. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  8637. if MatchInstruction(p, A_OR, []) and
  8638. { Can only match if they're both registers }
  8639. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  8640. begin
  8641. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  8642. taicpu(p).opcode := A_TEST;
  8643. { No need to set Result to True, as we've done all the optimisations we can }
  8644. end;
  8645. end;
  8646. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  8647. var
  8648. hp1,hp3 : tai;
  8649. {$ifndef x86_64}
  8650. hp2 : taicpu;
  8651. {$endif x86_64}
  8652. begin
  8653. Result:=false;
  8654. hp3:=nil;
  8655. {$ifndef x86_64}
  8656. { don't do this on modern CPUs, this really hurts them due to
  8657. broken call/ret pairing }
  8658. if (current_settings.optimizecputype < cpu_Pentium2) and
  8659. not(cs_create_pic in current_settings.moduleswitches) and
  8660. GetNextInstruction(p, hp1) and
  8661. MatchInstruction(hp1,A_JMP,[S_NO]) and
  8662. MatchOpType(taicpu(hp1),top_ref) and
  8663. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  8664. begin
  8665. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  8666. InsertLLItem(p.previous, p, hp2);
  8667. taicpu(p).opcode := A_JMP;
  8668. taicpu(p).is_jmp := true;
  8669. RemoveInstruction(hp1);
  8670. Result:=true;
  8671. end
  8672. else
  8673. {$endif x86_64}
  8674. { replace
  8675. call procname
  8676. ret
  8677. by
  8678. jmp procname
  8679. but do it only on level 4 because it destroys stack back traces
  8680. else if the subroutine is marked as no return, remove the ret
  8681. }
  8682. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  8683. (po_noreturn in current_procinfo.procdef.procoptions)) and
  8684. GetNextInstruction(p, hp1) and
  8685. (MatchInstruction(hp1,A_RET,[S_NO]) or
  8686. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  8687. SetAndTest(hp1,hp3) and
  8688. GetNextInstruction(hp1,hp1) and
  8689. MatchInstruction(hp1,A_RET,[S_NO])
  8690. )
  8691. ) and
  8692. (taicpu(hp1).ops=0) then
  8693. begin
  8694. if (cs_opt_level4 in current_settings.optimizerswitches) and
  8695. { we might destroy stack alignment here if we do not do a call }
  8696. (target_info.stackalign<=sizeof(SizeUInt)) then
  8697. begin
  8698. taicpu(p).opcode := A_JMP;
  8699. taicpu(p).is_jmp := true;
  8700. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  8701. end
  8702. else
  8703. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  8704. RemoveInstruction(hp1);
  8705. if Assigned(hp3) then
  8706. begin
  8707. AsmL.Remove(hp3);
  8708. AsmL.InsertBefore(hp3,p)
  8709. end;
  8710. Result:=true;
  8711. end;
  8712. end;
  8713. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  8714. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  8715. begin
  8716. case OpSize of
  8717. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8718. Result := (Val <= $FF) and (Val >= -128);
  8719. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8720. Result := (Val <= $FFFF) and (Val >= -32768);
  8721. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  8722. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  8723. else
  8724. Result := True;
  8725. end;
  8726. end;
  8727. var
  8728. hp1, hp2 : tai;
  8729. SizeChange: Boolean;
  8730. PreMessage: string;
  8731. begin
  8732. Result := False;
  8733. if (taicpu(p).oper[0]^.typ = top_reg) and
  8734. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  8735. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  8736. begin
  8737. { Change (using movzbl %al,%eax as an example):
  8738. movzbl %al, %eax movzbl %al, %eax
  8739. cmpl x, %eax testl %eax,%eax
  8740. To:
  8741. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  8742. movzbl %al, %eax movzbl %al, %eax
  8743. Smaller instruction and minimises pipeline stall as the CPU
  8744. doesn't have to wait for the register to get zero-extended. [Kit]
  8745. Also allow if the smaller of the two registers is being checked,
  8746. as this still removes the false dependency.
  8747. }
  8748. if
  8749. (
  8750. (
  8751. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  8752. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  8753. ) or (
  8754. { If MatchOperand returns True, they must both be registers }
  8755. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  8756. )
  8757. ) and
  8758. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  8759. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  8760. begin
  8761. 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);
  8762. asml.Remove(hp1);
  8763. asml.InsertBefore(hp1, p);
  8764. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  8765. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  8766. begin
  8767. taicpu(hp1).opcode := A_TEST;
  8768. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  8769. end;
  8770. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  8771. case taicpu(p).opsize of
  8772. S_BW, S_BL:
  8773. begin
  8774. SizeChange := taicpu(hp1).opsize <> S_B;
  8775. taicpu(hp1).changeopsize(S_B);
  8776. end;
  8777. S_WL:
  8778. begin
  8779. SizeChange := taicpu(hp1).opsize <> S_W;
  8780. taicpu(hp1).changeopsize(S_W);
  8781. end
  8782. else
  8783. InternalError(2020112701);
  8784. end;
  8785. UpdateUsedRegs(tai(p.Next));
  8786. { Check if the register is used aferwards - if not, we can
  8787. remove the movzx instruction completely }
  8788. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  8789. begin
  8790. { Hp1 is a better position than p for debugging purposes }
  8791. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  8792. RemoveCurrentp(p, hp1);
  8793. Result := True;
  8794. end;
  8795. if SizeChange then
  8796. DebugMsg(SPeepholeOptimization + PreMessage +
  8797. 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)
  8798. else
  8799. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  8800. Exit;
  8801. end;
  8802. { Change (using movzwl %ax,%eax as an example):
  8803. movzwl %ax, %eax
  8804. movb %al, (dest) (Register is smaller than read register in movz)
  8805. To:
  8806. movb %al, (dest) (Move one back to avoid a false dependency)
  8807. movzwl %ax, %eax
  8808. }
  8809. if (taicpu(hp1).opcode = A_MOV) and
  8810. (taicpu(hp1).oper[0]^.typ = top_reg) and
  8811. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  8812. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  8813. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  8814. begin
  8815. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  8816. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  8817. asml.Remove(hp1);
  8818. asml.InsertBefore(hp1, p);
  8819. if taicpu(hp1).oper[1]^.typ = top_reg then
  8820. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  8821. { Check if the register is used aferwards - if not, we can
  8822. remove the movzx instruction completely }
  8823. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  8824. begin
  8825. { Hp1 is a better position than p for debugging purposes }
  8826. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  8827. RemoveCurrentp(p, hp1);
  8828. Result := True;
  8829. end;
  8830. Exit;
  8831. end;
  8832. end;
  8833. {$ifdef x86_64}
  8834. { Code size reduction by J. Gareth "Kit" Moreton }
  8835. { Convert MOVZBQ and MOVZWQ to MOVZBL and MOVZWL respectively if it removes the REX prefix }
  8836. if (taicpu(p).opsize in [S_BQ, S_WQ]) and
  8837. (getsupreg(taicpu(p).oper[1]^.reg) in [RS_RAX, RS_RCX, RS_RDX, RS_RBX, RS_RSI, RS_RDI, RS_RBP, RS_RSP])
  8838. then
  8839. begin
  8840. { Has 64-bit register name and opcode suffix }
  8841. PreMessage := 'movz' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' -> movz';
  8842. { The actual optimization }
  8843. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  8844. if taicpu(p).opsize = S_BQ then
  8845. taicpu(p).changeopsize(S_BL)
  8846. else
  8847. taicpu(p).changeopsize(S_WL);
  8848. DebugMsg(SPeepholeOptimization + PreMessage +
  8849. debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (removes REX prefix)', p);
  8850. end;
  8851. {$endif}
  8852. end;
  8853. {$ifdef x86_64}
  8854. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  8855. var
  8856. PreMessage, RegName: string;
  8857. begin
  8858. { Code size reduction by J. Gareth "Kit" Moreton }
  8859. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  8860. as this removes the REX prefix }
  8861. Result := False;
  8862. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  8863. Exit;
  8864. if taicpu(p).oper[0]^.typ <> top_reg then
  8865. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  8866. InternalError(2018011500);
  8867. case taicpu(p).opsize of
  8868. S_Q:
  8869. begin
  8870. if (getsupreg(taicpu(p).oper[0]^.reg) in [RS_RAX, RS_RCX, RS_RDX, RS_RBX, RS_RSI, RS_RDI, RS_RBP, RS_RSP]) then
  8871. begin
  8872. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  8873. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  8874. { The actual optimization }
  8875. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  8876. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  8877. taicpu(p).changeopsize(S_L);
  8878. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  8879. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (removes REX prefix)', p);
  8880. end;
  8881. end;
  8882. else
  8883. ;
  8884. end;
  8885. end;
  8886. {$endif}
  8887. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  8888. var
  8889. OperIdx: Integer;
  8890. begin
  8891. for OperIdx := 0 to p.ops - 1 do
  8892. if p.oper[OperIdx]^.typ = top_ref then
  8893. optimize_ref(p.oper[OperIdx]^.ref^, False);
  8894. end;
  8895. end.