aoptx86.pas 398 KB

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