aoptx86.pas 441 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289
  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. { Attempts to allocate a volatile integer register for use between p and hp,
  68. using AUsedRegs for the current register usage information. Returns NR_NO
  69. if no free register could be found }
  70. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  71. { Attempts to allocate a volatile MM register for use between p and hp,
  72. using AUsedRegs for the current register usage information. Returns NR_NO
  73. if no free register could be found }
  74. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  75. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  76. function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  77. { checks whether reading the value in reg1 depends on the value of reg2. This
  78. is very similar to SuperRegisterEquals, except it takes into account that
  79. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  80. depend on the value in AH). }
  81. function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  82. { Replaces all references to AOldReg in a memory reference to ANewReg }
  83. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  84. { Replaces all references to AOldReg in an operand to ANewReg }
  85. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  86. { Replaces all references to AOldReg in an instruction to ANewReg,
  87. except where the register is being written }
  88. function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  89. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  90. or writes to a global symbol }
  91. class function IsRefSafe(const ref: PReference): Boolean; static; inline;
  92. { Returns true if the given MOV instruction can be safely converted to CMOV }
  93. class function CanBeCMOV(p : tai) : boolean; static;
  94. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  95. conversion was successful }
  96. function ConvertLEA(const p : taicpu): Boolean;
  97. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  98. procedure DebugMsg(const s : string; p : tai);inline;
  99. class function IsExitCode(p : tai) : boolean; static;
  100. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  101. procedure RemoveLastDeallocForFuncRes(p : tai);
  102. function DoSubAddOpt(var p : tai) : Boolean;
  103. function PrePeepholeOptSxx(var p : tai) : boolean;
  104. function PrePeepholeOptIMUL(var p : tai) : boolean;
  105. function PrePeepholeOptAND(var p : tai) : boolean;
  106. function OptPass1Test(var p: tai): boolean;
  107. function OptPass1Add(var p: tai): boolean;
  108. function OptPass1AND(var p : tai) : boolean;
  109. function OptPass1_V_MOVAP(var p : tai) : boolean;
  110. function OptPass1VOP(var p : tai) : boolean;
  111. function OptPass1MOV(var p : tai) : boolean;
  112. function OptPass1Movx(var p : tai) : boolean;
  113. function OptPass1MOVXX(var p : tai) : boolean;
  114. function OptPass1OP(var p : tai) : boolean;
  115. function OptPass1LEA(var p : tai) : boolean;
  116. function OptPass1Sub(var p : tai) : boolean;
  117. function OptPass1SHLSAL(var p : tai) : boolean;
  118. function OptPass1FSTP(var p : tai) : boolean;
  119. function OptPass1FLD(var p : tai) : boolean;
  120. function OptPass1Cmp(var p : tai) : boolean;
  121. function OptPass1PXor(var p : tai) : boolean;
  122. function OptPass1VPXor(var p: tai): boolean;
  123. function OptPass1Imul(var p : tai) : boolean;
  124. function OptPass1Jcc(var p : tai) : boolean;
  125. function OptPass1SHXX(var p: tai): boolean;
  126. function OptPass2Movx(var p : tai): Boolean;
  127. function OptPass2MOV(var p : tai) : boolean;
  128. function OptPass2Imul(var p : tai) : boolean;
  129. function OptPass2Jmp(var p : tai) : boolean;
  130. function OptPass2Jcc(var p : tai) : boolean;
  131. function OptPass2Lea(var p: tai): Boolean;
  132. function OptPass2SUB(var p: tai): Boolean;
  133. function OptPass2ADD(var p : tai): Boolean;
  134. function OptPass2SETcc(var p : tai) : boolean;
  135. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  136. function PostPeepholeOptMov(var p : tai) : Boolean;
  137. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  138. {$ifdef x86_64} { These post-peephole optimisations only affect 64-bit registers. [Kit] }
  139. function PostPeepholeOptXor(var p : tai) : Boolean;
  140. {$endif}
  141. function PostPeepholeOptAnd(var p : tai) : boolean;
  142. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  143. function PostPeepholeOptCmp(var p : tai) : Boolean;
  144. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  145. function PostPeepholeOptCall(var p : tai) : Boolean;
  146. function PostPeepholeOptLea(var p : tai) : Boolean;
  147. function PostPeepholeOptPush(var p: tai): Boolean;
  148. function PostPeepholeOptShr(var p : tai) : boolean;
  149. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  150. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  151. procedure SwapMovCmp(var p, hp1: tai);
  152. { Processor-dependent reference optimisation }
  153. class procedure OptimizeRefs(var p: taicpu); static;
  154. end;
  155. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  156. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  157. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  158. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  159. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  160. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  161. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  162. {$if max_operands>2}
  163. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  164. {$endif max_operands>2}
  165. function RefsEqual(const r1, r2: treference): boolean;
  166. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  167. { returns true, if ref is a reference using only the registers passed as base and index
  168. and having an offset }
  169. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  170. implementation
  171. uses
  172. cutils,verbose,
  173. systems,
  174. globals,
  175. cpuinfo,
  176. procinfo,
  177. paramgr,
  178. aasmbase,
  179. aoptbase,aoptutils,
  180. symconst,symsym,
  181. cgx86,
  182. itcpugas;
  183. {$ifdef DEBUG_AOPTCPU}
  184. const
  185. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  186. {$else DEBUG_AOPTCPU}
  187. { Empty strings help the optimizer to remove string concatenations that won't
  188. ever appear to the user on release builds. [Kit] }
  189. const
  190. SPeepholeOptimization = '';
  191. {$endif DEBUG_AOPTCPU}
  192. LIST_STEP_SIZE = 4;
  193. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  194. begin
  195. result :=
  196. (instr.typ = ait_instruction) and
  197. (taicpu(instr).opcode = op) and
  198. ((opsize = []) or (taicpu(instr).opsize in opsize));
  199. end;
  200. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  201. begin
  202. result :=
  203. (instr.typ = ait_instruction) and
  204. ((taicpu(instr).opcode = op1) or
  205. (taicpu(instr).opcode = op2)
  206. ) and
  207. ((opsize = []) or (taicpu(instr).opsize in opsize));
  208. end;
  209. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  210. begin
  211. result :=
  212. (instr.typ = ait_instruction) and
  213. ((taicpu(instr).opcode = op1) or
  214. (taicpu(instr).opcode = op2) or
  215. (taicpu(instr).opcode = op3)
  216. ) and
  217. ((opsize = []) or (taicpu(instr).opsize in opsize));
  218. end;
  219. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  220. const opsize : topsizes) : boolean;
  221. var
  222. op : TAsmOp;
  223. begin
  224. result:=false;
  225. for op in ops do
  226. begin
  227. if (instr.typ = ait_instruction) and
  228. (taicpu(instr).opcode = op) and
  229. ((opsize = []) or (taicpu(instr).opsize in opsize)) then
  230. begin
  231. result:=true;
  232. exit;
  233. end;
  234. end;
  235. end;
  236. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  237. begin
  238. result := (oper.typ = top_reg) and (oper.reg = reg);
  239. end;
  240. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  241. begin
  242. result := (oper.typ = top_const) and (oper.val = a);
  243. end;
  244. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  245. begin
  246. result := oper1.typ = oper2.typ;
  247. if result then
  248. case oper1.typ of
  249. top_const:
  250. Result:=oper1.val = oper2.val;
  251. top_reg:
  252. Result:=oper1.reg = oper2.reg;
  253. top_ref:
  254. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  255. else
  256. internalerror(2013102801);
  257. end
  258. end;
  259. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  260. begin
  261. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  262. if result then
  263. case oper1.typ of
  264. top_const:
  265. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  266. top_reg:
  267. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  268. top_ref:
  269. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  270. else
  271. internalerror(2020052401);
  272. end
  273. end;
  274. function RefsEqual(const r1, r2: treference): boolean;
  275. begin
  276. RefsEqual :=
  277. (r1.offset = r2.offset) and
  278. (r1.segment = r2.segment) and (r1.base = r2.base) and
  279. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  280. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  281. (r1.relsymbol = r2.relsymbol) and
  282. (r1.volatility=[]) and
  283. (r2.volatility=[]);
  284. end;
  285. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  286. begin
  287. Result:=(ref.offset=0) and
  288. (ref.scalefactor in [0,1]) and
  289. (ref.segment=NR_NO) and
  290. (ref.symbol=nil) and
  291. (ref.relsymbol=nil) and
  292. ((base=NR_INVALID) or
  293. (ref.base=base)) and
  294. ((index=NR_INVALID) or
  295. (ref.index=index)) and
  296. (ref.volatility=[]);
  297. end;
  298. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  299. begin
  300. Result:=(ref.scalefactor in [0,1]) and
  301. (ref.segment=NR_NO) and
  302. (ref.symbol=nil) and
  303. (ref.relsymbol=nil) and
  304. ((base=NR_INVALID) or
  305. (ref.base=base)) and
  306. ((index=NR_INVALID) or
  307. (ref.index=index)) and
  308. (ref.volatility=[]);
  309. end;
  310. function InstrReadsFlags(p: tai): boolean;
  311. begin
  312. InstrReadsFlags := true;
  313. case p.typ of
  314. ait_instruction:
  315. if InsProp[taicpu(p).opcode].Ch*
  316. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  317. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  318. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  319. exit;
  320. ait_label:
  321. exit;
  322. else
  323. ;
  324. end;
  325. InstrReadsFlags := false;
  326. end;
  327. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  328. begin
  329. Next:=Current;
  330. repeat
  331. Result:=GetNextInstruction(Next,Next);
  332. until not (Result) or
  333. not(cs_opt_level3 in current_settings.optimizerswitches) or
  334. (Next.typ<>ait_instruction) or
  335. RegInInstruction(reg,Next) or
  336. is_calljmp(taicpu(Next).opcode);
  337. end;
  338. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  339. begin
  340. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  341. Next := Current;
  342. repeat
  343. Result := GetNextInstruction(Next,Next);
  344. if Result and (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  345. if is_calljmpuncondret(taicpu(Next).opcode) then
  346. begin
  347. Result := False;
  348. Exit;
  349. end
  350. else
  351. CrossJump := True;
  352. until not Result or
  353. not (cs_opt_level3 in current_settings.optimizerswitches) or
  354. (Next.typ <> ait_instruction) or
  355. RegInInstruction(reg,Next);
  356. end;
  357. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  358. begin
  359. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  360. begin
  361. Result:=GetNextInstruction(Current,Next);
  362. exit;
  363. end;
  364. Next:=tai(Current.Next);
  365. Result:=false;
  366. while assigned(Next) do
  367. begin
  368. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  369. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  370. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  371. exit
  372. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  373. begin
  374. Result:=true;
  375. exit;
  376. end;
  377. Next:=tai(Next.Next);
  378. end;
  379. end;
  380. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  381. begin
  382. Result:=RegReadByInstruction(reg,hp);
  383. end;
  384. function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  385. var
  386. p: taicpu;
  387. opcount: longint;
  388. begin
  389. RegReadByInstruction := false;
  390. if hp.typ <> ait_instruction then
  391. exit;
  392. p := taicpu(hp);
  393. case p.opcode of
  394. A_CALL:
  395. regreadbyinstruction := true;
  396. A_IMUL:
  397. case p.ops of
  398. 1:
  399. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  400. (
  401. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  402. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  403. );
  404. 2,3:
  405. regReadByInstruction :=
  406. reginop(reg,p.oper[0]^) or
  407. reginop(reg,p.oper[1]^);
  408. else
  409. InternalError(2019112801);
  410. end;
  411. A_MUL:
  412. begin
  413. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  414. (
  415. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  416. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  417. );
  418. end;
  419. A_IDIV,A_DIV:
  420. begin
  421. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  422. (
  423. (getregtype(reg)=R_INTREGISTER) and
  424. (
  425. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  426. )
  427. );
  428. end;
  429. else
  430. begin
  431. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  432. begin
  433. RegReadByInstruction := false;
  434. exit;
  435. end;
  436. for opcount := 0 to p.ops-1 do
  437. if (p.oper[opCount]^.typ = top_ref) and
  438. RegInRef(reg,p.oper[opcount]^.ref^) then
  439. begin
  440. RegReadByInstruction := true;
  441. exit
  442. end;
  443. { special handling for SSE MOVSD }
  444. if (p.opcode=A_MOVSD) and (p.ops>0) then
  445. begin
  446. if p.ops<>2 then
  447. internalerror(2017042702);
  448. regReadByInstruction := reginop(reg,p.oper[0]^) or
  449. (
  450. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  451. );
  452. exit;
  453. end;
  454. with insprop[p.opcode] do
  455. begin
  456. if getregtype(reg)=R_INTREGISTER then
  457. begin
  458. case getsupreg(reg) of
  459. RS_EAX:
  460. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  461. begin
  462. RegReadByInstruction := true;
  463. exit
  464. end;
  465. RS_ECX:
  466. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  467. begin
  468. RegReadByInstruction := true;
  469. exit
  470. end;
  471. RS_EDX:
  472. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  473. begin
  474. RegReadByInstruction := true;
  475. exit
  476. end;
  477. RS_EBX:
  478. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  479. begin
  480. RegReadByInstruction := true;
  481. exit
  482. end;
  483. RS_ESP:
  484. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  485. begin
  486. RegReadByInstruction := true;
  487. exit
  488. end;
  489. RS_EBP:
  490. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  491. begin
  492. RegReadByInstruction := true;
  493. exit
  494. end;
  495. RS_ESI:
  496. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  497. begin
  498. RegReadByInstruction := true;
  499. exit
  500. end;
  501. RS_EDI:
  502. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  503. begin
  504. RegReadByInstruction := true;
  505. exit
  506. end;
  507. end;
  508. end;
  509. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  510. begin
  511. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  512. begin
  513. case p.condition of
  514. C_A,C_NBE, { CF=0 and ZF=0 }
  515. C_BE,C_NA: { CF=1 or ZF=1 }
  516. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  517. C_AE,C_NB,C_NC, { CF=0 }
  518. C_B,C_NAE,C_C: { CF=1 }
  519. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  520. C_NE,C_NZ, { ZF=0 }
  521. C_E,C_Z: { ZF=1 }
  522. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  523. C_G,C_NLE, { ZF=0 and SF=OF }
  524. C_LE,C_NG: { ZF=1 or SF<>OF }
  525. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  526. C_GE,C_NL, { SF=OF }
  527. C_L,C_NGE: { SF<>OF }
  528. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  529. C_NO, { OF=0 }
  530. C_O: { OF=1 }
  531. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  532. C_NP,C_PO, { PF=0 }
  533. C_P,C_PE: { PF=1 }
  534. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  535. C_NS, { SF=0 }
  536. C_S: { SF=1 }
  537. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  538. else
  539. internalerror(2017042701);
  540. end;
  541. if RegReadByInstruction then
  542. exit;
  543. end;
  544. case getsubreg(reg) of
  545. R_SUBW,R_SUBD,R_SUBQ:
  546. RegReadByInstruction :=
  547. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  548. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  549. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  550. R_SUBFLAGCARRY:
  551. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  552. R_SUBFLAGPARITY:
  553. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  554. R_SUBFLAGAUXILIARY:
  555. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  556. R_SUBFLAGZERO:
  557. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  558. R_SUBFLAGSIGN:
  559. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  560. R_SUBFLAGOVERFLOW:
  561. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  562. R_SUBFLAGINTERRUPT:
  563. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  564. R_SUBFLAGDIRECTION:
  565. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  566. else
  567. internalerror(2017042601);
  568. end;
  569. exit;
  570. end;
  571. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  572. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  573. (p.oper[0]^.reg=p.oper[1]^.reg) then
  574. exit;
  575. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  576. begin
  577. RegReadByInstruction := true;
  578. exit
  579. end;
  580. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  581. begin
  582. RegReadByInstruction := true;
  583. exit
  584. end;
  585. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  586. begin
  587. RegReadByInstruction := true;
  588. exit
  589. end;
  590. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  591. begin
  592. RegReadByInstruction := true;
  593. exit
  594. end;
  595. end;
  596. end;
  597. end;
  598. end;
  599. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  600. begin
  601. result:=false;
  602. if p1.typ<>ait_instruction then
  603. exit;
  604. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  605. exit(true);
  606. if (getregtype(reg)=R_INTREGISTER) and
  607. { change information for xmm movsd are not correct }
  608. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  609. begin
  610. case getsupreg(reg) of
  611. { RS_EAX = RS_RAX on x86-64 }
  612. RS_EAX:
  613. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  614. RS_ECX:
  615. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  616. RS_EDX:
  617. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  618. RS_EBX:
  619. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  620. RS_ESP:
  621. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  622. RS_EBP:
  623. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  624. RS_ESI:
  625. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  626. RS_EDI:
  627. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  628. else
  629. ;
  630. end;
  631. if result then
  632. exit;
  633. end
  634. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  635. begin
  636. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  637. exit(true);
  638. case getsubreg(reg) of
  639. R_SUBFLAGCARRY:
  640. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  641. R_SUBFLAGPARITY:
  642. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  643. R_SUBFLAGAUXILIARY:
  644. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  645. R_SUBFLAGZERO:
  646. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  647. R_SUBFLAGSIGN:
  648. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  649. R_SUBFLAGOVERFLOW:
  650. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  651. R_SUBFLAGINTERRUPT:
  652. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  653. R_SUBFLAGDIRECTION:
  654. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  655. else
  656. ;
  657. end;
  658. if result then
  659. exit;
  660. end
  661. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  662. exit(true);
  663. Result:=inherited RegInInstruction(Reg, p1);
  664. end;
  665. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  666. begin
  667. Result := False;
  668. if p1.typ <> ait_instruction then
  669. exit;
  670. with insprop[taicpu(p1).opcode] do
  671. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  672. begin
  673. case getsubreg(reg) of
  674. R_SUBW,R_SUBD,R_SUBQ:
  675. Result :=
  676. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  677. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  678. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  679. R_SUBFLAGCARRY:
  680. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  681. R_SUBFLAGPARITY:
  682. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  683. R_SUBFLAGAUXILIARY:
  684. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  685. R_SUBFLAGZERO:
  686. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  687. R_SUBFLAGSIGN:
  688. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  689. R_SUBFLAGOVERFLOW:
  690. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  691. R_SUBFLAGINTERRUPT:
  692. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  693. R_SUBFLAGDIRECTION:
  694. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  695. else
  696. internalerror(2017042602);
  697. end;
  698. exit;
  699. end;
  700. case taicpu(p1).opcode of
  701. A_CALL:
  702. { We could potentially set Result to False if the register in
  703. question is non-volatile for the subroutine's calling convention,
  704. but this would require detecting the calling convention in use and
  705. also assuming that the routine doesn't contain malformed assembly
  706. language, for example... so it could only be done under -O4 as it
  707. would be considered a side-effect. [Kit] }
  708. Result := True;
  709. A_MOVSD:
  710. { special handling for SSE MOVSD }
  711. if (taicpu(p1).ops>0) then
  712. begin
  713. if taicpu(p1).ops<>2 then
  714. internalerror(2017042703);
  715. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  716. end;
  717. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  718. so fix it here (FK)
  719. }
  720. A_VMOVSS,
  721. A_VMOVSD:
  722. begin
  723. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  724. exit;
  725. end;
  726. A_IMUL:
  727. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  728. else
  729. ;
  730. end;
  731. if Result then
  732. exit;
  733. with insprop[taicpu(p1).opcode] do
  734. begin
  735. if getregtype(reg)=R_INTREGISTER then
  736. begin
  737. case getsupreg(reg) of
  738. RS_EAX:
  739. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  740. begin
  741. Result := True;
  742. exit
  743. end;
  744. RS_ECX:
  745. if [Ch_WECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  746. begin
  747. Result := True;
  748. exit
  749. end;
  750. RS_EDX:
  751. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  752. begin
  753. Result := True;
  754. exit
  755. end;
  756. RS_EBX:
  757. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  758. begin
  759. Result := True;
  760. exit
  761. end;
  762. RS_ESP:
  763. if [Ch_WESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  764. begin
  765. Result := True;
  766. exit
  767. end;
  768. RS_EBP:
  769. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  770. begin
  771. Result := True;
  772. exit
  773. end;
  774. RS_ESI:
  775. if [Ch_WESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  776. begin
  777. Result := True;
  778. exit
  779. end;
  780. RS_EDI:
  781. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  782. begin
  783. Result := True;
  784. exit
  785. end;
  786. end;
  787. end;
  788. if ([CH_RWOP1,CH_WOP1,CH_MOP1]*Ch<>[]) and reginop(reg,taicpu(p1).oper[0]^) then
  789. begin
  790. Result := true;
  791. exit
  792. end;
  793. if ([Ch_RWOP2,Ch_WOP2,Ch_MOP2]*Ch<>[]) and reginop(reg,taicpu(p1).oper[1]^) then
  794. begin
  795. Result := true;
  796. exit
  797. end;
  798. if ([Ch_RWOP3,Ch_WOP3,Ch_MOP3]*Ch<>[]) and reginop(reg,taicpu(p1).oper[2]^) then
  799. begin
  800. Result := true;
  801. exit
  802. end;
  803. if ([Ch_RWOP4,Ch_WOP4,Ch_MOP4]*Ch<>[]) and reginop(reg,taicpu(p1).oper[3]^) then
  804. begin
  805. Result := true;
  806. exit
  807. end;
  808. end;
  809. end;
  810. {$ifdef DEBUG_AOPTCPU}
  811. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  812. begin
  813. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  814. end;
  815. function debug_tostr(i: tcgint): string; inline;
  816. begin
  817. Result := tostr(i);
  818. end;
  819. function debug_regname(r: TRegister): string; inline;
  820. begin
  821. Result := '%' + std_regname(r);
  822. end;
  823. { Debug output function - creates a string representation of an operator }
  824. function debug_operstr(oper: TOper): string;
  825. begin
  826. case oper.typ of
  827. top_const:
  828. Result := '$' + debug_tostr(oper.val);
  829. top_reg:
  830. Result := debug_regname(oper.reg);
  831. top_ref:
  832. begin
  833. if oper.ref^.offset <> 0 then
  834. Result := debug_tostr(oper.ref^.offset) + '('
  835. else
  836. Result := '(';
  837. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  838. begin
  839. Result := Result + debug_regname(oper.ref^.base);
  840. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  841. Result := Result + ',' + debug_regname(oper.ref^.index);
  842. end
  843. else
  844. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  845. Result := Result + debug_regname(oper.ref^.index);
  846. if (oper.ref^.scalefactor > 1) then
  847. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  848. else
  849. Result := Result + ')';
  850. end;
  851. else
  852. Result := '[UNKNOWN]';
  853. end;
  854. end;
  855. function debug_op2str(opcode: tasmop): string; inline;
  856. begin
  857. Result := std_op2str[opcode];
  858. end;
  859. function debug_opsize2str(opsize: topsize): string; inline;
  860. begin
  861. Result := gas_opsize2str[opsize];
  862. end;
  863. {$else DEBUG_AOPTCPU}
  864. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  865. begin
  866. end;
  867. function debug_tostr(i: tcgint): string; inline;
  868. begin
  869. Result := '';
  870. end;
  871. function debug_regname(r: TRegister): string; inline;
  872. begin
  873. Result := '';
  874. end;
  875. function debug_operstr(oper: TOper): string; inline;
  876. begin
  877. Result := '';
  878. end;
  879. function debug_op2str(opcode: tasmop): string; inline;
  880. begin
  881. Result := '';
  882. end;
  883. function debug_opsize2str(opsize: topsize): string; inline;
  884. begin
  885. Result := '';
  886. end;
  887. {$endif DEBUG_AOPTCPU}
  888. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  889. begin
  890. {$ifdef x86_64}
  891. { Always fine on x86-64 }
  892. Result := True;
  893. {$else x86_64}
  894. Result :=
  895. {$ifdef i8086}
  896. (current_settings.cputype >= cpu_386) and
  897. {$endif i8086}
  898. (
  899. { Always accept if optimising for size }
  900. (cs_opt_size in current_settings.optimizerswitches) or
  901. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  902. (current_settings.optimizecputype >= cpu_Pentium2)
  903. );
  904. {$endif x86_64}
  905. end;
  906. { Attempts to allocate a volatile integer register for use between p and hp,
  907. using AUsedRegs for the current register usage information. Returns NR_NO
  908. if no free register could be found }
  909. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  910. var
  911. RegSet: TCPURegisterSet;
  912. CurrentSuperReg: Integer;
  913. CurrentReg: TRegister;
  914. Currentp: tai;
  915. Breakout: Boolean;
  916. begin
  917. { TODO: Currently, only the volatile registers are checked - can this be extended to use any register the procedure has preserved? }
  918. Result := NR_NO;
  919. RegSet := paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption);
  920. for CurrentSuperReg := Low(RegSet) to High(RegSet) do
  921. begin
  922. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  923. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg) then
  924. begin
  925. Currentp := p;
  926. Breakout := False;
  927. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  928. begin
  929. case hp.typ of
  930. ait_instruction:
  931. begin
  932. if RegInInstruction(CurrentReg, Currentp) then
  933. begin
  934. Breakout := True;
  935. Break;
  936. end;
  937. { Cannot allocate across an unconditional jump }
  938. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  939. Exit;
  940. end;
  941. ait_marker:
  942. { Don't try anything more if a marker is hit }
  943. Exit;
  944. else
  945. ;
  946. end;
  947. end;
  948. if Breakout then
  949. { Try the next register }
  950. Continue;
  951. { We have a free register available }
  952. Result := CurrentReg;
  953. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  954. Exit;
  955. end;
  956. end;
  957. end;
  958. { Attempts to allocate a volatile MM register for use between p and hp,
  959. using AUsedRegs for the current register usage information. Returns NR_NO
  960. if no free register could be found }
  961. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  962. var
  963. RegSet: TCPURegisterSet;
  964. CurrentSuperReg: Integer;
  965. CurrentReg: TRegister;
  966. Currentp: tai;
  967. Breakout: Boolean;
  968. begin
  969. { TODO: Currently, only the volatile registers are checked - can this be extended to use any register the procedure has preserved? }
  970. Result := NR_NO;
  971. RegSet := paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption);
  972. for CurrentSuperReg := Low(RegSet) to High(RegSet) do
  973. begin
  974. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  975. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  976. begin
  977. Currentp := p;
  978. Breakout := False;
  979. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  980. begin
  981. case hp.typ of
  982. ait_instruction:
  983. begin
  984. if RegInInstruction(CurrentReg, Currentp) then
  985. begin
  986. Breakout := True;
  987. Break;
  988. end;
  989. { Cannot allocate across an unconditional jump }
  990. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  991. Exit;
  992. end;
  993. ait_marker:
  994. { Don't try anything more if a marker is hit }
  995. Exit;
  996. else
  997. ;
  998. end;
  999. end;
  1000. if Breakout then
  1001. { Try the next register }
  1002. Continue;
  1003. { We have a free register available }
  1004. Result := CurrentReg;
  1005. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1006. Exit;
  1007. end;
  1008. end;
  1009. end;
  1010. function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1011. begin
  1012. if not SuperRegistersEqual(reg1,reg2) then
  1013. exit(false);
  1014. if getregtype(reg1)<>R_INTREGISTER then
  1015. exit(true); {because SuperRegisterEqual is true}
  1016. case getsubreg(reg1) of
  1017. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1018. higher, it preserves the high bits, so the new value depends on
  1019. reg2's previous value. In other words, it is equivalent to doing:
  1020. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1021. R_SUBL:
  1022. exit(getsubreg(reg2)=R_SUBL);
  1023. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1024. higher, it actually does a:
  1025. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1026. R_SUBH:
  1027. exit(getsubreg(reg2)=R_SUBH);
  1028. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1029. bits of reg2:
  1030. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1031. R_SUBW:
  1032. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1033. { a write to R_SUBD always overwrites every other subregister,
  1034. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1035. R_SUBD,
  1036. R_SUBQ:
  1037. exit(true);
  1038. else
  1039. internalerror(2017042801);
  1040. end;
  1041. end;
  1042. function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1043. begin
  1044. if not SuperRegistersEqual(reg1,reg2) then
  1045. exit(false);
  1046. if getregtype(reg1)<>R_INTREGISTER then
  1047. exit(true); {because SuperRegisterEqual is true}
  1048. case getsubreg(reg1) of
  1049. R_SUBL:
  1050. exit(getsubreg(reg2)<>R_SUBH);
  1051. R_SUBH:
  1052. exit(getsubreg(reg2)<>R_SUBL);
  1053. R_SUBW,
  1054. R_SUBD,
  1055. R_SUBQ:
  1056. exit(true);
  1057. else
  1058. internalerror(2017042802);
  1059. end;
  1060. end;
  1061. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1062. var
  1063. hp1 : tai;
  1064. l : TCGInt;
  1065. begin
  1066. result:=false;
  1067. { changes the code sequence
  1068. shr/sar const1, x
  1069. shl const2, x
  1070. to
  1071. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1072. if GetNextInstruction(p, hp1) and
  1073. MatchInstruction(hp1,A_SHL,[]) and
  1074. (taicpu(p).oper[0]^.typ = top_const) and
  1075. (taicpu(hp1).oper[0]^.typ = top_const) and
  1076. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1077. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1078. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1079. begin
  1080. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1081. not(cs_opt_size in current_settings.optimizerswitches) then
  1082. begin
  1083. { shr/sar const1, %reg
  1084. shl const2, %reg
  1085. with const1 > const2 }
  1086. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1087. taicpu(hp1).opcode := A_AND;
  1088. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1089. case taicpu(p).opsize Of
  1090. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1091. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1092. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1093. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1094. else
  1095. Internalerror(2017050703)
  1096. end;
  1097. end
  1098. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1099. not(cs_opt_size in current_settings.optimizerswitches) then
  1100. begin
  1101. { shr/sar const1, %reg
  1102. shl const2, %reg
  1103. with const1 < const2 }
  1104. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1105. taicpu(p).opcode := A_AND;
  1106. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1107. case taicpu(p).opsize Of
  1108. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1109. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1110. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1111. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1112. else
  1113. Internalerror(2017050702)
  1114. end;
  1115. end
  1116. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1117. begin
  1118. { shr/sar const1, %reg
  1119. shl const2, %reg
  1120. with const1 = const2 }
  1121. taicpu(p).opcode := A_AND;
  1122. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1123. case taicpu(p).opsize Of
  1124. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1125. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1126. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1127. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1128. else
  1129. Internalerror(2017050701)
  1130. end;
  1131. RemoveInstruction(hp1);
  1132. end;
  1133. end;
  1134. end;
  1135. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1136. var
  1137. opsize : topsize;
  1138. hp1 : tai;
  1139. tmpref : treference;
  1140. ShiftValue : Cardinal;
  1141. BaseValue : TCGInt;
  1142. begin
  1143. result:=false;
  1144. opsize:=taicpu(p).opsize;
  1145. { changes certain "imul const, %reg"'s to lea sequences }
  1146. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1147. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1148. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1149. if (taicpu(p).oper[0]^.val = 1) then
  1150. if (taicpu(p).ops = 2) then
  1151. { remove "imul $1, reg" }
  1152. begin
  1153. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1154. Result := RemoveCurrentP(p);
  1155. end
  1156. else
  1157. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1158. begin
  1159. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1160. InsertLLItem(p.previous, p.next, hp1);
  1161. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1162. p.free;
  1163. p := hp1;
  1164. end
  1165. else if ((taicpu(p).ops <= 2) or
  1166. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1167. not(cs_opt_size in current_settings.optimizerswitches) and
  1168. (not(GetNextInstruction(p, hp1)) or
  1169. not((tai(hp1).typ = ait_instruction) and
  1170. ((taicpu(hp1).opcode=A_Jcc) and
  1171. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1172. begin
  1173. {
  1174. imul X, reg1, reg2 to
  1175. lea (reg1,reg1,Y), reg2
  1176. shl ZZ,reg2
  1177. imul XX, reg1 to
  1178. lea (reg1,reg1,YY), reg1
  1179. shl ZZ,reg2
  1180. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1181. it does not exist as a separate optimization target in FPC though.
  1182. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1183. at most two zeros
  1184. }
  1185. reference_reset(tmpref,1,[]);
  1186. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1187. begin
  1188. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1189. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1190. TmpRef.base := taicpu(p).oper[1]^.reg;
  1191. TmpRef.index := taicpu(p).oper[1]^.reg;
  1192. if not(BaseValue in [3,5,9]) then
  1193. Internalerror(2018110101);
  1194. TmpRef.ScaleFactor := BaseValue-1;
  1195. if (taicpu(p).ops = 2) then
  1196. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1197. else
  1198. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1199. AsmL.InsertAfter(hp1,p);
  1200. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1201. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1202. RemoveCurrentP(p, hp1);
  1203. if ShiftValue>0 then
  1204. AsmL.InsertAfter(taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg),hp1);
  1205. end;
  1206. end;
  1207. end;
  1208. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1209. begin
  1210. Result := False;
  1211. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1212. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1213. begin
  1214. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1215. taicpu(p).opcode := A_MOV;
  1216. Result := True;
  1217. end;
  1218. end;
  1219. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1220. var
  1221. p: taicpu absolute hp;
  1222. i: Integer;
  1223. begin
  1224. Result := False;
  1225. if not assigned(hp) or
  1226. (hp.typ <> ait_instruction) then
  1227. Exit;
  1228. // p := taicpu(hp);
  1229. Prefetch(insprop[p.opcode]);
  1230. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1231. with insprop[p.opcode] do
  1232. begin
  1233. case getsubreg(reg) of
  1234. R_SUBW,R_SUBD,R_SUBQ:
  1235. Result:=
  1236. RegLoadedWithNewValue(NR_CARRYFLAG,hp) and
  1237. RegLoadedWithNewValue(NR_PARITYFLAG,hp) and
  1238. RegLoadedWithNewValue(NR_AUXILIARYFLAG,hp) and
  1239. RegLoadedWithNewValue(NR_ZEROFLAG,hp) and
  1240. RegLoadedWithNewValue(NR_SIGNFLAG,hp) and
  1241. RegLoadedWithNewValue(NR_OVERFLOWFLAG,hp);
  1242. R_SUBFLAGCARRY:
  1243. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1244. R_SUBFLAGPARITY:
  1245. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1246. R_SUBFLAGAUXILIARY:
  1247. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1248. R_SUBFLAGZERO:
  1249. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1250. R_SUBFLAGSIGN:
  1251. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1252. R_SUBFLAGOVERFLOW:
  1253. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1254. R_SUBFLAGINTERRUPT:
  1255. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1256. R_SUBFLAGDIRECTION:
  1257. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1258. else
  1259. begin
  1260. writeln(getsubreg(reg));
  1261. internalerror(2017050501);
  1262. end;
  1263. end;
  1264. exit;
  1265. end;
  1266. { Handle special cases first }
  1267. case p.opcode of
  1268. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1269. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1270. begin
  1271. Result :=
  1272. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1273. (p.oper[1]^.typ = top_reg) and
  1274. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1275. (
  1276. (p.oper[0]^.typ = top_const) or
  1277. (
  1278. (p.oper[0]^.typ = top_reg) and
  1279. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1280. ) or (
  1281. (p.oper[0]^.typ = top_ref) and
  1282. not RegInRef(reg,p.oper[0]^.ref^)
  1283. )
  1284. );
  1285. end;
  1286. A_MUL, A_IMUL:
  1287. Result :=
  1288. (
  1289. (p.ops=3) and { IMUL only }
  1290. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1291. (
  1292. (
  1293. (p.oper[1]^.typ=top_reg) and
  1294. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1295. ) or (
  1296. (p.oper[1]^.typ=top_ref) and
  1297. not RegInRef(reg,p.oper[1]^.ref^)
  1298. )
  1299. )
  1300. ) or (
  1301. (
  1302. (p.ops=1) and
  1303. (
  1304. (
  1305. (
  1306. (p.oper[0]^.typ=top_reg) and
  1307. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1308. )
  1309. ) or (
  1310. (p.oper[0]^.typ=top_ref) and
  1311. not RegInRef(reg,p.oper[0]^.ref^)
  1312. )
  1313. ) and (
  1314. (
  1315. (p.opsize=S_B) and
  1316. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1317. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1318. ) or (
  1319. (p.opsize=S_W) and
  1320. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1321. ) or (
  1322. (p.opsize=S_L) and
  1323. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1324. {$ifdef x86_64}
  1325. ) or (
  1326. (p.opsize=S_Q) and
  1327. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1328. {$endif x86_64}
  1329. )
  1330. )
  1331. )
  1332. );
  1333. A_CBW:
  1334. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1335. {$ifndef x86_64}
  1336. A_LDS:
  1337. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1338. A_LES:
  1339. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1340. {$endif not x86_64}
  1341. A_LFS:
  1342. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1343. A_LGS:
  1344. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1345. A_LSS:
  1346. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1347. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1348. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1349. A_LODSB:
  1350. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1351. A_LODSW:
  1352. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1353. {$ifdef x86_64}
  1354. A_LODSQ:
  1355. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1356. {$endif x86_64}
  1357. A_LODSD:
  1358. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1359. A_FSTSW, A_FNSTSW:
  1360. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1361. else
  1362. begin
  1363. with insprop[p.opcode] do
  1364. begin
  1365. if (
  1366. { xor %reg,%reg etc. is classed as a new value }
  1367. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1368. MatchOpType(p, top_reg, top_reg) and
  1369. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1370. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1371. ) then
  1372. begin
  1373. Result := True;
  1374. Exit;
  1375. end;
  1376. { Make sure the entire register is overwritten }
  1377. if (getregtype(reg) = R_INTREGISTER) then
  1378. begin
  1379. if (p.ops > 0) then
  1380. begin
  1381. if RegInOp(reg, p.oper[0]^) then
  1382. begin
  1383. if (p.oper[0]^.typ = top_ref) then
  1384. begin
  1385. if RegInRef(reg, p.oper[0]^.ref^) then
  1386. begin
  1387. Result := False;
  1388. Exit;
  1389. end;
  1390. end
  1391. else if (p.oper[0]^.typ = top_reg) then
  1392. begin
  1393. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1394. begin
  1395. Result := False;
  1396. Exit;
  1397. end
  1398. else if ([Ch_WOp1]*Ch<>[]) then
  1399. begin
  1400. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1401. Result := True
  1402. else
  1403. begin
  1404. Result := False;
  1405. Exit;
  1406. end;
  1407. end;
  1408. end;
  1409. end;
  1410. if (p.ops > 1) then
  1411. begin
  1412. if RegInOp(reg, p.oper[1]^) then
  1413. begin
  1414. if (p.oper[1]^.typ = top_ref) then
  1415. begin
  1416. if RegInRef(reg, p.oper[1]^.ref^) then
  1417. begin
  1418. Result := False;
  1419. Exit;
  1420. end;
  1421. end
  1422. else if (p.oper[1]^.typ = top_reg) then
  1423. begin
  1424. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1425. begin
  1426. Result := False;
  1427. Exit;
  1428. end
  1429. else if ([Ch_WOp2]*Ch<>[]) then
  1430. begin
  1431. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1432. Result := True
  1433. else
  1434. begin
  1435. Result := False;
  1436. Exit;
  1437. end;
  1438. end;
  1439. end;
  1440. end;
  1441. if (p.ops > 2) then
  1442. begin
  1443. if RegInOp(reg, p.oper[2]^) then
  1444. begin
  1445. if (p.oper[2]^.typ = top_ref) then
  1446. begin
  1447. if RegInRef(reg, p.oper[2]^.ref^) then
  1448. begin
  1449. Result := False;
  1450. Exit;
  1451. end;
  1452. end
  1453. else if (p.oper[2]^.typ = top_reg) then
  1454. begin
  1455. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1456. begin
  1457. Result := False;
  1458. Exit;
  1459. end
  1460. else if ([Ch_WOp3]*Ch<>[]) then
  1461. begin
  1462. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1463. Result := True
  1464. else
  1465. begin
  1466. Result := False;
  1467. Exit;
  1468. end;
  1469. end;
  1470. end;
  1471. end;
  1472. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1473. begin
  1474. if (p.oper[3]^.typ = top_ref) then
  1475. begin
  1476. if RegInRef(reg, p.oper[3]^.ref^) then
  1477. begin
  1478. Result := False;
  1479. Exit;
  1480. end;
  1481. end
  1482. else if (p.oper[3]^.typ = top_reg) then
  1483. begin
  1484. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1485. begin
  1486. Result := False;
  1487. Exit;
  1488. end
  1489. else if ([Ch_WOp4]*Ch<>[]) then
  1490. begin
  1491. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1492. Result := True
  1493. else
  1494. begin
  1495. Result := False;
  1496. Exit;
  1497. end;
  1498. end;
  1499. end;
  1500. end;
  1501. end;
  1502. end;
  1503. end;
  1504. { Don't do these ones first in case an input operand is equal to an explicit output registers }
  1505. case getsupreg(reg) of
  1506. RS_EAX:
  1507. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1508. begin
  1509. Result := True;
  1510. Exit;
  1511. end;
  1512. RS_ECX:
  1513. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1514. begin
  1515. Result := True;
  1516. Exit;
  1517. end;
  1518. RS_EDX:
  1519. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1520. begin
  1521. Result := True;
  1522. Exit;
  1523. end;
  1524. RS_EBX:
  1525. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1526. begin
  1527. Result := True;
  1528. Exit;
  1529. end;
  1530. RS_ESP:
  1531. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1532. begin
  1533. Result := True;
  1534. Exit;
  1535. end;
  1536. RS_EBP:
  1537. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1538. begin
  1539. Result := True;
  1540. Exit;
  1541. end;
  1542. RS_ESI:
  1543. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1544. begin
  1545. Result := True;
  1546. Exit;
  1547. end;
  1548. RS_EDI:
  1549. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1550. begin
  1551. Result := True;
  1552. Exit;
  1553. end;
  1554. else
  1555. ;
  1556. end;
  1557. end;
  1558. end;
  1559. end;
  1560. end;
  1561. end;
  1562. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1563. var
  1564. hp2,hp3 : tai;
  1565. begin
  1566. { some x86-64 issue a NOP before the real exit code }
  1567. if MatchInstruction(p,A_NOP,[]) then
  1568. GetNextInstruction(p,p);
  1569. result:=assigned(p) and (p.typ=ait_instruction) and
  1570. ((taicpu(p).opcode = A_RET) or
  1571. ((taicpu(p).opcode=A_LEAVE) and
  1572. GetNextInstruction(p,hp2) and
  1573. MatchInstruction(hp2,A_RET,[S_NO])
  1574. ) or
  1575. (((taicpu(p).opcode=A_LEA) and
  1576. MatchOpType(taicpu(p),top_ref,top_reg) and
  1577. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1578. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1579. ) and
  1580. GetNextInstruction(p,hp2) and
  1581. MatchInstruction(hp2,A_RET,[S_NO])
  1582. ) or
  1583. ((((taicpu(p).opcode=A_MOV) and
  1584. MatchOpType(taicpu(p),top_reg,top_reg) and
  1585. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1586. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1587. ((taicpu(p).opcode=A_LEA) and
  1588. MatchOpType(taicpu(p),top_ref,top_reg) and
  1589. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1590. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1591. )
  1592. ) and
  1593. GetNextInstruction(p,hp2) and
  1594. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1595. MatchOpType(taicpu(hp2),top_reg) and
  1596. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1597. GetNextInstruction(hp2,hp3) and
  1598. MatchInstruction(hp3,A_RET,[S_NO])
  1599. )
  1600. );
  1601. end;
  1602. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1603. begin
  1604. isFoldableArithOp := False;
  1605. case hp1.opcode of
  1606. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1607. isFoldableArithOp :=
  1608. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1609. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1610. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1611. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1612. (taicpu(hp1).oper[1]^.reg = reg);
  1613. A_INC,A_DEC,A_NEG,A_NOT:
  1614. isFoldableArithOp :=
  1615. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1616. (taicpu(hp1).oper[0]^.reg = reg);
  1617. else
  1618. ;
  1619. end;
  1620. end;
  1621. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1622. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1623. var
  1624. hp2: tai;
  1625. begin
  1626. hp2 := p;
  1627. repeat
  1628. hp2 := tai(hp2.previous);
  1629. if assigned(hp2) and
  1630. (hp2.typ = ait_regalloc) and
  1631. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1632. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1633. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1634. begin
  1635. RemoveInstruction(hp2);
  1636. break;
  1637. end;
  1638. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1639. end;
  1640. begin
  1641. case current_procinfo.procdef.returndef.typ of
  1642. arraydef,recorddef,pointerdef,
  1643. stringdef,enumdef,procdef,objectdef,errordef,
  1644. filedef,setdef,procvardef,
  1645. classrefdef,forwarddef:
  1646. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1647. orddef:
  1648. if current_procinfo.procdef.returndef.size <> 0 then
  1649. begin
  1650. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1651. { for int64/qword }
  1652. if current_procinfo.procdef.returndef.size = 8 then
  1653. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1654. end;
  1655. else
  1656. ;
  1657. end;
  1658. end;
  1659. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1660. var
  1661. hp1,hp2 : tai;
  1662. begin
  1663. result:=false;
  1664. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1665. begin
  1666. { vmova* reg1,reg1
  1667. =>
  1668. <nop> }
  1669. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1670. begin
  1671. RemoveCurrentP(p);
  1672. result:=true;
  1673. exit;
  1674. end
  1675. else if GetNextInstruction(p,hp1) then
  1676. begin
  1677. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1678. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1679. begin
  1680. { vmova* reg1,reg2
  1681. vmova* reg2,reg3
  1682. dealloc reg2
  1683. =>
  1684. vmova* reg1,reg3 }
  1685. TransferUsedRegs(TmpUsedRegs);
  1686. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1687. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1688. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1689. begin
  1690. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1691. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1692. RemoveInstruction(hp1);
  1693. result:=true;
  1694. exit;
  1695. end
  1696. { special case:
  1697. vmova* reg1,<op>
  1698. vmova* <op>,reg1
  1699. =>
  1700. vmova* reg1,<op> }
  1701. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1702. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1703. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1704. ) then
  1705. begin
  1706. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1707. RemoveInstruction(hp1);
  1708. result:=true;
  1709. exit;
  1710. end
  1711. end
  1712. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  1713. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  1714. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  1715. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  1716. ) and
  1717. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1718. begin
  1719. { vmova* reg1,reg2
  1720. vmovs* reg2,<op>
  1721. dealloc reg2
  1722. =>
  1723. vmovs* reg1,reg3 }
  1724. TransferUsedRegs(TmpUsedRegs);
  1725. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1726. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1727. begin
  1728. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  1729. taicpu(p).opcode:=taicpu(hp1).opcode;
  1730. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1731. RemoveInstruction(hp1);
  1732. result:=true;
  1733. exit;
  1734. end
  1735. end;
  1736. end;
  1737. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  1738. begin
  1739. if MatchInstruction(hp1,[A_VFMADDPD,
  1740. A_VFMADD132PD,
  1741. A_VFMADD132PS,
  1742. A_VFMADD132SD,
  1743. A_VFMADD132SS,
  1744. A_VFMADD213PD,
  1745. A_VFMADD213PS,
  1746. A_VFMADD213SD,
  1747. A_VFMADD213SS,
  1748. A_VFMADD231PD,
  1749. A_VFMADD231PS,
  1750. A_VFMADD231SD,
  1751. A_VFMADD231SS,
  1752. A_VFMADDSUB132PD,
  1753. A_VFMADDSUB132PS,
  1754. A_VFMADDSUB213PD,
  1755. A_VFMADDSUB213PS,
  1756. A_VFMADDSUB231PD,
  1757. A_VFMADDSUB231PS,
  1758. A_VFMSUB132PD,
  1759. A_VFMSUB132PS,
  1760. A_VFMSUB132SD,
  1761. A_VFMSUB132SS,
  1762. A_VFMSUB213PD,
  1763. A_VFMSUB213PS,
  1764. A_VFMSUB213SD,
  1765. A_VFMSUB213SS,
  1766. A_VFMSUB231PD,
  1767. A_VFMSUB231PS,
  1768. A_VFMSUB231SD,
  1769. A_VFMSUB231SS,
  1770. A_VFMSUBADD132PD,
  1771. A_VFMSUBADD132PS,
  1772. A_VFMSUBADD213PD,
  1773. A_VFMSUBADD213PS,
  1774. A_VFMSUBADD231PD,
  1775. A_VFMSUBADD231PS,
  1776. A_VFNMADD132PD,
  1777. A_VFNMADD132PS,
  1778. A_VFNMADD132SD,
  1779. A_VFNMADD132SS,
  1780. A_VFNMADD213PD,
  1781. A_VFNMADD213PS,
  1782. A_VFNMADD213SD,
  1783. A_VFNMADD213SS,
  1784. A_VFNMADD231PD,
  1785. A_VFNMADD231PS,
  1786. A_VFNMADD231SD,
  1787. A_VFNMADD231SS,
  1788. A_VFNMSUB132PD,
  1789. A_VFNMSUB132PS,
  1790. A_VFNMSUB132SD,
  1791. A_VFNMSUB132SS,
  1792. A_VFNMSUB213PD,
  1793. A_VFNMSUB213PS,
  1794. A_VFNMSUB213SD,
  1795. A_VFNMSUB213SS,
  1796. A_VFNMSUB231PD,
  1797. A_VFNMSUB231PS,
  1798. A_VFNMSUB231SD,
  1799. A_VFNMSUB231SS],[S_NO]) and
  1800. { we mix single and double opperations here because we assume that the compiler
  1801. generates vmovapd only after double operations and vmovaps only after single operations }
  1802. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  1803. GetNextInstruction(hp1,hp2) and
  1804. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  1805. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  1806. begin
  1807. TransferUsedRegs(TmpUsedRegs);
  1808. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1809. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1810. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1811. begin
  1812. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  1813. RemoveCurrentP(p, hp1); // <-- Is this actually safe? hp1 is not necessarily the next instruction. [Kit]
  1814. RemoveInstruction(hp2);
  1815. end;
  1816. end
  1817. else if (hp1.typ = ait_instruction) and
  1818. GetNextInstruction(hp1, hp2) and
  1819. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  1820. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  1821. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  1822. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  1823. (((taicpu(p).opcode=A_MOVAPS) and
  1824. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  1825. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  1826. ((taicpu(p).opcode=A_MOVAPD) and
  1827. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  1828. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  1829. ) then
  1830. { change
  1831. movapX reg,reg2
  1832. addsX/subsX/... reg3, reg2
  1833. movapX reg2,reg
  1834. to
  1835. addsX/subsX/... reg3,reg
  1836. }
  1837. begin
  1838. TransferUsedRegs(TmpUsedRegs);
  1839. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1840. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1841. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1842. begin
  1843. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  1844. debug_op2str(taicpu(p).opcode)+' '+
  1845. debug_op2str(taicpu(hp1).opcode)+' '+
  1846. debug_op2str(taicpu(hp2).opcode)+') done',p);
  1847. { we cannot eliminate the first move if
  1848. the operations uses the same register for source and dest }
  1849. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  1850. RemoveCurrentP(p, nil);
  1851. p:=hp1;
  1852. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  1853. RemoveInstruction(hp2);
  1854. result:=true;
  1855. end;
  1856. end;
  1857. end;
  1858. end;
  1859. end;
  1860. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  1861. var
  1862. hp1 : tai;
  1863. begin
  1864. result:=false;
  1865. { replace
  1866. V<Op>X %mreg1,%mreg2,%mreg3
  1867. VMovX %mreg3,%mreg4
  1868. dealloc %mreg3
  1869. by
  1870. V<Op>X %mreg1,%mreg2,%mreg4
  1871. ?
  1872. }
  1873. if GetNextInstruction(p,hp1) and
  1874. { we mix single and double operations here because we assume that the compiler
  1875. generates vmovapd only after double operations and vmovaps only after single operations }
  1876. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  1877. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  1878. (taicpu(hp1).oper[1]^.typ=top_reg) then
  1879. begin
  1880. TransferUsedRegs(TmpUsedRegs);
  1881. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1882. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  1883. begin
  1884. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  1885. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  1886. RemoveInstruction(hp1);
  1887. result:=true;
  1888. end;
  1889. end;
  1890. end;
  1891. { Replaces all references to AOldReg in a memory reference to ANewReg }
  1892. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  1893. begin
  1894. Result := False;
  1895. { For safety reasons, only check for exact register matches }
  1896. { Check base register }
  1897. if (ref.base = AOldReg) then
  1898. begin
  1899. ref.base := ANewReg;
  1900. Result := True;
  1901. end;
  1902. { Check index register }
  1903. if (ref.index = AOldReg) then
  1904. begin
  1905. ref.index := ANewReg;
  1906. Result := True;
  1907. end;
  1908. end;
  1909. { Replaces all references to AOldReg in an operand to ANewReg }
  1910. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  1911. var
  1912. OldSupReg, NewSupReg: TSuperRegister;
  1913. OldSubReg, NewSubReg: TSubRegister;
  1914. OldRegType: TRegisterType;
  1915. ThisOper: POper;
  1916. begin
  1917. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  1918. Result := False;
  1919. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  1920. InternalError(2020011801);
  1921. OldSupReg := getsupreg(AOldReg);
  1922. OldSubReg := getsubreg(AOldReg);
  1923. OldRegType := getregtype(AOldReg);
  1924. NewSupReg := getsupreg(ANewReg);
  1925. NewSubReg := getsubreg(ANewReg);
  1926. if OldRegType <> getregtype(ANewReg) then
  1927. InternalError(2020011802);
  1928. if OldSubReg <> NewSubReg then
  1929. InternalError(2020011803);
  1930. case ThisOper^.typ of
  1931. top_reg:
  1932. if (
  1933. (ThisOper^.reg = AOldReg) or
  1934. (
  1935. (OldRegType = R_INTREGISTER) and
  1936. (getsupreg(ThisOper^.reg) = OldSupReg) and
  1937. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  1938. (
  1939. (getsubreg(ThisOper^.reg) <= OldSubReg)
  1940. {$ifndef x86_64}
  1941. and (
  1942. { Under i386 and i8086, ESI, EDI, EBP and ESP
  1943. don't have an 8-bit representation }
  1944. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  1945. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  1946. )
  1947. {$endif x86_64}
  1948. )
  1949. )
  1950. ) then
  1951. begin
  1952. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  1953. Result := True;
  1954. end;
  1955. top_ref:
  1956. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  1957. Result := True;
  1958. else
  1959. ;
  1960. end;
  1961. end;
  1962. { Replaces all references to AOldReg in an instruction to ANewReg }
  1963. function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  1964. const
  1965. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  1966. var
  1967. OperIdx: Integer;
  1968. begin
  1969. Result := False;
  1970. for OperIdx := 0 to p.ops - 1 do
  1971. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) and
  1972. { The shift and rotate instructions can only use CL }
  1973. not (
  1974. (OperIdx = 0) and
  1975. { This second condition just helps to avoid unnecessarily
  1976. calling MatchInstruction for 10 different opcodes }
  1977. (p.oper[0]^.reg = NR_CL) and
  1978. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  1979. ) then
  1980. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  1981. end;
  1982. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean; inline;
  1983. begin
  1984. Result :=
  1985. (ref^.index = NR_NO) and
  1986. (
  1987. {$ifdef x86_64}
  1988. (
  1989. (ref^.base = NR_RIP) and
  1990. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  1991. ) or
  1992. {$endif x86_64}
  1993. (ref^.base = NR_STACK_POINTER_REG) or
  1994. (ref^.base = current_procinfo.framepointer)
  1995. );
  1996. end;
  1997. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  1998. var
  1999. l: asizeint;
  2000. begin
  2001. Result := False;
  2002. { Should have been checked previously }
  2003. if p.opcode <> A_LEA then
  2004. InternalError(2020072501);
  2005. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2006. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2007. not(cs_opt_size in current_settings.optimizerswitches) then
  2008. exit;
  2009. with p.oper[0]^.ref^ do
  2010. begin
  2011. if (base <> p.oper[1]^.reg) or
  2012. (index <> NR_NO) or
  2013. assigned(symbol) then
  2014. exit;
  2015. l:=offset;
  2016. if (l=1) and UseIncDec then
  2017. begin
  2018. p.opcode:=A_INC;
  2019. p.loadreg(0,p.oper[1]^.reg);
  2020. p.ops:=1;
  2021. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2022. end
  2023. else if (l=-1) and UseIncDec then
  2024. begin
  2025. p.opcode:=A_DEC;
  2026. p.loadreg(0,p.oper[1]^.reg);
  2027. p.ops:=1;
  2028. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2029. end
  2030. else
  2031. begin
  2032. if (l<0) and (l<>-2147483648) then
  2033. begin
  2034. p.opcode:=A_SUB;
  2035. p.loadConst(0,-l);
  2036. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2037. end
  2038. else
  2039. begin
  2040. p.opcode:=A_ADD;
  2041. p.loadConst(0,l);
  2042. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2043. end;
  2044. end;
  2045. end;
  2046. Result := True;
  2047. end;
  2048. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2049. var
  2050. CurrentReg, ReplaceReg: TRegister;
  2051. begin
  2052. Result := False;
  2053. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2054. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2055. case hp.opcode of
  2056. A_FSTSW, A_FNSTSW,
  2057. A_IN, A_INS, A_OUT, A_OUTS,
  2058. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2059. { These routines have explicit operands, but they are restricted in
  2060. what they can be (e.g. IN and OUT can only read from AL, AX or
  2061. EAX. }
  2062. Exit;
  2063. A_IMUL:
  2064. begin
  2065. { The 1-operand version writes to implicit registers
  2066. The 2-operand version reads from the first operator, and reads
  2067. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2068. the 3-operand version reads from a register that it doesn't write to
  2069. }
  2070. case hp.ops of
  2071. 1:
  2072. if (
  2073. (
  2074. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2075. ) or
  2076. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2077. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2078. begin
  2079. Result := True;
  2080. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2081. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2082. end;
  2083. 2:
  2084. { Only modify the first parameter }
  2085. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2086. begin
  2087. Result := True;
  2088. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2089. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2090. end;
  2091. 3:
  2092. { Only modify the second parameter }
  2093. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2094. begin
  2095. Result := True;
  2096. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2097. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2098. end;
  2099. else
  2100. InternalError(2020012901);
  2101. end;
  2102. end;
  2103. else
  2104. if (hp.ops > 0) and
  2105. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2106. begin
  2107. Result := True;
  2108. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2109. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2110. end;
  2111. end;
  2112. end;
  2113. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2114. var
  2115. hp1, hp2, hp3: tai;
  2116. DoOptimisation, TempBool: Boolean;
  2117. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2118. begin
  2119. if taicpu(hp1).opcode = signed_movop then
  2120. begin
  2121. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2122. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2123. end
  2124. else
  2125. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2126. end;
  2127. var
  2128. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2129. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2130. NewSize: topsize;
  2131. CurrentReg, ActiveReg: TRegister;
  2132. SourceRef, TargetRef: TReference;
  2133. MovAligned, MovUnaligned: TAsmOp;
  2134. begin
  2135. Result:=false;
  2136. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2137. { remove mov reg1,reg1? }
  2138. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2139. then
  2140. begin
  2141. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2142. { take care of the register (de)allocs following p }
  2143. RemoveCurrentP(p, hp1);
  2144. Result:=true;
  2145. exit;
  2146. end;
  2147. { All the next optimisations require a next instruction }
  2148. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2149. Exit;
  2150. { Look for:
  2151. mov %reg1,%reg2
  2152. ??? %reg2,r/m
  2153. Change to:
  2154. mov %reg1,%reg2
  2155. ??? %reg1,r/m
  2156. }
  2157. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2158. begin
  2159. CurrentReg := taicpu(p).oper[1]^.reg;
  2160. if RegReadByInstruction(CurrentReg, hp1) and
  2161. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2162. begin
  2163. TransferUsedRegs(TmpUsedRegs);
  2164. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2165. if not RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs) and
  2166. { Just in case something didn't get modified (e.g. an
  2167. implicit register) }
  2168. not RegReadByInstruction(CurrentReg, hp1) then
  2169. begin
  2170. { We can remove the original MOV }
  2171. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2172. RemoveCurrentp(p, hp1);
  2173. { UsedRegs got updated by RemoveCurrentp }
  2174. Result := True;
  2175. Exit;
  2176. end;
  2177. { If we know a MOV instruction has become a null operation, we might as well
  2178. get rid of it now to save time. }
  2179. if (taicpu(hp1).opcode = A_MOV) and
  2180. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2181. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2182. { Just being a register is enough to confirm it's a null operation }
  2183. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2184. begin
  2185. Result := True;
  2186. { Speed-up to reduce a pipeline stall... if we had something like...
  2187. movl %eax,%edx
  2188. movw %dx,%ax
  2189. ... the second instruction would change to movw %ax,%ax, but
  2190. given that it is now %ax that's active rather than %eax,
  2191. penalties might occur due to a partial register write, so instead,
  2192. change it to a MOVZX instruction when optimising for speed.
  2193. }
  2194. if not (cs_opt_size in current_settings.optimizerswitches) and
  2195. IsMOVZXAcceptable and
  2196. (taicpu(hp1).opsize < taicpu(p).opsize)
  2197. {$ifdef x86_64}
  2198. { operations already implicitly set the upper 64 bits to zero }
  2199. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2200. {$endif x86_64}
  2201. then
  2202. begin
  2203. CurrentReg := taicpu(hp1).oper[1]^.reg;
  2204. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2205. case taicpu(p).opsize of
  2206. S_W:
  2207. if taicpu(hp1).opsize = S_B then
  2208. taicpu(hp1).opsize := S_BL
  2209. else
  2210. InternalError(2020012911);
  2211. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2212. case taicpu(hp1).opsize of
  2213. S_B:
  2214. taicpu(hp1).opsize := S_BL;
  2215. S_W:
  2216. taicpu(hp1).opsize := S_WL;
  2217. else
  2218. InternalError(2020012912);
  2219. end;
  2220. else
  2221. InternalError(2020012910);
  2222. end;
  2223. taicpu(hp1).opcode := A_MOVZX;
  2224. taicpu(hp1).oper[1]^.reg := newreg(getregtype(CurrentReg), getsupreg(CurrentReg), R_SUBD)
  2225. end
  2226. else
  2227. begin
  2228. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2229. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2230. RemoveInstruction(hp1);
  2231. { The instruction after what was hp1 is now the immediate next instruction,
  2232. so we can continue to make optimisations if it's present }
  2233. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2234. Exit;
  2235. hp1 := hp2;
  2236. end;
  2237. end;
  2238. end;
  2239. end;
  2240. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2241. overwrites the original destination register. e.g.
  2242. movl ###,%reg2d
  2243. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2244. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2245. }
  2246. if (taicpu(p).oper[1]^.typ = top_reg) and
  2247. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2248. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2249. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2250. begin
  2251. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2252. begin
  2253. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2254. case taicpu(p).oper[0]^.typ of
  2255. top_const:
  2256. { We have something like:
  2257. movb $x, %regb
  2258. movzbl %regb,%regd
  2259. Change to:
  2260. movl $x, %regd
  2261. }
  2262. begin
  2263. case taicpu(hp1).opsize of
  2264. S_BW:
  2265. begin
  2266. convert_mov_value(A_MOVSX, $FF);
  2267. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2268. taicpu(p).opsize := S_W;
  2269. end;
  2270. S_BL:
  2271. begin
  2272. convert_mov_value(A_MOVSX, $FF);
  2273. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2274. taicpu(p).opsize := S_L;
  2275. end;
  2276. S_WL:
  2277. begin
  2278. convert_mov_value(A_MOVSX, $FFFF);
  2279. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2280. taicpu(p).opsize := S_L;
  2281. end;
  2282. {$ifdef x86_64}
  2283. S_BQ:
  2284. begin
  2285. convert_mov_value(A_MOVSX, $FF);
  2286. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2287. taicpu(p).opsize := S_Q;
  2288. end;
  2289. S_WQ:
  2290. begin
  2291. convert_mov_value(A_MOVSX, $FFFF);
  2292. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2293. taicpu(p).opsize := S_Q;
  2294. end;
  2295. S_LQ:
  2296. begin
  2297. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2298. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2299. taicpu(p).opsize := S_Q;
  2300. end;
  2301. {$endif x86_64}
  2302. else
  2303. { If hp1 was a MOV instruction, it should have been
  2304. optimised already }
  2305. InternalError(2020021001);
  2306. end;
  2307. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2308. RemoveInstruction(hp1);
  2309. Result := True;
  2310. Exit;
  2311. end;
  2312. top_ref:
  2313. { We have something like:
  2314. movb mem, %regb
  2315. movzbl %regb,%regd
  2316. Change to:
  2317. movzbl mem, %regd
  2318. }
  2319. if (taicpu(p).oper[0]^.ref^.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2320. begin
  2321. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2322. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  2323. RemoveCurrentP(p, hp1);
  2324. Result:=True;
  2325. Exit;
  2326. end;
  2327. else
  2328. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2329. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2330. Exit;
  2331. end;
  2332. end
  2333. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2334. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2335. optimised }
  2336. else
  2337. begin
  2338. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2339. RemoveCurrentP(p, hp1);
  2340. Result := True;
  2341. Exit;
  2342. end;
  2343. end;
  2344. if (taicpu(hp1).opcode = A_AND) and
  2345. (taicpu(p).oper[1]^.typ = top_reg) and
  2346. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2347. begin
  2348. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2349. begin
  2350. case taicpu(p).opsize of
  2351. S_L:
  2352. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2353. begin
  2354. { Optimize out:
  2355. mov x, %reg
  2356. and ffffffffh, %reg
  2357. }
  2358. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2359. RemoveInstruction(hp1);
  2360. Result:=true;
  2361. exit;
  2362. end;
  2363. S_Q: { TODO: Confirm if this is even possible }
  2364. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2365. begin
  2366. { Optimize out:
  2367. mov x, %reg
  2368. and ffffffffffffffffh, %reg
  2369. }
  2370. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2371. RemoveInstruction(hp1);
  2372. Result:=true;
  2373. exit;
  2374. end;
  2375. else
  2376. ;
  2377. end;
  2378. if ((taicpu(p).oper[0]^.typ=top_reg) or
  2379. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  2380. GetNextInstruction(hp1,hp2) and
  2381. MatchInstruction(hp2,A_TEST,[taicpu(p).opsize]) and
  2382. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) and
  2383. (MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2384. MatchOperand(taicpu(hp2).oper[0]^,-1)) and
  2385. GetNextInstruction(hp2,hp3) and
  2386. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2387. (taicpu(hp3).condition in [C_E,C_NE]) then
  2388. begin
  2389. TransferUsedRegs(TmpUsedRegs);
  2390. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2391. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2392. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2393. begin
  2394. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2395. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2396. taicpu(hp1).opcode:=A_TEST;
  2397. RemoveInstruction(hp2);
  2398. RemoveCurrentP(p, hp1);
  2399. Result:=true;
  2400. exit;
  2401. end;
  2402. end;
  2403. end
  2404. else if IsMOVZXAcceptable and
  2405. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  2406. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  2407. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  2408. then
  2409. begin
  2410. InputVal := debug_operstr(taicpu(p).oper[0]^);
  2411. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  2412. case taicpu(p).opsize of
  2413. S_B:
  2414. if (taicpu(hp1).oper[0]^.val = $ff) then
  2415. begin
  2416. { Convert:
  2417. movb x, %regl movb x, %regl
  2418. andw ffh, %regw andl ffh, %regd
  2419. To:
  2420. movzbw x, %regd movzbl x, %regd
  2421. (Identical registers, just different sizes)
  2422. }
  2423. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  2424. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  2425. case taicpu(hp1).opsize of
  2426. S_W: NewSize := S_BW;
  2427. S_L: NewSize := S_BL;
  2428. {$ifdef x86_64}
  2429. S_Q: NewSize := S_BQ;
  2430. {$endif x86_64}
  2431. else
  2432. InternalError(2018011510);
  2433. end;
  2434. end
  2435. else
  2436. NewSize := S_NO;
  2437. S_W:
  2438. if (taicpu(hp1).oper[0]^.val = $ffff) then
  2439. begin
  2440. { Convert:
  2441. movw x, %regw
  2442. andl ffffh, %regd
  2443. To:
  2444. movzwl x, %regd
  2445. (Identical registers, just different sizes)
  2446. }
  2447. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  2448. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  2449. case taicpu(hp1).opsize of
  2450. S_L: NewSize := S_WL;
  2451. {$ifdef x86_64}
  2452. S_Q: NewSize := S_WQ;
  2453. {$endif x86_64}
  2454. else
  2455. InternalError(2018011511);
  2456. end;
  2457. end
  2458. else
  2459. NewSize := S_NO;
  2460. else
  2461. NewSize := S_NO;
  2462. end;
  2463. if NewSize <> S_NO then
  2464. begin
  2465. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  2466. { The actual optimization }
  2467. taicpu(p).opcode := A_MOVZX;
  2468. taicpu(p).changeopsize(NewSize);
  2469. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  2470. { Safeguard if "and" is followed by a conditional command }
  2471. TransferUsedRegs(TmpUsedRegs);
  2472. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  2473. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  2474. begin
  2475. { At this point, the "and" command is effectively equivalent to
  2476. "test %reg,%reg". This will be handled separately by the
  2477. Peephole Optimizer. [Kit] }
  2478. DebugMsg(SPeepholeOptimization + PreMessage +
  2479. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2480. end
  2481. else
  2482. begin
  2483. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  2484. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2485. RemoveInstruction(hp1);
  2486. end;
  2487. Result := True;
  2488. Exit;
  2489. end;
  2490. end;
  2491. end;
  2492. if (taicpu(hp1).opcode = A_OR) and
  2493. (taicpu(p).oper[1]^.typ = top_reg) and
  2494. MatchOperand(taicpu(p).oper[0]^, 0) and
  2495. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  2496. begin
  2497. { mov 0, %reg
  2498. or ###,%reg
  2499. Change to (only if the flags are not used):
  2500. mov ###,%reg
  2501. }
  2502. TransferUsedRegs(TmpUsedRegs);
  2503. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2504. DoOptimisation := True;
  2505. { Even if the flags are used, we might be able to do the optimisation
  2506. if the conditions are predictable }
  2507. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2508. begin
  2509. { Only perform if ### = %reg (the same register) or equal to 0,
  2510. so %reg is guaranteed to still have a value of zero }
  2511. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  2512. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  2513. begin
  2514. hp2 := hp1;
  2515. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2516. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  2517. GetNextInstruction(hp2, hp3) do
  2518. begin
  2519. { Don't continue modifying if the flags state is getting changed }
  2520. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  2521. Break;
  2522. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  2523. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  2524. begin
  2525. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  2526. begin
  2527. { Condition is always true }
  2528. case taicpu(hp3).opcode of
  2529. A_Jcc:
  2530. begin
  2531. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  2532. { Check for jump shortcuts before we destroy the condition }
  2533. DoJumpOptimizations(hp3, TempBool);
  2534. MakeUnconditional(taicpu(hp3));
  2535. Result := True;
  2536. end;
  2537. A_CMOVcc:
  2538. begin
  2539. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  2540. taicpu(hp3).opcode := A_MOV;
  2541. taicpu(hp3).condition := C_None;
  2542. Result := True;
  2543. end;
  2544. A_SETcc:
  2545. begin
  2546. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  2547. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  2548. taicpu(hp3).opcode := A_MOV;
  2549. taicpu(hp3).ops := 2;
  2550. taicpu(hp3).condition := C_None;
  2551. taicpu(hp3).opsize := S_B;
  2552. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2553. taicpu(hp3).loadconst(0, 1);
  2554. Result := True;
  2555. end;
  2556. else
  2557. InternalError(2021090701);
  2558. end;
  2559. end
  2560. 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
  2561. begin
  2562. { Condition is always false }
  2563. case taicpu(hp3).opcode of
  2564. A_Jcc:
  2565. begin
  2566. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  2567. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  2568. RemoveInstruction(hp3);
  2569. Result := True;
  2570. { Since hp3 was deleted, hp2 must not be updated }
  2571. Continue;
  2572. end;
  2573. A_CMOVcc:
  2574. begin
  2575. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  2576. RemoveInstruction(hp3);
  2577. Result := True;
  2578. { Since hp3 was deleted, hp2 must not be updated }
  2579. Continue;
  2580. end;
  2581. A_SETcc:
  2582. begin
  2583. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  2584. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  2585. taicpu(hp3).opcode := A_MOV;
  2586. taicpu(hp3).ops := 2;
  2587. taicpu(hp3).condition := C_None;
  2588. taicpu(hp3).opsize := S_B;
  2589. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2590. taicpu(hp3).loadconst(0, 0);
  2591. Result := True;
  2592. end;
  2593. else
  2594. InternalError(2021090702);
  2595. end;
  2596. end
  2597. else
  2598. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  2599. DoOptimisation := False;
  2600. end;
  2601. hp2 := hp3;
  2602. end;
  2603. { Flags are still in use - don't optimise }
  2604. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2605. DoOptimisation := False;
  2606. end
  2607. else
  2608. DoOptimisation := False;
  2609. end;
  2610. if DoOptimisation then
  2611. begin
  2612. {$ifdef x86_64}
  2613. { OR only supports 32-bit sign-extended constants for 64-bit
  2614. instructions, so compensate for this if the constant is
  2615. encoded as a value greater than or equal to 2^31 }
  2616. if (taicpu(hp1).opsize = S_Q) and
  2617. (taicpu(hp1).oper[0]^.typ = top_const) and
  2618. (taicpu(hp1).oper[0]^.val >= $80000000) then
  2619. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  2620. {$endif x86_64}
  2621. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  2622. taicpu(hp1).opcode := A_MOV;
  2623. RemoveCurrentP(p, hp1);
  2624. Result := True;
  2625. Exit;
  2626. end;
  2627. end;
  2628. { Next instruction is also a MOV ? }
  2629. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  2630. begin
  2631. if (taicpu(p).oper[1]^.typ = top_reg) and
  2632. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2633. begin
  2634. CurrentReg := taicpu(p).oper[1]^.reg;
  2635. TransferUsedRegs(TmpUsedRegs);
  2636. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2637. { we have
  2638. mov x, %treg
  2639. mov %treg, y
  2640. }
  2641. if not(RegInOp(CurrentReg, taicpu(hp1).oper[1]^)) then
  2642. if not(RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs)) then
  2643. { we've got
  2644. mov x, %treg
  2645. mov %treg, y
  2646. with %treg is not used after }
  2647. case taicpu(p).oper[0]^.typ Of
  2648. { top_reg is covered by DeepMOVOpt }
  2649. top_const:
  2650. begin
  2651. { change
  2652. mov const, %treg
  2653. mov %treg, y
  2654. to
  2655. mov const, y
  2656. }
  2657. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  2658. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  2659. begin
  2660. if taicpu(hp1).oper[1]^.typ=top_reg then
  2661. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2662. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  2663. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  2664. RemoveInstruction(hp1);
  2665. Result:=true;
  2666. Exit;
  2667. end;
  2668. end;
  2669. top_ref:
  2670. case taicpu(hp1).oper[1]^.typ of
  2671. top_reg:
  2672. begin
  2673. { change
  2674. mov mem, %treg
  2675. mov %treg, %reg
  2676. to
  2677. mov mem, %reg"
  2678. }
  2679. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2680. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  2681. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  2682. RemoveInstruction(hp1);
  2683. Result:=true;
  2684. Exit;
  2685. end;
  2686. top_ref:
  2687. begin
  2688. {$ifdef x86_64}
  2689. { Look for the following to simplify:
  2690. mov x(mem1), %reg
  2691. mov %reg, y(mem2)
  2692. mov x+8(mem1), %reg
  2693. mov %reg, y+8(mem2)
  2694. Change to:
  2695. movdqu x(mem1), %xmmreg
  2696. movdqu %xmmreg, y(mem2)
  2697. }
  2698. SourceRef := taicpu(p).oper[0]^.ref^;
  2699. TargetRef := taicpu(hp1).oper[1]^.ref^;
  2700. if (taicpu(p).opsize = S_Q) and
  2701. GetNextInstruction(hp1, hp2) and
  2702. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  2703. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  2704. begin
  2705. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  2706. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2707. Inc(SourceRef.offset, 8);
  2708. if UseAVX then
  2709. begin
  2710. MovAligned := A_VMOVDQA;
  2711. MovUnaligned := A_VMOVDQU;
  2712. end
  2713. else
  2714. begin
  2715. MovAligned := A_MOVDQA;
  2716. MovUnaligned := A_MOVDQU;
  2717. end;
  2718. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  2719. begin
  2720. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  2721. Inc(TargetRef.offset, 8);
  2722. if GetNextInstruction(hp2, hp3) and
  2723. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  2724. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  2725. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  2726. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  2727. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  2728. begin
  2729. CurrentReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  2730. if CurrentReg <> NR_NO then
  2731. begin
  2732. { Remember that the offsets are 8 ahead }
  2733. if ((SourceRef.offset mod 16) = 8) and
  2734. (
  2735. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2736. (SourceRef.base = current_procinfo.framepointer) or
  2737. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  2738. ) then
  2739. taicpu(p).opcode := MovAligned
  2740. else
  2741. taicpu(p).opcode := MovUnaligned;
  2742. taicpu(p).opsize := S_XMM;
  2743. taicpu(p).oper[1]^.reg := CurrentReg;
  2744. if ((TargetRef.offset mod 16) = 8) and
  2745. (
  2746. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2747. (TargetRef.base = current_procinfo.framepointer) or
  2748. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  2749. ) then
  2750. taicpu(hp1).opcode := MovAligned
  2751. else
  2752. taicpu(hp1).opcode := MovUnaligned;
  2753. taicpu(hp1).opsize := S_XMM;
  2754. taicpu(hp1).oper[0]^.reg := CurrentReg;
  2755. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  2756. RemoveInstruction(hp2);
  2757. RemoveInstruction(hp3);
  2758. Result := True;
  2759. Exit;
  2760. end;
  2761. end;
  2762. end
  2763. else
  2764. begin
  2765. { See if the next references are 8 less rather than 8 greater }
  2766. Dec(SourceRef.offset, 16); { -8 the other way }
  2767. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  2768. begin
  2769. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  2770. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  2771. if GetNextInstruction(hp2, hp3) and
  2772. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  2773. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  2774. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  2775. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  2776. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  2777. begin
  2778. CurrentReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  2779. if CurrentReg <> NR_NO then
  2780. begin
  2781. { hp2 and hp3 are the starting offsets, so mod 0 this time }
  2782. if ((SourceRef.offset mod 16) = 0) and
  2783. (
  2784. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2785. (SourceRef.base = current_procinfo.framepointer) or
  2786. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  2787. ) then
  2788. taicpu(hp2).opcode := MovAligned
  2789. else
  2790. taicpu(hp2).opcode := MovUnaligned;
  2791. taicpu(hp2).opsize := S_XMM;
  2792. taicpu(hp2).oper[1]^.reg := CurrentReg;
  2793. if ((TargetRef.offset mod 16) = 0) and
  2794. (
  2795. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2796. (TargetRef.base = current_procinfo.framepointer) or
  2797. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  2798. ) then
  2799. taicpu(hp3).opcode := MovAligned
  2800. else
  2801. taicpu(hp3).opcode := MovUnaligned;
  2802. taicpu(hp3).opsize := S_XMM;
  2803. taicpu(hp3).oper[0]^.reg := CurrentReg;
  2804. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  2805. RemoveInstruction(hp1);
  2806. RemoveCurrentP(p, hp2);
  2807. Result := True;
  2808. Exit;
  2809. end;
  2810. end;
  2811. end;
  2812. end;
  2813. end;
  2814. {$endif x86_64}
  2815. end;
  2816. else
  2817. { The write target should be a reg or a ref }
  2818. InternalError(2021091601);
  2819. end;
  2820. else
  2821. ;
  2822. end
  2823. else
  2824. { %treg is used afterwards, but all eventualities
  2825. other than the first MOV instruction being a constant
  2826. are covered by DeepMOVOpt, so only check for that }
  2827. if (taicpu(p).oper[0]^.typ = top_const) and
  2828. (
  2829. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  2830. not (cs_opt_size in current_settings.optimizerswitches) or
  2831. (taicpu(hp1).opsize = S_B)
  2832. ) and
  2833. (
  2834. (taicpu(hp1).oper[1]^.typ = top_reg) or
  2835. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  2836. ) then
  2837. begin
  2838. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  2839. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  2840. end;
  2841. end;
  2842. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  2843. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  2844. { mov reg1, mem1 or mov mem1, reg1
  2845. mov mem2, reg2 mov reg2, mem2}
  2846. begin
  2847. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  2848. { mov reg1, mem1 or mov mem1, reg1
  2849. mov mem2, reg1 mov reg2, mem1}
  2850. begin
  2851. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  2852. { Removes the second statement from
  2853. mov reg1, mem1/reg2
  2854. mov mem1/reg2, reg1 }
  2855. begin
  2856. if taicpu(p).oper[0]^.typ=top_reg then
  2857. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  2858. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  2859. RemoveInstruction(hp1);
  2860. Result:=true;
  2861. exit;
  2862. end
  2863. else
  2864. begin
  2865. TransferUsedRegs(TmpUsedRegs);
  2866. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2867. if (taicpu(p).oper[1]^.typ = top_ref) and
  2868. { mov reg1, mem1
  2869. mov mem2, reg1 }
  2870. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  2871. GetNextInstruction(hp1, hp2) and
  2872. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  2873. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  2874. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  2875. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  2876. { change to
  2877. mov reg1, mem1 mov reg1, mem1
  2878. mov mem2, reg1 cmp reg1, mem2
  2879. cmp mem1, reg1
  2880. }
  2881. begin
  2882. RemoveInstruction(hp2);
  2883. taicpu(hp1).opcode := A_CMP;
  2884. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  2885. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  2886. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  2887. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  2888. end;
  2889. end;
  2890. end
  2891. else if (taicpu(p).oper[1]^.typ=top_ref) and
  2892. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  2893. begin
  2894. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  2895. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  2896. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  2897. end
  2898. else
  2899. begin
  2900. TransferUsedRegs(TmpUsedRegs);
  2901. if GetNextInstruction(hp1, hp2) and
  2902. MatchOpType(taicpu(p),top_ref,top_reg) and
  2903. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  2904. (taicpu(hp1).oper[1]^.typ = top_ref) and
  2905. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  2906. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  2907. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  2908. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  2909. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  2910. { mov mem1, %reg1
  2911. mov %reg1, mem2
  2912. mov mem2, reg2
  2913. to:
  2914. mov mem1, reg2
  2915. mov reg2, mem2}
  2916. begin
  2917. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  2918. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  2919. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  2920. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  2921. RemoveInstruction(hp2);
  2922. Result := True;
  2923. end
  2924. {$ifdef i386}
  2925. { this is enabled for i386 only, as the rules to create the reg sets below
  2926. are too complicated for x86-64, so this makes this code too error prone
  2927. on x86-64
  2928. }
  2929. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  2930. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  2931. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  2932. { mov mem1, reg1 mov mem1, reg1
  2933. mov reg1, mem2 mov reg1, mem2
  2934. mov mem2, reg2 mov mem2, reg1
  2935. to: to:
  2936. mov mem1, reg1 mov mem1, reg1
  2937. mov mem1, reg2 mov reg1, mem2
  2938. mov reg1, mem2
  2939. or (if mem1 depends on reg1
  2940. and/or if mem2 depends on reg2)
  2941. to:
  2942. mov mem1, reg1
  2943. mov reg1, mem2
  2944. mov reg1, reg2
  2945. }
  2946. begin
  2947. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  2948. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  2949. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  2950. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  2951. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  2952. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  2953. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  2954. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  2955. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  2956. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  2957. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  2958. end
  2959. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  2960. begin
  2961. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  2962. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  2963. end
  2964. else
  2965. begin
  2966. RemoveInstruction(hp2);
  2967. end
  2968. {$endif i386}
  2969. ;
  2970. end;
  2971. end
  2972. { movl [mem1],reg1
  2973. movl [mem1],reg2
  2974. to
  2975. movl [mem1],reg1
  2976. movl reg1,reg2
  2977. }
  2978. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  2979. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2980. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2981. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2982. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2983. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2984. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2985. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2986. begin
  2987. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2988. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2989. end;
  2990. { movl const1,[mem1]
  2991. movl [mem1],reg1
  2992. to
  2993. movl const1,reg1
  2994. movl reg1,[mem1]
  2995. }
  2996. if MatchOpType(Taicpu(p),top_const,top_ref) and
  2997. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  2998. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2999. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3000. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3001. begin
  3002. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3003. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3004. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3005. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3006. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3007. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3008. Result:=true;
  3009. exit;
  3010. end;
  3011. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3012. end;
  3013. { search further than the next instruction for a mov (as long as it's not a jump) }
  3014. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3015. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3016. (taicpu(p).oper[1]^.typ = top_reg) and
  3017. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3018. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3019. begin
  3020. { we work with hp2 here, so hp1 can be still used later on when
  3021. checking for GetNextInstruction_p }
  3022. hp3 := hp1;
  3023. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3024. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3025. { Saves on a large number of dereferences }
  3026. ActiveReg := taicpu(p).oper[1]^.reg;
  3027. while GetNextInstructionUsingRegCond(hp3,hp2,ActiveReg,CrossJump) and
  3028. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3029. (hp2.typ=ait_instruction) do
  3030. begin
  3031. case taicpu(hp2).opcode of
  3032. A_MOV:
  3033. if MatchOperand(taicpu(hp2).oper[0]^,ActiveReg) and
  3034. ((taicpu(p).oper[0]^.typ=top_const) or
  3035. ((taicpu(p).oper[0]^.typ=top_reg) and
  3036. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3037. )
  3038. ) then
  3039. begin
  3040. { we have
  3041. mov x, %treg
  3042. mov %treg, y
  3043. }
  3044. TransferUsedRegs(TmpUsedRegs);
  3045. TmpUsedRegs[R_INTREGISTER].Update(tai(p.Next));
  3046. { We don't need to call UpdateUsedRegs for every instruction between
  3047. p and hp2 because the register we're concerned about will not
  3048. become deallocated (otherwise GetNextInstructionUsingReg would
  3049. have stopped at an earlier instruction). [Kit] }
  3050. TempRegUsed :=
  3051. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3052. RegUsedAfterInstruction(ActiveReg, hp2, TmpUsedRegs) or
  3053. RegReadByInstruction(ActiveReg, hp1);
  3054. case taicpu(p).oper[0]^.typ Of
  3055. top_reg:
  3056. begin
  3057. { change
  3058. mov %reg, %treg
  3059. mov %treg, y
  3060. to
  3061. mov %reg, y
  3062. }
  3063. CurrentReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3064. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3065. if taicpu(hp2).oper[1]^.reg = CurrentReg then
  3066. begin
  3067. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3068. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3069. if TempRegUsed then
  3070. begin
  3071. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3072. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  3073. { Set the start of the next GetNextInstructionUsingRegCond search
  3074. to start at the entry right before hp2 (which is about to be removed) }
  3075. hp3 := tai(hp2.Previous);
  3076. RemoveInstruction(hp2);
  3077. { See if there's more we can optimise }
  3078. Continue;
  3079. end
  3080. else
  3081. begin
  3082. RemoveInstruction(hp2);
  3083. { We can remove the original MOV too }
  3084. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3085. RemoveCurrentP(p, hp1);
  3086. Result:=true;
  3087. Exit;
  3088. end;
  3089. end
  3090. else
  3091. begin
  3092. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  3093. taicpu(hp2).loadReg(0, CurrentReg);
  3094. if TempRegUsed then
  3095. begin
  3096. { Don't remove the first instruction if the temporary register is in use }
  3097. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(CurrentReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3098. { No need to set Result to True. If there's another instruction later on
  3099. that can be optimised, it will be detected when the main Pass 1 loop
  3100. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3101. end
  3102. else
  3103. begin
  3104. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3105. RemoveCurrentP(p, hp1);
  3106. Result:=true;
  3107. Exit;
  3108. end;
  3109. end;
  3110. end;
  3111. top_const:
  3112. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3113. begin
  3114. { change
  3115. mov const, %treg
  3116. mov %treg, y
  3117. to
  3118. mov const, y
  3119. }
  3120. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3121. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3122. begin
  3123. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3124. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3125. if TempRegUsed then
  3126. begin
  3127. { Don't remove the first instruction if the temporary register is in use }
  3128. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3129. { No need to set Result to True. If there's another instruction later on
  3130. that can be optimised, it will be detected when the main Pass 1 loop
  3131. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3132. end
  3133. else
  3134. begin
  3135. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3136. RemoveCurrentP(p, hp1);
  3137. Result:=true;
  3138. Exit;
  3139. end;
  3140. end;
  3141. end;
  3142. else
  3143. Internalerror(2019103001);
  3144. end;
  3145. end
  3146. else
  3147. if MatchOperand(taicpu(hp2).oper[1]^, ActiveReg) then
  3148. begin
  3149. if not CrossJump and
  3150. not RegUsedBetween(ActiveReg, p, hp2) and
  3151. not RegReadByInstruction(ActiveReg, hp2) then
  3152. begin
  3153. { Register is not used before it is overwritten }
  3154. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3155. RemoveCurrentp(p, hp1);
  3156. Result := True;
  3157. Exit;
  3158. end;
  3159. if (taicpu(p).oper[0]^.typ = top_const) and
  3160. (taicpu(hp2).oper[0]^.typ = top_const) then
  3161. begin
  3162. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3163. begin
  3164. { Same value - register hasn't changed }
  3165. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3166. RemoveInstruction(hp2);
  3167. Result := True;
  3168. { See if there's more we can optimise }
  3169. Continue;
  3170. end;
  3171. end;
  3172. end;
  3173. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  3174. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  3175. MatchOperand(taicpu(hp2).oper[0]^, ActiveReg) and
  3176. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, ActiveReg) then
  3177. begin
  3178. {
  3179. Change from:
  3180. mov ###, %reg
  3181. ...
  3182. movs/z %reg,%reg (Same register, just different sizes)
  3183. To:
  3184. movs/z ###, %reg (Longer version)
  3185. ...
  3186. (remove)
  3187. }
  3188. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  3189. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  3190. { Keep the first instruction as mov if ### is a constant }
  3191. if taicpu(p).oper[0]^.typ = top_const then
  3192. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  3193. else
  3194. begin
  3195. taicpu(p).opcode := taicpu(hp2).opcode;
  3196. taicpu(p).opsize := taicpu(hp2).opsize;
  3197. end;
  3198. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  3199. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  3200. RemoveInstruction(hp2);
  3201. Result := True;
  3202. Exit;
  3203. end;
  3204. else
  3205. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3206. begin
  3207. TransferUsedRegs(TmpUsedRegs);
  3208. TmpUsedRegs[R_INTREGISTER].Update(tai(p.Next));
  3209. if
  3210. not RegModifiedByInstruction(taicpu(p).oper[0]^.reg, hp1) and
  3211. not RegModifiedBetween(taicpu(p).oper[0]^.reg, hp1, hp2) and
  3212. DeepMovOpt(taicpu(p), taicpu(hp2)) then
  3213. begin
  3214. { Just in case something didn't get modified (e.g. an
  3215. implicit register) }
  3216. if not RegReadByInstruction(ActiveReg, hp2) and
  3217. { If a conditional jump was crossed, do not delete
  3218. the original MOV no matter what }
  3219. not CrossJump then
  3220. begin
  3221. TransferUsedRegs(TmpUsedRegs);
  3222. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3223. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3224. if
  3225. { Make sure the original register isn't still present
  3226. and has been written to (e.g. with SHRX) }
  3227. RegLoadedWithNewValue(ActiveReg, hp2) or
  3228. not RegUsedAfterInstruction(ActiveReg, hp2, TmpUsedRegs) then
  3229. begin
  3230. RegUsedAfterInstruction(ActiveReg, hp2, TmpUsedRegs);
  3231. { We can remove the original MOV }
  3232. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  3233. RemoveCurrentp(p, hp1);
  3234. Result := True;
  3235. Exit;
  3236. end
  3237. else
  3238. begin
  3239. { See if there's more we can optimise }
  3240. hp3 := hp2;
  3241. Continue;
  3242. end;
  3243. end;
  3244. end;
  3245. end;
  3246. end;
  3247. { Break out of the while loop under normal circumstances }
  3248. Break;
  3249. end;
  3250. end;
  3251. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  3252. (taicpu(p).oper[1]^.typ = top_reg) and
  3253. (taicpu(p).opsize = S_L) and
  3254. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  3255. (taicpu(hp2).opcode = A_AND) and
  3256. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  3257. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3258. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  3259. ) then
  3260. begin
  3261. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  3262. begin
  3263. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  3264. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  3265. begin
  3266. { Optimize out:
  3267. mov x, %reg
  3268. and ffffffffh, %reg
  3269. }
  3270. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  3271. RemoveInstruction(hp2);
  3272. Result:=true;
  3273. exit;
  3274. end;
  3275. end;
  3276. end;
  3277. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  3278. x >= RetOffset) as it doesn't do anything (it writes either to a
  3279. parameter or to the temporary storage room for the function
  3280. result)
  3281. }
  3282. if IsExitCode(hp1) and
  3283. (taicpu(p).oper[1]^.typ = top_ref) and
  3284. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  3285. (
  3286. (
  3287. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  3288. not (
  3289. assigned(current_procinfo.procdef.funcretsym) and
  3290. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  3291. )
  3292. ) or
  3293. { Also discard writes to the stack that are below the base pointer,
  3294. as this is temporary storage rather than a function result on the
  3295. stack, say. }
  3296. (
  3297. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  3298. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  3299. )
  3300. ) then
  3301. begin
  3302. RemoveCurrentp(p, hp1);
  3303. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  3304. RemoveLastDeallocForFuncRes(p);
  3305. Result:=true;
  3306. exit;
  3307. end;
  3308. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  3309. begin
  3310. if MatchOpType(taicpu(p),top_reg,top_ref) and
  3311. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3312. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3313. begin
  3314. { change
  3315. mov reg1, mem1
  3316. test/cmp x, mem1
  3317. to
  3318. mov reg1, mem1
  3319. test/cmp x, reg1
  3320. }
  3321. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  3322. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  3323. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3324. Result := True;
  3325. Exit;
  3326. end;
  3327. if MatchOpType(taicpu(p),top_ref,top_reg) and
  3328. { The x86 assemblers have difficulty comparing values against absolute addresses }
  3329. (taicpu(p).oper[0]^.ref^.refaddr in [addr_no, addr_pic, addr_pic_no_got]) and
  3330. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  3331. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  3332. (
  3333. (
  3334. (taicpu(hp1).opcode = A_TEST)
  3335. ) or (
  3336. (taicpu(hp1).opcode = A_CMP) and
  3337. { A sanity check more than anything }
  3338. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  3339. )
  3340. ) then
  3341. begin
  3342. { change
  3343. mov mem, %reg
  3344. cmp/test x, %reg / test %reg,%reg
  3345. (reg deallocated)
  3346. to
  3347. cmp/test x, mem / cmp 0, mem
  3348. }
  3349. TransferUsedRegs(TmpUsedRegs);
  3350. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3351. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  3352. begin
  3353. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  3354. if (taicpu(hp1).opcode = A_TEST) and
  3355. (
  3356. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  3357. MatchOperand(taicpu(hp1).oper[0]^, -1)
  3358. ) then
  3359. begin
  3360. taicpu(hp1).opcode := A_CMP;
  3361. taicpu(hp1).loadconst(0, 0);
  3362. end;
  3363. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  3364. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  3365. RemoveCurrentP(p, hp1);
  3366. Result := True;
  3367. Exit;
  3368. end;
  3369. end;
  3370. end;
  3371. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  3372. { If the flags register is in use, don't change the instruction to an
  3373. ADD otherwise this will scramble the flags. [Kit] }
  3374. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  3375. begin
  3376. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  3377. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3378. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3379. ) or
  3380. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3381. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3382. )
  3383. ) then
  3384. { mov reg1,ref
  3385. lea reg2,[reg1,reg2]
  3386. to
  3387. add reg2,ref}
  3388. begin
  3389. TransferUsedRegs(TmpUsedRegs);
  3390. { reg1 may not be used afterwards }
  3391. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3392. begin
  3393. Taicpu(hp1).opcode:=A_ADD;
  3394. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3395. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3396. RemoveCurrentp(p, hp1);
  3397. result:=true;
  3398. exit;
  3399. end;
  3400. end;
  3401. { If the LEA instruction can be converted into an arithmetic instruction,
  3402. it may be possible to then fold it in the next optimisation, otherwise
  3403. there's nothing more that can be optimised here. }
  3404. if not ConvertLEA(taicpu(hp1)) then
  3405. Exit;
  3406. end;
  3407. if (taicpu(p).oper[1]^.typ = top_reg) and
  3408. (hp1.typ = ait_instruction) and
  3409. GetNextInstruction(hp1, hp2) and
  3410. MatchInstruction(hp2,A_MOV,[]) and
  3411. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  3412. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  3413. (
  3414. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  3415. {$ifdef x86_64}
  3416. or
  3417. (
  3418. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  3419. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  3420. )
  3421. {$endif x86_64}
  3422. ) then
  3423. begin
  3424. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  3425. (taicpu(hp2).oper[0]^.typ=top_reg) then
  3426. { change movsX/movzX reg/ref, reg2
  3427. add/sub/or/... reg3/$const, reg2
  3428. mov reg2 reg/ref
  3429. dealloc reg2
  3430. to
  3431. add/sub/or/... reg3/$const, reg/ref }
  3432. begin
  3433. TransferUsedRegs(TmpUsedRegs);
  3434. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3435. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3436. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3437. begin
  3438. { by example:
  3439. movswl %si,%eax movswl %si,%eax p
  3440. decl %eax addl %edx,%eax hp1
  3441. movw %ax,%si movw %ax,%si hp2
  3442. ->
  3443. movswl %si,%eax movswl %si,%eax p
  3444. decw %eax addw %edx,%eax hp1
  3445. movw %ax,%si movw %ax,%si hp2
  3446. }
  3447. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  3448. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3449. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3450. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3451. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3452. {
  3453. ->
  3454. movswl %si,%eax movswl %si,%eax p
  3455. decw %si addw %dx,%si hp1
  3456. movw %ax,%si movw %ax,%si hp2
  3457. }
  3458. case taicpu(hp1).ops of
  3459. 1:
  3460. begin
  3461. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3462. if taicpu(hp1).oper[0]^.typ=top_reg then
  3463. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3464. end;
  3465. 2:
  3466. begin
  3467. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3468. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3469. (taicpu(hp1).opcode<>A_SHL) and
  3470. (taicpu(hp1).opcode<>A_SHR) and
  3471. (taicpu(hp1).opcode<>A_SAR) then
  3472. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3473. end;
  3474. else
  3475. internalerror(2008042701);
  3476. end;
  3477. {
  3478. ->
  3479. decw %si addw %dx,%si p
  3480. }
  3481. RemoveInstruction(hp2);
  3482. RemoveCurrentP(p, hp1);
  3483. Result:=True;
  3484. Exit;
  3485. end;
  3486. end;
  3487. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3488. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  3489. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  3490. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  3491. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  3492. )
  3493. {$ifdef i386}
  3494. { byte registers of esi, edi, ebp, esp are not available on i386 }
  3495. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3496. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3497. {$endif i386}
  3498. then
  3499. { change movsX/movzX reg/ref, reg2
  3500. add/sub/or/... regX/$const, reg2
  3501. mov reg2, reg3
  3502. dealloc reg2
  3503. to
  3504. movsX/movzX reg/ref, reg3
  3505. add/sub/or/... reg3/$const, reg3
  3506. }
  3507. begin
  3508. TransferUsedRegs(TmpUsedRegs);
  3509. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3510. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3511. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3512. begin
  3513. { by example:
  3514. movswl %si,%eax movswl %si,%eax p
  3515. decl %eax addl %edx,%eax hp1
  3516. movw %ax,%si movw %ax,%si hp2
  3517. ->
  3518. movswl %si,%eax movswl %si,%eax p
  3519. decw %eax addw %edx,%eax hp1
  3520. movw %ax,%si movw %ax,%si hp2
  3521. }
  3522. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  3523. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3524. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3525. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3526. { limit size of constants as well to avoid assembler errors, but
  3527. check opsize to avoid overflow when left shifting the 1 }
  3528. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  3529. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  3530. {$ifdef x86_64}
  3531. { Be careful of, for example:
  3532. movl %reg1,%reg2
  3533. addl %reg3,%reg2
  3534. movq %reg2,%reg4
  3535. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  3536. }
  3537. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  3538. begin
  3539. taicpu(hp2).changeopsize(S_L);
  3540. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  3541. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  3542. end;
  3543. {$endif x86_64}
  3544. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3545. taicpu(p).changeopsize(taicpu(hp2).opsize);
  3546. if taicpu(p).oper[0]^.typ=top_reg then
  3547. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3548. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  3549. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  3550. {
  3551. ->
  3552. movswl %si,%eax movswl %si,%eax p
  3553. decw %si addw %dx,%si hp1
  3554. movw %ax,%si movw %ax,%si hp2
  3555. }
  3556. case taicpu(hp1).ops of
  3557. 1:
  3558. begin
  3559. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3560. if taicpu(hp1).oper[0]^.typ=top_reg then
  3561. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3562. end;
  3563. 2:
  3564. begin
  3565. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3566. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3567. (taicpu(hp1).opcode<>A_SHL) and
  3568. (taicpu(hp1).opcode<>A_SHR) and
  3569. (taicpu(hp1).opcode<>A_SAR) then
  3570. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3571. end;
  3572. else
  3573. internalerror(2018111801);
  3574. end;
  3575. {
  3576. ->
  3577. decw %si addw %dx,%si p
  3578. }
  3579. RemoveInstruction(hp2);
  3580. end;
  3581. end;
  3582. end;
  3583. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  3584. GetNextInstruction(hp1, hp2) and
  3585. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  3586. MatchOperand(Taicpu(p).oper[0]^,0) and
  3587. (Taicpu(p).oper[1]^.typ = top_reg) and
  3588. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  3589. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  3590. { mov reg1,0
  3591. bts reg1,operand1 --> mov reg1,operand2
  3592. or reg1,operand2 bts reg1,operand1}
  3593. begin
  3594. Taicpu(hp2).opcode:=A_MOV;
  3595. asml.remove(hp1);
  3596. insertllitem(hp2,hp2.next,hp1);
  3597. RemoveCurrentp(p, hp1);
  3598. Result:=true;
  3599. exit;
  3600. end;
  3601. {$ifdef x86_64}
  3602. { Convert:
  3603. movq x(ref),%reg64
  3604. shrq y,%reg64
  3605. To:
  3606. movq x+4(ref),%reg32
  3607. shrq y-32,%reg32 (Remove if y = 32)
  3608. }
  3609. if (taicpu(p).opsize = S_Q) and
  3610. (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  3611. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFB) and
  3612. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  3613. MatchOpType(taicpu(hp1), top_const, top_reg) and
  3614. (taicpu(hp1).oper[0]^.val >= 32) and
  3615. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  3616. begin
  3617. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  3618. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  3619. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  3620. { Convert to 32-bit }
  3621. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3622. taicpu(p).opsize := S_L;
  3623. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  3624. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  3625. if (taicpu(hp1).oper[0]^.val = 32) then
  3626. begin
  3627. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  3628. RemoveInstruction(hp1);
  3629. end
  3630. else
  3631. begin
  3632. { This will potentially open up more arithmetic operations since
  3633. the peephole optimizer now has a big hint that only the lower
  3634. 32 bits are currently in use (and opcodes are smaller in size) }
  3635. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3636. taicpu(hp1).opsize := S_L;
  3637. Dec(taicpu(hp1).oper[0]^.val, 32);
  3638. DebugMsg(SPeepholeOptimization + PreMessage +
  3639. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  3640. end;
  3641. Result := True;
  3642. Exit;
  3643. end;
  3644. {$endif x86_64}
  3645. end;
  3646. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  3647. var
  3648. hp1 : tai;
  3649. begin
  3650. Result:=false;
  3651. if taicpu(p).ops <> 2 then
  3652. exit;
  3653. if GetNextInstruction(p,hp1) and
  3654. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  3655. (taicpu(hp1).ops = 2) then
  3656. begin
  3657. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3658. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3659. { movXX reg1, mem1 or movXX mem1, reg1
  3660. movXX mem2, reg2 movXX reg2, mem2}
  3661. begin
  3662. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3663. { movXX reg1, mem1 or movXX mem1, reg1
  3664. movXX mem2, reg1 movXX reg2, mem1}
  3665. begin
  3666. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3667. begin
  3668. { Removes the second statement from
  3669. movXX reg1, mem1/reg2
  3670. movXX mem1/reg2, reg1
  3671. }
  3672. if taicpu(p).oper[0]^.typ=top_reg then
  3673. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3674. { Removes the second statement from
  3675. movXX mem1/reg1, reg2
  3676. movXX reg2, mem1/reg1
  3677. }
  3678. if (taicpu(p).oper[1]^.typ=top_reg) and
  3679. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  3680. begin
  3681. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  3682. RemoveInstruction(hp1);
  3683. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  3684. end
  3685. else
  3686. begin
  3687. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  3688. RemoveInstruction(hp1);
  3689. end;
  3690. Result:=true;
  3691. exit;
  3692. end
  3693. end;
  3694. end;
  3695. end;
  3696. end;
  3697. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  3698. var
  3699. hp1 : tai;
  3700. begin
  3701. result:=false;
  3702. { replace
  3703. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  3704. MovX %mreg2,%mreg1
  3705. dealloc %mreg2
  3706. by
  3707. <Op>X %mreg2,%mreg1
  3708. ?
  3709. }
  3710. if GetNextInstruction(p,hp1) and
  3711. { we mix single and double opperations here because we assume that the compiler
  3712. generates vmovapd only after double operations and vmovaps only after single operations }
  3713. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  3714. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3715. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  3716. (taicpu(p).oper[0]^.typ=top_reg) then
  3717. begin
  3718. TransferUsedRegs(TmpUsedRegs);
  3719. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3720. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3721. begin
  3722. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  3723. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  3724. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  3725. RemoveInstruction(hp1);
  3726. result:=true;
  3727. end;
  3728. end;
  3729. end;
  3730. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  3731. var
  3732. hp1, p_label, p_dist, hp1_dist: tai;
  3733. JumpLabel, JumpLabel_dist: TAsmLabel;
  3734. begin
  3735. Result := False;
  3736. if (taicpu(p).oper[1]^.typ = top_reg) then
  3737. begin
  3738. if GetNextInstruction(p, hp1) and
  3739. MatchInstruction(hp1,A_MOV,[]) and
  3740. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  3741. (
  3742. (taicpu(p).oper[0]^.typ <> top_reg) or
  3743. not RegInInstruction(taicpu(p).oper[0]^.reg, hp1)
  3744. ) then
  3745. begin
  3746. { If we have something like:
  3747. test %reg1,%reg1
  3748. mov 0,%reg2
  3749. And no registers are shared (the two %reg1's can be different, as
  3750. long as neither of them are also %reg2), move the MOV command to
  3751. before the comparison as this means it can be optimised without
  3752. worrying about the FLAGS register. (This combination is generated
  3753. by "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  3754. }
  3755. SwapMovCmp(p, hp1);
  3756. Result := True;
  3757. Exit;
  3758. end;
  3759. { Search for:
  3760. test %reg,%reg
  3761. j(c1) @lbl1
  3762. ...
  3763. @lbl:
  3764. test %reg,%reg (same register)
  3765. j(c2) @lbl2
  3766. If c2 is a subset of c1, change to:
  3767. test %reg,%reg
  3768. j(c1) @lbl2
  3769. (@lbl1 may become a dead label as a result)
  3770. }
  3771. if (taicpu(p).oper[0]^.typ = top_reg) and
  3772. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  3773. MatchInstruction(hp1, A_JCC, []) and
  3774. IsJumpToLabel(taicpu(hp1)) then
  3775. begin
  3776. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  3777. p_label := nil;
  3778. if Assigned(JumpLabel) then
  3779. p_label := getlabelwithsym(JumpLabel);
  3780. if Assigned(p_label) and
  3781. GetNextInstruction(p_label, p_dist) and
  3782. MatchInstruction(p_dist, A_TEST, []) and
  3783. { It's fine if the second test uses smaller sub-registers }
  3784. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  3785. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  3786. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  3787. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  3788. GetNextInstruction(p_dist, hp1_dist) and
  3789. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  3790. begin
  3791. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  3792. if JumpLabel = JumpLabel_dist then
  3793. { This is an infinite loop }
  3794. Exit;
  3795. { Best optimisation when the first condition is a subset (or equal) of the second }
  3796. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  3797. begin
  3798. { Any registers used here will already be allocated }
  3799. if Assigned(JumpLabel_dist) then
  3800. JumpLabel_dist.IncRefs;
  3801. if Assigned(JumpLabel) then
  3802. JumpLabel.DecRefs;
  3803. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  3804. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  3805. Result := True;
  3806. Exit;
  3807. end;
  3808. end;
  3809. end;
  3810. end;
  3811. end;
  3812. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  3813. var
  3814. hp1 : tai;
  3815. begin
  3816. result:=false;
  3817. { replace
  3818. addX const,%reg1
  3819. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  3820. dealloc %reg1
  3821. by
  3822. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  3823. }
  3824. if MatchOpType(taicpu(p),top_const,top_reg) and
  3825. GetNextInstruction(p,hp1) and
  3826. MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  3827. ((taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.base) or
  3828. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index)) then
  3829. begin
  3830. TransferUsedRegs(TmpUsedRegs);
  3831. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3832. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3833. begin
  3834. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  3835. if taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.base then
  3836. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  3837. if taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index then
  3838. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  3839. RemoveCurrentP(p);
  3840. result:=true;
  3841. end;
  3842. end;
  3843. end;
  3844. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  3845. var
  3846. hp1: tai;
  3847. ref: Integer;
  3848. saveref: treference;
  3849. TempReg: TRegister;
  3850. Multiple: TCGInt;
  3851. begin
  3852. Result:=false;
  3853. { removes seg register prefixes from LEA operations, as they
  3854. don't do anything}
  3855. taicpu(p).oper[0]^.ref^.Segment:=NR_NO;
  3856. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  3857. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3858. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  3859. (
  3860. { do not mess with leas accessing the stack pointer
  3861. unless it's a null operation }
  3862. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  3863. (
  3864. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  3865. (taicpu(p).oper[0]^.ref^.offset = 0)
  3866. )
  3867. ) and
  3868. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  3869. begin
  3870. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  3871. begin
  3872. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  3873. begin
  3874. hp1:=taicpu.op_reg_reg(A_MOV,taicpu(p).opsize,taicpu(p).oper[0]^.ref^.base,
  3875. taicpu(p).oper[1]^.reg);
  3876. InsertLLItem(p.previous,p.next, hp1);
  3877. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',hp1);
  3878. p.free;
  3879. p:=hp1;
  3880. end
  3881. else
  3882. begin
  3883. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  3884. RemoveCurrentP(p);
  3885. end;
  3886. Result:=true;
  3887. exit;
  3888. end
  3889. else if (
  3890. { continue to use lea to adjust the stack pointer,
  3891. it is the recommended way, but only if not optimizing for size }
  3892. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  3893. (cs_opt_size in current_settings.optimizerswitches)
  3894. ) and
  3895. { If the flags register is in use, don't change the instruction
  3896. to an ADD otherwise this will scramble the flags. [Kit] }
  3897. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  3898. ConvertLEA(taicpu(p)) then
  3899. begin
  3900. Result:=true;
  3901. exit;
  3902. end;
  3903. end;
  3904. if GetNextInstruction(p,hp1) and
  3905. (hp1.typ=ait_instruction) then
  3906. begin
  3907. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  3908. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3909. MatchOpType(Taicpu(hp1),top_reg,top_reg) and
  3910. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) then
  3911. begin
  3912. TransferUsedRegs(TmpUsedRegs);
  3913. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3914. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3915. begin
  3916. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  3917. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  3918. RemoveInstruction(hp1);
  3919. result:=true;
  3920. exit;
  3921. end;
  3922. end;
  3923. { changes
  3924. lea <ref1>, reg1
  3925. <op> ...,<ref. with reg1>,...
  3926. to
  3927. <op> ...,<ref1>,... }
  3928. if (taicpu(p).oper[1]^.reg<>current_procinfo.framepointer) and
  3929. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) and
  3930. not(MatchInstruction(hp1,A_LEA,[])) then
  3931. begin
  3932. { find a reference which uses reg1 }
  3933. 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
  3934. ref:=0
  3935. 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
  3936. ref:=1
  3937. else
  3938. ref:=-1;
  3939. if (ref<>-1) and
  3940. { reg1 must be either the base or the index }
  3941. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  3942. begin
  3943. { reg1 can be removed from the reference }
  3944. saveref:=taicpu(hp1).oper[ref]^.ref^;
  3945. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  3946. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  3947. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  3948. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  3949. else
  3950. Internalerror(2019111201);
  3951. { check if the can insert all data of the lea into the second instruction }
  3952. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  3953. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  3954. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  3955. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  3956. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  3957. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  3958. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  3959. {$ifdef x86_64}
  3960. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  3961. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  3962. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  3963. )
  3964. {$endif x86_64}
  3965. then
  3966. begin
  3967. { reg1 might not used by the second instruction after it is remove from the reference }
  3968. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  3969. begin
  3970. TransferUsedRegs(TmpUsedRegs);
  3971. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3972. { reg1 is not updated so it might not be used afterwards }
  3973. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3974. begin
  3975. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  3976. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  3977. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  3978. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  3979. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  3980. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  3981. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  3982. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  3983. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  3984. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  3985. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  3986. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  3987. RemoveCurrentP(p, hp1);
  3988. result:=true;
  3989. exit;
  3990. end
  3991. end;
  3992. end;
  3993. { recover }
  3994. taicpu(hp1).oper[ref]^.ref^:=saveref;
  3995. end;
  3996. end;
  3997. end;
  3998. { for now, we do not mess with the stack pointer, thought it might be usefull to remove
  3999. unneeded lea sequences on the stack pointer, it needs to be tested in detail }
  4000. if (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) and
  4001. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  4002. begin
  4003. { Check common LEA/LEA conditions }
  4004. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  4005. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  4006. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  4007. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  4008. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  4009. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  4010. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  4011. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  4012. (
  4013. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  4014. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  4015. ) and (
  4016. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  4017. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4018. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  4019. ) then
  4020. begin
  4021. { changes
  4022. lea (regX,scale), reg1
  4023. lea offset(reg1,reg1), reg1
  4024. to
  4025. lea offset(regX,scale*2), reg1
  4026. and
  4027. lea (regX,scale1), reg1
  4028. lea offset(reg1,scale2), reg1
  4029. to
  4030. lea offset(regX,scale1*scale2), reg1
  4031. ... so long as the final scale does not exceed 8
  4032. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  4033. }
  4034. if (taicpu(p).oper[0]^.ref^.offset = 0) and
  4035. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4036. (
  4037. (
  4038. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4039. ) or (
  4040. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4041. (
  4042. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  4043. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  4044. )
  4045. )
  4046. ) and (
  4047. (
  4048. { lea (reg1,scale2), reg1 variant }
  4049. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  4050. (
  4051. (
  4052. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  4053. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  4054. ) or (
  4055. { lea (regX,regX), reg1 variant }
  4056. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4057. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  4058. )
  4059. )
  4060. ) or (
  4061. { lea (reg1,reg1), reg1 variant }
  4062. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4063. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  4064. )
  4065. ) then
  4066. begin
  4067. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  4068. { Make everything homogeneous to make calculations easier }
  4069. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  4070. begin
  4071. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  4072. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  4073. taicpu(p).oper[0]^.ref^.scalefactor := 2
  4074. else
  4075. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  4076. taicpu(p).oper[0]^.ref^.base := NR_NO;
  4077. end;
  4078. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  4079. begin
  4080. { Just to prevent miscalculations }
  4081. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  4082. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  4083. else
  4084. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  4085. end
  4086. else
  4087. begin
  4088. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  4089. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  4090. end;
  4091. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  4092. RemoveCurrentP(p);
  4093. result:=true;
  4094. exit;
  4095. end
  4096. { changes
  4097. lea offset1(regX), reg1
  4098. lea offset2(reg1), reg1
  4099. to
  4100. lea offset1+offset2(regX), reg1 }
  4101. else if
  4102. (
  4103. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4104. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  4105. ) or (
  4106. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4107. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  4108. (
  4109. (
  4110. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4111. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4112. ) or (
  4113. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4114. (
  4115. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4116. (
  4117. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4118. (
  4119. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  4120. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  4121. )
  4122. )
  4123. )
  4124. )
  4125. )
  4126. ) then
  4127. begin
  4128. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  4129. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  4130. begin
  4131. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  4132. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4133. { if the register is used as index and base, we have to increase for base as well
  4134. and adapt base }
  4135. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  4136. begin
  4137. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4138. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4139. end;
  4140. end
  4141. else
  4142. begin
  4143. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4144. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4145. end;
  4146. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4147. begin
  4148. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  4149. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4150. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4151. end;
  4152. RemoveCurrentP(p);
  4153. result:=true;
  4154. exit;
  4155. end;
  4156. end;
  4157. { Change:
  4158. leal/q $x(%reg1),%reg2
  4159. ...
  4160. shll/q $y,%reg2
  4161. To:
  4162. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  4163. }
  4164. if MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  4165. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4166. (taicpu(hp1).oper[0]^.val <= 3) then
  4167. begin
  4168. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  4169. TransferUsedRegs(TmpUsedRegs);
  4170. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4171. TempReg := taicpu(hp1).oper[1]^.reg; { Store locally to reduce the number of dereferences }
  4172. if
  4173. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  4174. (this works even if scalefactor is zero) }
  4175. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  4176. { Ensure offset doesn't go out of bounds }
  4177. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  4178. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  4179. MatchOperand(taicpu(p).oper[1]^, TempReg) and
  4180. (
  4181. (
  4182. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, TempReg) and
  4183. (
  4184. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4185. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  4186. (
  4187. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  4188. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4189. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  4190. )
  4191. )
  4192. ) or (
  4193. (
  4194. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  4195. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  4196. ) and
  4197. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, TempReg)
  4198. )
  4199. ) then
  4200. begin
  4201. repeat
  4202. with taicpu(p).oper[0]^.ref^ do
  4203. begin
  4204. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  4205. if index = base then
  4206. begin
  4207. if Multiple > 4 then
  4208. { Optimisation will no longer work because resultant
  4209. scale factor will exceed 8 }
  4210. Break;
  4211. base := NR_NO;
  4212. scalefactor := 2;
  4213. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  4214. end
  4215. else if (base <> NR_NO) and (base <> NR_INVALID) then
  4216. begin
  4217. { Scale factor only works on the index register }
  4218. index := base;
  4219. base := NR_NO;
  4220. end;
  4221. { For safety }
  4222. if scalefactor <= 1 then
  4223. begin
  4224. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  4225. scalefactor := Multiple;
  4226. end
  4227. else
  4228. begin
  4229. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  4230. scalefactor := scalefactor * Multiple;
  4231. end;
  4232. offset := offset * Multiple;
  4233. end;
  4234. RemoveInstruction(hp1);
  4235. Result := True;
  4236. Exit;
  4237. { This repeat..until loop exists for the benefit of Break }
  4238. until True;
  4239. end;
  4240. end;
  4241. end;
  4242. end;
  4243. function TX86AsmOptimizer.DoSubAddOpt(var p: tai): Boolean;
  4244. var
  4245. hp1 : tai;
  4246. begin
  4247. DoSubAddOpt := False;
  4248. if GetLastInstruction(p, hp1) and
  4249. (hp1.typ = ait_instruction) and
  4250. (taicpu(hp1).opsize = taicpu(p).opsize) then
  4251. case taicpu(hp1).opcode Of
  4252. A_DEC:
  4253. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  4254. MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4255. begin
  4256. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+1);
  4257. RemoveInstruction(hp1);
  4258. end;
  4259. A_SUB:
  4260. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  4261. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  4262. begin
  4263. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val);
  4264. RemoveInstruction(hp1);
  4265. end;
  4266. A_ADD:
  4267. begin
  4268. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  4269. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  4270. begin
  4271. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  4272. RemoveInstruction(hp1);
  4273. if (taicpu(p).oper[0]^.val = 0) then
  4274. begin
  4275. hp1 := tai(p.next);
  4276. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  4277. if not GetLastInstruction(hp1, p) then
  4278. p := hp1;
  4279. DoSubAddOpt := True;
  4280. end
  4281. end;
  4282. end;
  4283. else
  4284. ;
  4285. end;
  4286. end;
  4287. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  4288. {$ifdef i386}
  4289. var
  4290. hp1 : tai;
  4291. {$endif i386}
  4292. begin
  4293. Result:=false;
  4294. { * change "subl $2, %esp; pushw x" to "pushl x"}
  4295. { * change "sub/add const1, reg" or "dec reg" followed by
  4296. "sub const2, reg" to one "sub ..., reg" }
  4297. if MatchOpType(taicpu(p),top_const,top_reg) then
  4298. begin
  4299. {$ifdef i386}
  4300. if (taicpu(p).oper[0]^.val = 2) and
  4301. (taicpu(p).oper[1]^.reg = NR_ESP) and
  4302. { Don't do the sub/push optimization if the sub }
  4303. { comes from setting up the stack frame (JM) }
  4304. (not(GetLastInstruction(p,hp1)) or
  4305. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  4306. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  4307. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  4308. begin
  4309. hp1 := tai(p.next);
  4310. while Assigned(hp1) and
  4311. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  4312. not RegReadByInstruction(NR_ESP,hp1) and
  4313. not RegModifiedByInstruction(NR_ESP,hp1) do
  4314. hp1 := tai(hp1.next);
  4315. if Assigned(hp1) and
  4316. MatchInstruction(hp1,A_PUSH,[S_W]) then
  4317. begin
  4318. taicpu(hp1).changeopsize(S_L);
  4319. if taicpu(hp1).oper[0]^.typ=top_reg then
  4320. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  4321. hp1 := tai(p.next);
  4322. RemoveCurrentp(p, hp1);
  4323. Result:=true;
  4324. exit;
  4325. end;
  4326. end;
  4327. {$endif i386}
  4328. if DoSubAddOpt(p) then
  4329. Result:=true;
  4330. end;
  4331. end;
  4332. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  4333. var
  4334. TmpBool1,TmpBool2 : Boolean;
  4335. tmpref : treference;
  4336. hp1,hp2: tai;
  4337. mask: tcgint;
  4338. begin
  4339. Result:=false;
  4340. { All these optimisations work on "shl/sal const,%reg" }
  4341. if not MatchOpType(taicpu(p),top_const,top_reg) then
  4342. Exit;
  4343. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4344. (taicpu(p).oper[0]^.val <= 3) then
  4345. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  4346. begin
  4347. { should we check the next instruction? }
  4348. TmpBool1 := True;
  4349. { have we found an add/sub which could be
  4350. integrated in the lea? }
  4351. TmpBool2 := False;
  4352. reference_reset(tmpref,2,[]);
  4353. TmpRef.index := taicpu(p).oper[1]^.reg;
  4354. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  4355. while TmpBool1 and
  4356. GetNextInstruction(p, hp1) and
  4357. (tai(hp1).typ = ait_instruction) and
  4358. ((((taicpu(hp1).opcode = A_ADD) or
  4359. (taicpu(hp1).opcode = A_SUB)) and
  4360. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  4361. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  4362. (((taicpu(hp1).opcode = A_INC) or
  4363. (taicpu(hp1).opcode = A_DEC)) and
  4364. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  4365. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  4366. ((taicpu(hp1).opcode = A_LEA) and
  4367. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4368. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  4369. (not GetNextInstruction(hp1,hp2) or
  4370. not instrReadsFlags(hp2)) Do
  4371. begin
  4372. TmpBool1 := False;
  4373. if taicpu(hp1).opcode=A_LEA then
  4374. begin
  4375. if (TmpRef.base = NR_NO) and
  4376. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  4377. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  4378. (taicpu(hp1).oper[0]^.ref^.segment=NR_NO) and
  4379. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  4380. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  4381. begin
  4382. TmpBool1 := True;
  4383. TmpBool2 := True;
  4384. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  4385. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  4386. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  4387. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  4388. RemoveInstruction(hp1);
  4389. end
  4390. end
  4391. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  4392. begin
  4393. TmpBool1 := True;
  4394. TmpBool2 := True;
  4395. case taicpu(hp1).opcode of
  4396. A_ADD:
  4397. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  4398. A_SUB:
  4399. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  4400. else
  4401. internalerror(2019050536);
  4402. end;
  4403. RemoveInstruction(hp1);
  4404. end
  4405. else
  4406. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  4407. (((taicpu(hp1).opcode = A_ADD) and
  4408. (TmpRef.base = NR_NO)) or
  4409. (taicpu(hp1).opcode = A_INC) or
  4410. (taicpu(hp1).opcode = A_DEC)) then
  4411. begin
  4412. TmpBool1 := True;
  4413. TmpBool2 := True;
  4414. case taicpu(hp1).opcode of
  4415. A_ADD:
  4416. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  4417. A_INC:
  4418. inc(TmpRef.offset);
  4419. A_DEC:
  4420. dec(TmpRef.offset);
  4421. else
  4422. internalerror(2019050535);
  4423. end;
  4424. RemoveInstruction(hp1);
  4425. end;
  4426. end;
  4427. if TmpBool2
  4428. {$ifndef x86_64}
  4429. or
  4430. ((current_settings.optimizecputype < cpu_Pentium2) and
  4431. (taicpu(p).oper[0]^.val <= 3) and
  4432. not(cs_opt_size in current_settings.optimizerswitches))
  4433. {$endif x86_64}
  4434. then
  4435. begin
  4436. if not(TmpBool2) and
  4437. (taicpu(p).oper[0]^.val=1) then
  4438. begin
  4439. hp1:=taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  4440. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  4441. end
  4442. else
  4443. hp1:=taicpu.op_ref_reg(A_LEA, taicpu(p).opsize, TmpRef,
  4444. taicpu(p).oper[1]^.reg);
  4445. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  4446. InsertLLItem(p.previous, p.next, hp1);
  4447. p.free;
  4448. p := hp1;
  4449. end;
  4450. end
  4451. {$ifndef x86_64}
  4452. else if (current_settings.optimizecputype < cpu_Pentium2) then
  4453. begin
  4454. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  4455. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  4456. (unlike shl, which is only Tairable in the U pipe) }
  4457. if taicpu(p).oper[0]^.val=1 then
  4458. begin
  4459. hp1 := taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  4460. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg);
  4461. InsertLLItem(p.previous, p.next, hp1);
  4462. p.free;
  4463. p := hp1;
  4464. end
  4465. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  4466. "shl $3, %reg" to "lea (,%reg,8), %reg }
  4467. else if (taicpu(p).opsize = S_L) and
  4468. (taicpu(p).oper[0]^.val<= 3) then
  4469. begin
  4470. reference_reset(tmpref,2,[]);
  4471. TmpRef.index := taicpu(p).oper[1]^.reg;
  4472. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  4473. hp1 := taicpu.Op_ref_reg(A_LEA,S_L,TmpRef, taicpu(p).oper[1]^.reg);
  4474. InsertLLItem(p.previous, p.next, hp1);
  4475. p.free;
  4476. p := hp1;
  4477. end;
  4478. end
  4479. {$endif x86_64}
  4480. else if
  4481. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  4482. (
  4483. (
  4484. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  4485. SetAndTest(hp1, hp2)
  4486. {$ifdef x86_64}
  4487. ) or
  4488. (
  4489. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  4490. GetNextInstruction(hp1, hp2) and
  4491. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  4492. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4493. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  4494. {$endif x86_64}
  4495. )
  4496. ) and
  4497. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  4498. begin
  4499. { Change:
  4500. shl x, %reg1
  4501. mov -(1<<x), %reg2
  4502. and %reg2, %reg1
  4503. Or:
  4504. shl x, %reg1
  4505. and -(1<<x), %reg1
  4506. To just:
  4507. shl x, %reg1
  4508. Since the and operation only zeroes bits that are already zero from the shl operation
  4509. }
  4510. case taicpu(p).oper[0]^.val of
  4511. 8:
  4512. mask:=$FFFFFFFFFFFFFF00;
  4513. 16:
  4514. mask:=$FFFFFFFFFFFF0000;
  4515. 32:
  4516. mask:=$FFFFFFFF00000000;
  4517. 63:
  4518. { Constant pre-calculated to prevent overflow errors with Int64 }
  4519. mask:=$8000000000000000;
  4520. else
  4521. begin
  4522. if taicpu(p).oper[0]^.val >= 64 then
  4523. { Shouldn't happen realistically, since the register
  4524. is guaranteed to be set to zero at this point }
  4525. mask := 0
  4526. else
  4527. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  4528. end;
  4529. end;
  4530. if taicpu(hp1).oper[0]^.val = mask then
  4531. begin
  4532. { Everything checks out, perform the optimisation, as long as
  4533. the FLAGS register isn't being used}
  4534. TransferUsedRegs(TmpUsedRegs);
  4535. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4536. {$ifdef x86_64}
  4537. if (hp1 <> hp2) then
  4538. begin
  4539. { "shl/mov/and" version }
  4540. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4541. { Don't do the optimisation if the FLAGS register is in use }
  4542. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  4543. begin
  4544. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  4545. { Don't remove the 'mov' instruction if its register is used elsewhere }
  4546. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  4547. begin
  4548. RemoveInstruction(hp1);
  4549. Result := True;
  4550. end;
  4551. { Only set Result to True if the 'mov' instruction was removed }
  4552. RemoveInstruction(hp2);
  4553. end;
  4554. end
  4555. else
  4556. {$endif x86_64}
  4557. begin
  4558. { "shl/and" version }
  4559. { Don't do the optimisation if the FLAGS register is in use }
  4560. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  4561. begin
  4562. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  4563. RemoveInstruction(hp1);
  4564. Result := True;
  4565. end;
  4566. end;
  4567. Exit;
  4568. end
  4569. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  4570. begin
  4571. { Even if the mask doesn't allow for its removal, we might be
  4572. able to optimise the mask for the "shl/and" version, which
  4573. may permit other peephole optimisations }
  4574. {$ifdef DEBUG_AOPTCPU}
  4575. mask := taicpu(hp1).oper[0]^.val and mask;
  4576. if taicpu(hp1).oper[0]^.val <> mask then
  4577. begin
  4578. DebugMsg(
  4579. SPeepholeOptimization +
  4580. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  4581. ' to $' + debug_tostr(mask) +
  4582. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  4583. taicpu(hp1).oper[0]^.val := mask;
  4584. end;
  4585. {$else DEBUG_AOPTCPU}
  4586. { If debugging is off, just set the operand even if it's the same }
  4587. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  4588. {$endif DEBUG_AOPTCPU}
  4589. end;
  4590. end;
  4591. {
  4592. change
  4593. shl/sal const,reg
  4594. <op> ...(...,reg,1),...
  4595. into
  4596. <op> ...(...,reg,1 shl const),...
  4597. if const in 1..3
  4598. }
  4599. if MatchOpType(taicpu(p), top_const, top_reg) and
  4600. (taicpu(p).oper[0]^.val in [1..3]) and
  4601. GetNextInstruction(p, hp1) and
  4602. MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  4603. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  4604. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  4605. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  4606. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  4607. begin
  4608. TransferUsedRegs(TmpUsedRegs);
  4609. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4610. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4611. begin
  4612. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  4613. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  4614. RemoveCurrentP(p);
  4615. Result:=true;
  4616. end;
  4617. end;
  4618. end;
  4619. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  4620. var
  4621. CurrentRef: TReference;
  4622. FullReg: TRegister;
  4623. hp1, hp2: tai;
  4624. begin
  4625. Result := False;
  4626. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  4627. Exit;
  4628. { We assume you've checked if the operand is actually a reference by
  4629. this point. If it isn't, you'll most likely get an access violation }
  4630. CurrentRef := first_mov.oper[1]^.ref^;
  4631. { Memory must be aligned }
  4632. if (CurrentRef.offset mod 4) <> 0 then
  4633. Exit;
  4634. Inc(CurrentRef.offset);
  4635. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  4636. if MatchOperand(second_mov.oper[0]^, 0) and
  4637. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  4638. GetNextInstruction(second_mov, hp1) and
  4639. (hp1.typ = ait_instruction) and
  4640. (taicpu(hp1).opcode = A_MOV) and
  4641. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4642. (taicpu(hp1).oper[0]^.val = 0) then
  4643. begin
  4644. Inc(CurrentRef.offset);
  4645. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  4646. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  4647. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  4648. begin
  4649. case taicpu(hp1).opsize of
  4650. S_B:
  4651. if GetNextInstruction(hp1, hp2) and
  4652. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  4653. MatchOpType(taicpu(hp2), top_const, top_ref) and
  4654. (taicpu(hp2).oper[0]^.val = 0) then
  4655. begin
  4656. Inc(CurrentRef.offset);
  4657. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  4658. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  4659. (taicpu(hp2).opsize = S_B) then
  4660. begin
  4661. RemoveInstruction(hp1);
  4662. RemoveInstruction(hp2);
  4663. first_mov.opsize := S_L;
  4664. if first_mov.oper[0]^.typ = top_reg then
  4665. begin
  4666. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  4667. { Reuse second_mov as a MOVZX instruction }
  4668. second_mov.opcode := A_MOVZX;
  4669. second_mov.opsize := S_BL;
  4670. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  4671. second_mov.loadreg(1, FullReg);
  4672. first_mov.oper[0]^.reg := FullReg;
  4673. asml.Remove(second_mov);
  4674. asml.InsertBefore(second_mov, first_mov);
  4675. end
  4676. else
  4677. { It's a value }
  4678. begin
  4679. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  4680. RemoveInstruction(second_mov);
  4681. end;
  4682. Result := True;
  4683. Exit;
  4684. end;
  4685. end;
  4686. S_W:
  4687. begin
  4688. RemoveInstruction(hp1);
  4689. first_mov.opsize := S_L;
  4690. if first_mov.oper[0]^.typ = top_reg then
  4691. begin
  4692. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  4693. { Reuse second_mov as a MOVZX instruction }
  4694. second_mov.opcode := A_MOVZX;
  4695. second_mov.opsize := S_BL;
  4696. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  4697. second_mov.loadreg(1, FullReg);
  4698. first_mov.oper[0]^.reg := FullReg;
  4699. asml.Remove(second_mov);
  4700. asml.InsertBefore(second_mov, first_mov);
  4701. end
  4702. else
  4703. { It's a value }
  4704. begin
  4705. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  4706. RemoveInstruction(second_mov);
  4707. end;
  4708. Result := True;
  4709. Exit;
  4710. end;
  4711. else
  4712. ;
  4713. end;
  4714. end;
  4715. end;
  4716. end;
  4717. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  4718. { returns true if a "continue" should be done after this optimization }
  4719. var
  4720. hp1, hp2: tai;
  4721. begin
  4722. Result := false;
  4723. if MatchOpType(taicpu(p),top_ref) and
  4724. GetNextInstruction(p, hp1) and
  4725. (hp1.typ = ait_instruction) and
  4726. (((taicpu(hp1).opcode = A_FLD) and
  4727. (taicpu(p).opcode = A_FSTP)) or
  4728. ((taicpu(p).opcode = A_FISTP) and
  4729. (taicpu(hp1).opcode = A_FILD))) and
  4730. MatchOpType(taicpu(hp1),top_ref) and
  4731. (taicpu(hp1).opsize = taicpu(p).opsize) and
  4732. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  4733. begin
  4734. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  4735. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  4736. GetNextInstruction(hp1, hp2) and
  4737. (hp2.typ = ait_instruction) and
  4738. IsExitCode(hp2) and
  4739. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  4740. not(assigned(current_procinfo.procdef.funcretsym) and
  4741. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  4742. (taicpu(p).oper[0]^.ref^.index = NR_NO) then
  4743. begin
  4744. RemoveInstruction(hp1);
  4745. RemoveCurrentP(p, hp2);
  4746. RemoveLastDeallocForFuncRes(p);
  4747. Result := true;
  4748. end
  4749. else
  4750. { we can do this only in fast math mode as fstp is rounding ...
  4751. ... still disabled as it breaks the compiler and/or rtl }
  4752. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  4753. { ... or if another fstp equal to the first one follows }
  4754. (GetNextInstruction(hp1,hp2) and
  4755. (hp2.typ = ait_instruction) and
  4756. (taicpu(p).opcode=taicpu(hp2).opcode) and
  4757. (taicpu(p).opsize=taicpu(hp2).opsize))
  4758. ) and
  4759. { fst can't store an extended/comp value }
  4760. (taicpu(p).opsize <> S_FX) and
  4761. (taicpu(p).opsize <> S_IQ) then
  4762. begin
  4763. if (taicpu(p).opcode = A_FSTP) then
  4764. taicpu(p).opcode := A_FST
  4765. else
  4766. taicpu(p).opcode := A_FIST;
  4767. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  4768. RemoveInstruction(hp1);
  4769. end;
  4770. end;
  4771. end;
  4772. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  4773. var
  4774. hp1, hp2: tai;
  4775. begin
  4776. result:=false;
  4777. if MatchOpType(taicpu(p),top_reg) and
  4778. GetNextInstruction(p, hp1) and
  4779. (hp1.typ = Ait_Instruction) and
  4780. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4781. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  4782. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  4783. { change to
  4784. fld reg fxxx reg,st
  4785. fxxxp st, st1 (hp1)
  4786. Remark: non commutative operations must be reversed!
  4787. }
  4788. begin
  4789. case taicpu(hp1).opcode Of
  4790. A_FMULP,A_FADDP,
  4791. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  4792. begin
  4793. case taicpu(hp1).opcode Of
  4794. A_FADDP: taicpu(hp1).opcode := A_FADD;
  4795. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  4796. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  4797. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  4798. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  4799. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  4800. else
  4801. internalerror(2019050534);
  4802. end;
  4803. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  4804. taicpu(hp1).oper[1]^.reg := NR_ST;
  4805. RemoveCurrentP(p, hp1);
  4806. Result:=true;
  4807. exit;
  4808. end;
  4809. else
  4810. ;
  4811. end;
  4812. end
  4813. else
  4814. if MatchOpType(taicpu(p),top_ref) and
  4815. GetNextInstruction(p, hp2) and
  4816. (hp2.typ = Ait_Instruction) and
  4817. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4818. (taicpu(p).opsize in [S_FS, S_FL]) and
  4819. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  4820. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  4821. if GetLastInstruction(p, hp1) and
  4822. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  4823. MatchOpType(taicpu(hp1),top_ref) and
  4824. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  4825. if ((taicpu(hp2).opcode = A_FMULP) or
  4826. (taicpu(hp2).opcode = A_FADDP)) then
  4827. { change to
  4828. fld/fst mem1 (hp1) fld/fst mem1
  4829. fld mem1 (p) fadd/
  4830. faddp/ fmul st, st
  4831. fmulp st, st1 (hp2) }
  4832. begin
  4833. RemoveCurrentP(p, hp1);
  4834. if (taicpu(hp2).opcode = A_FADDP) then
  4835. taicpu(hp2).opcode := A_FADD
  4836. else
  4837. taicpu(hp2).opcode := A_FMUL;
  4838. taicpu(hp2).oper[1]^.reg := NR_ST;
  4839. end
  4840. else
  4841. { change to
  4842. fld/fst mem1 (hp1) fld/fst mem1
  4843. fld mem1 (p) fld st}
  4844. begin
  4845. taicpu(p).changeopsize(S_FL);
  4846. taicpu(p).loadreg(0,NR_ST);
  4847. end
  4848. else
  4849. begin
  4850. case taicpu(hp2).opcode Of
  4851. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  4852. { change to
  4853. fld/fst mem1 (hp1) fld/fst mem1
  4854. fld mem2 (p) fxxx mem2
  4855. fxxxp st, st1 (hp2) }
  4856. begin
  4857. case taicpu(hp2).opcode Of
  4858. A_FADDP: taicpu(p).opcode := A_FADD;
  4859. A_FMULP: taicpu(p).opcode := A_FMUL;
  4860. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  4861. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  4862. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  4863. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  4864. else
  4865. internalerror(2019050533);
  4866. end;
  4867. RemoveInstruction(hp2);
  4868. end
  4869. else
  4870. ;
  4871. end
  4872. end
  4873. end;
  4874. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  4875. begin
  4876. Result := condition_in(cond1, cond2) or
  4877. { Not strictly subsets due to the actual flags checked, but because we're
  4878. comparing integers, E is a subset of AE and GE and their aliases }
  4879. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  4880. end;
  4881. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  4882. var
  4883. v: TCGInt;
  4884. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  4885. FirstMatch: Boolean;
  4886. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  4887. begin
  4888. Result:=false;
  4889. { All these optimisations need a next instruction }
  4890. if not GetNextInstruction(p, hp1) then
  4891. Exit;
  4892. { Search for:
  4893. cmp ###,###
  4894. j(c1) @lbl1
  4895. ...
  4896. @lbl:
  4897. cmp ###.### (same comparison as above)
  4898. j(c2) @lbl2
  4899. If c1 is a subset of c2, change to:
  4900. cmp ###,###
  4901. j(c2) @lbl2
  4902. (@lbl1 may become a dead label as a result)
  4903. }
  4904. { Also handle cases where there are multiple jumps in a row }
  4905. p_jump := hp1;
  4906. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  4907. begin
  4908. if IsJumpToLabel(taicpu(p_jump)) then
  4909. begin
  4910. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  4911. p_label := nil;
  4912. if Assigned(JumpLabel) then
  4913. p_label := getlabelwithsym(JumpLabel);
  4914. if Assigned(p_label) and
  4915. GetNextInstruction(p_label, p_dist) and
  4916. MatchInstruction(p_dist, A_CMP, []) and
  4917. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  4918. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4919. GetNextInstruction(p_dist, hp1_dist) and
  4920. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4921. begin
  4922. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4923. if JumpLabel = JumpLabel_dist then
  4924. { This is an infinite loop }
  4925. Exit;
  4926. { Best optimisation when the first condition is a subset (or equal) of the second }
  4927. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  4928. begin
  4929. { Any registers used here will already be allocated }
  4930. if Assigned(JumpLabel_dist) then
  4931. JumpLabel_dist.IncRefs;
  4932. if Assigned(JumpLabel) then
  4933. JumpLabel.DecRefs;
  4934. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  4935. taicpu(p_jump).condition := taicpu(hp1_dist).condition;
  4936. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  4937. Result := True;
  4938. { Don't exit yet. Since p and p_jump haven't actually been
  4939. removed, we can check for more on this iteration }
  4940. end
  4941. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  4942. GetNextInstruction(hp1_dist, hp1_label) and
  4943. SkipAligns(hp1_label, hp1_label) and
  4944. (hp1_label.typ = ait_label) then
  4945. begin
  4946. JumpLabel_far := tai_label(hp1_label).labsym;
  4947. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  4948. { This is an infinite loop }
  4949. Exit;
  4950. if Assigned(JumpLabel_far) then
  4951. begin
  4952. { In this situation, if the first jump branches, the second one will never,
  4953. branch so change the destination label to after the second jump }
  4954. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  4955. if Assigned(JumpLabel) then
  4956. JumpLabel.DecRefs;
  4957. JumpLabel_far.IncRefs;
  4958. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  4959. Result := True;
  4960. { Don't exit yet. Since p and p_jump haven't actually been
  4961. removed, we can check for more on this iteration }
  4962. Continue;
  4963. end;
  4964. end;
  4965. end;
  4966. end;
  4967. { Search for:
  4968. cmp ###,###
  4969. j(c1) @lbl1
  4970. cmp ###,### (same as first)
  4971. Remove second cmp
  4972. }
  4973. if GetNextInstruction(p_jump, hp2) and
  4974. (
  4975. (
  4976. MatchInstruction(hp2, A_CMP, []) and
  4977. (
  4978. (
  4979. MatchOpType(taicpu(p), top_const, top_reg) and
  4980. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  4981. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[1]^.reg)
  4982. ) or (
  4983. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  4984. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  4985. )
  4986. )
  4987. ) or (
  4988. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  4989. MatchOperand(taicpu(p).oper[0]^, 0) and
  4990. (taicpu(p).oper[1]^.typ = top_reg) and
  4991. MatchInstruction(hp2, A_TEST, []) and
  4992. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4993. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  4994. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[1]^.reg)
  4995. )
  4996. ) then
  4997. begin
  4998. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  4999. RemoveInstruction(hp2);
  5000. Result := True;
  5001. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  5002. end;
  5003. GetNextInstruction(p_jump, p_jump);
  5004. end;
  5005. if taicpu(p).oper[0]^.typ = top_const then
  5006. begin
  5007. if (taicpu(p).oper[0]^.val = 0) and
  5008. (taicpu(p).oper[1]^.typ = top_reg) and
  5009. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  5010. begin
  5011. hp2 := p;
  5012. FirstMatch := True;
  5013. { When dealing with "cmp $0,%reg", only ZF and SF contain
  5014. anything meaningful once it's converted to "test %reg,%reg";
  5015. additionally, some jumps will always (or never) branch, so
  5016. evaluate every jump immediately following the
  5017. comparison, optimising the conditions if possible.
  5018. Similarly with SETcc... those that are always set to 0 or 1
  5019. are changed to MOV instructions }
  5020. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  5021. (
  5022. GetNextInstruction(hp2, hp1) and
  5023. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  5024. ) do
  5025. begin
  5026. FirstMatch := False;
  5027. case taicpu(hp1).condition of
  5028. C_B, C_C, C_NAE, C_O:
  5029. { For B/NAE:
  5030. Will never branch since an unsigned integer can never be below zero
  5031. For C/O:
  5032. Result cannot overflow because 0 is being subtracted
  5033. }
  5034. begin
  5035. if taicpu(hp1).opcode = A_Jcc then
  5036. begin
  5037. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  5038. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  5039. RemoveInstruction(hp1);
  5040. { Since hp1 was deleted, hp2 must not be updated }
  5041. Continue;
  5042. end
  5043. else
  5044. begin
  5045. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  5046. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  5047. taicpu(hp1).opcode := A_MOV;
  5048. taicpu(hp1).ops := 2;
  5049. taicpu(hp1).condition := C_None;
  5050. taicpu(hp1).opsize := S_B;
  5051. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  5052. taicpu(hp1).loadconst(0, 0);
  5053. end;
  5054. end;
  5055. C_BE, C_NA:
  5056. begin
  5057. { Will only branch if equal to zero }
  5058. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  5059. taicpu(hp1).condition := C_E;
  5060. end;
  5061. C_A, C_NBE:
  5062. begin
  5063. { Will only branch if not equal to zero }
  5064. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  5065. taicpu(hp1).condition := C_NE;
  5066. end;
  5067. C_AE, C_NB, C_NC, C_NO:
  5068. begin
  5069. { Will always branch }
  5070. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  5071. if taicpu(hp1).opcode = A_Jcc then
  5072. begin
  5073. MakeUnconditional(taicpu(hp1));
  5074. { Any jumps/set that follow will now be dead code }
  5075. RemoveDeadCodeAfterJump(taicpu(hp1));
  5076. Break;
  5077. end
  5078. else
  5079. begin
  5080. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  5081. taicpu(hp1).opcode := A_MOV;
  5082. taicpu(hp1).ops := 2;
  5083. taicpu(hp1).condition := C_None;
  5084. taicpu(hp1).opsize := S_B;
  5085. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  5086. taicpu(hp1).loadconst(0, 1);
  5087. end;
  5088. end;
  5089. C_None:
  5090. InternalError(2020012201);
  5091. C_P, C_PE, C_NP, C_PO:
  5092. { We can't handle parity checks and they should never be generated
  5093. after a general-purpose CMP (it's used in some floating-point
  5094. comparisons that don't use CMP) }
  5095. InternalError(2020012202);
  5096. else
  5097. { Zero/Equality, Sign, their complements and all of the
  5098. signed comparisons do not need to be converted };
  5099. end;
  5100. hp2 := hp1;
  5101. end;
  5102. { Convert the instruction to a TEST }
  5103. taicpu(p).opcode := A_TEST;
  5104. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  5105. Result := True;
  5106. Exit;
  5107. end
  5108. else if (taicpu(p).oper[0]^.val = 1) and
  5109. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  5110. (taicpu(hp1).condition in [C_L, C_NGE]) then
  5111. begin
  5112. { Convert; To:
  5113. cmp $1,r/m cmp $0,r/m
  5114. jl @lbl jle @lbl
  5115. }
  5116. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  5117. taicpu(p).oper[0]^.val := 0;
  5118. taicpu(hp1).condition := C_LE;
  5119. { If the instruction is now "cmp $0,%reg", convert it to a
  5120. TEST (and effectively do the work of the "cmp $0,%reg" in
  5121. the block above)
  5122. If it's a reference, we can get away with not setting
  5123. Result to True because he haven't evaluated the jump
  5124. in this pass yet.
  5125. }
  5126. if (taicpu(p).oper[1]^.typ = top_reg) then
  5127. begin
  5128. taicpu(p).opcode := A_TEST;
  5129. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  5130. Result := True;
  5131. end;
  5132. Exit;
  5133. end
  5134. else if (taicpu(p).oper[1]^.typ = top_reg) then
  5135. begin
  5136. { cmp register,$8000 neg register
  5137. je target --> jo target
  5138. .... only if register is deallocated before jump.}
  5139. case Taicpu(p).opsize of
  5140. S_B: v:=$80;
  5141. S_W: v:=$8000;
  5142. S_L: v:=qword($80000000);
  5143. { S_Q will never happen: cmp with 64 bit constants is not possible }
  5144. S_Q:
  5145. Exit;
  5146. else
  5147. internalerror(2013112905);
  5148. end;
  5149. if (taicpu(p).oper[0]^.val=v) and
  5150. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  5151. (Taicpu(hp1).condition in [C_E,C_NE]) then
  5152. begin
  5153. TransferUsedRegs(TmpUsedRegs);
  5154. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  5155. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  5156. begin
  5157. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  5158. Taicpu(p).opcode:=A_NEG;
  5159. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  5160. Taicpu(p).clearop(1);
  5161. Taicpu(p).ops:=1;
  5162. if Taicpu(hp1).condition=C_E then
  5163. Taicpu(hp1).condition:=C_O
  5164. else
  5165. Taicpu(hp1).condition:=C_NO;
  5166. Result:=true;
  5167. exit;
  5168. end;
  5169. end;
  5170. end;
  5171. end;
  5172. if (taicpu(p).oper[1]^.typ = top_reg) and
  5173. MatchInstruction(hp1,A_MOV,[]) and
  5174. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  5175. (
  5176. (taicpu(p).oper[0]^.typ <> top_reg) or
  5177. not RegInInstruction(taicpu(p).oper[0]^.reg, hp1)
  5178. ) then
  5179. begin
  5180. { If we have something like:
  5181. cmp ###,%reg1
  5182. mov 0,%reg2
  5183. And no registers are shared, move the MOV command to before the
  5184. comparison as this means it can be optimised without worrying
  5185. about the FLAGS register. (This combination is generated by
  5186. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  5187. }
  5188. SwapMovCmp(p, hp1);
  5189. Result := True;
  5190. Exit;
  5191. end;
  5192. end;
  5193. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  5194. var
  5195. hp1: tai;
  5196. begin
  5197. {
  5198. remove the second (v)pxor from
  5199. pxor reg,reg
  5200. ...
  5201. pxor reg,reg
  5202. }
  5203. Result:=false;
  5204. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  5205. MatchOpType(taicpu(p),top_reg,top_reg) and
  5206. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  5207. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  5208. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  5209. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  5210. begin
  5211. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  5212. RemoveInstruction(hp1);
  5213. Result:=true;
  5214. Exit;
  5215. end
  5216. {
  5217. replace
  5218. pxor reg1,reg1
  5219. movapd/s reg1,reg2
  5220. dealloc reg1
  5221. by
  5222. pxor reg2,reg2
  5223. }
  5224. else if GetNextInstruction(p,hp1) and
  5225. { we mix single and double opperations here because we assume that the compiler
  5226. generates vmovapd only after double operations and vmovaps only after single operations }
  5227. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  5228. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  5229. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5230. (taicpu(p).oper[0]^.typ=top_reg) then
  5231. begin
  5232. TransferUsedRegs(TmpUsedRegs);
  5233. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5234. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5235. begin
  5236. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  5237. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5238. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  5239. RemoveInstruction(hp1);
  5240. result:=true;
  5241. end;
  5242. end;
  5243. end;
  5244. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  5245. var
  5246. hp1: tai;
  5247. begin
  5248. {
  5249. remove the second (v)pxor from
  5250. (v)pxor reg,reg
  5251. ...
  5252. (v)pxor reg,reg
  5253. }
  5254. Result:=false;
  5255. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  5256. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  5257. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  5258. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  5259. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  5260. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  5261. begin
  5262. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2PXor done',hp1);
  5263. RemoveInstruction(hp1);
  5264. Result:=true;
  5265. Exit;
  5266. end
  5267. else
  5268. Result:=OptPass1VOP(p);
  5269. end;
  5270. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  5271. var
  5272. hp1 : tai;
  5273. begin
  5274. result:=false;
  5275. { replace
  5276. IMul const,%mreg1,%mreg2
  5277. Mov %reg2,%mreg3
  5278. dealloc %mreg3
  5279. by
  5280. Imul const,%mreg1,%mreg23
  5281. }
  5282. if (taicpu(p).ops=3) and
  5283. GetNextInstruction(p,hp1) and
  5284. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5285. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  5286. (taicpu(hp1).oper[1]^.typ=top_reg) then
  5287. begin
  5288. TransferUsedRegs(TmpUsedRegs);
  5289. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5290. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  5291. begin
  5292. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  5293. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  5294. RemoveInstruction(hp1);
  5295. result:=true;
  5296. end;
  5297. end;
  5298. end;
  5299. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  5300. var
  5301. hp1 : tai;
  5302. begin
  5303. result:=false;
  5304. { replace
  5305. IMul %reg0,%reg1,%reg2
  5306. Mov %reg2,%reg3
  5307. dealloc %reg2
  5308. by
  5309. Imul %reg0,%reg1,%reg3
  5310. }
  5311. if GetNextInstruction(p,hp1) and
  5312. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5313. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  5314. (taicpu(hp1).oper[1]^.typ=top_reg) then
  5315. begin
  5316. TransferUsedRegs(TmpUsedRegs);
  5317. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5318. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  5319. begin
  5320. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  5321. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  5322. RemoveInstruction(hp1);
  5323. result:=true;
  5324. end;
  5325. end;
  5326. end;
  5327. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  5328. var
  5329. hp1, hp2, hp3, hp4, hp5: tai;
  5330. ThisReg: TRegister;
  5331. begin
  5332. Result := False;
  5333. if not GetNextInstruction(p,hp1) or (hp1.typ <> ait_instruction) then
  5334. Exit;
  5335. {
  5336. convert
  5337. j<c> .L1
  5338. mov 1,reg
  5339. jmp .L2
  5340. .L1
  5341. mov 0,reg
  5342. .L2
  5343. into
  5344. mov 0,reg
  5345. set<not(c)> reg
  5346. take care of alignment and that the mov 0,reg is not converted into a xor as this
  5347. would destroy the flag contents
  5348. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  5349. executed at the same time as a previous comparison.
  5350. set<not(c)> reg
  5351. movzx reg, reg
  5352. }
  5353. if MatchInstruction(hp1,A_MOV,[]) and
  5354. (taicpu(hp1).oper[0]^.typ = top_const) and
  5355. (
  5356. (
  5357. (taicpu(hp1).oper[1]^.typ = top_reg)
  5358. {$ifdef i386}
  5359. { Under i386, ESI, EDI, EBP and ESP
  5360. don't have an 8-bit representation }
  5361. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5362. {$endif i386}
  5363. ) or (
  5364. {$ifdef i386}
  5365. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  5366. {$endif i386}
  5367. (taicpu(hp1).opsize = S_B)
  5368. )
  5369. ) and
  5370. GetNextInstruction(hp1,hp2) and
  5371. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  5372. GetNextInstruction(hp2,hp3) and
  5373. SkipAligns(hp3, hp3) and
  5374. (hp3.typ=ait_label) and
  5375. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  5376. GetNextInstruction(hp3,hp4) and
  5377. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  5378. (taicpu(hp4).oper[0]^.typ = top_const) and
  5379. (
  5380. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  5381. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  5382. ) and
  5383. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  5384. GetNextInstruction(hp4,hp5) and
  5385. SkipAligns(hp5, hp5) and
  5386. (hp5.typ=ait_label) and
  5387. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  5388. begin
  5389. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  5390. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5391. tai_label(hp3).labsym.DecRefs;
  5392. { If this isn't the only reference to the middle label, we can
  5393. still make a saving - only that the first jump and everything
  5394. that follows will remain. }
  5395. if (tai_label(hp3).labsym.getrefs = 0) then
  5396. begin
  5397. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  5398. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  5399. else
  5400. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  5401. { remove jump, first label and second MOV (also catching any aligns) }
  5402. repeat
  5403. if not GetNextInstruction(hp2, hp3) then
  5404. InternalError(2021040810);
  5405. RemoveInstruction(hp2);
  5406. hp2 := hp3;
  5407. until hp2 = hp5;
  5408. { Don't decrement reference count before the removal loop
  5409. above, otherwise GetNextInstruction won't stop on the
  5410. the label }
  5411. tai_label(hp5).labsym.DecRefs;
  5412. end
  5413. else
  5414. begin
  5415. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  5416. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  5417. else
  5418. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  5419. end;
  5420. taicpu(p).opcode:=A_SETcc;
  5421. taicpu(p).opsize:=S_B;
  5422. taicpu(p).is_jmp:=False;
  5423. if taicpu(hp1).opsize=S_B then
  5424. begin
  5425. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  5426. RemoveInstruction(hp1);
  5427. end
  5428. else
  5429. begin
  5430. { Will be a register because the size can't be S_B otherwise }
  5431. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  5432. taicpu(p).loadreg(0, ThisReg);
  5433. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  5434. begin
  5435. case taicpu(hp1).opsize of
  5436. S_W:
  5437. taicpu(hp1).opsize := S_BW;
  5438. S_L:
  5439. taicpu(hp1).opsize := S_BL;
  5440. {$ifdef x86_64}
  5441. S_Q:
  5442. begin
  5443. taicpu(hp1).opsize := S_BL;
  5444. { Change the destination register to 32-bit }
  5445. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  5446. end;
  5447. {$endif x86_64}
  5448. else
  5449. InternalError(2021040820);
  5450. end;
  5451. taicpu(hp1).opcode := A_MOVZX;
  5452. taicpu(hp1).loadreg(0, ThisReg);
  5453. end
  5454. else
  5455. begin
  5456. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  5457. { hp1 is already a MOV instruction with the correct register }
  5458. taicpu(hp1).loadconst(0, 0);
  5459. { Inserting it right before p will guarantee that the flags are also tracked }
  5460. asml.Remove(hp1);
  5461. asml.InsertBefore(hp1, p);
  5462. end;
  5463. end;
  5464. Result:=true;
  5465. exit;
  5466. end
  5467. end;
  5468. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  5469. var
  5470. hp2, hp3, first_assignment: tai;
  5471. IncCount, OperIdx: Integer;
  5472. OrigLabel: TAsmLabel;
  5473. begin
  5474. Count := 0;
  5475. Result := False;
  5476. first_assignment := nil;
  5477. if (LoopCount >= 20) then
  5478. begin
  5479. { Guard against infinite loops }
  5480. Exit;
  5481. end;
  5482. if (taicpu(p).oper[0]^.typ <> top_ref) or
  5483. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  5484. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  5485. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  5486. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  5487. Exit;
  5488. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  5489. {
  5490. change
  5491. jmp .L1
  5492. ...
  5493. .L1:
  5494. mov ##, ## ( multiple movs possible )
  5495. jmp/ret
  5496. into
  5497. mov ##, ##
  5498. jmp/ret
  5499. }
  5500. if not Assigned(hp1) then
  5501. begin
  5502. hp1 := GetLabelWithSym(OrigLabel);
  5503. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  5504. Exit;
  5505. end;
  5506. hp2 := hp1;
  5507. while Assigned(hp2) do
  5508. begin
  5509. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  5510. SkipLabels(hp2,hp2);
  5511. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  5512. Break;
  5513. case taicpu(hp2).opcode of
  5514. A_MOVSS:
  5515. begin
  5516. if taicpu(hp2).ops = 0 then
  5517. { Wrong MOVSS }
  5518. Break;
  5519. Inc(Count);
  5520. if Count >= 5 then
  5521. { Too many to be worthwhile }
  5522. Break;
  5523. GetNextInstruction(hp2, hp2);
  5524. Continue;
  5525. end;
  5526. A_MOV,
  5527. A_MOVD,
  5528. A_MOVQ,
  5529. A_MOVSX,
  5530. {$ifdef x86_64}
  5531. A_MOVSXD,
  5532. {$endif x86_64}
  5533. A_MOVZX,
  5534. A_MOVAPS,
  5535. A_MOVUPS,
  5536. A_MOVSD,
  5537. A_MOVAPD,
  5538. A_MOVUPD,
  5539. A_MOVDQA,
  5540. A_MOVDQU,
  5541. A_VMOVSS,
  5542. A_VMOVAPS,
  5543. A_VMOVUPS,
  5544. A_VMOVSD,
  5545. A_VMOVAPD,
  5546. A_VMOVUPD,
  5547. A_VMOVDQA,
  5548. A_VMOVDQU:
  5549. begin
  5550. Inc(Count);
  5551. if Count >= 5 then
  5552. { Too many to be worthwhile }
  5553. Break;
  5554. GetNextInstruction(hp2, hp2);
  5555. Continue;
  5556. end;
  5557. A_JMP:
  5558. begin
  5559. { Guard against infinite loops }
  5560. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  5561. Exit;
  5562. { Analyse this jump first in case it also duplicates assignments }
  5563. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  5564. begin
  5565. { Something did change! }
  5566. Result := True;
  5567. Inc(Count, IncCount);
  5568. if Count >= 5 then
  5569. begin
  5570. { Too many to be worthwhile }
  5571. Exit;
  5572. end;
  5573. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  5574. Break;
  5575. end;
  5576. Result := True;
  5577. Break;
  5578. end;
  5579. A_RET:
  5580. begin
  5581. Result := True;
  5582. Break;
  5583. end;
  5584. else
  5585. Break;
  5586. end;
  5587. end;
  5588. if Result then
  5589. begin
  5590. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  5591. if Count = 0 then
  5592. begin
  5593. Result := False;
  5594. Exit;
  5595. end;
  5596. hp3 := p;
  5597. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  5598. while True do
  5599. begin
  5600. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  5601. SkipLabels(hp1,hp1);
  5602. if (hp1.typ <> ait_instruction) then
  5603. InternalError(2021040720);
  5604. case taicpu(hp1).opcode of
  5605. A_JMP:
  5606. begin
  5607. { Change the original jump to the new destination }
  5608. OrigLabel.decrefs;
  5609. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  5610. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  5611. { Set p to the first duplicated assignment so it can get optimised if needs be }
  5612. if not Assigned(first_assignment) then
  5613. InternalError(2021040810)
  5614. else
  5615. p := first_assignment;
  5616. Exit;
  5617. end;
  5618. A_RET:
  5619. begin
  5620. { Now change the jump into a RET instruction }
  5621. ConvertJumpToRET(p, hp1);
  5622. { Set p to the first duplicated assignment so it can get optimised if needs be }
  5623. if not Assigned(first_assignment) then
  5624. InternalError(2021040811)
  5625. else
  5626. p := first_assignment;
  5627. Exit;
  5628. end;
  5629. else
  5630. begin
  5631. { Duplicate the MOV instruction }
  5632. hp3:=tai(hp1.getcopy);
  5633. if first_assignment = nil then
  5634. first_assignment := hp3;
  5635. asml.InsertBefore(hp3, p);
  5636. { Make sure the compiler knows about any final registers written here }
  5637. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  5638. with taicpu(hp3).oper[OperIdx]^ do
  5639. begin
  5640. case typ of
  5641. top_ref:
  5642. begin
  5643. if (ref^.base <> NR_NO) and
  5644. (getsupreg(ref^.base) <> RS_ESP) and
  5645. (getsupreg(ref^.base) <> RS_EBP)
  5646. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  5647. then
  5648. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  5649. if (ref^.index <> NR_NO) and
  5650. (getsupreg(ref^.index) <> RS_ESP) and
  5651. (getsupreg(ref^.index) <> RS_EBP)
  5652. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  5653. (ref^.index <> ref^.base) then
  5654. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  5655. end;
  5656. top_reg:
  5657. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  5658. else
  5659. ;
  5660. end;
  5661. end;
  5662. end;
  5663. end;
  5664. if not GetNextInstruction(hp1, hp1) then
  5665. { Should have dropped out earlier }
  5666. InternalError(2021040710);
  5667. end;
  5668. end;
  5669. end;
  5670. procedure TX86AsmOptimizer.SwapMovCmp(var p, hp1: tai);
  5671. var
  5672. hp2: tai;
  5673. X: Integer;
  5674. begin
  5675. asml.Remove(hp1);
  5676. { Try to insert after the last instructions where the FLAGS register is not yet in use }
  5677. if not GetLastInstruction(p, hp2) then
  5678. asml.InsertBefore(hp1, p)
  5679. else
  5680. asml.InsertAfter(hp1, hp2);
  5681. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and mov instructions to improve optimisation potential', hp1);
  5682. for X := 0 to 1 do
  5683. case taicpu(hp1).oper[X]^.typ of
  5684. top_reg:
  5685. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  5686. top_ref:
  5687. begin
  5688. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  5689. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  5690. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  5691. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  5692. end;
  5693. else
  5694. ;
  5695. end;
  5696. end;
  5697. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  5698. function IsXCHGAcceptable: Boolean; inline;
  5699. begin
  5700. { Always accept if optimising for size }
  5701. Result := (cs_opt_size in current_settings.optimizerswitches) or
  5702. (
  5703. {$ifdef x86_64}
  5704. { XCHG takes 3 cycles on AMD Athlon64 }
  5705. (current_settings.optimizecputype >= cpu_core_i)
  5706. {$else x86_64}
  5707. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  5708. than 3, so it becomes a saving compared to three MOVs with two of
  5709. them able to execute simultaneously. [Kit] }
  5710. (current_settings.optimizecputype >= cpu_PentiumM)
  5711. {$endif x86_64}
  5712. );
  5713. end;
  5714. var
  5715. NewRef: TReference;
  5716. hp1, hp2, hp3, hp4: Tai;
  5717. {$ifndef x86_64}
  5718. OperIdx: Integer;
  5719. {$endif x86_64}
  5720. NewInstr : Taicpu;
  5721. NewAligh : Tai_align;
  5722. DestLabel: TAsmLabel;
  5723. begin
  5724. Result:=false;
  5725. { This optimisation adds an instruction, so only do it for speed }
  5726. if not (cs_opt_size in current_settings.optimizerswitches) and
  5727. MatchOpType(taicpu(p), top_const, top_reg) and
  5728. (taicpu(p).oper[0]^.val = 0) then
  5729. begin
  5730. { To avoid compiler warning }
  5731. DestLabel := nil;
  5732. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  5733. InternalError(2021040750);
  5734. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  5735. Exit;
  5736. case hp1.typ of
  5737. ait_label:
  5738. begin
  5739. { Change:
  5740. mov $0,%reg mov $0,%reg
  5741. @Lbl1: @Lbl1:
  5742. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  5743. je @Lbl2 jne @Lbl2
  5744. To: To:
  5745. mov $0,%reg mov $0,%reg
  5746. jmp @Lbl2 jmp @Lbl3
  5747. (align) (align)
  5748. @Lbl1: @Lbl1:
  5749. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  5750. je @Lbl2 je @Lbl2
  5751. @Lbl3: <-- Only if label exists
  5752. (Not if it's optimised for size)
  5753. }
  5754. if not GetNextInstruction(hp1, hp2) then
  5755. Exit;
  5756. if not (cs_opt_size in current_settings.optimizerswitches) and
  5757. (hp2.typ = ait_instruction) and
  5758. (
  5759. { Register sizes must exactly match }
  5760. (
  5761. (taicpu(hp2).opcode = A_CMP) and
  5762. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  5763. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  5764. ) or (
  5765. (taicpu(hp2).opcode = A_TEST) and
  5766. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  5767. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  5768. )
  5769. ) and GetNextInstruction(hp2, hp3) and
  5770. (hp3.typ = ait_instruction) and
  5771. (taicpu(hp3).opcode = A_JCC) and
  5772. (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
  5773. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  5774. begin
  5775. { Check condition of jump }
  5776. { Always true? }
  5777. if condition_in(C_E, taicpu(hp3).condition) then
  5778. begin
  5779. { Copy label symbol and obtain matching label entry for the
  5780. conditional jump, as this will be our destination}
  5781. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  5782. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  5783. Result := True;
  5784. end
  5785. { Always false? }
  5786. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  5787. begin
  5788. { This is only worth it if there's a jump to take }
  5789. case hp2.typ of
  5790. ait_instruction:
  5791. begin
  5792. if taicpu(hp2).opcode = A_JMP then
  5793. begin
  5794. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  5795. { An unconditional jump follows the conditional jump which will always be false,
  5796. so use this jump's destination for the new jump }
  5797. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  5798. Result := True;
  5799. end
  5800. else if taicpu(hp2).opcode = A_JCC then
  5801. begin
  5802. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  5803. if condition_in(C_E, taicpu(hp2).condition) then
  5804. begin
  5805. { A second conditional jump follows the conditional jump which will always be false,
  5806. while the second jump is always True, so use this jump's destination for the new jump }
  5807. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  5808. Result := True;
  5809. end;
  5810. { Don't risk it if the jump isn't always true (Result remains False) }
  5811. end;
  5812. end;
  5813. else
  5814. { If anything else don't optimise };
  5815. end;
  5816. end;
  5817. if Result then
  5818. begin
  5819. { Just so we have something to insert as a paremeter}
  5820. reference_reset(NewRef, 1, []);
  5821. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  5822. { Now actually load the correct parameter }
  5823. NewInstr.loadsymbol(0, DestLabel, 0);
  5824. { Get instruction before original label (may not be p under -O3) }
  5825. if not GetLastInstruction(hp1, hp2) then
  5826. { Shouldn't fail here }
  5827. InternalError(2021040701);
  5828. DestLabel.increfs;
  5829. AsmL.InsertAfter(NewInstr, hp2);
  5830. { Add new alignment field }
  5831. (* AsmL.InsertAfter(
  5832. cai_align.create_max(
  5833. current_settings.alignment.jumpalign,
  5834. current_settings.alignment.jumpalignskipmax
  5835. ),
  5836. NewInstr
  5837. ); *)
  5838. end;
  5839. Exit;
  5840. end;
  5841. end;
  5842. else
  5843. ;
  5844. end;
  5845. end;
  5846. if not GetNextInstruction(p, hp1) then
  5847. Exit;
  5848. if MatchInstruction(hp1, A_JMP, [S_NO]) then
  5849. begin
  5850. { Sometimes the MOVs that OptPass2JMP produces can be improved
  5851. further, but we can't just put this jump optimisation in pass 1
  5852. because it tends to perform worse when conditional jumps are
  5853. nearby (e.g. when converting CMOV instructions). [Kit] }
  5854. if OptPass2JMP(hp1) then
  5855. { call OptPass1MOV once to potentially merge any MOVs that were created }
  5856. Result := OptPass1MOV(p)
  5857. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  5858. returned True and the instruction is still a MOV, thus checking
  5859. the optimisations below }
  5860. { If OptPass2JMP returned False, no optimisations were done to
  5861. the jump and there are no further optimisations that can be done
  5862. to the MOV instruction on this pass }
  5863. end
  5864. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  5865. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  5866. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5867. MatchOpType(taicpu(hp1),top_const,top_reg) and
  5868. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5869. { be lazy, checking separately for sub would be slightly better }
  5870. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  5871. begin
  5872. { Change:
  5873. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  5874. addl/q $x,%reg2 subl/q $x,%reg2
  5875. To:
  5876. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  5877. }
  5878. TransferUsedRegs(TmpUsedRegs);
  5879. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5880. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5881. if not GetNextInstruction(hp1, hp2) or
  5882. (
  5883. { The FLAGS register isn't always tracked properly, so do not
  5884. perform this optimisation if a conditional statement follows }
  5885. not RegReadByInstruction(NR_DEFAULTFLAGS, hp2) and
  5886. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)
  5887. ) then
  5888. begin
  5889. reference_reset(NewRef, 1, []);
  5890. NewRef.base := taicpu(p).oper[0]^.reg;
  5891. NewRef.scalefactor := 1;
  5892. if taicpu(hp1).opcode = A_ADD then
  5893. begin
  5894. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  5895. NewRef.offset := taicpu(hp1).oper[0]^.val;
  5896. end
  5897. else
  5898. begin
  5899. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  5900. NewRef.offset := -taicpu(hp1).oper[0]^.val;
  5901. end;
  5902. taicpu(p).opcode := A_LEA;
  5903. taicpu(p).loadref(0, NewRef);
  5904. RemoveInstruction(hp1);
  5905. Result := True;
  5906. Exit;
  5907. end;
  5908. end
  5909. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  5910. {$ifdef x86_64}
  5911. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  5912. {$else x86_64}
  5913. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  5914. {$endif x86_64}
  5915. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5916. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  5917. { mov reg1, reg2 mov reg1, reg2
  5918. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  5919. begin
  5920. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  5921. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  5922. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  5923. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  5924. TransferUsedRegs(TmpUsedRegs);
  5925. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5926. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  5927. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  5928. then
  5929. begin
  5930. RemoveCurrentP(p, hp1);
  5931. Result:=true;
  5932. end;
  5933. exit;
  5934. end
  5935. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  5936. IsXCHGAcceptable and
  5937. { XCHG doesn't support 8-byte registers }
  5938. (taicpu(p).opsize <> S_B) and
  5939. MatchInstruction(hp1, A_MOV, []) and
  5940. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5941. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  5942. GetNextInstruction(hp1, hp2) and
  5943. MatchInstruction(hp2, A_MOV, []) and
  5944. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  5945. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  5946. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  5947. begin
  5948. { mov %reg1,%reg2
  5949. mov %reg3,%reg1 -> xchg %reg3,%reg1
  5950. mov %reg2,%reg3
  5951. (%reg2 not used afterwards)
  5952. Note that xchg takes 3 cycles to execute, and generally mov's take
  5953. only one cycle apiece, but the first two mov's can be executed in
  5954. parallel, only taking 2 cycles overall. Older processors should
  5955. therefore only optimise for size. [Kit]
  5956. }
  5957. TransferUsedRegs(TmpUsedRegs);
  5958. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5959. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5960. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  5961. begin
  5962. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  5963. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  5964. taicpu(hp1).opcode := A_XCHG;
  5965. RemoveCurrentP(p, hp1);
  5966. RemoveInstruction(hp2);
  5967. Result := True;
  5968. Exit;
  5969. end;
  5970. end
  5971. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  5972. MatchInstruction(hp1, A_SAR, []) then
  5973. begin
  5974. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  5975. begin
  5976. { the use of %edx also covers the opsize being S_L }
  5977. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  5978. begin
  5979. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  5980. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  5981. (taicpu(p).oper[1]^.reg = NR_EDX) then
  5982. begin
  5983. { Change:
  5984. movl %eax,%edx
  5985. sarl $31,%edx
  5986. To:
  5987. cltd
  5988. }
  5989. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  5990. RemoveInstruction(hp1);
  5991. taicpu(p).opcode := A_CDQ;
  5992. taicpu(p).opsize := S_NO;
  5993. taicpu(p).clearop(1);
  5994. taicpu(p).clearop(0);
  5995. taicpu(p).ops:=0;
  5996. Result := True;
  5997. end
  5998. else if (cs_opt_size in current_settings.optimizerswitches) and
  5999. (taicpu(p).oper[0]^.reg = NR_EDX) and
  6000. (taicpu(p).oper[1]^.reg = NR_EAX) then
  6001. begin
  6002. { Change:
  6003. movl %edx,%eax
  6004. sarl $31,%edx
  6005. To:
  6006. movl %edx,%eax
  6007. cltd
  6008. Note that this creates a dependency between the two instructions,
  6009. so only perform if optimising for size.
  6010. }
  6011. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  6012. taicpu(hp1).opcode := A_CDQ;
  6013. taicpu(hp1).opsize := S_NO;
  6014. taicpu(hp1).clearop(1);
  6015. taicpu(hp1).clearop(0);
  6016. taicpu(hp1).ops:=0;
  6017. end;
  6018. {$ifndef x86_64}
  6019. end
  6020. { Don't bother if CMOV is supported, because a more optimal
  6021. sequence would have been generated for the Abs() intrinsic }
  6022. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  6023. { the use of %eax also covers the opsize being S_L }
  6024. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  6025. (taicpu(p).oper[0]^.reg = NR_EAX) and
  6026. (taicpu(p).oper[1]^.reg = NR_EDX) and
  6027. GetNextInstruction(hp1, hp2) and
  6028. MatchInstruction(hp2, A_XOR, [S_L]) and
  6029. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  6030. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  6031. GetNextInstruction(hp2, hp3) and
  6032. MatchInstruction(hp3, A_SUB, [S_L]) and
  6033. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  6034. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  6035. begin
  6036. { Change:
  6037. movl %eax,%edx
  6038. sarl $31,%eax
  6039. xorl %eax,%edx
  6040. subl %eax,%edx
  6041. (Instruction that uses %edx)
  6042. (%eax deallocated)
  6043. (%edx deallocated)
  6044. To:
  6045. cltd
  6046. xorl %edx,%eax <-- Note the registers have swapped
  6047. subl %edx,%eax
  6048. (Instruction that uses %eax) <-- %eax rather than %edx
  6049. }
  6050. TransferUsedRegs(TmpUsedRegs);
  6051. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6052. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6053. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6054. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  6055. begin
  6056. if GetNextInstruction(hp3, hp4) and
  6057. not RegModifiedByInstruction(NR_EDX, hp4) and
  6058. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  6059. begin
  6060. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  6061. taicpu(p).opcode := A_CDQ;
  6062. taicpu(p).clearop(1);
  6063. taicpu(p).clearop(0);
  6064. taicpu(p).ops:=0;
  6065. RemoveInstruction(hp1);
  6066. taicpu(hp2).loadreg(0, NR_EDX);
  6067. taicpu(hp2).loadreg(1, NR_EAX);
  6068. taicpu(hp3).loadreg(0, NR_EDX);
  6069. taicpu(hp3).loadreg(1, NR_EAX);
  6070. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  6071. { Convert references in the following instruction (hp4) from %edx to %eax }
  6072. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  6073. with taicpu(hp4).oper[OperIdx]^ do
  6074. case typ of
  6075. top_reg:
  6076. if getsupreg(reg) = RS_EDX then
  6077. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  6078. top_ref:
  6079. begin
  6080. if getsupreg(reg) = RS_EDX then
  6081. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  6082. if getsupreg(reg) = RS_EDX then
  6083. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  6084. end;
  6085. else
  6086. ;
  6087. end;
  6088. end;
  6089. end;
  6090. {$else x86_64}
  6091. end;
  6092. end
  6093. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  6094. { the use of %rdx also covers the opsize being S_Q }
  6095. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  6096. begin
  6097. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  6098. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  6099. (taicpu(p).oper[1]^.reg = NR_RDX) then
  6100. begin
  6101. { Change:
  6102. movq %rax,%rdx
  6103. sarq $63,%rdx
  6104. To:
  6105. cqto
  6106. }
  6107. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  6108. RemoveInstruction(hp1);
  6109. taicpu(p).opcode := A_CQO;
  6110. taicpu(p).opsize := S_NO;
  6111. taicpu(p).clearop(1);
  6112. taicpu(p).clearop(0);
  6113. taicpu(p).ops:=0;
  6114. Result := True;
  6115. end
  6116. else if (cs_opt_size in current_settings.optimizerswitches) and
  6117. (taicpu(p).oper[0]^.reg = NR_RDX) and
  6118. (taicpu(p).oper[1]^.reg = NR_RAX) then
  6119. begin
  6120. { Change:
  6121. movq %rdx,%rax
  6122. sarq $63,%rdx
  6123. To:
  6124. movq %rdx,%rax
  6125. cqto
  6126. Note that this creates a dependency between the two instructions,
  6127. so only perform if optimising for size.
  6128. }
  6129. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  6130. taicpu(hp1).opcode := A_CQO;
  6131. taicpu(hp1).opsize := S_NO;
  6132. taicpu(hp1).clearop(1);
  6133. taicpu(hp1).clearop(0);
  6134. taicpu(hp1).ops:=0;
  6135. {$endif x86_64}
  6136. end;
  6137. end;
  6138. end
  6139. else if MatchInstruction(hp1, A_MOV, []) and
  6140. (taicpu(hp1).oper[1]^.typ = top_reg) then
  6141. { Though "GetNextInstruction" could be factored out, along with
  6142. the instructions that depend on hp2, it is an expensive call that
  6143. should be delayed for as long as possible, hence we do cheaper
  6144. checks first that are likely to be False. [Kit] }
  6145. begin
  6146. if (
  6147. (
  6148. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  6149. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  6150. (
  6151. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  6152. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  6153. )
  6154. ) or
  6155. (
  6156. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  6157. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  6158. (
  6159. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  6160. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  6161. )
  6162. )
  6163. ) and
  6164. GetNextInstruction(hp1, hp2) and
  6165. MatchInstruction(hp2, A_SAR, []) and
  6166. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  6167. begin
  6168. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  6169. begin
  6170. { Change:
  6171. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  6172. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  6173. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  6174. To:
  6175. movl r/m,%eax <- Note the change in register
  6176. cltd
  6177. }
  6178. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  6179. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  6180. taicpu(p).loadreg(1, NR_EAX);
  6181. taicpu(hp1).opcode := A_CDQ;
  6182. taicpu(hp1).clearop(1);
  6183. taicpu(hp1).clearop(0);
  6184. taicpu(hp1).ops:=0;
  6185. RemoveInstruction(hp2);
  6186. (*
  6187. {$ifdef x86_64}
  6188. end
  6189. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  6190. { This code sequence does not get generated - however it might become useful
  6191. if and when 128-bit signed integer types make an appearance, so the code
  6192. is kept here for when it is eventually needed. [Kit] }
  6193. (
  6194. (
  6195. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  6196. (
  6197. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  6198. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  6199. )
  6200. ) or
  6201. (
  6202. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  6203. (
  6204. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  6205. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  6206. )
  6207. )
  6208. ) and
  6209. GetNextInstruction(hp1, hp2) and
  6210. MatchInstruction(hp2, A_SAR, [S_Q]) and
  6211. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  6212. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  6213. begin
  6214. { Change:
  6215. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  6216. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  6217. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  6218. To:
  6219. movq r/m,%rax <- Note the change in register
  6220. cqto
  6221. }
  6222. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  6223. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  6224. taicpu(p).loadreg(1, NR_RAX);
  6225. taicpu(hp1).opcode := A_CQO;
  6226. taicpu(hp1).clearop(1);
  6227. taicpu(hp1).clearop(0);
  6228. taicpu(hp1).ops:=0;
  6229. RemoveInstruction(hp2);
  6230. {$endif x86_64}
  6231. *)
  6232. end;
  6233. end;
  6234. {$ifdef x86_64}
  6235. end
  6236. else if (taicpu(p).opsize = S_L) and
  6237. (taicpu(p).oper[1]^.typ = top_reg) and
  6238. (
  6239. MatchInstruction(hp1, A_MOV,[]) and
  6240. (taicpu(hp1).opsize = S_L) and
  6241. (taicpu(hp1).oper[1]^.typ = top_reg)
  6242. ) and (
  6243. GetNextInstruction(hp1, hp2) and
  6244. (tai(hp2).typ=ait_instruction) and
  6245. (taicpu(hp2).opsize = S_Q) and
  6246. (
  6247. (
  6248. MatchInstruction(hp2, A_ADD,[]) and
  6249. (taicpu(hp2).opsize = S_Q) and
  6250. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  6251. (
  6252. (
  6253. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  6254. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  6255. ) or (
  6256. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  6257. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  6258. )
  6259. )
  6260. ) or (
  6261. MatchInstruction(hp2, A_LEA,[]) and
  6262. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  6263. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  6264. (
  6265. (
  6266. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  6267. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  6268. ) or (
  6269. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  6270. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  6271. )
  6272. ) and (
  6273. (
  6274. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  6275. ) or (
  6276. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  6277. )
  6278. )
  6279. )
  6280. )
  6281. ) and (
  6282. GetNextInstruction(hp2, hp3) and
  6283. MatchInstruction(hp3, A_SHR,[]) and
  6284. (taicpu(hp3).opsize = S_Q) and
  6285. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  6286. (taicpu(hp3).oper[0]^.val = 1) and
  6287. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  6288. ) then
  6289. begin
  6290. { Change movl x, reg1d movl x, reg1d
  6291. movl y, reg2d movl y, reg2d
  6292. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  6293. shrq $1, reg1q shrq $1, reg1q
  6294. ( reg1d and reg2d can be switched around in the first two instructions )
  6295. To movl x, reg1d
  6296. addl y, reg1d
  6297. rcrl $1, reg1d
  6298. This corresponds to the common expression (x + y) shr 1, where
  6299. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  6300. smaller code, but won't account for x + y causing an overflow). [Kit]
  6301. }
  6302. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  6303. { Change first MOV command to have the same register as the final output }
  6304. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  6305. else
  6306. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  6307. { Change second MOV command to an ADD command. This is easier than
  6308. converting the existing command because it means we don't have to
  6309. touch 'y', which might be a complicated reference, and also the
  6310. fact that the third command might either be ADD or LEA. [Kit] }
  6311. taicpu(hp1).opcode := A_ADD;
  6312. { Delete old ADD/LEA instruction }
  6313. RemoveInstruction(hp2);
  6314. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  6315. taicpu(hp3).opcode := A_RCR;
  6316. taicpu(hp3).changeopsize(S_L);
  6317. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  6318. {$endif x86_64}
  6319. end;
  6320. end;
  6321. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  6322. var
  6323. ThisReg: TRegister;
  6324. MinSize, MaxSize, TrySmaller, TargetSize: TOpSize;
  6325. TargetSubReg: TSubRegister;
  6326. hp1, hp2: tai;
  6327. RegInUse, RegChanged, p_removed: Boolean;
  6328. { Store list of found instructions so we don't have to call
  6329. GetNextInstructionUsingReg multiple times }
  6330. InstrList: array of taicpu;
  6331. InstrMax, Index: Integer;
  6332. UpperLimit, TrySmallerLimit: TCgInt;
  6333. PreMessage: string;
  6334. { Data flow analysis }
  6335. TestValMin, TestValMax: TCgInt;
  6336. SmallerOverflow: Boolean;
  6337. begin
  6338. Result := False;
  6339. p_removed := False;
  6340. { This is anything but quick! }
  6341. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  6342. Exit;
  6343. SetLength(InstrList, 0);
  6344. InstrMax := -1;
  6345. ThisReg := taicpu(p).oper[1]^.reg;
  6346. case taicpu(p).opsize of
  6347. S_BW, S_BL:
  6348. begin
  6349. {$if defined(i386) or defined(i8086)}
  6350. { If the target size is 8-bit, make sure we can actually encode it }
  6351. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  6352. Exit;
  6353. {$endif i386 or i8086}
  6354. UpperLimit := $FF;
  6355. MinSize := S_B;
  6356. if taicpu(p).opsize = S_BW then
  6357. MaxSize := S_W
  6358. else
  6359. MaxSize := S_L;
  6360. end;
  6361. S_WL:
  6362. begin
  6363. UpperLimit := $FFFF;
  6364. MinSize := S_W;
  6365. MaxSize := S_L;
  6366. end
  6367. else
  6368. InternalError(2020112301);
  6369. end;
  6370. TestValMin := 0;
  6371. TestValMax := UpperLimit;
  6372. TrySmallerLimit := UpperLimit;
  6373. TrySmaller := S_NO;
  6374. SmallerOverflow := False;
  6375. RegChanged := False;
  6376. hp1 := p;
  6377. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  6378. (hp1.typ = ait_instruction) and
  6379. (
  6380. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  6381. instruction that doesn't actually contain ThisReg }
  6382. (cs_opt_level3 in current_settings.optimizerswitches) or
  6383. RegInInstruction(ThisReg, hp1)
  6384. ) do
  6385. begin
  6386. case taicpu(hp1).opcode of
  6387. A_INC,A_DEC:
  6388. begin
  6389. { Has to be an exact match on the register }
  6390. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  6391. Break;
  6392. if taicpu(hp1).opcode = A_INC then
  6393. begin
  6394. Inc(TestValMin);
  6395. Inc(TestValMax);
  6396. end
  6397. else
  6398. begin
  6399. Dec(TestValMin);
  6400. Dec(TestValMax);
  6401. end;
  6402. end;
  6403. A_CMP:
  6404. begin
  6405. if (taicpu(hp1).oper[1]^.typ <> top_reg) or
  6406. { Has to be an exact match on the register }
  6407. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  6408. (taicpu(hp1).oper[0]^.typ <> top_const) or
  6409. { Make sure the comparison value is not smaller than the
  6410. smallest allowed signed value for the minimum size (e.g.
  6411. -128 for 8-bit) }
  6412. not (
  6413. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  6414. { Is it in the negative range? }
  6415. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  6416. ) then
  6417. Break;
  6418. TestValMin := TestValMin - taicpu(hp1).oper[0]^.val;
  6419. TestValMax := TestValMax - taicpu(hp1).oper[0]^.val;
  6420. if (TestValMin < TrySmallerLimit) or (TestValMax < TrySmallerLimit) or
  6421. (TestValMin > UpperLimit) or (TestValMax > UpperLimit) then
  6422. { Overflow }
  6423. Break;
  6424. { Check to see if the active register is used afterwards }
  6425. TransferUsedRegs(TmpUsedRegs);
  6426. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  6427. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  6428. begin
  6429. case MinSize of
  6430. S_B:
  6431. TargetSubReg := R_SUBL;
  6432. S_W:
  6433. TargetSubReg := R_SUBW;
  6434. else
  6435. InternalError(2021051002);
  6436. end;
  6437. { Update the register to its new size }
  6438. setsubreg(ThisReg, TargetSubReg);
  6439. taicpu(hp1).oper[1]^.reg := ThisReg;
  6440. taicpu(hp1).opsize := MinSize;
  6441. { Convert the input MOVZX to a MOV }
  6442. if (taicpu(p).oper[0]^.typ = top_reg) and
  6443. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  6444. begin
  6445. { Or remove it completely! }
  6446. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  6447. RemoveCurrentP(p);
  6448. p_removed := True;
  6449. end
  6450. else
  6451. begin
  6452. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  6453. taicpu(p).opcode := A_MOV;
  6454. taicpu(p).oper[1]^.reg := ThisReg;
  6455. taicpu(p).opsize := MinSize;
  6456. end;
  6457. if (InstrMax >= 0) then
  6458. begin
  6459. for Index := 0 to InstrMax do
  6460. begin
  6461. { If p_removed is true, then the original MOV/Z was removed
  6462. and removing the AND instruction may not be safe if it
  6463. appears first }
  6464. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  6465. InternalError(2020112311);
  6466. if InstrList[Index].oper[0]^.typ = top_reg then
  6467. InstrList[Index].oper[0]^.reg := ThisReg;
  6468. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  6469. InstrList[Index].opsize := MinSize;
  6470. end;
  6471. end;
  6472. Result := True;
  6473. Exit;
  6474. end;
  6475. end;
  6476. { OR and XOR are not included because they can too easily fool
  6477. the data flow analysis (they can cause non-linear behaviour) }
  6478. A_ADD,A_SUB,A_AND,A_SHL,A_SHR:
  6479. begin
  6480. if
  6481. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  6482. { Has to be an exact match on the register }
  6483. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  6484. (
  6485. (
  6486. (taicpu(hp1).oper[0]^.typ = top_const) and
  6487. (
  6488. (
  6489. (taicpu(hp1).opcode = A_SHL) and
  6490. (
  6491. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  6492. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  6493. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  6494. )
  6495. ) or (
  6496. (taicpu(hp1).opcode <> A_SHL) and
  6497. (
  6498. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  6499. { Is it in the negative range? }
  6500. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  6501. )
  6502. )
  6503. )
  6504. ) or (
  6505. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  6506. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  6507. )
  6508. ) then
  6509. Break;
  6510. case taicpu(hp1).opcode of
  6511. A_ADD:
  6512. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  6513. begin
  6514. TestValMin := TestValMin * 2;
  6515. TestValMax := TestValMax * 2;
  6516. end
  6517. else
  6518. begin
  6519. TestValMin := TestValMin + taicpu(hp1).oper[0]^.val;
  6520. TestValMax := TestValMax + taicpu(hp1).oper[0]^.val;
  6521. end;
  6522. A_SUB:
  6523. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  6524. begin
  6525. TestValMin := 0;
  6526. TestValMax := 0;
  6527. end
  6528. else
  6529. begin
  6530. TestValMin := TestValMin - taicpu(hp1).oper[0]^.val;
  6531. TestValMax := TestValMax - taicpu(hp1).oper[0]^.val;
  6532. end;
  6533. A_AND:
  6534. if (taicpu(hp1).oper[0]^.typ = top_const) then
  6535. begin
  6536. { we might be able to go smaller if AND appears first }
  6537. if InstrMax = -1 then
  6538. case MinSize of
  6539. S_B:
  6540. ;
  6541. S_W:
  6542. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  6543. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  6544. begin
  6545. TrySmaller := S_B;
  6546. TrySmallerLimit := $FF;
  6547. end;
  6548. S_L:
  6549. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  6550. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  6551. begin
  6552. TrySmaller := S_B;
  6553. TrySmallerLimit := $FF;
  6554. end
  6555. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  6556. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  6557. begin
  6558. TrySmaller := S_W;
  6559. TrySmallerLimit := $FFFF;
  6560. end;
  6561. else
  6562. InternalError(2020112320);
  6563. end;
  6564. TestValMin := TestValMin and taicpu(hp1).oper[0]^.val;
  6565. TestValMax := TestValMax and taicpu(hp1).oper[0]^.val;
  6566. end;
  6567. A_SHL:
  6568. begin
  6569. TestValMin := TestValMin shl taicpu(hp1).oper[0]^.val;
  6570. TestValMax := TestValMax shl taicpu(hp1).oper[0]^.val;
  6571. end;
  6572. A_SHR:
  6573. begin
  6574. { we might be able to go smaller if SHR appears first }
  6575. if InstrMax = -1 then
  6576. case MinSize of
  6577. S_B:
  6578. ;
  6579. S_W:
  6580. if (taicpu(hp1).oper[0]^.val >= 8) then
  6581. begin
  6582. TrySmaller := S_B;
  6583. TrySmallerLimit := $FF;
  6584. end;
  6585. S_L:
  6586. if (taicpu(hp1).oper[0]^.val >= 24) then
  6587. begin
  6588. TrySmaller := S_B;
  6589. TrySmallerLimit := $FF;
  6590. end
  6591. else if (taicpu(hp1).oper[0]^.val >= 16) then
  6592. begin
  6593. TrySmaller := S_W;
  6594. TrySmallerLimit := $FFFF;
  6595. end;
  6596. else
  6597. InternalError(2020112321);
  6598. end;
  6599. TestValMin := TestValMin shr taicpu(hp1).oper[0]^.val;
  6600. TestValMax := TestValMax shr taicpu(hp1).oper[0]^.val;
  6601. end;
  6602. else
  6603. InternalError(2020112303);
  6604. end;
  6605. end;
  6606. (*
  6607. A_IMUL:
  6608. case taicpu(hp1).ops of
  6609. 2:
  6610. begin
  6611. if not MatchOpType(hp1, top_reg, top_reg) or
  6612. { Has to be an exact match on the register }
  6613. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  6614. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  6615. Break;
  6616. TestValMin := TestValMin * TestValMin;
  6617. TestValMax := TestValMax * TestValMax;
  6618. end;
  6619. 3:
  6620. begin
  6621. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  6622. { Has to be an exact match on the register }
  6623. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  6624. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  6625. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  6626. { Is it in the negative range? }
  6627. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  6628. Break;
  6629. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  6630. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  6631. end;
  6632. else
  6633. Break;
  6634. end;
  6635. A_IDIV:
  6636. case taicpu(hp1).ops of
  6637. 3:
  6638. begin
  6639. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  6640. { Has to be an exact match on the register }
  6641. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  6642. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  6643. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  6644. { Is it in the negative range? }
  6645. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  6646. Break;
  6647. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  6648. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  6649. end;
  6650. else
  6651. Break;
  6652. end;
  6653. *)
  6654. A_MOVZX:
  6655. begin
  6656. if not MatchOpType(taicpu(hp1), top_reg, top_reg) then
  6657. Break;
  6658. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  6659. begin
  6660. { Because hp1 was obtained via GetNextInstructionUsingReg
  6661. and ThisReg doesn't appear in the first operand, it
  6662. must appear in the second operand and hence gets
  6663. overwritten }
  6664. if (InstrMax = -1) and
  6665. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  6666. begin
  6667. { The two MOVZX instructions are adjacent, so remove the first one }
  6668. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  6669. RemoveCurrentP(p);
  6670. Result := True;
  6671. Exit;
  6672. end;
  6673. Break;
  6674. end;
  6675. { The objective here is to try to find a combination that
  6676. removes one of the MOV/Z instructions. }
  6677. case taicpu(hp1).opsize of
  6678. S_WL:
  6679. if (MinSize in [S_B, S_W]) then
  6680. begin
  6681. TargetSize := S_L;
  6682. TargetSubReg := R_SUBD;
  6683. end
  6684. else if ((TrySmaller in [S_B, S_W]) and not SmallerOverflow) then
  6685. begin
  6686. TargetSize := TrySmaller;
  6687. if TrySmaller = S_B then
  6688. TargetSubReg := R_SUBL
  6689. else
  6690. TargetSubReg := R_SUBW;
  6691. end
  6692. else
  6693. Break;
  6694. S_BW:
  6695. if (MinSize in [S_B, S_W]) then
  6696. begin
  6697. TargetSize := S_W;
  6698. TargetSubReg := R_SUBW;
  6699. end
  6700. else if ((TrySmaller = S_B) and not SmallerOverflow) then
  6701. begin
  6702. TargetSize := S_B;
  6703. TargetSubReg := R_SUBL;
  6704. end
  6705. else
  6706. Break;
  6707. S_BL:
  6708. if (MinSize in [S_B, S_W]) then
  6709. begin
  6710. TargetSize := S_L;
  6711. TargetSubReg := R_SUBD;
  6712. end
  6713. else if ((TrySmaller = S_B) and not SmallerOverflow) then
  6714. begin
  6715. TargetSize := S_B;
  6716. TargetSubReg := R_SUBL;
  6717. end
  6718. else
  6719. Break;
  6720. else
  6721. InternalError(2020112302);
  6722. end;
  6723. { Update the register to its new size }
  6724. setsubreg(ThisReg, TargetSubReg);
  6725. if TargetSize = MinSize then
  6726. begin
  6727. { Convert the input MOVZX to a MOV }
  6728. if (taicpu(p).oper[0]^.typ = top_reg) and
  6729. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  6730. begin
  6731. { Or remove it completely! }
  6732. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  6733. RemoveCurrentP(p);
  6734. p_removed := True;
  6735. end
  6736. else
  6737. begin
  6738. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  6739. taicpu(p).opcode := A_MOV;
  6740. taicpu(p).oper[1]^.reg := ThisReg;
  6741. taicpu(p).opsize := TargetSize;
  6742. end;
  6743. Result := True;
  6744. end
  6745. else if TargetSize <> MaxSize then
  6746. begin
  6747. case MaxSize of
  6748. S_L:
  6749. if TargetSize = S_W then
  6750. begin
  6751. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  6752. taicpu(p).opsize := S_BW;
  6753. taicpu(p).oper[1]^.reg := ThisReg;
  6754. Result := True;
  6755. end
  6756. else
  6757. InternalError(2020112341);
  6758. S_W:
  6759. if TargetSize = S_L then
  6760. begin
  6761. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  6762. taicpu(p).opsize := S_BL;
  6763. taicpu(p).oper[1]^.reg := ThisReg;
  6764. Result := True;
  6765. end
  6766. else
  6767. InternalError(2020112342);
  6768. else
  6769. ;
  6770. end;
  6771. end;
  6772. if (MaxSize = TargetSize) or
  6773. ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  6774. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  6775. begin
  6776. { Convert the output MOVZX to a MOV }
  6777. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  6778. begin
  6779. { Or remove it completely! }
  6780. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  6781. { Be careful; if p = hp1 and p was also removed, p
  6782. will become a dangling pointer }
  6783. if p = hp1 then
  6784. RemoveCurrentp(p) { p = hp1 and will then become the next instruction }
  6785. else
  6786. RemoveInstruction(hp1);
  6787. end
  6788. else
  6789. begin
  6790. taicpu(hp1).opcode := A_MOV;
  6791. taicpu(hp1).oper[0]^.reg := ThisReg;
  6792. taicpu(hp1).opsize := TargetSize;
  6793. { Check to see if the active register is used afterwards;
  6794. if not, we can change it and make a saving. }
  6795. RegInUse := False;
  6796. TransferUsedRegs(TmpUsedRegs);
  6797. { The target register may be marked as in use to cross
  6798. a jump to a distant label, so exclude it }
  6799. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  6800. hp2 := p;
  6801. repeat
  6802. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6803. { Explicitly check for the excluded register (don't include the first
  6804. instruction as it may be reading from here }
  6805. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  6806. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  6807. begin
  6808. RegInUse := True;
  6809. Break;
  6810. end;
  6811. if not GetNextInstruction(hp2, hp2) then
  6812. InternalError(2020112340);
  6813. until (hp2 = hp1);
  6814. if not RegInUse and not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  6815. begin
  6816. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  6817. ThisReg := taicpu(hp1).oper[1]^.reg;
  6818. RegChanged := True;
  6819. TransferUsedRegs(TmpUsedRegs);
  6820. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  6821. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  6822. if p = hp1 then
  6823. RemoveCurrentp(p) { p = hp1 and will then become the next instruction }
  6824. else
  6825. RemoveInstruction(hp1);
  6826. { Instruction will become "mov %reg,%reg" }
  6827. if not p_removed and (taicpu(p).opcode = A_MOV) and
  6828. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  6829. begin
  6830. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  6831. RemoveCurrentP(p);
  6832. p_removed := True;
  6833. end
  6834. else
  6835. taicpu(p).oper[1]^.reg := ThisReg;
  6836. Result := True;
  6837. end
  6838. else
  6839. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  6840. end;
  6841. end
  6842. else
  6843. InternalError(2020112330);
  6844. { Now go through every instruction we found and change the
  6845. size. If TargetSize = MaxSize, then almost no changes are
  6846. needed and Result can remain False if it hasn't been set
  6847. yet.
  6848. If RegChanged is True, then the register requires changing
  6849. and so the point about TargetSize = MaxSize doesn't apply. }
  6850. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  6851. begin
  6852. for Index := 0 to InstrMax do
  6853. begin
  6854. { If p_removed is true, then the original MOV/Z was removed
  6855. and removing the AND instruction may not be safe if it
  6856. appears first }
  6857. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  6858. InternalError(2020112310);
  6859. if InstrList[Index].oper[0]^.typ = top_reg then
  6860. InstrList[Index].oper[0]^.reg := ThisReg;
  6861. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  6862. InstrList[Index].opsize := TargetSize;
  6863. end;
  6864. Result := True;
  6865. end;
  6866. Exit;
  6867. end;
  6868. else
  6869. { This includes ADC, SBB, IDIV and SAR }
  6870. Break;
  6871. end;
  6872. if (TestValMin < 0) or (TestValMax < 0) or
  6873. (TestValMin > UpperLimit) or (TestValMax > UpperLimit) then
  6874. { Overflow }
  6875. Break
  6876. else if not SmallerOverflow and (TrySmaller <> S_NO) and
  6877. ((TestValMin > TrySmallerLimit) or (TestValMax > TrySmallerLimit)) then
  6878. SmallerOverflow := True;
  6879. { Contains highest index (so instruction count - 1) }
  6880. Inc(InstrMax);
  6881. if InstrMax > High(InstrList) then
  6882. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  6883. InstrList[InstrMax] := taicpu(hp1);
  6884. end;
  6885. end;
  6886. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  6887. var
  6888. hp1 : tai;
  6889. begin
  6890. Result:=false;
  6891. if (taicpu(p).ops >= 2) and
  6892. ((taicpu(p).oper[0]^.typ = top_const) or
  6893. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  6894. (taicpu(p).oper[1]^.typ = top_reg) and
  6895. ((taicpu(p).ops = 2) or
  6896. ((taicpu(p).oper[2]^.typ = top_reg) and
  6897. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  6898. GetLastInstruction(p,hp1) and
  6899. MatchInstruction(hp1,A_MOV,[]) and
  6900. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6901. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  6902. begin
  6903. TransferUsedRegs(TmpUsedRegs);
  6904. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  6905. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  6906. { change
  6907. mov reg1,reg2
  6908. imul y,reg2 to imul y,reg1,reg2 }
  6909. begin
  6910. taicpu(p).ops := 3;
  6911. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  6912. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6913. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  6914. RemoveInstruction(hp1);
  6915. result:=true;
  6916. end;
  6917. end;
  6918. end;
  6919. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  6920. var
  6921. ThisLabel: TAsmLabel;
  6922. begin
  6923. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  6924. ThisLabel.decrefs;
  6925. taicpu(p).opcode := A_RET;
  6926. taicpu(p).is_jmp := false;
  6927. taicpu(p).ops := taicpu(ret_p).ops;
  6928. case taicpu(ret_p).ops of
  6929. 0:
  6930. taicpu(p).clearop(0);
  6931. 1:
  6932. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  6933. else
  6934. internalerror(2016041301);
  6935. end;
  6936. { If the original label is now dead, it might turn out that the label
  6937. immediately follows p. As a result, everything beyond it, which will
  6938. be just some final register configuration and a RET instruction, is
  6939. now dead code. [Kit] }
  6940. { NOTE: This is much faster than introducing a OptPass2RET routine and
  6941. running RemoveDeadCodeAfterJump for each RET instruction, because
  6942. this optimisation rarely happens and most RETs appear at the end of
  6943. routines where there is nothing that can be stripped. [Kit] }
  6944. if not ThisLabel.is_used then
  6945. RemoveDeadCodeAfterJump(p);
  6946. end;
  6947. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  6948. var
  6949. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  6950. Unconditional, PotentialModified: Boolean;
  6951. OperPtr: POper;
  6952. NewRef: TReference;
  6953. InstrList: array of taicpu;
  6954. InstrMax, Index: Integer;
  6955. const
  6956. {$ifdef DEBUG_AOPTCPU}
  6957. SNoFlags: shortstring = ' so the flags aren''t modified';
  6958. {$else DEBUG_AOPTCPU}
  6959. SNoFlags = '';
  6960. {$endif DEBUG_AOPTCPU}
  6961. begin
  6962. Result:=false;
  6963. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  6964. begin
  6965. if MatchInstruction(hp1, A_TEST, [S_B]) and
  6966. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6967. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  6968. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  6969. GetNextInstruction(hp1, hp2) and
  6970. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  6971. { Change from: To:
  6972. set(C) %reg j(~C) label
  6973. test %reg,%reg/cmp $0,%reg
  6974. je label
  6975. set(C) %reg j(C) label
  6976. test %reg,%reg/cmp $0,%reg
  6977. jne label
  6978. (Also do something similar with sete/setne instead of je/jne)
  6979. }
  6980. begin
  6981. { Before we do anything else, we need to check the instructions
  6982. in between SETcc and TEST to make sure they don't modify the
  6983. FLAGS register - if -O2 or under, there won't be any
  6984. instructions between SET and TEST }
  6985. TransferUsedRegs(TmpUsedRegs);
  6986. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6987. if (cs_opt_level3 in current_settings.optimizerswitches) then
  6988. begin
  6989. next := p;
  6990. SetLength(InstrList, 0);
  6991. InstrMax := -1;
  6992. PotentialModified := False;
  6993. { Make a note of every instruction that modifies the FLAGS
  6994. register }
  6995. while GetNextInstruction(next, next) and (next <> hp1) do
  6996. begin
  6997. if next.typ <> ait_instruction then
  6998. { GetNextInstructionUsingReg should have returned False }
  6999. InternalError(2021051701);
  7000. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  7001. begin
  7002. case taicpu(next).opcode of
  7003. A_SETcc,
  7004. A_CMOVcc,
  7005. A_Jcc:
  7006. begin
  7007. if PotentialModified then
  7008. { Not safe because the flags were modified earlier }
  7009. Exit
  7010. else
  7011. { Condition is the same as the initial SETcc, so this is safe
  7012. (don't add to instruction list though) }
  7013. Continue;
  7014. end;
  7015. A_ADD:
  7016. begin
  7017. if (taicpu(next).opsize = S_B) or
  7018. { LEA doesn't support 8-bit operands }
  7019. (taicpu(next).oper[1]^.typ <> top_reg) or
  7020. { Must write to a register }
  7021. (taicpu(next).oper[0]^.typ = top_ref) then
  7022. { Require a constant or a register }
  7023. Exit;
  7024. PotentialModified := True;
  7025. end;
  7026. A_SUB:
  7027. begin
  7028. if (taicpu(next).opsize = S_B) or
  7029. { LEA doesn't support 8-bit operands }
  7030. (taicpu(next).oper[1]^.typ <> top_reg) or
  7031. { Must write to a register }
  7032. (taicpu(next).oper[0]^.typ <> top_const) or
  7033. (taicpu(next).oper[0]^.val = $80000000) then
  7034. { Can't subtract a register with LEA - also
  7035. check that the value isn't -2^31, as this
  7036. can't be negated }
  7037. Exit;
  7038. PotentialModified := True;
  7039. end;
  7040. A_SAL,
  7041. A_SHL:
  7042. begin
  7043. if (taicpu(next).opsize = S_B) or
  7044. { LEA doesn't support 8-bit operands }
  7045. (taicpu(next).oper[1]^.typ <> top_reg) or
  7046. { Must write to a register }
  7047. (taicpu(next).oper[0]^.typ <> top_const) or
  7048. (taicpu(next).oper[0]^.val < 0) or
  7049. (taicpu(next).oper[0]^.val > 3) then
  7050. Exit;
  7051. PotentialModified := True;
  7052. end;
  7053. A_IMUL:
  7054. begin
  7055. if (taicpu(next).ops <> 3) or
  7056. (taicpu(next).oper[1]^.typ <> top_reg) or
  7057. { Must write to a register }
  7058. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  7059. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  7060. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  7061. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  7062. Exit
  7063. else
  7064. PotentialModified := True;
  7065. end;
  7066. else
  7067. { Don't know how to change this, so abort }
  7068. Exit;
  7069. end;
  7070. { Contains highest index (so instruction count - 1) }
  7071. Inc(InstrMax);
  7072. if InstrMax > High(InstrList) then
  7073. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  7074. InstrList[InstrMax] := taicpu(next);
  7075. end;
  7076. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  7077. end;
  7078. if not Assigned(next) or (next <> hp1) then
  7079. { It should be equal to hp1 }
  7080. InternalError(2021051702);
  7081. { Cycle through each instruction and check to see if we can
  7082. change them to versions that don't modify the flags }
  7083. if (InstrMax >= 0) then
  7084. begin
  7085. for Index := 0 to InstrMax do
  7086. case InstrList[Index].opcode of
  7087. A_ADD:
  7088. begin
  7089. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  7090. InstrList[Index].opcode := A_LEA;
  7091. reference_reset(NewRef, 1, []);
  7092. NewRef.base := InstrList[Index].oper[1]^.reg;
  7093. if InstrList[Index].oper[0]^.typ = top_reg then
  7094. begin
  7095. NewRef.index := InstrList[Index].oper[0]^.reg;
  7096. NewRef.scalefactor := 1;
  7097. end
  7098. else
  7099. NewRef.offset := InstrList[Index].oper[0]^.val;
  7100. InstrList[Index].loadref(0, NewRef);
  7101. end;
  7102. A_SUB:
  7103. begin
  7104. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  7105. InstrList[Index].opcode := A_LEA;
  7106. reference_reset(NewRef, 1, []);
  7107. NewRef.base := InstrList[Index].oper[1]^.reg;
  7108. NewRef.offset := -InstrList[Index].oper[0]^.val;
  7109. InstrList[Index].loadref(0, NewRef);
  7110. end;
  7111. A_SHL,
  7112. A_SAL:
  7113. begin
  7114. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  7115. InstrList[Index].opcode := A_LEA;
  7116. reference_reset(NewRef, 1, []);
  7117. NewRef.index := InstrList[Index].oper[1]^.reg;
  7118. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  7119. InstrList[Index].loadref(0, NewRef);
  7120. end;
  7121. A_IMUL:
  7122. begin
  7123. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  7124. InstrList[Index].opcode := A_LEA;
  7125. reference_reset(NewRef, 1, []);
  7126. NewRef.index := InstrList[Index].oper[1]^.reg;
  7127. case InstrList[Index].oper[0]^.val of
  7128. 2, 4, 8:
  7129. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  7130. else {3, 5 and 9}
  7131. begin
  7132. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  7133. NewRef.base := InstrList[Index].oper[1]^.reg;
  7134. end;
  7135. end;
  7136. InstrList[Index].loadref(0, NewRef);
  7137. end;
  7138. else
  7139. InternalError(2021051710);
  7140. end;
  7141. end;
  7142. { Mark the FLAGS register as used across this whole block }
  7143. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  7144. end;
  7145. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  7146. JumpC := taicpu(hp2).condition;
  7147. Unconditional := False;
  7148. if conditions_equal(JumpC, C_E) then
  7149. SetC := inverse_cond(taicpu(p).condition)
  7150. else if conditions_equal(JumpC, C_NE) then
  7151. SetC := taicpu(p).condition
  7152. else
  7153. { We've got something weird here (and inefficent) }
  7154. begin
  7155. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  7156. SetC := C_NONE;
  7157. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  7158. if condition_in(C_AE, JumpC) then
  7159. Unconditional := True
  7160. else
  7161. { Not sure what to do with this jump - drop out }
  7162. Exit;
  7163. end;
  7164. RemoveInstruction(hp1);
  7165. if Unconditional then
  7166. MakeUnconditional(taicpu(hp2))
  7167. else
  7168. begin
  7169. if SetC = C_NONE then
  7170. InternalError(2018061402);
  7171. taicpu(hp2).SetCondition(SetC);
  7172. end;
  7173. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  7174. TmpUsedRegs }
  7175. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  7176. begin
  7177. RemoveCurrentp(p, hp2);
  7178. if taicpu(hp2).opcode = A_SETcc then
  7179. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  7180. else
  7181. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  7182. end
  7183. else
  7184. if taicpu(hp2).opcode = A_SETcc then
  7185. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  7186. else
  7187. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  7188. Result := True;
  7189. end
  7190. else if
  7191. { Make sure the instructions are adjacent }
  7192. (
  7193. not (cs_opt_level3 in current_settings.optimizerswitches) or
  7194. GetNextInstruction(p, hp1)
  7195. ) and
  7196. MatchInstruction(hp1, A_MOV, [S_B]) and
  7197. { Writing to memory is allowed }
  7198. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  7199. begin
  7200. {
  7201. Watch out for sequences such as:
  7202. set(c)b %regb
  7203. movb %regb,(ref)
  7204. movb $0,1(ref)
  7205. movb $0,2(ref)
  7206. movb $0,3(ref)
  7207. Much more efficient to turn it into:
  7208. movl $0,%regl
  7209. set(c)b %regb
  7210. movl %regl,(ref)
  7211. Or:
  7212. set(c)b %regb
  7213. movzbl %regb,%regl
  7214. movl %regl,(ref)
  7215. }
  7216. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  7217. GetNextInstruction(hp1, hp2) and
  7218. MatchInstruction(hp2, A_MOV, [S_B]) and
  7219. (taicpu(hp2).oper[1]^.typ = top_ref) and
  7220. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  7221. begin
  7222. { Don't do anything else except set Result to True }
  7223. end
  7224. else
  7225. begin
  7226. if taicpu(p).oper[0]^.typ = top_reg then
  7227. begin
  7228. TransferUsedRegs(TmpUsedRegs);
  7229. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7230. end;
  7231. { If it's not a register, it's a memory address }
  7232. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  7233. begin
  7234. { Even if the register is still in use, we can minimise the
  7235. pipeline stall by changing the MOV into another SETcc. }
  7236. taicpu(hp1).opcode := A_SETcc;
  7237. taicpu(hp1).condition := taicpu(p).condition;
  7238. if taicpu(hp1).oper[1]^.typ = top_ref then
  7239. begin
  7240. { Swapping the operand pointers like this is probably a
  7241. bit naughty, but it is far faster than using loadoper
  7242. to transfer the reference from oper[1] to oper[0] if
  7243. you take into account the extra procedure calls and
  7244. the memory allocation and deallocation required }
  7245. OperPtr := taicpu(hp1).oper[1];
  7246. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  7247. taicpu(hp1).oper[0] := OperPtr;
  7248. end
  7249. else
  7250. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  7251. taicpu(hp1).clearop(1);
  7252. taicpu(hp1).ops := 1;
  7253. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  7254. end
  7255. else
  7256. begin
  7257. if taicpu(hp1).oper[1]^.typ = top_reg then
  7258. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  7259. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  7260. RemoveInstruction(hp1);
  7261. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  7262. end
  7263. end;
  7264. Result := True;
  7265. end;
  7266. end;
  7267. end;
  7268. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  7269. var
  7270. hp1: tai;
  7271. Count: Integer;
  7272. OrigLabel: TAsmLabel;
  7273. begin
  7274. result := False;
  7275. { Sometimes, the optimisations below can permit this }
  7276. RemoveDeadCodeAfterJump(p);
  7277. 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
  7278. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  7279. begin
  7280. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  7281. { Also a side-effect of optimisations }
  7282. if CollapseZeroDistJump(p, OrigLabel) then
  7283. begin
  7284. Result := True;
  7285. Exit;
  7286. end;
  7287. hp1 := GetLabelWithSym(OrigLabel);
  7288. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  7289. begin
  7290. case taicpu(hp1).opcode of
  7291. A_RET:
  7292. {
  7293. change
  7294. jmp .L1
  7295. ...
  7296. .L1:
  7297. ret
  7298. into
  7299. ret
  7300. }
  7301. begin
  7302. ConvertJumpToRET(p, hp1);
  7303. result:=true;
  7304. end;
  7305. { Check any kind of direct assignment instruction }
  7306. A_MOV,
  7307. A_MOVD,
  7308. A_MOVQ,
  7309. A_MOVSX,
  7310. {$ifdef x86_64}
  7311. A_MOVSXD,
  7312. {$endif x86_64}
  7313. A_MOVZX,
  7314. A_MOVAPS,
  7315. A_MOVUPS,
  7316. A_MOVSD,
  7317. A_MOVAPD,
  7318. A_MOVUPD,
  7319. A_MOVDQA,
  7320. A_MOVDQU,
  7321. A_VMOVSS,
  7322. A_VMOVAPS,
  7323. A_VMOVUPS,
  7324. A_VMOVSD,
  7325. A_VMOVAPD,
  7326. A_VMOVUPD,
  7327. A_VMOVDQA,
  7328. A_VMOVDQU:
  7329. if ((current_settings.optimizerswitches * [cs_opt_level3, cs_opt_size]) <> [cs_opt_size]) and
  7330. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  7331. begin
  7332. Result := True;
  7333. Exit;
  7334. end;
  7335. else
  7336. ;
  7337. end;
  7338. end;
  7339. end;
  7340. end;
  7341. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  7342. begin
  7343. CanBeCMOV:=assigned(p) and
  7344. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  7345. { we can't use cmov ref,reg because
  7346. ref could be nil and cmov still throws an exception
  7347. if ref=nil but the mov isn't done (FK)
  7348. or ((taicpu(p).oper[0]^.typ = top_ref) and
  7349. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  7350. }
  7351. (taicpu(p).oper[1]^.typ = top_reg) and
  7352. (
  7353. (taicpu(p).oper[0]^.typ = top_reg) or
  7354. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  7355. it is not expected that this can cause a seg. violation }
  7356. (
  7357. (taicpu(p).oper[0]^.typ = top_ref) and
  7358. IsRefSafe(taicpu(p).oper[0]^.ref)
  7359. )
  7360. );
  7361. end;
  7362. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  7363. var
  7364. hp1,hp2: tai;
  7365. {$ifndef i8086}
  7366. hp3,hp4,hpmov2, hp5: tai;
  7367. l : Longint;
  7368. condition : TAsmCond;
  7369. {$endif i8086}
  7370. carryadd_opcode : TAsmOp;
  7371. symbol: TAsmSymbol;
  7372. reg: tsuperregister;
  7373. increg, tmpreg: TRegister;
  7374. begin
  7375. result:=false;
  7376. if GetNextInstruction(p,hp1) and (hp1.typ=ait_instruction) then
  7377. begin
  7378. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  7379. if (
  7380. (
  7381. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  7382. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  7383. (Taicpu(hp1).oper[0]^.val=1)
  7384. ) or
  7385. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  7386. ) and
  7387. GetNextInstruction(hp1,hp2) and
  7388. SkipAligns(hp2, hp2) and
  7389. (hp2.typ = ait_label) and
  7390. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  7391. { jb @@1 cmc
  7392. inc/dec operand --> adc/sbb operand,0
  7393. @@1:
  7394. ... and ...
  7395. jnb @@1
  7396. inc/dec operand --> adc/sbb operand,0
  7397. @@1: }
  7398. begin
  7399. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  7400. begin
  7401. case taicpu(hp1).opcode of
  7402. A_INC,
  7403. A_ADD:
  7404. carryadd_opcode:=A_ADC;
  7405. A_DEC,
  7406. A_SUB:
  7407. carryadd_opcode:=A_SBB;
  7408. else
  7409. InternalError(2021011001);
  7410. end;
  7411. Taicpu(p).clearop(0);
  7412. Taicpu(p).ops:=0;
  7413. Taicpu(p).is_jmp:=false;
  7414. Taicpu(p).opcode:=A_CMC;
  7415. Taicpu(p).condition:=C_NONE;
  7416. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  7417. Taicpu(hp1).ops:=2;
  7418. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  7419. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  7420. else
  7421. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  7422. Taicpu(hp1).loadconst(0,0);
  7423. Taicpu(hp1).opcode:=carryadd_opcode;
  7424. result:=true;
  7425. exit;
  7426. end
  7427. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  7428. begin
  7429. case taicpu(hp1).opcode of
  7430. A_INC,
  7431. A_ADD:
  7432. carryadd_opcode:=A_ADC;
  7433. A_DEC,
  7434. A_SUB:
  7435. carryadd_opcode:=A_SBB;
  7436. else
  7437. InternalError(2021011002);
  7438. end;
  7439. Taicpu(hp1).ops:=2;
  7440. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  7441. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  7442. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  7443. else
  7444. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  7445. Taicpu(hp1).loadconst(0,0);
  7446. Taicpu(hp1).opcode:=carryadd_opcode;
  7447. RemoveCurrentP(p, hp1);
  7448. result:=true;
  7449. exit;
  7450. end
  7451. {
  7452. jcc @@1 setcc tmpreg
  7453. inc/dec/add/sub operand -> (movzx tmpreg)
  7454. @@1: add/sub tmpreg,operand
  7455. While this increases code size slightly, it makes the code much faster if the
  7456. jump is unpredictable
  7457. }
  7458. else if not(cs_opt_size in current_settings.optimizerswitches) then
  7459. begin
  7460. { search for an available register which is volatile }
  7461. for reg in tcpuregisterset do
  7462. begin
  7463. if
  7464. {$if defined(i386) or defined(i8086)}
  7465. { Only use registers whose lowest 8-bits can Be accessed }
  7466. (reg in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) and
  7467. {$endif i386 or i8086}
  7468. (reg in paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption)) and
  7469. not(reg in UsedRegs[R_INTREGISTER].GetUsedRegs)
  7470. { We don't need to check if tmpreg is in hp1 or not, because
  7471. it will be marked as in use at p (if not, this is
  7472. indictive of a compiler bug). }
  7473. then
  7474. begin
  7475. TAsmLabel(symbol).decrefs;
  7476. increg := newreg(R_INTREGISTER,reg,R_SUBL);
  7477. Taicpu(p).clearop(0);
  7478. Taicpu(p).ops:=1;
  7479. Taicpu(p).is_jmp:=false;
  7480. Taicpu(p).opcode:=A_SETcc;
  7481. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  7482. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  7483. Taicpu(p).loadreg(0,increg);
  7484. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  7485. begin
  7486. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  7487. R_SUBW:
  7488. begin
  7489. tmpreg := newreg(R_INTREGISTER,reg,R_SUBW);
  7490. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  7491. end;
  7492. R_SUBD:
  7493. begin
  7494. tmpreg := newreg(R_INTREGISTER,reg,R_SUBD);
  7495. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  7496. end;
  7497. {$ifdef x86_64}
  7498. R_SUBQ:
  7499. begin
  7500. { MOVZX doesn't have a 64-bit variant, because
  7501. the 32-bit version implicitly zeroes the
  7502. upper 32-bits of the destination register }
  7503. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,
  7504. newreg(R_INTREGISTER,reg,R_SUBD));
  7505. tmpreg := newreg(R_INTREGISTER,reg,R_SUBQ);
  7506. end;
  7507. {$endif x86_64}
  7508. else
  7509. Internalerror(2020030601);
  7510. end;
  7511. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  7512. asml.InsertAfter(hp2,p);
  7513. end
  7514. else
  7515. tmpreg := increg;
  7516. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  7517. begin
  7518. Taicpu(hp1).ops:=2;
  7519. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  7520. end;
  7521. Taicpu(hp1).loadreg(0,tmpreg);
  7522. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  7523. Result := True;
  7524. { p is no longer a Jcc instruction, so exit }
  7525. Exit;
  7526. end;
  7527. end;
  7528. end;
  7529. end;
  7530. { Detect the following:
  7531. jmp<cond> @Lbl1
  7532. jmp @Lbl2
  7533. ...
  7534. @Lbl1:
  7535. ret
  7536. Change to:
  7537. jmp<inv_cond> @Lbl2
  7538. ret
  7539. }
  7540. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  7541. begin
  7542. hp2:=getlabelwithsym(TAsmLabel(symbol));
  7543. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  7544. MatchInstruction(hp2,A_RET,[S_NO]) then
  7545. begin
  7546. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7547. { Change label address to that of the unconditional jump }
  7548. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  7549. TAsmLabel(symbol).DecRefs;
  7550. taicpu(hp1).opcode := A_RET;
  7551. taicpu(hp1).is_jmp := false;
  7552. taicpu(hp1).ops := taicpu(hp2).ops;
  7553. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  7554. case taicpu(hp2).ops of
  7555. 0:
  7556. taicpu(hp1).clearop(0);
  7557. 1:
  7558. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  7559. else
  7560. internalerror(2016041302);
  7561. end;
  7562. end;
  7563. {$ifndef i8086}
  7564. end
  7565. {
  7566. convert
  7567. j<c> .L1
  7568. mov 1,reg
  7569. jmp .L2
  7570. .L1
  7571. mov 0,reg
  7572. .L2
  7573. into
  7574. mov 0,reg
  7575. set<not(c)> reg
  7576. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7577. would destroy the flag contents
  7578. }
  7579. else if MatchInstruction(hp1,A_MOV,[]) and
  7580. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7581. {$ifdef i386}
  7582. (
  7583. { Under i386, ESI, EDI, EBP and ESP
  7584. don't have an 8-bit representation }
  7585. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7586. ) and
  7587. {$endif i386}
  7588. (taicpu(hp1).oper[0]^.val=1) and
  7589. GetNextInstruction(hp1,hp2) and
  7590. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7591. GetNextInstruction(hp2,hp3) and
  7592. { skip align }
  7593. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  7594. (hp3.typ=ait_label) and
  7595. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7596. (tai_label(hp3).labsym.getrefs=1) and
  7597. GetNextInstruction(hp3,hp4) and
  7598. MatchInstruction(hp4,A_MOV,[]) and
  7599. MatchOpType(taicpu(hp4),top_const,top_reg) and
  7600. (taicpu(hp4).oper[0]^.val=0) and
  7601. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7602. GetNextInstruction(hp4,hp5) and
  7603. (hp5.typ=ait_label) and
  7604. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  7605. (tai_label(hp5).labsym.getrefs=1) then
  7606. begin
  7607. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  7608. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  7609. { remove last label }
  7610. RemoveInstruction(hp5);
  7611. { remove second label }
  7612. RemoveInstruction(hp3);
  7613. { if align is present remove it }
  7614. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  7615. RemoveInstruction(hp3);
  7616. { remove jmp }
  7617. RemoveInstruction(hp2);
  7618. if taicpu(hp1).opsize=S_B then
  7619. RemoveInstruction(hp1)
  7620. else
  7621. taicpu(hp1).loadconst(0,0);
  7622. taicpu(hp4).opcode:=A_SETcc;
  7623. taicpu(hp4).opsize:=S_B;
  7624. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  7625. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  7626. taicpu(hp4).opercnt:=1;
  7627. taicpu(hp4).ops:=1;
  7628. taicpu(hp4).freeop(1);
  7629. RemoveCurrentP(p);
  7630. Result:=true;
  7631. exit;
  7632. end
  7633. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  7634. begin
  7635. { check for
  7636. jCC xxx
  7637. <several movs>
  7638. xxx:
  7639. }
  7640. l:=0;
  7641. while assigned(hp1) and
  7642. CanBeCMOV(hp1) and
  7643. { stop on labels }
  7644. not(hp1.typ=ait_label) do
  7645. begin
  7646. inc(l);
  7647. GetNextInstruction(hp1,hp1);
  7648. end;
  7649. if assigned(hp1) then
  7650. begin
  7651. if FindLabel(tasmlabel(symbol),hp1) then
  7652. begin
  7653. if (l<=4) and (l>0) then
  7654. begin
  7655. condition:=inverse_cond(taicpu(p).condition);
  7656. GetNextInstruction(p,hp1);
  7657. repeat
  7658. if not Assigned(hp1) then
  7659. InternalError(2018062900);
  7660. taicpu(hp1).opcode:=A_CMOVcc;
  7661. taicpu(hp1).condition:=condition;
  7662. UpdateUsedRegs(hp1);
  7663. GetNextInstruction(hp1,hp1);
  7664. until not(CanBeCMOV(hp1));
  7665. { Remember what hp1 is in case there's multiple aligns to get rid of }
  7666. hp2 := hp1;
  7667. repeat
  7668. if not Assigned(hp2) then
  7669. InternalError(2018062910);
  7670. case hp2.typ of
  7671. ait_label:
  7672. { What we expected - break out of the loop (it won't be a dead label at the top of
  7673. a cluster because that was optimised at an earlier stage) }
  7674. Break;
  7675. ait_align:
  7676. { Go to the next entry until a label is found (may be multiple aligns before it) }
  7677. begin
  7678. hp2 := tai(hp2.Next);
  7679. Continue;
  7680. end;
  7681. else
  7682. begin
  7683. { Might be a comment or temporary allocation entry }
  7684. if not (hp2.typ in SkipInstr) then
  7685. InternalError(2018062911);
  7686. hp2 := tai(hp2.Next);
  7687. Continue;
  7688. end;
  7689. end;
  7690. until False;
  7691. { Now we can safely decrement the reference count }
  7692. tasmlabel(symbol).decrefs;
  7693. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  7694. { Remove the original jump }
  7695. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  7696. GetNextInstruction(hp2, p); { Instruction after the label }
  7697. { Remove the label if this is its final reference }
  7698. if (tasmlabel(symbol).getrefs=0) then
  7699. StripLabelFast(hp1);
  7700. if Assigned(p) then
  7701. begin
  7702. UpdateUsedRegs(p);
  7703. result:=true;
  7704. end;
  7705. exit;
  7706. end;
  7707. end
  7708. else
  7709. begin
  7710. { check further for
  7711. jCC xxx
  7712. <several movs 1>
  7713. jmp yyy
  7714. xxx:
  7715. <several movs 2>
  7716. yyy:
  7717. }
  7718. { hp2 points to jmp yyy }
  7719. hp2:=hp1;
  7720. { skip hp1 to xxx (or an align right before it) }
  7721. GetNextInstruction(hp1, hp1);
  7722. if assigned(hp2) and
  7723. assigned(hp1) and
  7724. (l<=3) and
  7725. (hp2.typ=ait_instruction) and
  7726. (taicpu(hp2).is_jmp) and
  7727. (taicpu(hp2).condition=C_None) and
  7728. { real label and jump, no further references to the
  7729. label are allowed }
  7730. (tasmlabel(symbol).getrefs=1) and
  7731. FindLabel(tasmlabel(symbol),hp1) then
  7732. begin
  7733. l:=0;
  7734. { skip hp1 to <several moves 2> }
  7735. if (hp1.typ = ait_align) then
  7736. GetNextInstruction(hp1, hp1);
  7737. GetNextInstruction(hp1, hpmov2);
  7738. hp1 := hpmov2;
  7739. while assigned(hp1) and
  7740. CanBeCMOV(hp1) do
  7741. begin
  7742. inc(l);
  7743. GetNextInstruction(hp1, hp1);
  7744. end;
  7745. { hp1 points to yyy (or an align right before it) }
  7746. hp3 := hp1;
  7747. if assigned(hp1) and
  7748. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  7749. begin
  7750. condition:=inverse_cond(taicpu(p).condition);
  7751. GetNextInstruction(p,hp1);
  7752. repeat
  7753. taicpu(hp1).opcode:=A_CMOVcc;
  7754. taicpu(hp1).condition:=condition;
  7755. UpdateUsedRegs(hp1);
  7756. GetNextInstruction(hp1,hp1);
  7757. until not(assigned(hp1)) or
  7758. not(CanBeCMOV(hp1));
  7759. condition:=inverse_cond(condition);
  7760. hp1 := hpmov2;
  7761. { hp1 is now at <several movs 2> }
  7762. while Assigned(hp1) and CanBeCMOV(hp1) do
  7763. begin
  7764. taicpu(hp1).opcode:=A_CMOVcc;
  7765. taicpu(hp1).condition:=condition;
  7766. UpdateUsedRegs(hp1);
  7767. GetNextInstruction(hp1,hp1);
  7768. end;
  7769. hp1 := p;
  7770. { Get first instruction after label }
  7771. GetNextInstruction(hp3, p);
  7772. if assigned(p) and (hp3.typ = ait_align) then
  7773. GetNextInstruction(p, p);
  7774. { Don't dereference yet, as doing so will cause
  7775. GetNextInstruction to skip the label and
  7776. optional align marker. [Kit] }
  7777. GetNextInstruction(hp2, hp4);
  7778. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  7779. { remove jCC }
  7780. RemoveInstruction(hp1);
  7781. { Now we can safely decrement it }
  7782. tasmlabel(symbol).decrefs;
  7783. { Remove label xxx (it will have a ref of zero due to the initial check }
  7784. StripLabelFast(hp4);
  7785. { remove jmp }
  7786. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  7787. RemoveInstruction(hp2);
  7788. { As before, now we can safely decrement it }
  7789. tasmlabel(symbol).decrefs;
  7790. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  7791. if tasmlabel(symbol).getrefs = 0 then
  7792. StripLabelFast(hp3);
  7793. if Assigned(p) then
  7794. begin
  7795. UpdateUsedRegs(p);
  7796. result:=true;
  7797. end;
  7798. exit;
  7799. end;
  7800. end;
  7801. end;
  7802. end;
  7803. {$endif i8086}
  7804. end;
  7805. end;
  7806. end;
  7807. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  7808. var
  7809. hp1,hp2: tai;
  7810. reg_and_hp1_is_instr: Boolean;
  7811. begin
  7812. result:=false;
  7813. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  7814. GetNextInstruction(p,hp1) and
  7815. (hp1.typ = ait_instruction);
  7816. if reg_and_hp1_is_instr and
  7817. (
  7818. (taicpu(hp1).opcode <> A_LEA) or
  7819. { If the LEA instruction can be converted into an arithmetic instruction,
  7820. it may be possible to then fold it. }
  7821. (
  7822. { If the flags register is in use, don't change the instruction
  7823. to an ADD otherwise this will scramble the flags. [Kit] }
  7824. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  7825. ConvertLEA(taicpu(hp1))
  7826. )
  7827. ) and
  7828. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  7829. GetNextInstruction(hp1,hp2) and
  7830. MatchInstruction(hp2,A_MOV,[]) and
  7831. (taicpu(hp2).oper[0]^.typ = top_reg) and
  7832. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  7833. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  7834. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  7835. {$ifdef i386}
  7836. { not all registers have byte size sub registers on i386 }
  7837. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  7838. {$endif i386}
  7839. (((taicpu(hp1).ops=2) and
  7840. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7841. ((taicpu(hp1).ops=1) and
  7842. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  7843. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  7844. begin
  7845. { change movsX/movzX reg/ref, reg2
  7846. add/sub/or/... reg3/$const, reg2
  7847. mov reg2 reg/ref
  7848. to add/sub/or/... reg3/$const, reg/ref }
  7849. { by example:
  7850. movswl %si,%eax movswl %si,%eax p
  7851. decl %eax addl %edx,%eax hp1
  7852. movw %ax,%si movw %ax,%si hp2
  7853. ->
  7854. movswl %si,%eax movswl %si,%eax p
  7855. decw %eax addw %edx,%eax hp1
  7856. movw %ax,%si movw %ax,%si hp2
  7857. }
  7858. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  7859. {
  7860. ->
  7861. movswl %si,%eax movswl %si,%eax p
  7862. decw %si addw %dx,%si hp1
  7863. movw %ax,%si movw %ax,%si hp2
  7864. }
  7865. case taicpu(hp1).ops of
  7866. 1:
  7867. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  7868. 2:
  7869. begin
  7870. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  7871. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  7872. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  7873. end;
  7874. else
  7875. internalerror(2008042702);
  7876. end;
  7877. {
  7878. ->
  7879. decw %si addw %dx,%si p
  7880. }
  7881. DebugMsg(SPeepholeOptimization + 'var3',p);
  7882. RemoveCurrentP(p, hp1);
  7883. RemoveInstruction(hp2);
  7884. end
  7885. else if reg_and_hp1_is_instr and
  7886. (taicpu(hp1).opcode = A_MOV) and
  7887. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7888. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  7889. {$ifdef x86_64}
  7890. { check for implicit extension to 64 bit }
  7891. or
  7892. ((taicpu(p).opsize in [S_BL,S_WL]) and
  7893. (taicpu(hp1).opsize=S_Q) and
  7894. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  7895. )
  7896. {$endif x86_64}
  7897. )
  7898. then
  7899. begin
  7900. { change
  7901. movx %reg1,%reg2
  7902. mov %reg2,%reg3
  7903. dealloc %reg2
  7904. into
  7905. movx %reg,%reg3
  7906. }
  7907. TransferUsedRegs(TmpUsedRegs);
  7908. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7909. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7910. begin
  7911. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  7912. {$ifdef x86_64}
  7913. if (taicpu(p).opsize in [S_BL,S_WL]) and
  7914. (taicpu(hp1).opsize=S_Q) then
  7915. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  7916. else
  7917. {$endif x86_64}
  7918. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7919. RemoveInstruction(hp1);
  7920. end;
  7921. end
  7922. else if reg_and_hp1_is_instr and
  7923. (taicpu(hp1).opcode = A_MOV) and
  7924. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7925. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  7926. (taicpu(hp1).opsize=S_B)) or
  7927. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  7928. (taicpu(hp1).opsize=S_W))
  7929. {$ifdef x86_64}
  7930. or ((taicpu(p).opsize=S_LQ) and
  7931. (taicpu(hp1).opsize=S_L))
  7932. {$endif x86_64}
  7933. ) and
  7934. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  7935. begin
  7936. { change
  7937. movx %reg1,%reg2
  7938. mov %reg2,%reg3
  7939. dealloc %reg2
  7940. into
  7941. mov %reg1,%reg3
  7942. if the second mov accesses only the bits stored in reg1
  7943. }
  7944. TransferUsedRegs(TmpUsedRegs);
  7945. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7946. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7947. begin
  7948. DebugMsg(SPeepholeOptimization + 'MovxMov2Mov',p);
  7949. if taicpu(p).oper[0]^.typ=top_reg then
  7950. begin
  7951. case taicpu(hp1).opsize of
  7952. S_B:
  7953. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  7954. S_W:
  7955. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  7956. S_L:
  7957. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  7958. else
  7959. Internalerror(2020102301);
  7960. end;
  7961. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  7962. end
  7963. else
  7964. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  7965. RemoveCurrentP(p);
  7966. result:=true;
  7967. exit;
  7968. end;
  7969. end
  7970. else if reg_and_hp1_is_instr and
  7971. (taicpu(p).oper[0]^.typ = top_reg) and
  7972. (
  7973. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  7974. ) and
  7975. (taicpu(hp1).oper[0]^.typ = top_const) and
  7976. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  7977. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  7978. { Minimum shift value allowed is the bit difference between the sizes }
  7979. (taicpu(hp1).oper[0]^.val >=
  7980. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  7981. 8 * (
  7982. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  7983. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  7984. )
  7985. ) then
  7986. begin
  7987. { For:
  7988. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  7989. shl/sal ##, %reg1
  7990. Remove the movsx/movzx instruction if the shift overwrites the
  7991. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  7992. }
  7993. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  7994. RemoveCurrentP(p, hp1);
  7995. Result := True;
  7996. Exit;
  7997. end
  7998. else if reg_and_hp1_is_instr and
  7999. (taicpu(p).oper[0]^.typ = top_reg) and
  8000. (
  8001. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  8002. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  8003. ) and
  8004. (taicpu(hp1).oper[0]^.typ = top_const) and
  8005. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  8006. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  8007. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  8008. (taicpu(hp1).oper[0]^.val <
  8009. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  8010. 8 * (
  8011. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  8012. )
  8013. ) then
  8014. begin
  8015. { For:
  8016. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  8017. sar ##, %reg1 shr ##, %reg1
  8018. Move the shift to before the movx instruction if the shift value
  8019. is not too large.
  8020. }
  8021. asml.Remove(hp1);
  8022. asml.InsertBefore(hp1, p);
  8023. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  8024. case taicpu(p).opsize of
  8025. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  8026. taicpu(hp1).opsize := S_B;
  8027. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  8028. taicpu(hp1).opsize := S_W;
  8029. {$ifdef x86_64}
  8030. S_LQ:
  8031. taicpu(hp1).opsize := S_L;
  8032. {$endif}
  8033. else
  8034. InternalError(2020112401);
  8035. end;
  8036. if (taicpu(hp1).opcode = A_SHR) then
  8037. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  8038. else
  8039. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  8040. Result := True;
  8041. end
  8042. else if taicpu(p).opcode=A_MOVZX then
  8043. begin
  8044. { removes superfluous And's after movzx's }
  8045. if reg_and_hp1_is_instr and
  8046. (taicpu(hp1).opcode = A_AND) and
  8047. MatchOpType(taicpu(hp1),top_const,top_reg) and
  8048. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  8049. {$ifdef x86_64}
  8050. { check for implicit extension to 64 bit }
  8051. or
  8052. ((taicpu(p).opsize in [S_BL,S_WL]) and
  8053. (taicpu(hp1).opsize=S_Q) and
  8054. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  8055. )
  8056. {$endif x86_64}
  8057. )
  8058. then
  8059. begin
  8060. case taicpu(p).opsize Of
  8061. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8062. if (taicpu(hp1).oper[0]^.val = $ff) then
  8063. begin
  8064. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  8065. RemoveInstruction(hp1);
  8066. Result:=true;
  8067. exit;
  8068. end;
  8069. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8070. if (taicpu(hp1).oper[0]^.val = $ffff) then
  8071. begin
  8072. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  8073. RemoveInstruction(hp1);
  8074. Result:=true;
  8075. exit;
  8076. end;
  8077. {$ifdef x86_64}
  8078. S_LQ:
  8079. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  8080. begin
  8081. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  8082. RemoveInstruction(hp1);
  8083. Result:=true;
  8084. exit;
  8085. end;
  8086. {$endif x86_64}
  8087. else
  8088. ;
  8089. end;
  8090. { we cannot get rid of the and, but can we get rid of the movz ?}
  8091. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  8092. begin
  8093. case taicpu(p).opsize Of
  8094. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8095. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  8096. begin
  8097. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  8098. RemoveCurrentP(p,hp1);
  8099. Result:=true;
  8100. exit;
  8101. end;
  8102. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8103. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  8104. begin
  8105. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  8106. RemoveCurrentP(p,hp1);
  8107. Result:=true;
  8108. exit;
  8109. end;
  8110. {$ifdef x86_64}
  8111. S_LQ:
  8112. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  8113. begin
  8114. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  8115. RemoveCurrentP(p,hp1);
  8116. Result:=true;
  8117. exit;
  8118. end;
  8119. {$endif x86_64}
  8120. else
  8121. ;
  8122. end;
  8123. end;
  8124. end;
  8125. { changes some movzx constructs to faster synonyms (all examples
  8126. are given with eax/ax, but are also valid for other registers)}
  8127. if MatchOpType(taicpu(p),top_reg,top_reg) then
  8128. begin
  8129. case taicpu(p).opsize of
  8130. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  8131. (the machine code is equivalent to movzbl %al,%eax), but the
  8132. code generator still generates that assembler instruction and
  8133. it is silently converted. This should probably be checked.
  8134. [Kit] }
  8135. S_BW:
  8136. begin
  8137. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  8138. (
  8139. not IsMOVZXAcceptable
  8140. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  8141. or (
  8142. (cs_opt_size in current_settings.optimizerswitches) and
  8143. (taicpu(p).oper[1]^.reg = NR_AX)
  8144. )
  8145. ) then
  8146. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  8147. begin
  8148. DebugMsg(SPeepholeOptimization + 'var7',p);
  8149. taicpu(p).opcode := A_AND;
  8150. taicpu(p).changeopsize(S_W);
  8151. taicpu(p).loadConst(0,$ff);
  8152. Result := True;
  8153. end
  8154. else if not IsMOVZXAcceptable and
  8155. GetNextInstruction(p, hp1) and
  8156. (tai(hp1).typ = ait_instruction) and
  8157. (taicpu(hp1).opcode = A_AND) and
  8158. MatchOpType(taicpu(hp1),top_const,top_reg) and
  8159. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8160. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  8161. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  8162. begin
  8163. DebugMsg(SPeepholeOptimization + 'var8',p);
  8164. taicpu(p).opcode := A_MOV;
  8165. taicpu(p).changeopsize(S_W);
  8166. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  8167. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  8168. Result := True;
  8169. end;
  8170. end;
  8171. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  8172. S_BL:
  8173. begin
  8174. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  8175. (
  8176. not IsMOVZXAcceptable
  8177. { and $0xff,%eax has a smaller encoding but risks a partial write penalty }
  8178. or (
  8179. (cs_opt_size in current_settings.optimizerswitches) and
  8180. (taicpu(p).oper[1]^.reg = NR_EAX)
  8181. )
  8182. ) then
  8183. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  8184. begin
  8185. DebugMsg(SPeepholeOptimization + 'var9',p);
  8186. taicpu(p).opcode := A_AND;
  8187. taicpu(p).changeopsize(S_L);
  8188. taicpu(p).loadConst(0,$ff);
  8189. Result := True;
  8190. end
  8191. else if not IsMOVZXAcceptable and
  8192. GetNextInstruction(p, hp1) and
  8193. (tai(hp1).typ = ait_instruction) and
  8194. (taicpu(hp1).opcode = A_AND) and
  8195. MatchOpType(taicpu(hp1),top_const,top_reg) and
  8196. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8197. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  8198. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  8199. begin
  8200. DebugMsg(SPeepholeOptimization + 'var10',p);
  8201. taicpu(p).opcode := A_MOV;
  8202. taicpu(p).changeopsize(S_L);
  8203. { do not use R_SUBWHOLE
  8204. as movl %rdx,%eax
  8205. is invalid in assembler PM }
  8206. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  8207. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  8208. Result := True;
  8209. end;
  8210. end;
  8211. {$endif i8086}
  8212. S_WL:
  8213. if not IsMOVZXAcceptable then
  8214. begin
  8215. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  8216. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  8217. begin
  8218. DebugMsg(SPeepholeOptimization + 'var11',p);
  8219. taicpu(p).opcode := A_AND;
  8220. taicpu(p).changeopsize(S_L);
  8221. taicpu(p).loadConst(0,$ffff);
  8222. Result := True;
  8223. end
  8224. else if GetNextInstruction(p, hp1) and
  8225. (tai(hp1).typ = ait_instruction) and
  8226. (taicpu(hp1).opcode = A_AND) and
  8227. (taicpu(hp1).oper[0]^.typ = top_const) and
  8228. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8229. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8230. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  8231. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  8232. begin
  8233. DebugMsg(SPeepholeOptimization + 'var12',p);
  8234. taicpu(p).opcode := A_MOV;
  8235. taicpu(p).changeopsize(S_L);
  8236. { do not use R_SUBWHOLE
  8237. as movl %rdx,%eax
  8238. is invalid in assembler PM }
  8239. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  8240. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  8241. Result := True;
  8242. end;
  8243. end;
  8244. else
  8245. InternalError(2017050705);
  8246. end;
  8247. end
  8248. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  8249. begin
  8250. if GetNextInstruction(p, hp1) and
  8251. (tai(hp1).typ = ait_instruction) and
  8252. (taicpu(hp1).opcode = A_AND) and
  8253. MatchOpType(taicpu(hp1),top_const,top_reg) and
  8254. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8255. begin
  8256. //taicpu(p).opcode := A_MOV;
  8257. case taicpu(p).opsize Of
  8258. S_BL:
  8259. begin
  8260. DebugMsg(SPeepholeOptimization + 'var13',p);
  8261. taicpu(hp1).changeopsize(S_L);
  8262. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  8263. end;
  8264. S_WL:
  8265. begin
  8266. DebugMsg(SPeepholeOptimization + 'var14',p);
  8267. taicpu(hp1).changeopsize(S_L);
  8268. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  8269. end;
  8270. S_BW:
  8271. begin
  8272. DebugMsg(SPeepholeOptimization + 'var15',p);
  8273. taicpu(hp1).changeopsize(S_W);
  8274. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  8275. end;
  8276. else
  8277. Internalerror(2017050704)
  8278. end;
  8279. Result := True;
  8280. end;
  8281. end;
  8282. end;
  8283. end;
  8284. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  8285. var
  8286. hp1, hp2 : tai;
  8287. MaskLength : Cardinal;
  8288. MaskedBits : TCgInt;
  8289. begin
  8290. Result:=false;
  8291. { There are no optimisations for reference targets }
  8292. if (taicpu(p).oper[1]^.typ <> top_reg) then
  8293. Exit;
  8294. while GetNextInstruction(p, hp1) and
  8295. (hp1.typ = ait_instruction) do
  8296. begin
  8297. if (taicpu(p).oper[0]^.typ = top_const) then
  8298. begin
  8299. case taicpu(hp1).opcode of
  8300. A_AND:
  8301. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  8302. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8303. { the second register must contain the first one, so compare their subreg types }
  8304. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  8305. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  8306. { change
  8307. and const1, reg
  8308. and const2, reg
  8309. to
  8310. and (const1 and const2), reg
  8311. }
  8312. begin
  8313. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  8314. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  8315. RemoveCurrentP(p, hp1);
  8316. Result:=true;
  8317. exit;
  8318. end;
  8319. A_CMP:
  8320. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  8321. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  8322. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  8323. { Just check that the condition on the next instruction is compatible }
  8324. GetNextInstruction(hp1, hp2) and
  8325. (hp2.typ = ait_instruction) and
  8326. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  8327. then
  8328. { change
  8329. and 2^n, reg
  8330. cmp 2^n, reg
  8331. j(c) / set(c) / cmov(c) (c is equal or not equal)
  8332. to
  8333. and 2^n, reg
  8334. test reg, reg
  8335. j(~c) / set(~c) / cmov(~c)
  8336. }
  8337. begin
  8338. { Keep TEST instruction in, rather than remove it, because
  8339. it may trigger other optimisations such as MovAndTest2Test }
  8340. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  8341. taicpu(hp1).opcode := A_TEST;
  8342. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  8343. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  8344. Result := True;
  8345. Exit;
  8346. end;
  8347. A_MOVZX:
  8348. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8349. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  8350. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8351. (
  8352. (
  8353. (taicpu(p).opsize=S_W) and
  8354. (taicpu(hp1).opsize=S_BW)
  8355. ) or
  8356. (
  8357. (taicpu(p).opsize=S_L) and
  8358. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  8359. )
  8360. {$ifdef x86_64}
  8361. or
  8362. (
  8363. (taicpu(p).opsize=S_Q) and
  8364. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  8365. )
  8366. {$endif x86_64}
  8367. ) then
  8368. begin
  8369. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  8370. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  8371. ) or
  8372. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  8373. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  8374. then
  8375. begin
  8376. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  8377. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  8378. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  8379. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  8380. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  8381. }
  8382. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  8383. RemoveInstruction(hp1);
  8384. { See if there are other optimisations possible }
  8385. Continue;
  8386. end;
  8387. end;
  8388. A_SHL:
  8389. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  8390. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  8391. begin
  8392. {$ifopt R+}
  8393. {$define RANGE_WAS_ON}
  8394. {$R-}
  8395. {$endif}
  8396. { get length of potential and mask }
  8397. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  8398. { really a mask? }
  8399. {$ifdef RANGE_WAS_ON}
  8400. {$R+}
  8401. {$endif}
  8402. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  8403. { unmasked part shifted out? }
  8404. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  8405. begin
  8406. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  8407. RemoveCurrentP(p, hp1);
  8408. Result:=true;
  8409. exit;
  8410. end;
  8411. end;
  8412. A_SHR:
  8413. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  8414. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  8415. (taicpu(hp1).oper[0]^.val <= 63) then
  8416. begin
  8417. { Does SHR combined with the AND cover all the bits?
  8418. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  8419. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  8420. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  8421. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  8422. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  8423. begin
  8424. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  8425. RemoveCurrentP(p, hp1);
  8426. Result := True;
  8427. Exit;
  8428. end;
  8429. end;
  8430. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  8431. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  8432. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  8433. begin
  8434. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  8435. (
  8436. (
  8437. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  8438. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  8439. ) or (
  8440. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  8441. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  8442. {$ifdef x86_64}
  8443. ) or (
  8444. (taicpu(hp1).opsize = S_LQ) and
  8445. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  8446. {$endif x86_64}
  8447. )
  8448. ) then
  8449. begin
  8450. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  8451. begin
  8452. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  8453. RemoveInstruction(hp1);
  8454. { See if there are other optimisations possible }
  8455. Continue;
  8456. end;
  8457. { The super-registers are the same though.
  8458. Note that this change by itself doesn't improve
  8459. code speed, but it opens up other optimisations. }
  8460. {$ifdef x86_64}
  8461. { Convert 64-bit register to 32-bit }
  8462. case taicpu(hp1).opsize of
  8463. S_BQ:
  8464. begin
  8465. taicpu(hp1).opsize := S_BL;
  8466. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  8467. end;
  8468. S_WQ:
  8469. begin
  8470. taicpu(hp1).opsize := S_WL;
  8471. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  8472. end
  8473. else
  8474. ;
  8475. end;
  8476. {$endif x86_64}
  8477. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  8478. taicpu(hp1).opcode := A_MOVZX;
  8479. { See if there are other optimisations possible }
  8480. Continue;
  8481. end;
  8482. end;
  8483. else
  8484. ;
  8485. end;
  8486. end;
  8487. if (taicpu(hp1).is_jmp) and
  8488. (taicpu(hp1).opcode<>A_JMP) and
  8489. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  8490. begin
  8491. { change
  8492. and x, reg
  8493. jxx
  8494. to
  8495. test x, reg
  8496. jxx
  8497. if reg is deallocated before the
  8498. jump, but only if it's a conditional jump (PFV)
  8499. }
  8500. taicpu(p).opcode := A_TEST;
  8501. Exit;
  8502. end;
  8503. Break;
  8504. end;
  8505. { Lone AND tests }
  8506. if (taicpu(p).oper[0]^.typ = top_const) then
  8507. begin
  8508. {
  8509. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  8510. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  8511. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  8512. }
  8513. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  8514. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  8515. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  8516. begin
  8517. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  8518. if taicpu(p).opsize = S_L then
  8519. begin
  8520. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  8521. Result := True;
  8522. end;
  8523. end;
  8524. end;
  8525. { Backward check to determine necessity of and %reg,%reg }
  8526. if (taicpu(p).oper[0]^.typ = top_reg) and
  8527. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  8528. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  8529. GetLastInstruction(p, hp2) and
  8530. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  8531. { Check size of adjacent instruction to determine if the AND is
  8532. effectively a null operation }
  8533. (
  8534. (taicpu(p).opsize = taicpu(hp2).opsize) or
  8535. { Note: Don't include S_Q }
  8536. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  8537. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  8538. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  8539. ) then
  8540. begin
  8541. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  8542. { If GetNextInstruction returned False, hp1 will be nil }
  8543. RemoveCurrentP(p, hp1);
  8544. Result := True;
  8545. Exit;
  8546. end;
  8547. end;
  8548. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  8549. var
  8550. hp1: tai; NewRef: TReference;
  8551. { This entire nested function is used in an if-statement below, but we
  8552. want to avoid all the used reg transfers and GetNextInstruction calls
  8553. until we really have to check }
  8554. function MemRegisterNotUsedLater: Boolean; inline;
  8555. var
  8556. hp2: tai;
  8557. begin
  8558. TransferUsedRegs(TmpUsedRegs);
  8559. hp2 := p;
  8560. repeat
  8561. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8562. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  8563. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  8564. end;
  8565. begin
  8566. Result := False;
  8567. if not GetNextInstruction(p, hp1) or (hp1.typ <> ait_instruction) then
  8568. Exit;
  8569. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) then
  8570. begin
  8571. { Change:
  8572. add %reg2,%reg1
  8573. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  8574. To:
  8575. mov/s/z #(%reg1,%reg2),%reg1
  8576. }
  8577. if MatchOpType(taicpu(p), top_reg, top_reg) and
  8578. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  8579. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  8580. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  8581. (
  8582. (
  8583. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  8584. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  8585. { r/esp cannot be an index }
  8586. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  8587. ) or (
  8588. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  8589. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  8590. )
  8591. ) and (
  8592. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  8593. (
  8594. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  8595. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  8596. MemRegisterNotUsedLater
  8597. )
  8598. ) then
  8599. begin
  8600. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  8601. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  8602. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  8603. RemoveCurrentp(p, hp1);
  8604. Result := True;
  8605. Exit;
  8606. end;
  8607. { Change:
  8608. addl/q $x,%reg1
  8609. movl/q %reg1,%reg2
  8610. To:
  8611. leal/q $x(%reg1),%reg2
  8612. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  8613. Breaks the dependency chain.
  8614. }
  8615. if MatchOpType(taicpu(p),top_const,top_reg) and
  8616. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  8617. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8618. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  8619. (
  8620. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  8621. not (cs_opt_size in current_settings.optimizerswitches) or
  8622. (
  8623. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  8624. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  8625. )
  8626. ) then
  8627. begin
  8628. { Change the MOV instruction to a LEA instruction, and update the
  8629. first operand }
  8630. reference_reset(NewRef, 1, []);
  8631. NewRef.base := taicpu(p).oper[1]^.reg;
  8632. NewRef.scalefactor := 1;
  8633. NewRef.offset := taicpu(p).oper[0]^.val;
  8634. taicpu(hp1).opcode := A_LEA;
  8635. taicpu(hp1).loadref(0, NewRef);
  8636. TransferUsedRegs(TmpUsedRegs);
  8637. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8638. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  8639. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  8640. begin
  8641. { Move what is now the LEA instruction to before the SUB instruction }
  8642. Asml.Remove(hp1);
  8643. Asml.InsertBefore(hp1, p);
  8644. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  8645. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  8646. p := hp1;
  8647. end
  8648. else
  8649. begin
  8650. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  8651. RemoveCurrentP(p, hp1);
  8652. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', p);
  8653. end;
  8654. Result := True;
  8655. end;
  8656. end;
  8657. end;
  8658. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  8659. begin
  8660. Result:=false;
  8661. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  8662. begin
  8663. if MatchReference(taicpu(p).oper[0]^.ref^,taicpu(p).oper[1]^.reg,NR_INVALID) and
  8664. (taicpu(p).oper[0]^.ref^.index<>NR_NO) then
  8665. begin
  8666. taicpu(p).loadreg(1,taicpu(p).oper[0]^.ref^.base);
  8667. taicpu(p).loadreg(0,taicpu(p).oper[0]^.ref^.index);
  8668. taicpu(p).opcode:=A_ADD;
  8669. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  8670. result:=true;
  8671. end
  8672. else if MatchReference(taicpu(p).oper[0]^.ref^,NR_INVALID,taicpu(p).oper[1]^.reg) and
  8673. (taicpu(p).oper[0]^.ref^.base<>NR_NO) then
  8674. begin
  8675. taicpu(p).loadreg(1,taicpu(p).oper[0]^.ref^.index);
  8676. taicpu(p).loadreg(0,taicpu(p).oper[0]^.ref^.base);
  8677. taicpu(p).opcode:=A_ADD;
  8678. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  8679. result:=true;
  8680. end;
  8681. end;
  8682. end;
  8683. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  8684. var
  8685. hp1: tai; NewRef: TReference;
  8686. begin
  8687. { Change:
  8688. subl/q $x,%reg1
  8689. movl/q %reg1,%reg2
  8690. To:
  8691. leal/q $-x(%reg1),%reg2
  8692. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  8693. Breaks the dependency chain and potentially permits the removal of
  8694. a CMP instruction if one follows.
  8695. }
  8696. Result := False;
  8697. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  8698. MatchOpType(taicpu(p),top_const,top_reg) and
  8699. GetNextInstruction(p, hp1) and
  8700. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  8701. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8702. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  8703. (
  8704. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  8705. not (cs_opt_size in current_settings.optimizerswitches) or
  8706. (
  8707. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  8708. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  8709. )
  8710. ) then
  8711. begin
  8712. { Change the MOV instruction to a LEA instruction, and update the
  8713. first operand }
  8714. reference_reset(NewRef, 1, []);
  8715. NewRef.base := taicpu(p).oper[1]^.reg;
  8716. NewRef.scalefactor := 1;
  8717. NewRef.offset := -taicpu(p).oper[0]^.val;
  8718. taicpu(hp1).opcode := A_LEA;
  8719. taicpu(hp1).loadref(0, NewRef);
  8720. TransferUsedRegs(TmpUsedRegs);
  8721. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8722. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  8723. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  8724. begin
  8725. { Move what is now the LEA instruction to before the SUB instruction }
  8726. Asml.Remove(hp1);
  8727. Asml.InsertBefore(hp1, p);
  8728. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  8729. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  8730. p := hp1;
  8731. end
  8732. else
  8733. begin
  8734. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  8735. RemoveCurrentP(p, hp1);
  8736. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', p);
  8737. end;
  8738. Result := True;
  8739. end;
  8740. end;
  8741. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  8742. begin
  8743. { we can skip all instructions not messing with the stack pointer }
  8744. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  8745. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  8746. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  8747. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  8748. ({(taicpu(hp1).ops=0) or }
  8749. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  8750. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  8751. ) and }
  8752. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  8753. )
  8754. ) do
  8755. GetNextInstruction(hp1,hp1);
  8756. Result:=assigned(hp1);
  8757. end;
  8758. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  8759. var
  8760. hp1, hp2, hp3, hp4, hp5: tai;
  8761. begin
  8762. Result:=false;
  8763. hp5:=nil;
  8764. { replace
  8765. leal(q) x(<stackpointer>),<stackpointer>
  8766. call procname
  8767. leal(q) -x(<stackpointer>),<stackpointer>
  8768. ret
  8769. by
  8770. jmp procname
  8771. but do it only on level 4 because it destroys stack back traces
  8772. }
  8773. if (cs_opt_level4 in current_settings.optimizerswitches) and
  8774. MatchOpType(taicpu(p),top_ref,top_reg) and
  8775. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  8776. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  8777. { the -8 or -24 are not required, but bail out early if possible,
  8778. higher values are unlikely }
  8779. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  8780. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  8781. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  8782. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  8783. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and
  8784. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  8785. GetNextInstruction(p, hp1) and
  8786. { Take a copy of hp1 }
  8787. SetAndTest(hp1, hp4) and
  8788. { trick to skip label }
  8789. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  8790. SkipSimpleInstructions(hp1) and
  8791. MatchInstruction(hp1,A_CALL,[S_NO]) and
  8792. GetNextInstruction(hp1, hp2) and
  8793. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  8794. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  8795. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  8796. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  8797. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  8798. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  8799. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  8800. (taicpu(hp2).oper[0]^.ref^.segment=NR_NO) and
  8801. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  8802. GetNextInstruction(hp2, hp3) and
  8803. { trick to skip label }
  8804. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  8805. (MatchInstruction(hp3,A_RET,[S_NO]) or
  8806. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  8807. SetAndTest(hp3,hp5) and
  8808. GetNextInstruction(hp3,hp3) and
  8809. MatchInstruction(hp3,A_RET,[S_NO])
  8810. )
  8811. ) and
  8812. (taicpu(hp3).ops=0) then
  8813. begin
  8814. taicpu(hp1).opcode := A_JMP;
  8815. taicpu(hp1).is_jmp := true;
  8816. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  8817. RemoveCurrentP(p, hp4);
  8818. RemoveInstruction(hp2);
  8819. RemoveInstruction(hp3);
  8820. if Assigned(hp5) then
  8821. begin
  8822. AsmL.Remove(hp5);
  8823. ASmL.InsertBefore(hp5,hp1)
  8824. end;
  8825. Result:=true;
  8826. end;
  8827. end;
  8828. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  8829. {$ifdef x86_64}
  8830. var
  8831. hp1, hp2, hp3, hp4, hp5: tai;
  8832. {$endif x86_64}
  8833. begin
  8834. Result:=false;
  8835. {$ifdef x86_64}
  8836. hp5:=nil;
  8837. { replace
  8838. push %rax
  8839. call procname
  8840. pop %rcx
  8841. ret
  8842. by
  8843. jmp procname
  8844. but do it only on level 4 because it destroys stack back traces
  8845. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  8846. for all supported calling conventions
  8847. }
  8848. if (cs_opt_level4 in current_settings.optimizerswitches) and
  8849. MatchOpType(taicpu(p),top_reg) and
  8850. (taicpu(p).oper[0]^.reg=NR_RAX) and
  8851. GetNextInstruction(p, hp1) and
  8852. { Take a copy of hp1 }
  8853. SetAndTest(hp1, hp4) and
  8854. { trick to skip label }
  8855. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  8856. SkipSimpleInstructions(hp1) and
  8857. MatchInstruction(hp1,A_CALL,[S_NO]) and
  8858. GetNextInstruction(hp1, hp2) and
  8859. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  8860. MatchOpType(taicpu(hp2),top_reg) and
  8861. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  8862. GetNextInstruction(hp2, hp3) and
  8863. { trick to skip label }
  8864. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  8865. (MatchInstruction(hp3,A_RET,[S_NO]) or
  8866. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  8867. SetAndTest(hp3,hp5) and
  8868. GetNextInstruction(hp3,hp3) and
  8869. MatchInstruction(hp3,A_RET,[S_NO])
  8870. )
  8871. ) and
  8872. (taicpu(hp3).ops=0) then
  8873. begin
  8874. taicpu(hp1).opcode := A_JMP;
  8875. taicpu(hp1).is_jmp := true;
  8876. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  8877. RemoveCurrentP(p, hp4);
  8878. RemoveInstruction(hp2);
  8879. RemoveInstruction(hp3);
  8880. if Assigned(hp5) then
  8881. begin
  8882. AsmL.Remove(hp5);
  8883. ASmL.InsertBefore(hp5,hp1)
  8884. end;
  8885. Result:=true;
  8886. end;
  8887. {$endif x86_64}
  8888. end;
  8889. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  8890. var
  8891. Value, RegName: string;
  8892. begin
  8893. Result:=false;
  8894. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  8895. begin
  8896. case taicpu(p).oper[0]^.val of
  8897. 0:
  8898. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  8899. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  8900. begin
  8901. { change "mov $0,%reg" into "xor %reg,%reg" }
  8902. taicpu(p).opcode := A_XOR;
  8903. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  8904. Result := True;
  8905. end;
  8906. $1..$FFFFFFFF:
  8907. begin
  8908. { Code size reduction by J. Gareth "Kit" Moreton }
  8909. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  8910. case taicpu(p).opsize of
  8911. S_Q:
  8912. begin
  8913. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  8914. Value := debug_tostr(taicpu(p).oper[0]^.val);
  8915. { The actual optimization }
  8916. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  8917. taicpu(p).changeopsize(S_L);
  8918. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  8919. Result := True;
  8920. end;
  8921. else
  8922. { Do nothing };
  8923. end;
  8924. end;
  8925. -1:
  8926. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  8927. if (cs_opt_size in current_settings.optimizerswitches) and
  8928. (taicpu(p).opsize <> S_B) and
  8929. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  8930. begin
  8931. { change "mov $-1,%reg" into "or $-1,%reg" }
  8932. { NOTES:
  8933. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  8934. - This operation creates a false dependency on the register, so only do it when optimising for size
  8935. - 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
  8936. }
  8937. taicpu(p).opcode := A_OR;
  8938. Result := True;
  8939. end;
  8940. end;
  8941. end;
  8942. end;
  8943. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  8944. var
  8945. hp1: tai;
  8946. begin
  8947. { Detect:
  8948. andw x, %ax (0 <= x < $8000)
  8949. ...
  8950. movzwl %ax,%eax
  8951. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  8952. }
  8953. Result := False; if MatchOpType(taicpu(p), top_const, top_reg) and
  8954. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  8955. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  8956. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  8957. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  8958. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  8959. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  8960. begin
  8961. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  8962. taicpu(hp1).opcode := A_CWDE;
  8963. taicpu(hp1).clearop(0);
  8964. taicpu(hp1).clearop(1);
  8965. taicpu(hp1).ops := 0;
  8966. { A change was made, but not with p, so move forward 1 }
  8967. p := tai(p.Next);
  8968. Result := True;
  8969. end;
  8970. end;
  8971. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  8972. begin
  8973. Result := False;
  8974. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  8975. Exit;
  8976. { Convert:
  8977. movswl %ax,%eax -> cwtl
  8978. movslq %eax,%rax -> cdqe
  8979. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  8980. refer to the same opcode and depends only on the assembler's
  8981. current operand-size attribute. [Kit]
  8982. }
  8983. with taicpu(p) do
  8984. case opsize of
  8985. S_WL:
  8986. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  8987. begin
  8988. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  8989. opcode := A_CWDE;
  8990. clearop(0);
  8991. clearop(1);
  8992. ops := 0;
  8993. Result := True;
  8994. end;
  8995. {$ifdef x86_64}
  8996. S_LQ:
  8997. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  8998. begin
  8999. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  9000. opcode := A_CDQE;
  9001. clearop(0);
  9002. clearop(1);
  9003. ops := 0;
  9004. Result := True;
  9005. end;
  9006. {$endif x86_64}
  9007. else
  9008. ;
  9009. end;
  9010. end;
  9011. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  9012. var
  9013. hp1: tai;
  9014. begin
  9015. { Detect:
  9016. shr x, %ax (x > 0)
  9017. ...
  9018. movzwl %ax,%eax
  9019. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  9020. }
  9021. Result := False;
  9022. if MatchOpType(taicpu(p), top_const, top_reg) and
  9023. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  9024. (taicpu(p).oper[0]^.val > 0) and
  9025. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  9026. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  9027. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  9028. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  9029. begin
  9030. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  9031. taicpu(hp1).opcode := A_CWDE;
  9032. taicpu(hp1).clearop(0);
  9033. taicpu(hp1).clearop(1);
  9034. taicpu(hp1).ops := 0;
  9035. { A change was made, but not with p, so move forward 1 }
  9036. p := tai(p.Next);
  9037. Result := True;
  9038. end;
  9039. end;
  9040. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  9041. begin
  9042. Result:=false;
  9043. { change "cmp $0, %reg" to "test %reg, %reg" }
  9044. if MatchOpType(taicpu(p),top_const,top_reg) and
  9045. (taicpu(p).oper[0]^.val = 0) then
  9046. begin
  9047. taicpu(p).opcode := A_TEST;
  9048. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  9049. Result:=true;
  9050. end;
  9051. end;
  9052. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  9053. var
  9054. IsTestConstX : Boolean;
  9055. hp1,hp2 : tai;
  9056. begin
  9057. Result:=false;
  9058. { removes the line marked with (x) from the sequence
  9059. and/or/xor/add/sub/... $x, %y
  9060. test/or %y, %y | test $-1, %y (x)
  9061. j(n)z _Label
  9062. as the first instruction already adjusts the ZF
  9063. %y operand may also be a reference }
  9064. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  9065. MatchOperand(taicpu(p).oper[0]^,-1);
  9066. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  9067. GetLastInstruction(p, hp1) and
  9068. (tai(hp1).typ = ait_instruction) and
  9069. GetNextInstruction(p,hp2) and
  9070. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  9071. case taicpu(hp1).opcode Of
  9072. A_ADD, A_SUB, A_OR, A_XOR, A_AND:
  9073. begin
  9074. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  9075. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  9076. { and in case of carry for A(E)/B(E)/C/NC }
  9077. ((taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  9078. ((taicpu(hp1).opcode <> A_ADD) and
  9079. (taicpu(hp1).opcode <> A_SUB))) then
  9080. begin
  9081. RemoveCurrentP(p, hp2);
  9082. Result:=true;
  9083. Exit;
  9084. end;
  9085. end;
  9086. A_SHL, A_SAL, A_SHR, A_SAR:
  9087. begin
  9088. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  9089. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  9090. { therefore, it's only safe to do this optimization for }
  9091. { shifts by a (nonzero) constant }
  9092. (taicpu(hp1).oper[0]^.typ = top_const) and
  9093. (taicpu(hp1).oper[0]^.val <> 0) and
  9094. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  9095. { and in case of carry for A(E)/B(E)/C/NC }
  9096. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  9097. begin
  9098. RemoveCurrentP(p, hp2);
  9099. Result:=true;
  9100. Exit;
  9101. end;
  9102. end;
  9103. A_DEC, A_INC, A_NEG:
  9104. begin
  9105. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  9106. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  9107. { and in case of carry for A(E)/B(E)/C/NC }
  9108. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  9109. begin
  9110. RemoveCurrentP(p, hp2);
  9111. Result:=true;
  9112. Exit;
  9113. end;
  9114. end
  9115. else
  9116. ;
  9117. end; { case }
  9118. { change "test $-1,%reg" into "test %reg,%reg" }
  9119. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  9120. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  9121. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  9122. if MatchInstruction(p, A_OR, []) and
  9123. { Can only match if they're both registers }
  9124. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  9125. begin
  9126. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  9127. taicpu(p).opcode := A_TEST;
  9128. { No need to set Result to True, as we've done all the optimisations we can }
  9129. end;
  9130. end;
  9131. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  9132. var
  9133. hp1,hp3 : tai;
  9134. {$ifndef x86_64}
  9135. hp2 : taicpu;
  9136. {$endif x86_64}
  9137. begin
  9138. Result:=false;
  9139. hp3:=nil;
  9140. {$ifndef x86_64}
  9141. { don't do this on modern CPUs, this really hurts them due to
  9142. broken call/ret pairing }
  9143. if (current_settings.optimizecputype < cpu_Pentium2) and
  9144. not(cs_create_pic in current_settings.moduleswitches) and
  9145. GetNextInstruction(p, hp1) and
  9146. MatchInstruction(hp1,A_JMP,[S_NO]) and
  9147. MatchOpType(taicpu(hp1),top_ref) and
  9148. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  9149. begin
  9150. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  9151. InsertLLItem(p.previous, p, hp2);
  9152. taicpu(p).opcode := A_JMP;
  9153. taicpu(p).is_jmp := true;
  9154. RemoveInstruction(hp1);
  9155. Result:=true;
  9156. end
  9157. else
  9158. {$endif x86_64}
  9159. { replace
  9160. call procname
  9161. ret
  9162. by
  9163. jmp procname
  9164. but do it only on level 4 because it destroys stack back traces
  9165. else if the subroutine is marked as no return, remove the ret
  9166. }
  9167. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  9168. (po_noreturn in current_procinfo.procdef.procoptions)) and
  9169. GetNextInstruction(p, hp1) and
  9170. (MatchInstruction(hp1,A_RET,[S_NO]) or
  9171. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  9172. SetAndTest(hp1,hp3) and
  9173. GetNextInstruction(hp1,hp1) and
  9174. MatchInstruction(hp1,A_RET,[S_NO])
  9175. )
  9176. ) and
  9177. (taicpu(hp1).ops=0) then
  9178. begin
  9179. if (cs_opt_level4 in current_settings.optimizerswitches) and
  9180. { we might destroy stack alignment here if we do not do a call }
  9181. (target_info.stackalign<=sizeof(SizeUInt)) then
  9182. begin
  9183. taicpu(p).opcode := A_JMP;
  9184. taicpu(p).is_jmp := true;
  9185. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  9186. end
  9187. else
  9188. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  9189. RemoveInstruction(hp1);
  9190. if Assigned(hp3) then
  9191. begin
  9192. AsmL.Remove(hp3);
  9193. AsmL.InsertBefore(hp3,p)
  9194. end;
  9195. Result:=true;
  9196. end;
  9197. end;
  9198. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  9199. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  9200. begin
  9201. case OpSize of
  9202. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9203. Result := (Val <= $FF) and (Val >= -128);
  9204. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9205. Result := (Val <= $FFFF) and (Val >= -32768);
  9206. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  9207. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  9208. else
  9209. Result := True;
  9210. end;
  9211. end;
  9212. var
  9213. hp1, hp2 : tai;
  9214. SizeChange: Boolean;
  9215. PreMessage: string;
  9216. begin
  9217. Result := False;
  9218. if (taicpu(p).oper[0]^.typ = top_reg) and
  9219. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  9220. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  9221. begin
  9222. { Change (using movzbl %al,%eax as an example):
  9223. movzbl %al, %eax movzbl %al, %eax
  9224. cmpl x, %eax testl %eax,%eax
  9225. To:
  9226. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  9227. movzbl %al, %eax movzbl %al, %eax
  9228. Smaller instruction and minimises pipeline stall as the CPU
  9229. doesn't have to wait for the register to get zero-extended. [Kit]
  9230. Also allow if the smaller of the two registers is being checked,
  9231. as this still removes the false dependency.
  9232. }
  9233. if
  9234. (
  9235. (
  9236. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  9237. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  9238. ) or (
  9239. { If MatchOperand returns True, they must both be registers }
  9240. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  9241. )
  9242. ) and
  9243. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  9244. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  9245. begin
  9246. 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);
  9247. asml.Remove(hp1);
  9248. asml.InsertBefore(hp1, p);
  9249. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  9250. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  9251. begin
  9252. taicpu(hp1).opcode := A_TEST;
  9253. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  9254. end;
  9255. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  9256. case taicpu(p).opsize of
  9257. S_BW, S_BL:
  9258. begin
  9259. SizeChange := taicpu(hp1).opsize <> S_B;
  9260. taicpu(hp1).changeopsize(S_B);
  9261. end;
  9262. S_WL:
  9263. begin
  9264. SizeChange := taicpu(hp1).opsize <> S_W;
  9265. taicpu(hp1).changeopsize(S_W);
  9266. end
  9267. else
  9268. InternalError(2020112701);
  9269. end;
  9270. UpdateUsedRegs(tai(p.Next));
  9271. { Check if the register is used aferwards - if not, we can
  9272. remove the movzx instruction completely }
  9273. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  9274. begin
  9275. { Hp1 is a better position than p for debugging purposes }
  9276. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  9277. RemoveCurrentp(p, hp1);
  9278. Result := True;
  9279. end;
  9280. if SizeChange then
  9281. DebugMsg(SPeepholeOptimization + PreMessage +
  9282. 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)
  9283. else
  9284. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  9285. Exit;
  9286. end;
  9287. { Change (using movzwl %ax,%eax as an example):
  9288. movzwl %ax, %eax
  9289. movb %al, (dest) (Register is smaller than read register in movz)
  9290. To:
  9291. movb %al, (dest) (Move one back to avoid a false dependency)
  9292. movzwl %ax, %eax
  9293. }
  9294. if (taicpu(hp1).opcode = A_MOV) and
  9295. (taicpu(hp1).oper[0]^.typ = top_reg) and
  9296. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  9297. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  9298. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  9299. begin
  9300. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  9301. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  9302. asml.Remove(hp1);
  9303. asml.InsertBefore(hp1, p);
  9304. if taicpu(hp1).oper[1]^.typ = top_reg then
  9305. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  9306. { Check if the register is used aferwards - if not, we can
  9307. remove the movzx instruction completely }
  9308. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  9309. begin
  9310. { Hp1 is a better position than p for debugging purposes }
  9311. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  9312. RemoveCurrentp(p, hp1);
  9313. Result := True;
  9314. end;
  9315. Exit;
  9316. end;
  9317. end;
  9318. {$ifdef x86_64}
  9319. { Code size reduction by J. Gareth "Kit" Moreton }
  9320. { Convert MOVZBQ and MOVZWQ to MOVZBL and MOVZWL respectively if it removes the REX prefix }
  9321. if (taicpu(p).opsize in [S_BQ, S_WQ]) and
  9322. (getsupreg(taicpu(p).oper[1]^.reg) in [RS_RAX, RS_RCX, RS_RDX, RS_RBX, RS_RSI, RS_RDI, RS_RBP, RS_RSP])
  9323. then
  9324. begin
  9325. { Has 64-bit register name and opcode suffix }
  9326. PreMessage := 'movz' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' -> movz';
  9327. { The actual optimization }
  9328. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  9329. if taicpu(p).opsize = S_BQ then
  9330. taicpu(p).changeopsize(S_BL)
  9331. else
  9332. taicpu(p).changeopsize(S_WL);
  9333. DebugMsg(SPeepholeOptimization + PreMessage +
  9334. debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (removes REX prefix)', p);
  9335. end;
  9336. {$endif}
  9337. end;
  9338. {$ifdef x86_64}
  9339. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  9340. var
  9341. PreMessage, RegName: string;
  9342. begin
  9343. { Code size reduction by J. Gareth "Kit" Moreton }
  9344. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  9345. as this removes the REX prefix }
  9346. Result := False;
  9347. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  9348. Exit;
  9349. if taicpu(p).oper[0]^.typ <> top_reg then
  9350. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  9351. InternalError(2018011500);
  9352. case taicpu(p).opsize of
  9353. S_Q:
  9354. begin
  9355. 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
  9356. begin
  9357. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  9358. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  9359. { The actual optimization }
  9360. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  9361. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  9362. taicpu(p).changeopsize(S_L);
  9363. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  9364. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (removes REX prefix)', p);
  9365. end;
  9366. end;
  9367. else
  9368. ;
  9369. end;
  9370. end;
  9371. {$endif}
  9372. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  9373. var
  9374. OperIdx: Integer;
  9375. begin
  9376. for OperIdx := 0 to p.ops - 1 do
  9377. if p.oper[OperIdx]^.typ = top_ref then
  9378. optimize_ref(p.oper[OperIdx]^.ref^, False);
  9379. end;
  9380. end.