aoptx86.pas 426 KB

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