AArch64InstrInfo.cpp 291 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317
  1. //===- AArch64InstrInfo.cpp - AArch64 Instruction Information -------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file contains the AArch64 implementation of the TargetInstrInfo class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "AArch64InstrInfo.h"
  13. #include "AArch64MachineFunctionInfo.h"
  14. #include "AArch64Subtarget.h"
  15. #include "MCTargetDesc/AArch64AddressingModes.h"
  16. #include "Utils/AArch64BaseInfo.h"
  17. #include "llvm/ADT/ArrayRef.h"
  18. #include "llvm/ADT/STLExtras.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/CodeGen/MachineBasicBlock.h"
  21. #include "llvm/CodeGen/MachineCombinerPattern.h"
  22. #include "llvm/CodeGen/MachineFrameInfo.h"
  23. #include "llvm/CodeGen/MachineFunction.h"
  24. #include "llvm/CodeGen/MachineInstr.h"
  25. #include "llvm/CodeGen/MachineInstrBuilder.h"
  26. #include "llvm/CodeGen/MachineMemOperand.h"
  27. #include "llvm/CodeGen/MachineModuleInfo.h"
  28. #include "llvm/CodeGen/MachineOperand.h"
  29. #include "llvm/CodeGen/MachineRegisterInfo.h"
  30. #include "llvm/CodeGen/StackMaps.h"
  31. #include "llvm/CodeGen/TargetRegisterInfo.h"
  32. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  33. #include "llvm/IR/DebugInfoMetadata.h"
  34. #include "llvm/IR/DebugLoc.h"
  35. #include "llvm/IR/GlobalValue.h"
  36. #include "llvm/MC/MCAsmInfo.h"
  37. #include "llvm/MC/MCInst.h"
  38. #include "llvm/MC/MCInstBuilder.h"
  39. #include "llvm/MC/MCInstrDesc.h"
  40. #include "llvm/Support/Casting.h"
  41. #include "llvm/Support/CodeGen.h"
  42. #include "llvm/Support/CommandLine.h"
  43. #include "llvm/Support/Compiler.h"
  44. #include "llvm/Support/ErrorHandling.h"
  45. #include "llvm/Support/LEB128.h"
  46. #include "llvm/Support/MathExtras.h"
  47. #include "llvm/Target/TargetMachine.h"
  48. #include "llvm/Target/TargetOptions.h"
  49. #include <cassert>
  50. #include <cstdint>
  51. #include <iterator>
  52. #include <utility>
  53. using namespace llvm;
  54. #define GET_INSTRINFO_CTOR_DTOR
  55. #include "AArch64GenInstrInfo.inc"
  56. static cl::opt<unsigned> TBZDisplacementBits(
  57. "aarch64-tbz-offset-bits", cl::Hidden, cl::init(14),
  58. cl::desc("Restrict range of TB[N]Z instructions (DEBUG)"));
  59. static cl::opt<unsigned> CBZDisplacementBits(
  60. "aarch64-cbz-offset-bits", cl::Hidden, cl::init(19),
  61. cl::desc("Restrict range of CB[N]Z instructions (DEBUG)"));
  62. static cl::opt<unsigned>
  63. BCCDisplacementBits("aarch64-bcc-offset-bits", cl::Hidden, cl::init(19),
  64. cl::desc("Restrict range of Bcc instructions (DEBUG)"));
  65. AArch64InstrInfo::AArch64InstrInfo(const AArch64Subtarget &STI)
  66. : AArch64GenInstrInfo(AArch64::ADJCALLSTACKDOWN, AArch64::ADJCALLSTACKUP,
  67. AArch64::CATCHRET),
  68. RI(STI.getTargetTriple()), Subtarget(STI) {}
  69. /// GetInstSize - Return the number of bytes of code the specified
  70. /// instruction may be. This returns the maximum number of bytes.
  71. unsigned AArch64InstrInfo::getInstSizeInBytes(const MachineInstr &MI) const {
  72. const MachineBasicBlock &MBB = *MI.getParent();
  73. const MachineFunction *MF = MBB.getParent();
  74. const MCAsmInfo *MAI = MF->getTarget().getMCAsmInfo();
  75. {
  76. auto Op = MI.getOpcode();
  77. if (Op == AArch64::INLINEASM || Op == AArch64::INLINEASM_BR)
  78. return getInlineAsmLength(MI.getOperand(0).getSymbolName(), *MAI);
  79. }
  80. // Meta-instructions emit no code.
  81. if (MI.isMetaInstruction())
  82. return 0;
  83. // FIXME: We currently only handle pseudoinstructions that don't get expanded
  84. // before the assembly printer.
  85. unsigned NumBytes = 0;
  86. const MCInstrDesc &Desc = MI.getDesc();
  87. // Size should be preferably set in
  88. // llvm/lib/Target/AArch64/AArch64InstrInfo.td (default case).
  89. // Specific cases handle instructions of variable sizes
  90. switch (Desc.getOpcode()) {
  91. default:
  92. if (Desc.getSize())
  93. return Desc.getSize();
  94. // Anything not explicitly designated otherwise (i.e. pseudo-instructions
  95. // with fixed constant size but not specified in .td file) is a normal
  96. // 4-byte insn.
  97. NumBytes = 4;
  98. break;
  99. case TargetOpcode::STACKMAP:
  100. // The upper bound for a stackmap intrinsic is the full length of its shadow
  101. NumBytes = StackMapOpers(&MI).getNumPatchBytes();
  102. assert(NumBytes % 4 == 0 && "Invalid number of NOP bytes requested!");
  103. break;
  104. case TargetOpcode::PATCHPOINT:
  105. // The size of the patchpoint intrinsic is the number of bytes requested
  106. NumBytes = PatchPointOpers(&MI).getNumPatchBytes();
  107. assert(NumBytes % 4 == 0 && "Invalid number of NOP bytes requested!");
  108. break;
  109. case TargetOpcode::STATEPOINT:
  110. NumBytes = StatepointOpers(&MI).getNumPatchBytes();
  111. assert(NumBytes % 4 == 0 && "Invalid number of NOP bytes requested!");
  112. // No patch bytes means a normal call inst is emitted
  113. if (NumBytes == 0)
  114. NumBytes = 4;
  115. break;
  116. case AArch64::SPACE:
  117. NumBytes = MI.getOperand(1).getImm();
  118. break;
  119. case TargetOpcode::BUNDLE:
  120. NumBytes = getInstBundleLength(MI);
  121. break;
  122. }
  123. return NumBytes;
  124. }
  125. unsigned AArch64InstrInfo::getInstBundleLength(const MachineInstr &MI) const {
  126. unsigned Size = 0;
  127. MachineBasicBlock::const_instr_iterator I = MI.getIterator();
  128. MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end();
  129. while (++I != E && I->isInsideBundle()) {
  130. assert(!I->isBundle() && "No nested bundle!");
  131. Size += getInstSizeInBytes(*I);
  132. }
  133. return Size;
  134. }
  135. static void parseCondBranch(MachineInstr *LastInst, MachineBasicBlock *&Target,
  136. SmallVectorImpl<MachineOperand> &Cond) {
  137. // Block ends with fall-through condbranch.
  138. switch (LastInst->getOpcode()) {
  139. default:
  140. llvm_unreachable("Unknown branch instruction?");
  141. case AArch64::Bcc:
  142. Target = LastInst->getOperand(1).getMBB();
  143. Cond.push_back(LastInst->getOperand(0));
  144. break;
  145. case AArch64::CBZW:
  146. case AArch64::CBZX:
  147. case AArch64::CBNZW:
  148. case AArch64::CBNZX:
  149. Target = LastInst->getOperand(1).getMBB();
  150. Cond.push_back(MachineOperand::CreateImm(-1));
  151. Cond.push_back(MachineOperand::CreateImm(LastInst->getOpcode()));
  152. Cond.push_back(LastInst->getOperand(0));
  153. break;
  154. case AArch64::TBZW:
  155. case AArch64::TBZX:
  156. case AArch64::TBNZW:
  157. case AArch64::TBNZX:
  158. Target = LastInst->getOperand(2).getMBB();
  159. Cond.push_back(MachineOperand::CreateImm(-1));
  160. Cond.push_back(MachineOperand::CreateImm(LastInst->getOpcode()));
  161. Cond.push_back(LastInst->getOperand(0));
  162. Cond.push_back(LastInst->getOperand(1));
  163. }
  164. }
  165. static unsigned getBranchDisplacementBits(unsigned Opc) {
  166. switch (Opc) {
  167. default:
  168. llvm_unreachable("unexpected opcode!");
  169. case AArch64::B:
  170. return 64;
  171. case AArch64::TBNZW:
  172. case AArch64::TBZW:
  173. case AArch64::TBNZX:
  174. case AArch64::TBZX:
  175. return TBZDisplacementBits;
  176. case AArch64::CBNZW:
  177. case AArch64::CBZW:
  178. case AArch64::CBNZX:
  179. case AArch64::CBZX:
  180. return CBZDisplacementBits;
  181. case AArch64::Bcc:
  182. return BCCDisplacementBits;
  183. }
  184. }
  185. bool AArch64InstrInfo::isBranchOffsetInRange(unsigned BranchOp,
  186. int64_t BrOffset) const {
  187. unsigned Bits = getBranchDisplacementBits(BranchOp);
  188. assert(Bits >= 3 && "max branch displacement must be enough to jump"
  189. "over conditional branch expansion");
  190. return isIntN(Bits, BrOffset / 4);
  191. }
  192. MachineBasicBlock *
  193. AArch64InstrInfo::getBranchDestBlock(const MachineInstr &MI) const {
  194. switch (MI.getOpcode()) {
  195. default:
  196. llvm_unreachable("unexpected opcode!");
  197. case AArch64::B:
  198. return MI.getOperand(0).getMBB();
  199. case AArch64::TBZW:
  200. case AArch64::TBNZW:
  201. case AArch64::TBZX:
  202. case AArch64::TBNZX:
  203. return MI.getOperand(2).getMBB();
  204. case AArch64::CBZW:
  205. case AArch64::CBNZW:
  206. case AArch64::CBZX:
  207. case AArch64::CBNZX:
  208. case AArch64::Bcc:
  209. return MI.getOperand(1).getMBB();
  210. }
  211. }
  212. // Branch analysis.
  213. bool AArch64InstrInfo::analyzeBranch(MachineBasicBlock &MBB,
  214. MachineBasicBlock *&TBB,
  215. MachineBasicBlock *&FBB,
  216. SmallVectorImpl<MachineOperand> &Cond,
  217. bool AllowModify) const {
  218. // If the block has no terminators, it just falls into the block after it.
  219. MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
  220. if (I == MBB.end())
  221. return false;
  222. // Skip over SpeculationBarrierEndBB terminators
  223. if (I->getOpcode() == AArch64::SpeculationBarrierISBDSBEndBB ||
  224. I->getOpcode() == AArch64::SpeculationBarrierSBEndBB) {
  225. --I;
  226. }
  227. if (!isUnpredicatedTerminator(*I))
  228. return false;
  229. // Get the last instruction in the block.
  230. MachineInstr *LastInst = &*I;
  231. // If there is only one terminator instruction, process it.
  232. unsigned LastOpc = LastInst->getOpcode();
  233. if (I == MBB.begin() || !isUnpredicatedTerminator(*--I)) {
  234. if (isUncondBranchOpcode(LastOpc)) {
  235. TBB = LastInst->getOperand(0).getMBB();
  236. return false;
  237. }
  238. if (isCondBranchOpcode(LastOpc)) {
  239. // Block ends with fall-through condbranch.
  240. parseCondBranch(LastInst, TBB, Cond);
  241. return false;
  242. }
  243. return true; // Can't handle indirect branch.
  244. }
  245. // Get the instruction before it if it is a terminator.
  246. MachineInstr *SecondLastInst = &*I;
  247. unsigned SecondLastOpc = SecondLastInst->getOpcode();
  248. // If AllowModify is true and the block ends with two or more unconditional
  249. // branches, delete all but the first unconditional branch.
  250. if (AllowModify && isUncondBranchOpcode(LastOpc)) {
  251. while (isUncondBranchOpcode(SecondLastOpc)) {
  252. LastInst->eraseFromParent();
  253. LastInst = SecondLastInst;
  254. LastOpc = LastInst->getOpcode();
  255. if (I == MBB.begin() || !isUnpredicatedTerminator(*--I)) {
  256. // Return now the only terminator is an unconditional branch.
  257. TBB = LastInst->getOperand(0).getMBB();
  258. return false;
  259. } else {
  260. SecondLastInst = &*I;
  261. SecondLastOpc = SecondLastInst->getOpcode();
  262. }
  263. }
  264. }
  265. // If we're allowed to modify and the block ends in a unconditional branch
  266. // which could simply fallthrough, remove the branch. (Note: This case only
  267. // matters when we can't understand the whole sequence, otherwise it's also
  268. // handled by BranchFolding.cpp.)
  269. if (AllowModify && isUncondBranchOpcode(LastOpc) &&
  270. MBB.isLayoutSuccessor(getBranchDestBlock(*LastInst))) {
  271. LastInst->eraseFromParent();
  272. LastInst = SecondLastInst;
  273. LastOpc = LastInst->getOpcode();
  274. if (I == MBB.begin() || !isUnpredicatedTerminator(*--I)) {
  275. assert(!isUncondBranchOpcode(LastOpc) &&
  276. "unreachable unconditional branches removed above");
  277. if (isCondBranchOpcode(LastOpc)) {
  278. // Block ends with fall-through condbranch.
  279. parseCondBranch(LastInst, TBB, Cond);
  280. return false;
  281. }
  282. return true; // Can't handle indirect branch.
  283. } else {
  284. SecondLastInst = &*I;
  285. SecondLastOpc = SecondLastInst->getOpcode();
  286. }
  287. }
  288. // If there are three terminators, we don't know what sort of block this is.
  289. if (SecondLastInst && I != MBB.begin() && isUnpredicatedTerminator(*--I))
  290. return true;
  291. // If the block ends with a B and a Bcc, handle it.
  292. if (isCondBranchOpcode(SecondLastOpc) && isUncondBranchOpcode(LastOpc)) {
  293. parseCondBranch(SecondLastInst, TBB, Cond);
  294. FBB = LastInst->getOperand(0).getMBB();
  295. return false;
  296. }
  297. // If the block ends with two unconditional branches, handle it. The second
  298. // one is not executed, so remove it.
  299. if (isUncondBranchOpcode(SecondLastOpc) && isUncondBranchOpcode(LastOpc)) {
  300. TBB = SecondLastInst->getOperand(0).getMBB();
  301. I = LastInst;
  302. if (AllowModify)
  303. I->eraseFromParent();
  304. return false;
  305. }
  306. // ...likewise if it ends with an indirect branch followed by an unconditional
  307. // branch.
  308. if (isIndirectBranchOpcode(SecondLastOpc) && isUncondBranchOpcode(LastOpc)) {
  309. I = LastInst;
  310. if (AllowModify)
  311. I->eraseFromParent();
  312. return true;
  313. }
  314. // Otherwise, can't handle this.
  315. return true;
  316. }
  317. bool AArch64InstrInfo::analyzeBranchPredicate(MachineBasicBlock &MBB,
  318. MachineBranchPredicate &MBP,
  319. bool AllowModify) const {
  320. // For the moment, handle only a block which ends with a cb(n)zx followed by
  321. // a fallthrough. Why this? Because it is a common form.
  322. // TODO: Should we handle b.cc?
  323. MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
  324. if (I == MBB.end())
  325. return true;
  326. // Skip over SpeculationBarrierEndBB terminators
  327. if (I->getOpcode() == AArch64::SpeculationBarrierISBDSBEndBB ||
  328. I->getOpcode() == AArch64::SpeculationBarrierSBEndBB) {
  329. --I;
  330. }
  331. if (!isUnpredicatedTerminator(*I))
  332. return true;
  333. // Get the last instruction in the block.
  334. MachineInstr *LastInst = &*I;
  335. unsigned LastOpc = LastInst->getOpcode();
  336. if (!isCondBranchOpcode(LastOpc))
  337. return true;
  338. switch (LastOpc) {
  339. default:
  340. return true;
  341. case AArch64::CBZW:
  342. case AArch64::CBZX:
  343. case AArch64::CBNZW:
  344. case AArch64::CBNZX:
  345. break;
  346. };
  347. MBP.TrueDest = LastInst->getOperand(1).getMBB();
  348. assert(MBP.TrueDest && "expected!");
  349. MBP.FalseDest = MBB.getNextNode();
  350. MBP.ConditionDef = nullptr;
  351. MBP.SingleUseCondition = false;
  352. MBP.LHS = LastInst->getOperand(0);
  353. MBP.RHS = MachineOperand::CreateImm(0);
  354. MBP.Predicate = LastOpc == AArch64::CBNZX ? MachineBranchPredicate::PRED_NE
  355. : MachineBranchPredicate::PRED_EQ;
  356. return false;
  357. }
  358. bool AArch64InstrInfo::reverseBranchCondition(
  359. SmallVectorImpl<MachineOperand> &Cond) const {
  360. if (Cond[0].getImm() != -1) {
  361. // Regular Bcc
  362. AArch64CC::CondCode CC = (AArch64CC::CondCode)(int)Cond[0].getImm();
  363. Cond[0].setImm(AArch64CC::getInvertedCondCode(CC));
  364. } else {
  365. // Folded compare-and-branch
  366. switch (Cond[1].getImm()) {
  367. default:
  368. llvm_unreachable("Unknown conditional branch!");
  369. case AArch64::CBZW:
  370. Cond[1].setImm(AArch64::CBNZW);
  371. break;
  372. case AArch64::CBNZW:
  373. Cond[1].setImm(AArch64::CBZW);
  374. break;
  375. case AArch64::CBZX:
  376. Cond[1].setImm(AArch64::CBNZX);
  377. break;
  378. case AArch64::CBNZX:
  379. Cond[1].setImm(AArch64::CBZX);
  380. break;
  381. case AArch64::TBZW:
  382. Cond[1].setImm(AArch64::TBNZW);
  383. break;
  384. case AArch64::TBNZW:
  385. Cond[1].setImm(AArch64::TBZW);
  386. break;
  387. case AArch64::TBZX:
  388. Cond[1].setImm(AArch64::TBNZX);
  389. break;
  390. case AArch64::TBNZX:
  391. Cond[1].setImm(AArch64::TBZX);
  392. break;
  393. }
  394. }
  395. return false;
  396. }
  397. unsigned AArch64InstrInfo::removeBranch(MachineBasicBlock &MBB,
  398. int *BytesRemoved) const {
  399. MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
  400. if (I == MBB.end())
  401. return 0;
  402. if (!isUncondBranchOpcode(I->getOpcode()) &&
  403. !isCondBranchOpcode(I->getOpcode()))
  404. return 0;
  405. // Remove the branch.
  406. I->eraseFromParent();
  407. I = MBB.end();
  408. if (I == MBB.begin()) {
  409. if (BytesRemoved)
  410. *BytesRemoved = 4;
  411. return 1;
  412. }
  413. --I;
  414. if (!isCondBranchOpcode(I->getOpcode())) {
  415. if (BytesRemoved)
  416. *BytesRemoved = 4;
  417. return 1;
  418. }
  419. // Remove the branch.
  420. I->eraseFromParent();
  421. if (BytesRemoved)
  422. *BytesRemoved = 8;
  423. return 2;
  424. }
  425. void AArch64InstrInfo::instantiateCondBranch(
  426. MachineBasicBlock &MBB, const DebugLoc &DL, MachineBasicBlock *TBB,
  427. ArrayRef<MachineOperand> Cond) const {
  428. if (Cond[0].getImm() != -1) {
  429. // Regular Bcc
  430. BuildMI(&MBB, DL, get(AArch64::Bcc)).addImm(Cond[0].getImm()).addMBB(TBB);
  431. } else {
  432. // Folded compare-and-branch
  433. // Note that we use addOperand instead of addReg to keep the flags.
  434. const MachineInstrBuilder MIB =
  435. BuildMI(&MBB, DL, get(Cond[1].getImm())).add(Cond[2]);
  436. if (Cond.size() > 3)
  437. MIB.addImm(Cond[3].getImm());
  438. MIB.addMBB(TBB);
  439. }
  440. }
  441. unsigned AArch64InstrInfo::insertBranch(
  442. MachineBasicBlock &MBB, MachineBasicBlock *TBB, MachineBasicBlock *FBB,
  443. ArrayRef<MachineOperand> Cond, const DebugLoc &DL, int *BytesAdded) const {
  444. // Shouldn't be a fall through.
  445. assert(TBB && "insertBranch must not be told to insert a fallthrough");
  446. if (!FBB) {
  447. if (Cond.empty()) // Unconditional branch?
  448. BuildMI(&MBB, DL, get(AArch64::B)).addMBB(TBB);
  449. else
  450. instantiateCondBranch(MBB, DL, TBB, Cond);
  451. if (BytesAdded)
  452. *BytesAdded = 4;
  453. return 1;
  454. }
  455. // Two-way conditional branch.
  456. instantiateCondBranch(MBB, DL, TBB, Cond);
  457. BuildMI(&MBB, DL, get(AArch64::B)).addMBB(FBB);
  458. if (BytesAdded)
  459. *BytesAdded = 8;
  460. return 2;
  461. }
  462. // Find the original register that VReg is copied from.
  463. static unsigned removeCopies(const MachineRegisterInfo &MRI, unsigned VReg) {
  464. while (Register::isVirtualRegister(VReg)) {
  465. const MachineInstr *DefMI = MRI.getVRegDef(VReg);
  466. if (!DefMI->isFullCopy())
  467. return VReg;
  468. VReg = DefMI->getOperand(1).getReg();
  469. }
  470. return VReg;
  471. }
  472. // Determine if VReg is defined by an instruction that can be folded into a
  473. // csel instruction. If so, return the folded opcode, and the replacement
  474. // register.
  475. static unsigned canFoldIntoCSel(const MachineRegisterInfo &MRI, unsigned VReg,
  476. unsigned *NewVReg = nullptr) {
  477. VReg = removeCopies(MRI, VReg);
  478. if (!Register::isVirtualRegister(VReg))
  479. return 0;
  480. bool Is64Bit = AArch64::GPR64allRegClass.hasSubClassEq(MRI.getRegClass(VReg));
  481. const MachineInstr *DefMI = MRI.getVRegDef(VReg);
  482. unsigned Opc = 0;
  483. unsigned SrcOpNum = 0;
  484. switch (DefMI->getOpcode()) {
  485. case AArch64::ADDSXri:
  486. case AArch64::ADDSWri:
  487. // if NZCV is used, do not fold.
  488. if (DefMI->findRegisterDefOperandIdx(AArch64::NZCV, true) == -1)
  489. return 0;
  490. // fall-through to ADDXri and ADDWri.
  491. [[fallthrough]];
  492. case AArch64::ADDXri:
  493. case AArch64::ADDWri:
  494. // add x, 1 -> csinc.
  495. if (!DefMI->getOperand(2).isImm() || DefMI->getOperand(2).getImm() != 1 ||
  496. DefMI->getOperand(3).getImm() != 0)
  497. return 0;
  498. SrcOpNum = 1;
  499. Opc = Is64Bit ? AArch64::CSINCXr : AArch64::CSINCWr;
  500. break;
  501. case AArch64::ORNXrr:
  502. case AArch64::ORNWrr: {
  503. // not x -> csinv, represented as orn dst, xzr, src.
  504. unsigned ZReg = removeCopies(MRI, DefMI->getOperand(1).getReg());
  505. if (ZReg != AArch64::XZR && ZReg != AArch64::WZR)
  506. return 0;
  507. SrcOpNum = 2;
  508. Opc = Is64Bit ? AArch64::CSINVXr : AArch64::CSINVWr;
  509. break;
  510. }
  511. case AArch64::SUBSXrr:
  512. case AArch64::SUBSWrr:
  513. // if NZCV is used, do not fold.
  514. if (DefMI->findRegisterDefOperandIdx(AArch64::NZCV, true) == -1)
  515. return 0;
  516. // fall-through to SUBXrr and SUBWrr.
  517. [[fallthrough]];
  518. case AArch64::SUBXrr:
  519. case AArch64::SUBWrr: {
  520. // neg x -> csneg, represented as sub dst, xzr, src.
  521. unsigned ZReg = removeCopies(MRI, DefMI->getOperand(1).getReg());
  522. if (ZReg != AArch64::XZR && ZReg != AArch64::WZR)
  523. return 0;
  524. SrcOpNum = 2;
  525. Opc = Is64Bit ? AArch64::CSNEGXr : AArch64::CSNEGWr;
  526. break;
  527. }
  528. default:
  529. return 0;
  530. }
  531. assert(Opc && SrcOpNum && "Missing parameters");
  532. if (NewVReg)
  533. *NewVReg = DefMI->getOperand(SrcOpNum).getReg();
  534. return Opc;
  535. }
  536. bool AArch64InstrInfo::canInsertSelect(const MachineBasicBlock &MBB,
  537. ArrayRef<MachineOperand> Cond,
  538. Register DstReg, Register TrueReg,
  539. Register FalseReg, int &CondCycles,
  540. int &TrueCycles,
  541. int &FalseCycles) const {
  542. // Check register classes.
  543. const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
  544. const TargetRegisterClass *RC =
  545. RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
  546. if (!RC)
  547. return false;
  548. // Also need to check the dest regclass, in case we're trying to optimize
  549. // something like:
  550. // %1(gpr) = PHI %2(fpr), bb1, %(fpr), bb2
  551. if (!RI.getCommonSubClass(RC, MRI.getRegClass(DstReg)))
  552. return false;
  553. // Expanding cbz/tbz requires an extra cycle of latency on the condition.
  554. unsigned ExtraCondLat = Cond.size() != 1;
  555. // GPRs are handled by csel.
  556. // FIXME: Fold in x+1, -x, and ~x when applicable.
  557. if (AArch64::GPR64allRegClass.hasSubClassEq(RC) ||
  558. AArch64::GPR32allRegClass.hasSubClassEq(RC)) {
  559. // Single-cycle csel, csinc, csinv, and csneg.
  560. CondCycles = 1 + ExtraCondLat;
  561. TrueCycles = FalseCycles = 1;
  562. if (canFoldIntoCSel(MRI, TrueReg))
  563. TrueCycles = 0;
  564. else if (canFoldIntoCSel(MRI, FalseReg))
  565. FalseCycles = 0;
  566. return true;
  567. }
  568. // Scalar floating point is handled by fcsel.
  569. // FIXME: Form fabs, fmin, and fmax when applicable.
  570. if (AArch64::FPR64RegClass.hasSubClassEq(RC) ||
  571. AArch64::FPR32RegClass.hasSubClassEq(RC)) {
  572. CondCycles = 5 + ExtraCondLat;
  573. TrueCycles = FalseCycles = 2;
  574. return true;
  575. }
  576. // Can't do vectors.
  577. return false;
  578. }
  579. void AArch64InstrInfo::insertSelect(MachineBasicBlock &MBB,
  580. MachineBasicBlock::iterator I,
  581. const DebugLoc &DL, Register DstReg,
  582. ArrayRef<MachineOperand> Cond,
  583. Register TrueReg, Register FalseReg) const {
  584. MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
  585. // Parse the condition code, see parseCondBranch() above.
  586. AArch64CC::CondCode CC;
  587. switch (Cond.size()) {
  588. default:
  589. llvm_unreachable("Unknown condition opcode in Cond");
  590. case 1: // b.cc
  591. CC = AArch64CC::CondCode(Cond[0].getImm());
  592. break;
  593. case 3: { // cbz/cbnz
  594. // We must insert a compare against 0.
  595. bool Is64Bit;
  596. switch (Cond[1].getImm()) {
  597. default:
  598. llvm_unreachable("Unknown branch opcode in Cond");
  599. case AArch64::CBZW:
  600. Is64Bit = false;
  601. CC = AArch64CC::EQ;
  602. break;
  603. case AArch64::CBZX:
  604. Is64Bit = true;
  605. CC = AArch64CC::EQ;
  606. break;
  607. case AArch64::CBNZW:
  608. Is64Bit = false;
  609. CC = AArch64CC::NE;
  610. break;
  611. case AArch64::CBNZX:
  612. Is64Bit = true;
  613. CC = AArch64CC::NE;
  614. break;
  615. }
  616. Register SrcReg = Cond[2].getReg();
  617. if (Is64Bit) {
  618. // cmp reg, #0 is actually subs xzr, reg, #0.
  619. MRI.constrainRegClass(SrcReg, &AArch64::GPR64spRegClass);
  620. BuildMI(MBB, I, DL, get(AArch64::SUBSXri), AArch64::XZR)
  621. .addReg(SrcReg)
  622. .addImm(0)
  623. .addImm(0);
  624. } else {
  625. MRI.constrainRegClass(SrcReg, &AArch64::GPR32spRegClass);
  626. BuildMI(MBB, I, DL, get(AArch64::SUBSWri), AArch64::WZR)
  627. .addReg(SrcReg)
  628. .addImm(0)
  629. .addImm(0);
  630. }
  631. break;
  632. }
  633. case 4: { // tbz/tbnz
  634. // We must insert a tst instruction.
  635. switch (Cond[1].getImm()) {
  636. default:
  637. llvm_unreachable("Unknown branch opcode in Cond");
  638. case AArch64::TBZW:
  639. case AArch64::TBZX:
  640. CC = AArch64CC::EQ;
  641. break;
  642. case AArch64::TBNZW:
  643. case AArch64::TBNZX:
  644. CC = AArch64CC::NE;
  645. break;
  646. }
  647. // cmp reg, #foo is actually ands xzr, reg, #1<<foo.
  648. if (Cond[1].getImm() == AArch64::TBZW || Cond[1].getImm() == AArch64::TBNZW)
  649. BuildMI(MBB, I, DL, get(AArch64::ANDSWri), AArch64::WZR)
  650. .addReg(Cond[2].getReg())
  651. .addImm(
  652. AArch64_AM::encodeLogicalImmediate(1ull << Cond[3].getImm(), 32));
  653. else
  654. BuildMI(MBB, I, DL, get(AArch64::ANDSXri), AArch64::XZR)
  655. .addReg(Cond[2].getReg())
  656. .addImm(
  657. AArch64_AM::encodeLogicalImmediate(1ull << Cond[3].getImm(), 64));
  658. break;
  659. }
  660. }
  661. unsigned Opc = 0;
  662. const TargetRegisterClass *RC = nullptr;
  663. bool TryFold = false;
  664. if (MRI.constrainRegClass(DstReg, &AArch64::GPR64RegClass)) {
  665. RC = &AArch64::GPR64RegClass;
  666. Opc = AArch64::CSELXr;
  667. TryFold = true;
  668. } else if (MRI.constrainRegClass(DstReg, &AArch64::GPR32RegClass)) {
  669. RC = &AArch64::GPR32RegClass;
  670. Opc = AArch64::CSELWr;
  671. TryFold = true;
  672. } else if (MRI.constrainRegClass(DstReg, &AArch64::FPR64RegClass)) {
  673. RC = &AArch64::FPR64RegClass;
  674. Opc = AArch64::FCSELDrrr;
  675. } else if (MRI.constrainRegClass(DstReg, &AArch64::FPR32RegClass)) {
  676. RC = &AArch64::FPR32RegClass;
  677. Opc = AArch64::FCSELSrrr;
  678. }
  679. assert(RC && "Unsupported regclass");
  680. // Try folding simple instructions into the csel.
  681. if (TryFold) {
  682. unsigned NewVReg = 0;
  683. unsigned FoldedOpc = canFoldIntoCSel(MRI, TrueReg, &NewVReg);
  684. if (FoldedOpc) {
  685. // The folded opcodes csinc, csinc and csneg apply the operation to
  686. // FalseReg, so we need to invert the condition.
  687. CC = AArch64CC::getInvertedCondCode(CC);
  688. TrueReg = FalseReg;
  689. } else
  690. FoldedOpc = canFoldIntoCSel(MRI, FalseReg, &NewVReg);
  691. // Fold the operation. Leave any dead instructions for DCE to clean up.
  692. if (FoldedOpc) {
  693. FalseReg = NewVReg;
  694. Opc = FoldedOpc;
  695. // The extends the live range of NewVReg.
  696. MRI.clearKillFlags(NewVReg);
  697. }
  698. }
  699. // Pull all virtual register into the appropriate class.
  700. MRI.constrainRegClass(TrueReg, RC);
  701. MRI.constrainRegClass(FalseReg, RC);
  702. // Insert the csel.
  703. BuildMI(MBB, I, DL, get(Opc), DstReg)
  704. .addReg(TrueReg)
  705. .addReg(FalseReg)
  706. .addImm(CC);
  707. }
  708. /// Returns true if a MOVi32imm or MOVi64imm can be expanded to an ORRxx.
  709. static bool canBeExpandedToORR(const MachineInstr &MI, unsigned BitSize) {
  710. uint64_t Imm = MI.getOperand(1).getImm();
  711. uint64_t UImm = Imm << (64 - BitSize) >> (64 - BitSize);
  712. uint64_t Encoding;
  713. return AArch64_AM::processLogicalImmediate(UImm, BitSize, Encoding);
  714. }
  715. // FIXME: this implementation should be micro-architecture dependent, so a
  716. // micro-architecture target hook should be introduced here in future.
  717. bool AArch64InstrInfo::isAsCheapAsAMove(const MachineInstr &MI) const {
  718. if (!Subtarget.hasCustomCheapAsMoveHandling())
  719. return MI.isAsCheapAsAMove();
  720. const unsigned Opcode = MI.getOpcode();
  721. // Firstly, check cases gated by features.
  722. if (Subtarget.hasZeroCycleZeroingFP()) {
  723. if (Opcode == AArch64::FMOVH0 ||
  724. Opcode == AArch64::FMOVS0 ||
  725. Opcode == AArch64::FMOVD0)
  726. return true;
  727. }
  728. if (Subtarget.hasZeroCycleZeroingGP()) {
  729. if (Opcode == TargetOpcode::COPY &&
  730. (MI.getOperand(1).getReg() == AArch64::WZR ||
  731. MI.getOperand(1).getReg() == AArch64::XZR))
  732. return true;
  733. }
  734. // Secondly, check cases specific to sub-targets.
  735. if (Subtarget.hasExynosCheapAsMoveHandling()) {
  736. if (isExynosCheapAsMove(MI))
  737. return true;
  738. return MI.isAsCheapAsAMove();
  739. }
  740. // Finally, check generic cases.
  741. switch (Opcode) {
  742. default:
  743. return false;
  744. // add/sub on register without shift
  745. case AArch64::ADDWri:
  746. case AArch64::ADDXri:
  747. case AArch64::SUBWri:
  748. case AArch64::SUBXri:
  749. return (MI.getOperand(3).getImm() == 0);
  750. // logical ops on immediate
  751. case AArch64::ANDWri:
  752. case AArch64::ANDXri:
  753. case AArch64::EORWri:
  754. case AArch64::EORXri:
  755. case AArch64::ORRWri:
  756. case AArch64::ORRXri:
  757. return true;
  758. // logical ops on register without shift
  759. case AArch64::ANDWrr:
  760. case AArch64::ANDXrr:
  761. case AArch64::BICWrr:
  762. case AArch64::BICXrr:
  763. case AArch64::EONWrr:
  764. case AArch64::EONXrr:
  765. case AArch64::EORWrr:
  766. case AArch64::EORXrr:
  767. case AArch64::ORNWrr:
  768. case AArch64::ORNXrr:
  769. case AArch64::ORRWrr:
  770. case AArch64::ORRXrr:
  771. return true;
  772. // If MOVi32imm or MOVi64imm can be expanded into ORRWri or
  773. // ORRXri, it is as cheap as MOV
  774. case AArch64::MOVi32imm:
  775. return canBeExpandedToORR(MI, 32);
  776. case AArch64::MOVi64imm:
  777. return canBeExpandedToORR(MI, 64);
  778. }
  779. llvm_unreachable("Unknown opcode to check as cheap as a move!");
  780. }
  781. bool AArch64InstrInfo::isFalkorShiftExtFast(const MachineInstr &MI) {
  782. switch (MI.getOpcode()) {
  783. default:
  784. return false;
  785. case AArch64::ADDWrs:
  786. case AArch64::ADDXrs:
  787. case AArch64::ADDSWrs:
  788. case AArch64::ADDSXrs: {
  789. unsigned Imm = MI.getOperand(3).getImm();
  790. unsigned ShiftVal = AArch64_AM::getShiftValue(Imm);
  791. if (ShiftVal == 0)
  792. return true;
  793. return AArch64_AM::getShiftType(Imm) == AArch64_AM::LSL && ShiftVal <= 5;
  794. }
  795. case AArch64::ADDWrx:
  796. case AArch64::ADDXrx:
  797. case AArch64::ADDXrx64:
  798. case AArch64::ADDSWrx:
  799. case AArch64::ADDSXrx:
  800. case AArch64::ADDSXrx64: {
  801. unsigned Imm = MI.getOperand(3).getImm();
  802. switch (AArch64_AM::getArithExtendType(Imm)) {
  803. default:
  804. return false;
  805. case AArch64_AM::UXTB:
  806. case AArch64_AM::UXTH:
  807. case AArch64_AM::UXTW:
  808. case AArch64_AM::UXTX:
  809. return AArch64_AM::getArithShiftValue(Imm) <= 4;
  810. }
  811. }
  812. case AArch64::SUBWrs:
  813. case AArch64::SUBSWrs: {
  814. unsigned Imm = MI.getOperand(3).getImm();
  815. unsigned ShiftVal = AArch64_AM::getShiftValue(Imm);
  816. return ShiftVal == 0 ||
  817. (AArch64_AM::getShiftType(Imm) == AArch64_AM::ASR && ShiftVal == 31);
  818. }
  819. case AArch64::SUBXrs:
  820. case AArch64::SUBSXrs: {
  821. unsigned Imm = MI.getOperand(3).getImm();
  822. unsigned ShiftVal = AArch64_AM::getShiftValue(Imm);
  823. return ShiftVal == 0 ||
  824. (AArch64_AM::getShiftType(Imm) == AArch64_AM::ASR && ShiftVal == 63);
  825. }
  826. case AArch64::SUBWrx:
  827. case AArch64::SUBXrx:
  828. case AArch64::SUBXrx64:
  829. case AArch64::SUBSWrx:
  830. case AArch64::SUBSXrx:
  831. case AArch64::SUBSXrx64: {
  832. unsigned Imm = MI.getOperand(3).getImm();
  833. switch (AArch64_AM::getArithExtendType(Imm)) {
  834. default:
  835. return false;
  836. case AArch64_AM::UXTB:
  837. case AArch64_AM::UXTH:
  838. case AArch64_AM::UXTW:
  839. case AArch64_AM::UXTX:
  840. return AArch64_AM::getArithShiftValue(Imm) == 0;
  841. }
  842. }
  843. case AArch64::LDRBBroW:
  844. case AArch64::LDRBBroX:
  845. case AArch64::LDRBroW:
  846. case AArch64::LDRBroX:
  847. case AArch64::LDRDroW:
  848. case AArch64::LDRDroX:
  849. case AArch64::LDRHHroW:
  850. case AArch64::LDRHHroX:
  851. case AArch64::LDRHroW:
  852. case AArch64::LDRHroX:
  853. case AArch64::LDRQroW:
  854. case AArch64::LDRQroX:
  855. case AArch64::LDRSBWroW:
  856. case AArch64::LDRSBWroX:
  857. case AArch64::LDRSBXroW:
  858. case AArch64::LDRSBXroX:
  859. case AArch64::LDRSHWroW:
  860. case AArch64::LDRSHWroX:
  861. case AArch64::LDRSHXroW:
  862. case AArch64::LDRSHXroX:
  863. case AArch64::LDRSWroW:
  864. case AArch64::LDRSWroX:
  865. case AArch64::LDRSroW:
  866. case AArch64::LDRSroX:
  867. case AArch64::LDRWroW:
  868. case AArch64::LDRWroX:
  869. case AArch64::LDRXroW:
  870. case AArch64::LDRXroX:
  871. case AArch64::PRFMroW:
  872. case AArch64::PRFMroX:
  873. case AArch64::STRBBroW:
  874. case AArch64::STRBBroX:
  875. case AArch64::STRBroW:
  876. case AArch64::STRBroX:
  877. case AArch64::STRDroW:
  878. case AArch64::STRDroX:
  879. case AArch64::STRHHroW:
  880. case AArch64::STRHHroX:
  881. case AArch64::STRHroW:
  882. case AArch64::STRHroX:
  883. case AArch64::STRQroW:
  884. case AArch64::STRQroX:
  885. case AArch64::STRSroW:
  886. case AArch64::STRSroX:
  887. case AArch64::STRWroW:
  888. case AArch64::STRWroX:
  889. case AArch64::STRXroW:
  890. case AArch64::STRXroX: {
  891. unsigned IsSigned = MI.getOperand(3).getImm();
  892. return !IsSigned;
  893. }
  894. }
  895. }
  896. bool AArch64InstrInfo::isSEHInstruction(const MachineInstr &MI) {
  897. unsigned Opc = MI.getOpcode();
  898. switch (Opc) {
  899. default:
  900. return false;
  901. case AArch64::SEH_StackAlloc:
  902. case AArch64::SEH_SaveFPLR:
  903. case AArch64::SEH_SaveFPLR_X:
  904. case AArch64::SEH_SaveReg:
  905. case AArch64::SEH_SaveReg_X:
  906. case AArch64::SEH_SaveRegP:
  907. case AArch64::SEH_SaveRegP_X:
  908. case AArch64::SEH_SaveFReg:
  909. case AArch64::SEH_SaveFReg_X:
  910. case AArch64::SEH_SaveFRegP:
  911. case AArch64::SEH_SaveFRegP_X:
  912. case AArch64::SEH_SetFP:
  913. case AArch64::SEH_AddFP:
  914. case AArch64::SEH_Nop:
  915. case AArch64::SEH_PrologEnd:
  916. case AArch64::SEH_EpilogStart:
  917. case AArch64::SEH_EpilogEnd:
  918. case AArch64::SEH_PACSignLR:
  919. return true;
  920. }
  921. }
  922. bool AArch64InstrInfo::isCoalescableExtInstr(const MachineInstr &MI,
  923. Register &SrcReg, Register &DstReg,
  924. unsigned &SubIdx) const {
  925. switch (MI.getOpcode()) {
  926. default:
  927. return false;
  928. case AArch64::SBFMXri: // aka sxtw
  929. case AArch64::UBFMXri: // aka uxtw
  930. // Check for the 32 -> 64 bit extension case, these instructions can do
  931. // much more.
  932. if (MI.getOperand(2).getImm() != 0 || MI.getOperand(3).getImm() != 31)
  933. return false;
  934. // This is a signed or unsigned 32 -> 64 bit extension.
  935. SrcReg = MI.getOperand(1).getReg();
  936. DstReg = MI.getOperand(0).getReg();
  937. SubIdx = AArch64::sub_32;
  938. return true;
  939. }
  940. }
  941. bool AArch64InstrInfo::areMemAccessesTriviallyDisjoint(
  942. const MachineInstr &MIa, const MachineInstr &MIb) const {
  943. const TargetRegisterInfo *TRI = &getRegisterInfo();
  944. const MachineOperand *BaseOpA = nullptr, *BaseOpB = nullptr;
  945. int64_t OffsetA = 0, OffsetB = 0;
  946. unsigned WidthA = 0, WidthB = 0;
  947. bool OffsetAIsScalable = false, OffsetBIsScalable = false;
  948. assert(MIa.mayLoadOrStore() && "MIa must be a load or store.");
  949. assert(MIb.mayLoadOrStore() && "MIb must be a load or store.");
  950. if (MIa.hasUnmodeledSideEffects() || MIb.hasUnmodeledSideEffects() ||
  951. MIa.hasOrderedMemoryRef() || MIb.hasOrderedMemoryRef())
  952. return false;
  953. // Retrieve the base, offset from the base and width. Width
  954. // is the size of memory that is being loaded/stored (e.g. 1, 2, 4, 8). If
  955. // base are identical, and the offset of a lower memory access +
  956. // the width doesn't overlap the offset of a higher memory access,
  957. // then the memory accesses are different.
  958. // If OffsetAIsScalable and OffsetBIsScalable are both true, they
  959. // are assumed to have the same scale (vscale).
  960. if (getMemOperandWithOffsetWidth(MIa, BaseOpA, OffsetA, OffsetAIsScalable,
  961. WidthA, TRI) &&
  962. getMemOperandWithOffsetWidth(MIb, BaseOpB, OffsetB, OffsetBIsScalable,
  963. WidthB, TRI)) {
  964. if (BaseOpA->isIdenticalTo(*BaseOpB) &&
  965. OffsetAIsScalable == OffsetBIsScalable) {
  966. int LowOffset = OffsetA < OffsetB ? OffsetA : OffsetB;
  967. int HighOffset = OffsetA < OffsetB ? OffsetB : OffsetA;
  968. int LowWidth = (LowOffset == OffsetA) ? WidthA : WidthB;
  969. if (LowOffset + LowWidth <= HighOffset)
  970. return true;
  971. }
  972. }
  973. return false;
  974. }
  975. bool AArch64InstrInfo::isSchedulingBoundary(const MachineInstr &MI,
  976. const MachineBasicBlock *MBB,
  977. const MachineFunction &MF) const {
  978. if (TargetInstrInfo::isSchedulingBoundary(MI, MBB, MF))
  979. return true;
  980. switch (MI.getOpcode()) {
  981. case AArch64::HINT:
  982. // CSDB hints are scheduling barriers.
  983. if (MI.getOperand(0).getImm() == 0x14)
  984. return true;
  985. break;
  986. case AArch64::DSB:
  987. case AArch64::ISB:
  988. // DSB and ISB also are scheduling barriers.
  989. return true;
  990. case AArch64::MSRpstatesvcrImm1:
  991. // SMSTART and SMSTOP are also scheduling barriers.
  992. return true;
  993. default:;
  994. }
  995. if (isSEHInstruction(MI))
  996. return true;
  997. auto Next = std::next(MI.getIterator());
  998. return Next != MBB->end() && Next->isCFIInstruction();
  999. }
  1000. /// analyzeCompare - For a comparison instruction, return the source registers
  1001. /// in SrcReg and SrcReg2, and the value it compares against in CmpValue.
  1002. /// Return true if the comparison instruction can be analyzed.
  1003. bool AArch64InstrInfo::analyzeCompare(const MachineInstr &MI, Register &SrcReg,
  1004. Register &SrcReg2, int64_t &CmpMask,
  1005. int64_t &CmpValue) const {
  1006. // The first operand can be a frame index where we'd normally expect a
  1007. // register.
  1008. assert(MI.getNumOperands() >= 2 && "All AArch64 cmps should have 2 operands");
  1009. if (!MI.getOperand(1).isReg())
  1010. return false;
  1011. switch (MI.getOpcode()) {
  1012. default:
  1013. break;
  1014. case AArch64::PTEST_PP:
  1015. case AArch64::PTEST_PP_ANY:
  1016. SrcReg = MI.getOperand(0).getReg();
  1017. SrcReg2 = MI.getOperand(1).getReg();
  1018. // Not sure about the mask and value for now...
  1019. CmpMask = ~0;
  1020. CmpValue = 0;
  1021. return true;
  1022. case AArch64::SUBSWrr:
  1023. case AArch64::SUBSWrs:
  1024. case AArch64::SUBSWrx:
  1025. case AArch64::SUBSXrr:
  1026. case AArch64::SUBSXrs:
  1027. case AArch64::SUBSXrx:
  1028. case AArch64::ADDSWrr:
  1029. case AArch64::ADDSWrs:
  1030. case AArch64::ADDSWrx:
  1031. case AArch64::ADDSXrr:
  1032. case AArch64::ADDSXrs:
  1033. case AArch64::ADDSXrx:
  1034. // Replace SUBSWrr with SUBWrr if NZCV is not used.
  1035. SrcReg = MI.getOperand(1).getReg();
  1036. SrcReg2 = MI.getOperand(2).getReg();
  1037. CmpMask = ~0;
  1038. CmpValue = 0;
  1039. return true;
  1040. case AArch64::SUBSWri:
  1041. case AArch64::ADDSWri:
  1042. case AArch64::SUBSXri:
  1043. case AArch64::ADDSXri:
  1044. SrcReg = MI.getOperand(1).getReg();
  1045. SrcReg2 = 0;
  1046. CmpMask = ~0;
  1047. CmpValue = MI.getOperand(2).getImm();
  1048. return true;
  1049. case AArch64::ANDSWri:
  1050. case AArch64::ANDSXri:
  1051. // ANDS does not use the same encoding scheme as the others xxxS
  1052. // instructions.
  1053. SrcReg = MI.getOperand(1).getReg();
  1054. SrcReg2 = 0;
  1055. CmpMask = ~0;
  1056. CmpValue = AArch64_AM::decodeLogicalImmediate(
  1057. MI.getOperand(2).getImm(),
  1058. MI.getOpcode() == AArch64::ANDSWri ? 32 : 64);
  1059. return true;
  1060. }
  1061. return false;
  1062. }
  1063. static bool UpdateOperandRegClass(MachineInstr &Instr) {
  1064. MachineBasicBlock *MBB = Instr.getParent();
  1065. assert(MBB && "Can't get MachineBasicBlock here");
  1066. MachineFunction *MF = MBB->getParent();
  1067. assert(MF && "Can't get MachineFunction here");
  1068. const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
  1069. const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
  1070. MachineRegisterInfo *MRI = &MF->getRegInfo();
  1071. for (unsigned OpIdx = 0, EndIdx = Instr.getNumOperands(); OpIdx < EndIdx;
  1072. ++OpIdx) {
  1073. MachineOperand &MO = Instr.getOperand(OpIdx);
  1074. const TargetRegisterClass *OpRegCstraints =
  1075. Instr.getRegClassConstraint(OpIdx, TII, TRI);
  1076. // If there's no constraint, there's nothing to do.
  1077. if (!OpRegCstraints)
  1078. continue;
  1079. // If the operand is a frame index, there's nothing to do here.
  1080. // A frame index operand will resolve correctly during PEI.
  1081. if (MO.isFI())
  1082. continue;
  1083. assert(MO.isReg() &&
  1084. "Operand has register constraints without being a register!");
  1085. Register Reg = MO.getReg();
  1086. if (Reg.isPhysical()) {
  1087. if (!OpRegCstraints->contains(Reg))
  1088. return false;
  1089. } else if (!OpRegCstraints->hasSubClassEq(MRI->getRegClass(Reg)) &&
  1090. !MRI->constrainRegClass(Reg, OpRegCstraints))
  1091. return false;
  1092. }
  1093. return true;
  1094. }
  1095. /// Return the opcode that does not set flags when possible - otherwise
  1096. /// return the original opcode. The caller is responsible to do the actual
  1097. /// substitution and legality checking.
  1098. static unsigned convertToNonFlagSettingOpc(const MachineInstr &MI) {
  1099. // Don't convert all compare instructions, because for some the zero register
  1100. // encoding becomes the sp register.
  1101. bool MIDefinesZeroReg = false;
  1102. if (MI.definesRegister(AArch64::WZR) || MI.definesRegister(AArch64::XZR))
  1103. MIDefinesZeroReg = true;
  1104. switch (MI.getOpcode()) {
  1105. default:
  1106. return MI.getOpcode();
  1107. case AArch64::ADDSWrr:
  1108. return AArch64::ADDWrr;
  1109. case AArch64::ADDSWri:
  1110. return MIDefinesZeroReg ? AArch64::ADDSWri : AArch64::ADDWri;
  1111. case AArch64::ADDSWrs:
  1112. return MIDefinesZeroReg ? AArch64::ADDSWrs : AArch64::ADDWrs;
  1113. case AArch64::ADDSWrx:
  1114. return AArch64::ADDWrx;
  1115. case AArch64::ADDSXrr:
  1116. return AArch64::ADDXrr;
  1117. case AArch64::ADDSXri:
  1118. return MIDefinesZeroReg ? AArch64::ADDSXri : AArch64::ADDXri;
  1119. case AArch64::ADDSXrs:
  1120. return MIDefinesZeroReg ? AArch64::ADDSXrs : AArch64::ADDXrs;
  1121. case AArch64::ADDSXrx:
  1122. return AArch64::ADDXrx;
  1123. case AArch64::SUBSWrr:
  1124. return AArch64::SUBWrr;
  1125. case AArch64::SUBSWri:
  1126. return MIDefinesZeroReg ? AArch64::SUBSWri : AArch64::SUBWri;
  1127. case AArch64::SUBSWrs:
  1128. return MIDefinesZeroReg ? AArch64::SUBSWrs : AArch64::SUBWrs;
  1129. case AArch64::SUBSWrx:
  1130. return AArch64::SUBWrx;
  1131. case AArch64::SUBSXrr:
  1132. return AArch64::SUBXrr;
  1133. case AArch64::SUBSXri:
  1134. return MIDefinesZeroReg ? AArch64::SUBSXri : AArch64::SUBXri;
  1135. case AArch64::SUBSXrs:
  1136. return MIDefinesZeroReg ? AArch64::SUBSXrs : AArch64::SUBXrs;
  1137. case AArch64::SUBSXrx:
  1138. return AArch64::SUBXrx;
  1139. }
  1140. }
  1141. enum AccessKind { AK_Write = 0x01, AK_Read = 0x10, AK_All = 0x11 };
  1142. /// True when condition flags are accessed (either by writing or reading)
  1143. /// on the instruction trace starting at From and ending at To.
  1144. ///
  1145. /// Note: If From and To are from different blocks it's assumed CC are accessed
  1146. /// on the path.
  1147. static bool areCFlagsAccessedBetweenInstrs(
  1148. MachineBasicBlock::iterator From, MachineBasicBlock::iterator To,
  1149. const TargetRegisterInfo *TRI, const AccessKind AccessToCheck = AK_All) {
  1150. // Early exit if To is at the beginning of the BB.
  1151. if (To == To->getParent()->begin())
  1152. return true;
  1153. // Check whether the instructions are in the same basic block
  1154. // If not, assume the condition flags might get modified somewhere.
  1155. if (To->getParent() != From->getParent())
  1156. return true;
  1157. // From must be above To.
  1158. assert(std::any_of(
  1159. ++To.getReverse(), To->getParent()->rend(),
  1160. [From](MachineInstr &MI) { return MI.getIterator() == From; }));
  1161. // We iterate backward starting at \p To until we hit \p From.
  1162. for (const MachineInstr &Instr :
  1163. instructionsWithoutDebug(++To.getReverse(), From.getReverse())) {
  1164. if (((AccessToCheck & AK_Write) &&
  1165. Instr.modifiesRegister(AArch64::NZCV, TRI)) ||
  1166. ((AccessToCheck & AK_Read) && Instr.readsRegister(AArch64::NZCV, TRI)))
  1167. return true;
  1168. }
  1169. return false;
  1170. }
  1171. /// optimizePTestInstr - Attempt to remove a ptest of a predicate-generating
  1172. /// operation which could set the flags in an identical manner
  1173. bool AArch64InstrInfo::optimizePTestInstr(
  1174. MachineInstr *PTest, unsigned MaskReg, unsigned PredReg,
  1175. const MachineRegisterInfo *MRI) const {
  1176. auto *Mask = MRI->getUniqueVRegDef(MaskReg);
  1177. auto *Pred = MRI->getUniqueVRegDef(PredReg);
  1178. auto NewOp = Pred->getOpcode();
  1179. bool OpChanged = false;
  1180. unsigned MaskOpcode = Mask->getOpcode();
  1181. unsigned PredOpcode = Pred->getOpcode();
  1182. bool PredIsPTestLike = isPTestLikeOpcode(PredOpcode);
  1183. bool PredIsWhileLike = isWhileOpcode(PredOpcode);
  1184. if (isPTrueOpcode(MaskOpcode) && (PredIsPTestLike || PredIsWhileLike) &&
  1185. getElementSizeForOpcode(MaskOpcode) ==
  1186. getElementSizeForOpcode(PredOpcode) &&
  1187. Mask->getOperand(1).getImm() == 31) {
  1188. // For PTEST(PTRUE_ALL, WHILE), if the element size matches, the PTEST is
  1189. // redundant since WHILE performs an implicit PTEST with an all active
  1190. // mask. Must be an all active predicate of matching element size.
  1191. // For PTEST(PTRUE_ALL, PTEST_LIKE), the PTEST is redundant if the
  1192. // PTEST_LIKE instruction uses the same all active mask and the element
  1193. // size matches. If the PTEST has a condition of any then it is always
  1194. // redundant.
  1195. if (PredIsPTestLike) {
  1196. auto PTestLikeMask = MRI->getUniqueVRegDef(Pred->getOperand(1).getReg());
  1197. if (Mask != PTestLikeMask && PTest->getOpcode() != AArch64::PTEST_PP_ANY)
  1198. return false;
  1199. }
  1200. // Fallthough to simply remove the PTEST.
  1201. } else if ((Mask == Pred) && (PredIsPTestLike || PredIsWhileLike) &&
  1202. PTest->getOpcode() == AArch64::PTEST_PP_ANY) {
  1203. // For PTEST(PG, PG), PTEST is redundant when PG is the result of an
  1204. // instruction that sets the flags as PTEST would. This is only valid when
  1205. // the condition is any.
  1206. // Fallthough to simply remove the PTEST.
  1207. } else if (PredIsPTestLike) {
  1208. // For PTEST(PG, PTEST_LIKE(PG, ...)), the PTEST is redundant since the
  1209. // flags are set based on the same mask 'PG', but PTEST_LIKE must operate
  1210. // on 8-bit predicates like the PTEST. Otherwise, for instructions like
  1211. // compare that also support 16/32/64-bit predicates, the implicit PTEST
  1212. // performed by the compare could consider fewer lanes for these element
  1213. // sizes.
  1214. //
  1215. // For example, consider
  1216. //
  1217. // ptrue p0.b ; P0=1111-1111-1111-1111
  1218. // index z0.s, #0, #1 ; Z0=<0,1,2,3>
  1219. // index z1.s, #1, #1 ; Z1=<1,2,3,4>
  1220. // cmphi p1.s, p0/z, z1.s, z0.s ; P1=0001-0001-0001-0001
  1221. // ; ^ last active
  1222. // ptest p0, p1.b ; P1=0001-0001-0001-0001
  1223. // ; ^ last active
  1224. //
  1225. // where the compare generates a canonical all active 32-bit predicate
  1226. // (equivalent to 'ptrue p1.s, all'). The implicit PTEST sets the last
  1227. // active flag, whereas the PTEST instruction with the same mask doesn't.
  1228. // For PTEST_ANY this doesn't apply as the flags in this case would be
  1229. // identical regardless of element size.
  1230. auto PTestLikeMask = MRI->getUniqueVRegDef(Pred->getOperand(1).getReg());
  1231. uint64_t PredElementSize = getElementSizeForOpcode(PredOpcode);
  1232. if ((Mask != PTestLikeMask) ||
  1233. (PredElementSize != AArch64::ElementSizeB &&
  1234. PTest->getOpcode() != AArch64::PTEST_PP_ANY))
  1235. return false;
  1236. // Fallthough to simply remove the PTEST.
  1237. } else {
  1238. // If OP in PTEST(PG, OP(PG, ...)) has a flag-setting variant change the
  1239. // opcode so the PTEST becomes redundant.
  1240. switch (PredOpcode) {
  1241. case AArch64::AND_PPzPP:
  1242. case AArch64::BIC_PPzPP:
  1243. case AArch64::EOR_PPzPP:
  1244. case AArch64::NAND_PPzPP:
  1245. case AArch64::NOR_PPzPP:
  1246. case AArch64::ORN_PPzPP:
  1247. case AArch64::ORR_PPzPP:
  1248. case AArch64::BRKA_PPzP:
  1249. case AArch64::BRKPA_PPzPP:
  1250. case AArch64::BRKB_PPzP:
  1251. case AArch64::BRKPB_PPzPP:
  1252. case AArch64::RDFFR_PPz: {
  1253. // Check to see if our mask is the same. If not the resulting flag bits
  1254. // may be different and we can't remove the ptest.
  1255. auto *PredMask = MRI->getUniqueVRegDef(Pred->getOperand(1).getReg());
  1256. if (Mask != PredMask)
  1257. return false;
  1258. break;
  1259. }
  1260. case AArch64::BRKN_PPzP: {
  1261. // BRKN uses an all active implicit mask to set flags unlike the other
  1262. // flag-setting instructions.
  1263. // PTEST(PTRUE_B(31), BRKN(PG, A, B)) -> BRKNS(PG, A, B).
  1264. if ((MaskOpcode != AArch64::PTRUE_B) ||
  1265. (Mask->getOperand(1).getImm() != 31))
  1266. return false;
  1267. break;
  1268. }
  1269. case AArch64::PTRUE_B:
  1270. // PTEST(OP=PTRUE_B(A), OP) -> PTRUES_B(A)
  1271. break;
  1272. default:
  1273. // Bail out if we don't recognize the input
  1274. return false;
  1275. }
  1276. NewOp = convertToFlagSettingOpc(PredOpcode);
  1277. OpChanged = true;
  1278. }
  1279. const TargetRegisterInfo *TRI = &getRegisterInfo();
  1280. // If another instruction between Pred and PTest accesses flags, don't remove
  1281. // the ptest or update the earlier instruction to modify them.
  1282. if (areCFlagsAccessedBetweenInstrs(Pred, PTest, TRI))
  1283. return false;
  1284. // If we pass all the checks, it's safe to remove the PTEST and use the flags
  1285. // as they are prior to PTEST. Sometimes this requires the tested PTEST
  1286. // operand to be replaced with an equivalent instruction that also sets the
  1287. // flags.
  1288. Pred->setDesc(get(NewOp));
  1289. PTest->eraseFromParent();
  1290. if (OpChanged) {
  1291. bool succeeded = UpdateOperandRegClass(*Pred);
  1292. (void)succeeded;
  1293. assert(succeeded && "Operands have incompatible register classes!");
  1294. Pred->addRegisterDefined(AArch64::NZCV, TRI);
  1295. }
  1296. // Ensure that the flags def is live.
  1297. if (Pred->registerDefIsDead(AArch64::NZCV, TRI)) {
  1298. unsigned i = 0, e = Pred->getNumOperands();
  1299. for (; i != e; ++i) {
  1300. MachineOperand &MO = Pred->getOperand(i);
  1301. if (MO.isReg() && MO.isDef() && MO.getReg() == AArch64::NZCV) {
  1302. MO.setIsDead(false);
  1303. break;
  1304. }
  1305. }
  1306. }
  1307. return true;
  1308. }
  1309. /// Try to optimize a compare instruction. A compare instruction is an
  1310. /// instruction which produces AArch64::NZCV. It can be truly compare
  1311. /// instruction
  1312. /// when there are no uses of its destination register.
  1313. ///
  1314. /// The following steps are tried in order:
  1315. /// 1. Convert CmpInstr into an unconditional version.
  1316. /// 2. Remove CmpInstr if above there is an instruction producing a needed
  1317. /// condition code or an instruction which can be converted into such an
  1318. /// instruction.
  1319. /// Only comparison with zero is supported.
  1320. bool AArch64InstrInfo::optimizeCompareInstr(
  1321. MachineInstr &CmpInstr, Register SrcReg, Register SrcReg2, int64_t CmpMask,
  1322. int64_t CmpValue, const MachineRegisterInfo *MRI) const {
  1323. assert(CmpInstr.getParent());
  1324. assert(MRI);
  1325. // Replace SUBSWrr with SUBWrr if NZCV is not used.
  1326. int DeadNZCVIdx = CmpInstr.findRegisterDefOperandIdx(AArch64::NZCV, true);
  1327. if (DeadNZCVIdx != -1) {
  1328. if (CmpInstr.definesRegister(AArch64::WZR) ||
  1329. CmpInstr.definesRegister(AArch64::XZR)) {
  1330. CmpInstr.eraseFromParent();
  1331. return true;
  1332. }
  1333. unsigned Opc = CmpInstr.getOpcode();
  1334. unsigned NewOpc = convertToNonFlagSettingOpc(CmpInstr);
  1335. if (NewOpc == Opc)
  1336. return false;
  1337. const MCInstrDesc &MCID = get(NewOpc);
  1338. CmpInstr.setDesc(MCID);
  1339. CmpInstr.removeOperand(DeadNZCVIdx);
  1340. bool succeeded = UpdateOperandRegClass(CmpInstr);
  1341. (void)succeeded;
  1342. assert(succeeded && "Some operands reg class are incompatible!");
  1343. return true;
  1344. }
  1345. if (CmpInstr.getOpcode() == AArch64::PTEST_PP ||
  1346. CmpInstr.getOpcode() == AArch64::PTEST_PP_ANY)
  1347. return optimizePTestInstr(&CmpInstr, SrcReg, SrcReg2, MRI);
  1348. if (SrcReg2 != 0)
  1349. return false;
  1350. // CmpInstr is a Compare instruction if destination register is not used.
  1351. if (!MRI->use_nodbg_empty(CmpInstr.getOperand(0).getReg()))
  1352. return false;
  1353. if (CmpValue == 0 && substituteCmpToZero(CmpInstr, SrcReg, *MRI))
  1354. return true;
  1355. return (CmpValue == 0 || CmpValue == 1) &&
  1356. removeCmpToZeroOrOne(CmpInstr, SrcReg, CmpValue, *MRI);
  1357. }
  1358. /// Get opcode of S version of Instr.
  1359. /// If Instr is S version its opcode is returned.
  1360. /// AArch64::INSTRUCTION_LIST_END is returned if Instr does not have S version
  1361. /// or we are not interested in it.
  1362. static unsigned sForm(MachineInstr &Instr) {
  1363. switch (Instr.getOpcode()) {
  1364. default:
  1365. return AArch64::INSTRUCTION_LIST_END;
  1366. case AArch64::ADDSWrr:
  1367. case AArch64::ADDSWri:
  1368. case AArch64::ADDSXrr:
  1369. case AArch64::ADDSXri:
  1370. case AArch64::SUBSWrr:
  1371. case AArch64::SUBSWri:
  1372. case AArch64::SUBSXrr:
  1373. case AArch64::SUBSXri:
  1374. return Instr.getOpcode();
  1375. case AArch64::ADDWrr:
  1376. return AArch64::ADDSWrr;
  1377. case AArch64::ADDWri:
  1378. return AArch64::ADDSWri;
  1379. case AArch64::ADDXrr:
  1380. return AArch64::ADDSXrr;
  1381. case AArch64::ADDXri:
  1382. return AArch64::ADDSXri;
  1383. case AArch64::ADCWr:
  1384. return AArch64::ADCSWr;
  1385. case AArch64::ADCXr:
  1386. return AArch64::ADCSXr;
  1387. case AArch64::SUBWrr:
  1388. return AArch64::SUBSWrr;
  1389. case AArch64::SUBWri:
  1390. return AArch64::SUBSWri;
  1391. case AArch64::SUBXrr:
  1392. return AArch64::SUBSXrr;
  1393. case AArch64::SUBXri:
  1394. return AArch64::SUBSXri;
  1395. case AArch64::SBCWr:
  1396. return AArch64::SBCSWr;
  1397. case AArch64::SBCXr:
  1398. return AArch64::SBCSXr;
  1399. case AArch64::ANDWri:
  1400. return AArch64::ANDSWri;
  1401. case AArch64::ANDXri:
  1402. return AArch64::ANDSXri;
  1403. }
  1404. }
  1405. /// Check if AArch64::NZCV should be alive in successors of MBB.
  1406. static bool areCFlagsAliveInSuccessors(const MachineBasicBlock *MBB) {
  1407. for (auto *BB : MBB->successors())
  1408. if (BB->isLiveIn(AArch64::NZCV))
  1409. return true;
  1410. return false;
  1411. }
  1412. /// \returns The condition code operand index for \p Instr if it is a branch
  1413. /// or select and -1 otherwise.
  1414. static int
  1415. findCondCodeUseOperandIdxForBranchOrSelect(const MachineInstr &Instr) {
  1416. switch (Instr.getOpcode()) {
  1417. default:
  1418. return -1;
  1419. case AArch64::Bcc: {
  1420. int Idx = Instr.findRegisterUseOperandIdx(AArch64::NZCV);
  1421. assert(Idx >= 2);
  1422. return Idx - 2;
  1423. }
  1424. case AArch64::CSINVWr:
  1425. case AArch64::CSINVXr:
  1426. case AArch64::CSINCWr:
  1427. case AArch64::CSINCXr:
  1428. case AArch64::CSELWr:
  1429. case AArch64::CSELXr:
  1430. case AArch64::CSNEGWr:
  1431. case AArch64::CSNEGXr:
  1432. case AArch64::FCSELSrrr:
  1433. case AArch64::FCSELDrrr: {
  1434. int Idx = Instr.findRegisterUseOperandIdx(AArch64::NZCV);
  1435. assert(Idx >= 1);
  1436. return Idx - 1;
  1437. }
  1438. }
  1439. }
  1440. /// Find a condition code used by the instruction.
  1441. /// Returns AArch64CC::Invalid if either the instruction does not use condition
  1442. /// codes or we don't optimize CmpInstr in the presence of such instructions.
  1443. static AArch64CC::CondCode findCondCodeUsedByInstr(const MachineInstr &Instr) {
  1444. int CCIdx = findCondCodeUseOperandIdxForBranchOrSelect(Instr);
  1445. return CCIdx >= 0 ? static_cast<AArch64CC::CondCode>(
  1446. Instr.getOperand(CCIdx).getImm())
  1447. : AArch64CC::Invalid;
  1448. }
  1449. static UsedNZCV getUsedNZCV(AArch64CC::CondCode CC) {
  1450. assert(CC != AArch64CC::Invalid);
  1451. UsedNZCV UsedFlags;
  1452. switch (CC) {
  1453. default:
  1454. break;
  1455. case AArch64CC::EQ: // Z set
  1456. case AArch64CC::NE: // Z clear
  1457. UsedFlags.Z = true;
  1458. break;
  1459. case AArch64CC::HI: // Z clear and C set
  1460. case AArch64CC::LS: // Z set or C clear
  1461. UsedFlags.Z = true;
  1462. [[fallthrough]];
  1463. case AArch64CC::HS: // C set
  1464. case AArch64CC::LO: // C clear
  1465. UsedFlags.C = true;
  1466. break;
  1467. case AArch64CC::MI: // N set
  1468. case AArch64CC::PL: // N clear
  1469. UsedFlags.N = true;
  1470. break;
  1471. case AArch64CC::VS: // V set
  1472. case AArch64CC::VC: // V clear
  1473. UsedFlags.V = true;
  1474. break;
  1475. case AArch64CC::GT: // Z clear, N and V the same
  1476. case AArch64CC::LE: // Z set, N and V differ
  1477. UsedFlags.Z = true;
  1478. [[fallthrough]];
  1479. case AArch64CC::GE: // N and V the same
  1480. case AArch64CC::LT: // N and V differ
  1481. UsedFlags.N = true;
  1482. UsedFlags.V = true;
  1483. break;
  1484. }
  1485. return UsedFlags;
  1486. }
  1487. /// \returns Conditions flags used after \p CmpInstr in its MachineBB if NZCV
  1488. /// flags are not alive in successors of the same \p CmpInstr and \p MI parent.
  1489. /// \returns std::nullopt otherwise.
  1490. ///
  1491. /// Collect instructions using that flags in \p CCUseInstrs if provided.
  1492. std::optional<UsedNZCV>
  1493. llvm::examineCFlagsUse(MachineInstr &MI, MachineInstr &CmpInstr,
  1494. const TargetRegisterInfo &TRI,
  1495. SmallVectorImpl<MachineInstr *> *CCUseInstrs) {
  1496. MachineBasicBlock *CmpParent = CmpInstr.getParent();
  1497. if (MI.getParent() != CmpParent)
  1498. return std::nullopt;
  1499. if (areCFlagsAliveInSuccessors(CmpParent))
  1500. return std::nullopt;
  1501. UsedNZCV NZCVUsedAfterCmp;
  1502. for (MachineInstr &Instr : instructionsWithoutDebug(
  1503. std::next(CmpInstr.getIterator()), CmpParent->instr_end())) {
  1504. if (Instr.readsRegister(AArch64::NZCV, &TRI)) {
  1505. AArch64CC::CondCode CC = findCondCodeUsedByInstr(Instr);
  1506. if (CC == AArch64CC::Invalid) // Unsupported conditional instruction
  1507. return std::nullopt;
  1508. NZCVUsedAfterCmp |= getUsedNZCV(CC);
  1509. if (CCUseInstrs)
  1510. CCUseInstrs->push_back(&Instr);
  1511. }
  1512. if (Instr.modifiesRegister(AArch64::NZCV, &TRI))
  1513. break;
  1514. }
  1515. return NZCVUsedAfterCmp;
  1516. }
  1517. static bool isADDSRegImm(unsigned Opcode) {
  1518. return Opcode == AArch64::ADDSWri || Opcode == AArch64::ADDSXri;
  1519. }
  1520. static bool isSUBSRegImm(unsigned Opcode) {
  1521. return Opcode == AArch64::SUBSWri || Opcode == AArch64::SUBSXri;
  1522. }
  1523. /// Check if CmpInstr can be substituted by MI.
  1524. ///
  1525. /// CmpInstr can be substituted:
  1526. /// - CmpInstr is either 'ADDS %vreg, 0' or 'SUBS %vreg, 0'
  1527. /// - and, MI and CmpInstr are from the same MachineBB
  1528. /// - and, condition flags are not alive in successors of the CmpInstr parent
  1529. /// - and, if MI opcode is the S form there must be no defs of flags between
  1530. /// MI and CmpInstr
  1531. /// or if MI opcode is not the S form there must be neither defs of flags
  1532. /// nor uses of flags between MI and CmpInstr.
  1533. /// - and C/V flags are not used after CmpInstr
  1534. static bool canInstrSubstituteCmpInstr(MachineInstr &MI, MachineInstr &CmpInstr,
  1535. const TargetRegisterInfo &TRI) {
  1536. assert(sForm(MI) != AArch64::INSTRUCTION_LIST_END);
  1537. const unsigned CmpOpcode = CmpInstr.getOpcode();
  1538. if (!isADDSRegImm(CmpOpcode) && !isSUBSRegImm(CmpOpcode))
  1539. return false;
  1540. std::optional<UsedNZCV> NZVCUsed = examineCFlagsUse(MI, CmpInstr, TRI);
  1541. if (!NZVCUsed || NZVCUsed->C || NZVCUsed->V)
  1542. return false;
  1543. AccessKind AccessToCheck = AK_Write;
  1544. if (sForm(MI) != MI.getOpcode())
  1545. AccessToCheck = AK_All;
  1546. return !areCFlagsAccessedBetweenInstrs(&MI, &CmpInstr, &TRI, AccessToCheck);
  1547. }
  1548. /// Substitute an instruction comparing to zero with another instruction
  1549. /// which produces needed condition flags.
  1550. ///
  1551. /// Return true on success.
  1552. bool AArch64InstrInfo::substituteCmpToZero(
  1553. MachineInstr &CmpInstr, unsigned SrcReg,
  1554. const MachineRegisterInfo &MRI) const {
  1555. // Get the unique definition of SrcReg.
  1556. MachineInstr *MI = MRI.getUniqueVRegDef(SrcReg);
  1557. if (!MI)
  1558. return false;
  1559. const TargetRegisterInfo &TRI = getRegisterInfo();
  1560. unsigned NewOpc = sForm(*MI);
  1561. if (NewOpc == AArch64::INSTRUCTION_LIST_END)
  1562. return false;
  1563. if (!canInstrSubstituteCmpInstr(*MI, CmpInstr, TRI))
  1564. return false;
  1565. // Update the instruction to set NZCV.
  1566. MI->setDesc(get(NewOpc));
  1567. CmpInstr.eraseFromParent();
  1568. bool succeeded = UpdateOperandRegClass(*MI);
  1569. (void)succeeded;
  1570. assert(succeeded && "Some operands reg class are incompatible!");
  1571. MI->addRegisterDefined(AArch64::NZCV, &TRI);
  1572. return true;
  1573. }
  1574. /// \returns True if \p CmpInstr can be removed.
  1575. ///
  1576. /// \p IsInvertCC is true if, after removing \p CmpInstr, condition
  1577. /// codes used in \p CCUseInstrs must be inverted.
  1578. static bool canCmpInstrBeRemoved(MachineInstr &MI, MachineInstr &CmpInstr,
  1579. int CmpValue, const TargetRegisterInfo &TRI,
  1580. SmallVectorImpl<MachineInstr *> &CCUseInstrs,
  1581. bool &IsInvertCC) {
  1582. assert((CmpValue == 0 || CmpValue == 1) &&
  1583. "Only comparisons to 0 or 1 considered for removal!");
  1584. // MI is 'CSINCWr %vreg, wzr, wzr, <cc>' or 'CSINCXr %vreg, xzr, xzr, <cc>'
  1585. unsigned MIOpc = MI.getOpcode();
  1586. if (MIOpc == AArch64::CSINCWr) {
  1587. if (MI.getOperand(1).getReg() != AArch64::WZR ||
  1588. MI.getOperand(2).getReg() != AArch64::WZR)
  1589. return false;
  1590. } else if (MIOpc == AArch64::CSINCXr) {
  1591. if (MI.getOperand(1).getReg() != AArch64::XZR ||
  1592. MI.getOperand(2).getReg() != AArch64::XZR)
  1593. return false;
  1594. } else {
  1595. return false;
  1596. }
  1597. AArch64CC::CondCode MICC = findCondCodeUsedByInstr(MI);
  1598. if (MICC == AArch64CC::Invalid)
  1599. return false;
  1600. // NZCV needs to be defined
  1601. if (MI.findRegisterDefOperandIdx(AArch64::NZCV, true) != -1)
  1602. return false;
  1603. // CmpInstr is 'ADDS %vreg, 0' or 'SUBS %vreg, 0' or 'SUBS %vreg, 1'
  1604. const unsigned CmpOpcode = CmpInstr.getOpcode();
  1605. bool IsSubsRegImm = isSUBSRegImm(CmpOpcode);
  1606. if (CmpValue && !IsSubsRegImm)
  1607. return false;
  1608. if (!CmpValue && !IsSubsRegImm && !isADDSRegImm(CmpOpcode))
  1609. return false;
  1610. // MI conditions allowed: eq, ne, mi, pl
  1611. UsedNZCV MIUsedNZCV = getUsedNZCV(MICC);
  1612. if (MIUsedNZCV.C || MIUsedNZCV.V)
  1613. return false;
  1614. std::optional<UsedNZCV> NZCVUsedAfterCmp =
  1615. examineCFlagsUse(MI, CmpInstr, TRI, &CCUseInstrs);
  1616. // Condition flags are not used in CmpInstr basic block successors and only
  1617. // Z or N flags allowed to be used after CmpInstr within its basic block
  1618. if (!NZCVUsedAfterCmp || NZCVUsedAfterCmp->C || NZCVUsedAfterCmp->V)
  1619. return false;
  1620. // Z or N flag used after CmpInstr must correspond to the flag used in MI
  1621. if ((MIUsedNZCV.Z && NZCVUsedAfterCmp->N) ||
  1622. (MIUsedNZCV.N && NZCVUsedAfterCmp->Z))
  1623. return false;
  1624. // If CmpInstr is comparison to zero MI conditions are limited to eq, ne
  1625. if (MIUsedNZCV.N && !CmpValue)
  1626. return false;
  1627. // There must be no defs of flags between MI and CmpInstr
  1628. if (areCFlagsAccessedBetweenInstrs(&MI, &CmpInstr, &TRI, AK_Write))
  1629. return false;
  1630. // Condition code is inverted in the following cases:
  1631. // 1. MI condition is ne; CmpInstr is 'ADDS %vreg, 0' or 'SUBS %vreg, 0'
  1632. // 2. MI condition is eq, pl; CmpInstr is 'SUBS %vreg, 1'
  1633. IsInvertCC = (CmpValue && (MICC == AArch64CC::EQ || MICC == AArch64CC::PL)) ||
  1634. (!CmpValue && MICC == AArch64CC::NE);
  1635. return true;
  1636. }
  1637. /// Remove comparison in csinc-cmp sequence
  1638. ///
  1639. /// Examples:
  1640. /// 1. \code
  1641. /// csinc w9, wzr, wzr, ne
  1642. /// cmp w9, #0
  1643. /// b.eq
  1644. /// \endcode
  1645. /// to
  1646. /// \code
  1647. /// csinc w9, wzr, wzr, ne
  1648. /// b.ne
  1649. /// \endcode
  1650. ///
  1651. /// 2. \code
  1652. /// csinc x2, xzr, xzr, mi
  1653. /// cmp x2, #1
  1654. /// b.pl
  1655. /// \endcode
  1656. /// to
  1657. /// \code
  1658. /// csinc x2, xzr, xzr, mi
  1659. /// b.pl
  1660. /// \endcode
  1661. ///
  1662. /// \param CmpInstr comparison instruction
  1663. /// \return True when comparison removed
  1664. bool AArch64InstrInfo::removeCmpToZeroOrOne(
  1665. MachineInstr &CmpInstr, unsigned SrcReg, int CmpValue,
  1666. const MachineRegisterInfo &MRI) const {
  1667. MachineInstr *MI = MRI.getUniqueVRegDef(SrcReg);
  1668. if (!MI)
  1669. return false;
  1670. const TargetRegisterInfo &TRI = getRegisterInfo();
  1671. SmallVector<MachineInstr *, 4> CCUseInstrs;
  1672. bool IsInvertCC = false;
  1673. if (!canCmpInstrBeRemoved(*MI, CmpInstr, CmpValue, TRI, CCUseInstrs,
  1674. IsInvertCC))
  1675. return false;
  1676. // Make transformation
  1677. CmpInstr.eraseFromParent();
  1678. if (IsInvertCC) {
  1679. // Invert condition codes in CmpInstr CC users
  1680. for (MachineInstr *CCUseInstr : CCUseInstrs) {
  1681. int Idx = findCondCodeUseOperandIdxForBranchOrSelect(*CCUseInstr);
  1682. assert(Idx >= 0 && "Unexpected instruction using CC.");
  1683. MachineOperand &CCOperand = CCUseInstr->getOperand(Idx);
  1684. AArch64CC::CondCode CCUse = AArch64CC::getInvertedCondCode(
  1685. static_cast<AArch64CC::CondCode>(CCOperand.getImm()));
  1686. CCOperand.setImm(CCUse);
  1687. }
  1688. }
  1689. return true;
  1690. }
  1691. bool AArch64InstrInfo::expandPostRAPseudo(MachineInstr &MI) const {
  1692. if (MI.getOpcode() != TargetOpcode::LOAD_STACK_GUARD &&
  1693. MI.getOpcode() != AArch64::CATCHRET)
  1694. return false;
  1695. MachineBasicBlock &MBB = *MI.getParent();
  1696. auto &Subtarget = MBB.getParent()->getSubtarget<AArch64Subtarget>();
  1697. auto TRI = Subtarget.getRegisterInfo();
  1698. DebugLoc DL = MI.getDebugLoc();
  1699. if (MI.getOpcode() == AArch64::CATCHRET) {
  1700. // Skip to the first instruction before the epilog.
  1701. const TargetInstrInfo *TII =
  1702. MBB.getParent()->getSubtarget().getInstrInfo();
  1703. MachineBasicBlock *TargetMBB = MI.getOperand(0).getMBB();
  1704. auto MBBI = MachineBasicBlock::iterator(MI);
  1705. MachineBasicBlock::iterator FirstEpilogSEH = std::prev(MBBI);
  1706. while (FirstEpilogSEH->getFlag(MachineInstr::FrameDestroy) &&
  1707. FirstEpilogSEH != MBB.begin())
  1708. FirstEpilogSEH = std::prev(FirstEpilogSEH);
  1709. if (FirstEpilogSEH != MBB.begin())
  1710. FirstEpilogSEH = std::next(FirstEpilogSEH);
  1711. BuildMI(MBB, FirstEpilogSEH, DL, TII->get(AArch64::ADRP))
  1712. .addReg(AArch64::X0, RegState::Define)
  1713. .addMBB(TargetMBB);
  1714. BuildMI(MBB, FirstEpilogSEH, DL, TII->get(AArch64::ADDXri))
  1715. .addReg(AArch64::X0, RegState::Define)
  1716. .addReg(AArch64::X0)
  1717. .addMBB(TargetMBB)
  1718. .addImm(0);
  1719. return true;
  1720. }
  1721. Register Reg = MI.getOperand(0).getReg();
  1722. Module &M = *MBB.getParent()->getFunction().getParent();
  1723. if (M.getStackProtectorGuard() == "sysreg") {
  1724. const AArch64SysReg::SysReg *SrcReg =
  1725. AArch64SysReg::lookupSysRegByName(M.getStackProtectorGuardReg());
  1726. if (!SrcReg)
  1727. report_fatal_error("Unknown SysReg for Stack Protector Guard Register");
  1728. // mrs xN, sysreg
  1729. BuildMI(MBB, MI, DL, get(AArch64::MRS))
  1730. .addDef(Reg, RegState::Renamable)
  1731. .addImm(SrcReg->Encoding);
  1732. int Offset = M.getStackProtectorGuardOffset();
  1733. if (Offset >= 0 && Offset <= 32760 && Offset % 8 == 0) {
  1734. // ldr xN, [xN, #offset]
  1735. BuildMI(MBB, MI, DL, get(AArch64::LDRXui))
  1736. .addDef(Reg)
  1737. .addUse(Reg, RegState::Kill)
  1738. .addImm(Offset / 8);
  1739. } else if (Offset >= -256 && Offset <= 255) {
  1740. // ldur xN, [xN, #offset]
  1741. BuildMI(MBB, MI, DL, get(AArch64::LDURXi))
  1742. .addDef(Reg)
  1743. .addUse(Reg, RegState::Kill)
  1744. .addImm(Offset);
  1745. } else if (Offset >= -4095 && Offset <= 4095) {
  1746. if (Offset > 0) {
  1747. // add xN, xN, #offset
  1748. BuildMI(MBB, MI, DL, get(AArch64::ADDXri))
  1749. .addDef(Reg)
  1750. .addUse(Reg, RegState::Kill)
  1751. .addImm(Offset)
  1752. .addImm(0);
  1753. } else {
  1754. // sub xN, xN, #offset
  1755. BuildMI(MBB, MI, DL, get(AArch64::SUBXri))
  1756. .addDef(Reg)
  1757. .addUse(Reg, RegState::Kill)
  1758. .addImm(-Offset)
  1759. .addImm(0);
  1760. }
  1761. // ldr xN, [xN]
  1762. BuildMI(MBB, MI, DL, get(AArch64::LDRXui))
  1763. .addDef(Reg)
  1764. .addUse(Reg, RegState::Kill)
  1765. .addImm(0);
  1766. } else {
  1767. // Cases that are larger than +/- 4095 and not a multiple of 8, or larger
  1768. // than 23760.
  1769. // It might be nice to use AArch64::MOVi32imm here, which would get
  1770. // expanded in PreSched2 after PostRA, but our lone scratch Reg already
  1771. // contains the MRS result. findScratchNonCalleeSaveRegister() in
  1772. // AArch64FrameLowering might help us find such a scratch register
  1773. // though. If we failed to find a scratch register, we could emit a
  1774. // stream of add instructions to build up the immediate. Or, we could try
  1775. // to insert a AArch64::MOVi32imm before register allocation so that we
  1776. // didn't need to scavenge for a scratch register.
  1777. report_fatal_error("Unable to encode Stack Protector Guard Offset");
  1778. }
  1779. MBB.erase(MI);
  1780. return true;
  1781. }
  1782. const GlobalValue *GV =
  1783. cast<GlobalValue>((*MI.memoperands_begin())->getValue());
  1784. const TargetMachine &TM = MBB.getParent()->getTarget();
  1785. unsigned OpFlags = Subtarget.ClassifyGlobalReference(GV, TM);
  1786. const unsigned char MO_NC = AArch64II::MO_NC;
  1787. if ((OpFlags & AArch64II::MO_GOT) != 0) {
  1788. BuildMI(MBB, MI, DL, get(AArch64::LOADgot), Reg)
  1789. .addGlobalAddress(GV, 0, OpFlags);
  1790. if (Subtarget.isTargetILP32()) {
  1791. unsigned Reg32 = TRI->getSubReg(Reg, AArch64::sub_32);
  1792. BuildMI(MBB, MI, DL, get(AArch64::LDRWui))
  1793. .addDef(Reg32, RegState::Dead)
  1794. .addUse(Reg, RegState::Kill)
  1795. .addImm(0)
  1796. .addMemOperand(*MI.memoperands_begin())
  1797. .addDef(Reg, RegState::Implicit);
  1798. } else {
  1799. BuildMI(MBB, MI, DL, get(AArch64::LDRXui), Reg)
  1800. .addReg(Reg, RegState::Kill)
  1801. .addImm(0)
  1802. .addMemOperand(*MI.memoperands_begin());
  1803. }
  1804. } else if (TM.getCodeModel() == CodeModel::Large) {
  1805. assert(!Subtarget.isTargetILP32() && "how can large exist in ILP32?");
  1806. BuildMI(MBB, MI, DL, get(AArch64::MOVZXi), Reg)
  1807. .addGlobalAddress(GV, 0, AArch64II::MO_G0 | MO_NC)
  1808. .addImm(0);
  1809. BuildMI(MBB, MI, DL, get(AArch64::MOVKXi), Reg)
  1810. .addReg(Reg, RegState::Kill)
  1811. .addGlobalAddress(GV, 0, AArch64II::MO_G1 | MO_NC)
  1812. .addImm(16);
  1813. BuildMI(MBB, MI, DL, get(AArch64::MOVKXi), Reg)
  1814. .addReg(Reg, RegState::Kill)
  1815. .addGlobalAddress(GV, 0, AArch64II::MO_G2 | MO_NC)
  1816. .addImm(32);
  1817. BuildMI(MBB, MI, DL, get(AArch64::MOVKXi), Reg)
  1818. .addReg(Reg, RegState::Kill)
  1819. .addGlobalAddress(GV, 0, AArch64II::MO_G3)
  1820. .addImm(48);
  1821. BuildMI(MBB, MI, DL, get(AArch64::LDRXui), Reg)
  1822. .addReg(Reg, RegState::Kill)
  1823. .addImm(0)
  1824. .addMemOperand(*MI.memoperands_begin());
  1825. } else if (TM.getCodeModel() == CodeModel::Tiny) {
  1826. BuildMI(MBB, MI, DL, get(AArch64::ADR), Reg)
  1827. .addGlobalAddress(GV, 0, OpFlags);
  1828. } else {
  1829. BuildMI(MBB, MI, DL, get(AArch64::ADRP), Reg)
  1830. .addGlobalAddress(GV, 0, OpFlags | AArch64II::MO_PAGE);
  1831. unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | MO_NC;
  1832. if (Subtarget.isTargetILP32()) {
  1833. unsigned Reg32 = TRI->getSubReg(Reg, AArch64::sub_32);
  1834. BuildMI(MBB, MI, DL, get(AArch64::LDRWui))
  1835. .addDef(Reg32, RegState::Dead)
  1836. .addUse(Reg, RegState::Kill)
  1837. .addGlobalAddress(GV, 0, LoFlags)
  1838. .addMemOperand(*MI.memoperands_begin())
  1839. .addDef(Reg, RegState::Implicit);
  1840. } else {
  1841. BuildMI(MBB, MI, DL, get(AArch64::LDRXui), Reg)
  1842. .addReg(Reg, RegState::Kill)
  1843. .addGlobalAddress(GV, 0, LoFlags)
  1844. .addMemOperand(*MI.memoperands_begin());
  1845. }
  1846. }
  1847. MBB.erase(MI);
  1848. return true;
  1849. }
  1850. // Return true if this instruction simply sets its single destination register
  1851. // to zero. This is equivalent to a register rename of the zero-register.
  1852. bool AArch64InstrInfo::isGPRZero(const MachineInstr &MI) {
  1853. switch (MI.getOpcode()) {
  1854. default:
  1855. break;
  1856. case AArch64::MOVZWi:
  1857. case AArch64::MOVZXi: // movz Rd, #0 (LSL #0)
  1858. if (MI.getOperand(1).isImm() && MI.getOperand(1).getImm() == 0) {
  1859. assert(MI.getDesc().getNumOperands() == 3 &&
  1860. MI.getOperand(2).getImm() == 0 && "invalid MOVZi operands");
  1861. return true;
  1862. }
  1863. break;
  1864. case AArch64::ANDWri: // and Rd, Rzr, #imm
  1865. return MI.getOperand(1).getReg() == AArch64::WZR;
  1866. case AArch64::ANDXri:
  1867. return MI.getOperand(1).getReg() == AArch64::XZR;
  1868. case TargetOpcode::COPY:
  1869. return MI.getOperand(1).getReg() == AArch64::WZR;
  1870. }
  1871. return false;
  1872. }
  1873. // Return true if this instruction simply renames a general register without
  1874. // modifying bits.
  1875. bool AArch64InstrInfo::isGPRCopy(const MachineInstr &MI) {
  1876. switch (MI.getOpcode()) {
  1877. default:
  1878. break;
  1879. case TargetOpcode::COPY: {
  1880. // GPR32 copies will by lowered to ORRXrs
  1881. Register DstReg = MI.getOperand(0).getReg();
  1882. return (AArch64::GPR32RegClass.contains(DstReg) ||
  1883. AArch64::GPR64RegClass.contains(DstReg));
  1884. }
  1885. case AArch64::ORRXrs: // orr Xd, Xzr, Xm (LSL #0)
  1886. if (MI.getOperand(1).getReg() == AArch64::XZR) {
  1887. assert(MI.getDesc().getNumOperands() == 4 &&
  1888. MI.getOperand(3).getImm() == 0 && "invalid ORRrs operands");
  1889. return true;
  1890. }
  1891. break;
  1892. case AArch64::ADDXri: // add Xd, Xn, #0 (LSL #0)
  1893. if (MI.getOperand(2).getImm() == 0) {
  1894. assert(MI.getDesc().getNumOperands() == 4 &&
  1895. MI.getOperand(3).getImm() == 0 && "invalid ADDXri operands");
  1896. return true;
  1897. }
  1898. break;
  1899. }
  1900. return false;
  1901. }
  1902. // Return true if this instruction simply renames a general register without
  1903. // modifying bits.
  1904. bool AArch64InstrInfo::isFPRCopy(const MachineInstr &MI) {
  1905. switch (MI.getOpcode()) {
  1906. default:
  1907. break;
  1908. case TargetOpcode::COPY: {
  1909. Register DstReg = MI.getOperand(0).getReg();
  1910. return AArch64::FPR128RegClass.contains(DstReg);
  1911. }
  1912. case AArch64::ORRv16i8:
  1913. if (MI.getOperand(1).getReg() == MI.getOperand(2).getReg()) {
  1914. assert(MI.getDesc().getNumOperands() == 3 && MI.getOperand(0).isReg() &&
  1915. "invalid ORRv16i8 operands");
  1916. return true;
  1917. }
  1918. break;
  1919. }
  1920. return false;
  1921. }
  1922. unsigned AArch64InstrInfo::isLoadFromStackSlot(const MachineInstr &MI,
  1923. int &FrameIndex) const {
  1924. switch (MI.getOpcode()) {
  1925. default:
  1926. break;
  1927. case AArch64::LDRWui:
  1928. case AArch64::LDRXui:
  1929. case AArch64::LDRBui:
  1930. case AArch64::LDRHui:
  1931. case AArch64::LDRSui:
  1932. case AArch64::LDRDui:
  1933. case AArch64::LDRQui:
  1934. if (MI.getOperand(0).getSubReg() == 0 && MI.getOperand(1).isFI() &&
  1935. MI.getOperand(2).isImm() && MI.getOperand(2).getImm() == 0) {
  1936. FrameIndex = MI.getOperand(1).getIndex();
  1937. return MI.getOperand(0).getReg();
  1938. }
  1939. break;
  1940. }
  1941. return 0;
  1942. }
  1943. unsigned AArch64InstrInfo::isStoreToStackSlot(const MachineInstr &MI,
  1944. int &FrameIndex) const {
  1945. switch (MI.getOpcode()) {
  1946. default:
  1947. break;
  1948. case AArch64::STRWui:
  1949. case AArch64::STRXui:
  1950. case AArch64::STRBui:
  1951. case AArch64::STRHui:
  1952. case AArch64::STRSui:
  1953. case AArch64::STRDui:
  1954. case AArch64::STRQui:
  1955. case AArch64::LDR_PXI:
  1956. case AArch64::STR_PXI:
  1957. if (MI.getOperand(0).getSubReg() == 0 && MI.getOperand(1).isFI() &&
  1958. MI.getOperand(2).isImm() && MI.getOperand(2).getImm() == 0) {
  1959. FrameIndex = MI.getOperand(1).getIndex();
  1960. return MI.getOperand(0).getReg();
  1961. }
  1962. break;
  1963. }
  1964. return 0;
  1965. }
  1966. /// Check all MachineMemOperands for a hint to suppress pairing.
  1967. bool AArch64InstrInfo::isLdStPairSuppressed(const MachineInstr &MI) {
  1968. return llvm::any_of(MI.memoperands(), [](MachineMemOperand *MMO) {
  1969. return MMO->getFlags() & MOSuppressPair;
  1970. });
  1971. }
  1972. /// Set a flag on the first MachineMemOperand to suppress pairing.
  1973. void AArch64InstrInfo::suppressLdStPair(MachineInstr &MI) {
  1974. if (MI.memoperands_empty())
  1975. return;
  1976. (*MI.memoperands_begin())->setFlags(MOSuppressPair);
  1977. }
  1978. /// Check all MachineMemOperands for a hint that the load/store is strided.
  1979. bool AArch64InstrInfo::isStridedAccess(const MachineInstr &MI) {
  1980. return llvm::any_of(MI.memoperands(), [](MachineMemOperand *MMO) {
  1981. return MMO->getFlags() & MOStridedAccess;
  1982. });
  1983. }
  1984. bool AArch64InstrInfo::hasUnscaledLdStOffset(unsigned Opc) {
  1985. switch (Opc) {
  1986. default:
  1987. return false;
  1988. case AArch64::STURSi:
  1989. case AArch64::STRSpre:
  1990. case AArch64::STURDi:
  1991. case AArch64::STRDpre:
  1992. case AArch64::STURQi:
  1993. case AArch64::STRQpre:
  1994. case AArch64::STURBBi:
  1995. case AArch64::STURHHi:
  1996. case AArch64::STURWi:
  1997. case AArch64::STRWpre:
  1998. case AArch64::STURXi:
  1999. case AArch64::STRXpre:
  2000. case AArch64::LDURSi:
  2001. case AArch64::LDRSpre:
  2002. case AArch64::LDURDi:
  2003. case AArch64::LDRDpre:
  2004. case AArch64::LDURQi:
  2005. case AArch64::LDRQpre:
  2006. case AArch64::LDURWi:
  2007. case AArch64::LDRWpre:
  2008. case AArch64::LDURXi:
  2009. case AArch64::LDRXpre:
  2010. case AArch64::LDURSWi:
  2011. case AArch64::LDURHHi:
  2012. case AArch64::LDURBBi:
  2013. case AArch64::LDURSBWi:
  2014. case AArch64::LDURSHWi:
  2015. return true;
  2016. }
  2017. }
  2018. std::optional<unsigned> AArch64InstrInfo::getUnscaledLdSt(unsigned Opc) {
  2019. switch (Opc) {
  2020. default: return {};
  2021. case AArch64::PRFMui: return AArch64::PRFUMi;
  2022. case AArch64::LDRXui: return AArch64::LDURXi;
  2023. case AArch64::LDRWui: return AArch64::LDURWi;
  2024. case AArch64::LDRBui: return AArch64::LDURBi;
  2025. case AArch64::LDRHui: return AArch64::LDURHi;
  2026. case AArch64::LDRSui: return AArch64::LDURSi;
  2027. case AArch64::LDRDui: return AArch64::LDURDi;
  2028. case AArch64::LDRQui: return AArch64::LDURQi;
  2029. case AArch64::LDRBBui: return AArch64::LDURBBi;
  2030. case AArch64::LDRHHui: return AArch64::LDURHHi;
  2031. case AArch64::LDRSBXui: return AArch64::LDURSBXi;
  2032. case AArch64::LDRSBWui: return AArch64::LDURSBWi;
  2033. case AArch64::LDRSHXui: return AArch64::LDURSHXi;
  2034. case AArch64::LDRSHWui: return AArch64::LDURSHWi;
  2035. case AArch64::LDRSWui: return AArch64::LDURSWi;
  2036. case AArch64::STRXui: return AArch64::STURXi;
  2037. case AArch64::STRWui: return AArch64::STURWi;
  2038. case AArch64::STRBui: return AArch64::STURBi;
  2039. case AArch64::STRHui: return AArch64::STURHi;
  2040. case AArch64::STRSui: return AArch64::STURSi;
  2041. case AArch64::STRDui: return AArch64::STURDi;
  2042. case AArch64::STRQui: return AArch64::STURQi;
  2043. case AArch64::STRBBui: return AArch64::STURBBi;
  2044. case AArch64::STRHHui: return AArch64::STURHHi;
  2045. }
  2046. }
  2047. unsigned AArch64InstrInfo::getLoadStoreImmIdx(unsigned Opc) {
  2048. switch (Opc) {
  2049. default:
  2050. return 2;
  2051. case AArch64::LDPXi:
  2052. case AArch64::LDPDi:
  2053. case AArch64::STPXi:
  2054. case AArch64::STPDi:
  2055. case AArch64::LDNPXi:
  2056. case AArch64::LDNPDi:
  2057. case AArch64::STNPXi:
  2058. case AArch64::STNPDi:
  2059. case AArch64::LDPQi:
  2060. case AArch64::STPQi:
  2061. case AArch64::LDNPQi:
  2062. case AArch64::STNPQi:
  2063. case AArch64::LDPWi:
  2064. case AArch64::LDPSi:
  2065. case AArch64::STPWi:
  2066. case AArch64::STPSi:
  2067. case AArch64::LDNPWi:
  2068. case AArch64::LDNPSi:
  2069. case AArch64::STNPWi:
  2070. case AArch64::STNPSi:
  2071. case AArch64::LDG:
  2072. case AArch64::STGPi:
  2073. case AArch64::LD1B_IMM:
  2074. case AArch64::LD1B_H_IMM:
  2075. case AArch64::LD1B_S_IMM:
  2076. case AArch64::LD1B_D_IMM:
  2077. case AArch64::LD1SB_H_IMM:
  2078. case AArch64::LD1SB_S_IMM:
  2079. case AArch64::LD1SB_D_IMM:
  2080. case AArch64::LD1H_IMM:
  2081. case AArch64::LD1H_S_IMM:
  2082. case AArch64::LD1H_D_IMM:
  2083. case AArch64::LD1SH_S_IMM:
  2084. case AArch64::LD1SH_D_IMM:
  2085. case AArch64::LD1W_IMM:
  2086. case AArch64::LD1W_D_IMM:
  2087. case AArch64::LD1SW_D_IMM:
  2088. case AArch64::LD1D_IMM:
  2089. case AArch64::LD2B_IMM:
  2090. case AArch64::LD2H_IMM:
  2091. case AArch64::LD2W_IMM:
  2092. case AArch64::LD2D_IMM:
  2093. case AArch64::LD3B_IMM:
  2094. case AArch64::LD3H_IMM:
  2095. case AArch64::LD3W_IMM:
  2096. case AArch64::LD3D_IMM:
  2097. case AArch64::LD4B_IMM:
  2098. case AArch64::LD4H_IMM:
  2099. case AArch64::LD4W_IMM:
  2100. case AArch64::LD4D_IMM:
  2101. case AArch64::ST1B_IMM:
  2102. case AArch64::ST1B_H_IMM:
  2103. case AArch64::ST1B_S_IMM:
  2104. case AArch64::ST1B_D_IMM:
  2105. case AArch64::ST1H_IMM:
  2106. case AArch64::ST1H_S_IMM:
  2107. case AArch64::ST1H_D_IMM:
  2108. case AArch64::ST1W_IMM:
  2109. case AArch64::ST1W_D_IMM:
  2110. case AArch64::ST1D_IMM:
  2111. case AArch64::ST2B_IMM:
  2112. case AArch64::ST2H_IMM:
  2113. case AArch64::ST2W_IMM:
  2114. case AArch64::ST2D_IMM:
  2115. case AArch64::ST3B_IMM:
  2116. case AArch64::ST3H_IMM:
  2117. case AArch64::ST3W_IMM:
  2118. case AArch64::ST3D_IMM:
  2119. case AArch64::ST4B_IMM:
  2120. case AArch64::ST4H_IMM:
  2121. case AArch64::ST4W_IMM:
  2122. case AArch64::ST4D_IMM:
  2123. case AArch64::LD1RB_IMM:
  2124. case AArch64::LD1RB_H_IMM:
  2125. case AArch64::LD1RB_S_IMM:
  2126. case AArch64::LD1RB_D_IMM:
  2127. case AArch64::LD1RSB_H_IMM:
  2128. case AArch64::LD1RSB_S_IMM:
  2129. case AArch64::LD1RSB_D_IMM:
  2130. case AArch64::LD1RH_IMM:
  2131. case AArch64::LD1RH_S_IMM:
  2132. case AArch64::LD1RH_D_IMM:
  2133. case AArch64::LD1RSH_S_IMM:
  2134. case AArch64::LD1RSH_D_IMM:
  2135. case AArch64::LD1RW_IMM:
  2136. case AArch64::LD1RW_D_IMM:
  2137. case AArch64::LD1RSW_IMM:
  2138. case AArch64::LD1RD_IMM:
  2139. case AArch64::LDNT1B_ZRI:
  2140. case AArch64::LDNT1H_ZRI:
  2141. case AArch64::LDNT1W_ZRI:
  2142. case AArch64::LDNT1D_ZRI:
  2143. case AArch64::STNT1B_ZRI:
  2144. case AArch64::STNT1H_ZRI:
  2145. case AArch64::STNT1W_ZRI:
  2146. case AArch64::STNT1D_ZRI:
  2147. case AArch64::LDNF1B_IMM:
  2148. case AArch64::LDNF1B_H_IMM:
  2149. case AArch64::LDNF1B_S_IMM:
  2150. case AArch64::LDNF1B_D_IMM:
  2151. case AArch64::LDNF1SB_H_IMM:
  2152. case AArch64::LDNF1SB_S_IMM:
  2153. case AArch64::LDNF1SB_D_IMM:
  2154. case AArch64::LDNF1H_IMM:
  2155. case AArch64::LDNF1H_S_IMM:
  2156. case AArch64::LDNF1H_D_IMM:
  2157. case AArch64::LDNF1SH_S_IMM:
  2158. case AArch64::LDNF1SH_D_IMM:
  2159. case AArch64::LDNF1W_IMM:
  2160. case AArch64::LDNF1W_D_IMM:
  2161. case AArch64::LDNF1SW_D_IMM:
  2162. case AArch64::LDNF1D_IMM:
  2163. return 3;
  2164. case AArch64::ADDG:
  2165. case AArch64::STGOffset:
  2166. case AArch64::LDR_PXI:
  2167. case AArch64::STR_PXI:
  2168. return 2;
  2169. }
  2170. }
  2171. bool AArch64InstrInfo::isPairableLdStInst(const MachineInstr &MI) {
  2172. switch (MI.getOpcode()) {
  2173. default:
  2174. return false;
  2175. // Scaled instructions.
  2176. case AArch64::STRSui:
  2177. case AArch64::STRDui:
  2178. case AArch64::STRQui:
  2179. case AArch64::STRXui:
  2180. case AArch64::STRWui:
  2181. case AArch64::LDRSui:
  2182. case AArch64::LDRDui:
  2183. case AArch64::LDRQui:
  2184. case AArch64::LDRXui:
  2185. case AArch64::LDRWui:
  2186. case AArch64::LDRSWui:
  2187. // Unscaled instructions.
  2188. case AArch64::STURSi:
  2189. case AArch64::STRSpre:
  2190. case AArch64::STURDi:
  2191. case AArch64::STRDpre:
  2192. case AArch64::STURQi:
  2193. case AArch64::STRQpre:
  2194. case AArch64::STURWi:
  2195. case AArch64::STRWpre:
  2196. case AArch64::STURXi:
  2197. case AArch64::STRXpre:
  2198. case AArch64::LDURSi:
  2199. case AArch64::LDRSpre:
  2200. case AArch64::LDURDi:
  2201. case AArch64::LDRDpre:
  2202. case AArch64::LDURQi:
  2203. case AArch64::LDRQpre:
  2204. case AArch64::LDURWi:
  2205. case AArch64::LDRWpre:
  2206. case AArch64::LDURXi:
  2207. case AArch64::LDRXpre:
  2208. case AArch64::LDURSWi:
  2209. return true;
  2210. }
  2211. }
  2212. unsigned AArch64InstrInfo::convertToFlagSettingOpc(unsigned Opc) {
  2213. switch (Opc) {
  2214. default:
  2215. llvm_unreachable("Opcode has no flag setting equivalent!");
  2216. // 32-bit cases:
  2217. case AArch64::ADDWri:
  2218. return AArch64::ADDSWri;
  2219. case AArch64::ADDWrr:
  2220. return AArch64::ADDSWrr;
  2221. case AArch64::ADDWrs:
  2222. return AArch64::ADDSWrs;
  2223. case AArch64::ADDWrx:
  2224. return AArch64::ADDSWrx;
  2225. case AArch64::ANDWri:
  2226. return AArch64::ANDSWri;
  2227. case AArch64::ANDWrr:
  2228. return AArch64::ANDSWrr;
  2229. case AArch64::ANDWrs:
  2230. return AArch64::ANDSWrs;
  2231. case AArch64::BICWrr:
  2232. return AArch64::BICSWrr;
  2233. case AArch64::BICWrs:
  2234. return AArch64::BICSWrs;
  2235. case AArch64::SUBWri:
  2236. return AArch64::SUBSWri;
  2237. case AArch64::SUBWrr:
  2238. return AArch64::SUBSWrr;
  2239. case AArch64::SUBWrs:
  2240. return AArch64::SUBSWrs;
  2241. case AArch64::SUBWrx:
  2242. return AArch64::SUBSWrx;
  2243. // 64-bit cases:
  2244. case AArch64::ADDXri:
  2245. return AArch64::ADDSXri;
  2246. case AArch64::ADDXrr:
  2247. return AArch64::ADDSXrr;
  2248. case AArch64::ADDXrs:
  2249. return AArch64::ADDSXrs;
  2250. case AArch64::ADDXrx:
  2251. return AArch64::ADDSXrx;
  2252. case AArch64::ANDXri:
  2253. return AArch64::ANDSXri;
  2254. case AArch64::ANDXrr:
  2255. return AArch64::ANDSXrr;
  2256. case AArch64::ANDXrs:
  2257. return AArch64::ANDSXrs;
  2258. case AArch64::BICXrr:
  2259. return AArch64::BICSXrr;
  2260. case AArch64::BICXrs:
  2261. return AArch64::BICSXrs;
  2262. case AArch64::SUBXri:
  2263. return AArch64::SUBSXri;
  2264. case AArch64::SUBXrr:
  2265. return AArch64::SUBSXrr;
  2266. case AArch64::SUBXrs:
  2267. return AArch64::SUBSXrs;
  2268. case AArch64::SUBXrx:
  2269. return AArch64::SUBSXrx;
  2270. // SVE instructions:
  2271. case AArch64::AND_PPzPP:
  2272. return AArch64::ANDS_PPzPP;
  2273. case AArch64::BIC_PPzPP:
  2274. return AArch64::BICS_PPzPP;
  2275. case AArch64::EOR_PPzPP:
  2276. return AArch64::EORS_PPzPP;
  2277. case AArch64::NAND_PPzPP:
  2278. return AArch64::NANDS_PPzPP;
  2279. case AArch64::NOR_PPzPP:
  2280. return AArch64::NORS_PPzPP;
  2281. case AArch64::ORN_PPzPP:
  2282. return AArch64::ORNS_PPzPP;
  2283. case AArch64::ORR_PPzPP:
  2284. return AArch64::ORRS_PPzPP;
  2285. case AArch64::BRKA_PPzP:
  2286. return AArch64::BRKAS_PPzP;
  2287. case AArch64::BRKPA_PPzPP:
  2288. return AArch64::BRKPAS_PPzPP;
  2289. case AArch64::BRKB_PPzP:
  2290. return AArch64::BRKBS_PPzP;
  2291. case AArch64::BRKPB_PPzPP:
  2292. return AArch64::BRKPBS_PPzPP;
  2293. case AArch64::BRKN_PPzP:
  2294. return AArch64::BRKNS_PPzP;
  2295. case AArch64::RDFFR_PPz:
  2296. return AArch64::RDFFRS_PPz;
  2297. case AArch64::PTRUE_B:
  2298. return AArch64::PTRUES_B;
  2299. }
  2300. }
  2301. // Is this a candidate for ld/st merging or pairing? For example, we don't
  2302. // touch volatiles or load/stores that have a hint to avoid pair formation.
  2303. bool AArch64InstrInfo::isCandidateToMergeOrPair(const MachineInstr &MI) const {
  2304. bool IsPreLdSt = isPreLdSt(MI);
  2305. // If this is a volatile load/store, don't mess with it.
  2306. if (MI.hasOrderedMemoryRef())
  2307. return false;
  2308. // Make sure this is a reg/fi+imm (as opposed to an address reloc).
  2309. // For Pre-inc LD/ST, the operand is shifted by one.
  2310. assert((MI.getOperand(IsPreLdSt ? 2 : 1).isReg() ||
  2311. MI.getOperand(IsPreLdSt ? 2 : 1).isFI()) &&
  2312. "Expected a reg or frame index operand.");
  2313. // For Pre-indexed addressing quadword instructions, the third operand is the
  2314. // immediate value.
  2315. bool IsImmPreLdSt = IsPreLdSt && MI.getOperand(3).isImm();
  2316. if (!MI.getOperand(2).isImm() && !IsImmPreLdSt)
  2317. return false;
  2318. // Can't merge/pair if the instruction modifies the base register.
  2319. // e.g., ldr x0, [x0]
  2320. // This case will never occur with an FI base.
  2321. // However, if the instruction is an LDR/STR<S,D,Q,W,X>pre, it can be merged.
  2322. // For example:
  2323. // ldr q0, [x11, #32]!
  2324. // ldr q1, [x11, #16]
  2325. // to
  2326. // ldp q0, q1, [x11, #32]!
  2327. if (MI.getOperand(1).isReg() && !IsPreLdSt) {
  2328. Register BaseReg = MI.getOperand(1).getReg();
  2329. const TargetRegisterInfo *TRI = &getRegisterInfo();
  2330. if (MI.modifiesRegister(BaseReg, TRI))
  2331. return false;
  2332. }
  2333. // Check if this load/store has a hint to avoid pair formation.
  2334. // MachineMemOperands hints are set by the AArch64StorePairSuppress pass.
  2335. if (isLdStPairSuppressed(MI))
  2336. return false;
  2337. // Do not pair any callee-save store/reload instructions in the
  2338. // prologue/epilogue if the CFI information encoded the operations as separate
  2339. // instructions, as that will cause the size of the actual prologue to mismatch
  2340. // with the prologue size recorded in the Windows CFI.
  2341. const MCAsmInfo *MAI = MI.getMF()->getTarget().getMCAsmInfo();
  2342. bool NeedsWinCFI = MAI->usesWindowsCFI() &&
  2343. MI.getMF()->getFunction().needsUnwindTableEntry();
  2344. if (NeedsWinCFI && (MI.getFlag(MachineInstr::FrameSetup) ||
  2345. MI.getFlag(MachineInstr::FrameDestroy)))
  2346. return false;
  2347. // On some CPUs quad load/store pairs are slower than two single load/stores.
  2348. if (Subtarget.isPaired128Slow()) {
  2349. switch (MI.getOpcode()) {
  2350. default:
  2351. break;
  2352. case AArch64::LDURQi:
  2353. case AArch64::STURQi:
  2354. case AArch64::LDRQui:
  2355. case AArch64::STRQui:
  2356. return false;
  2357. }
  2358. }
  2359. return true;
  2360. }
  2361. bool AArch64InstrInfo::getMemOperandsWithOffsetWidth(
  2362. const MachineInstr &LdSt, SmallVectorImpl<const MachineOperand *> &BaseOps,
  2363. int64_t &Offset, bool &OffsetIsScalable, unsigned &Width,
  2364. const TargetRegisterInfo *TRI) const {
  2365. if (!LdSt.mayLoadOrStore())
  2366. return false;
  2367. const MachineOperand *BaseOp;
  2368. if (!getMemOperandWithOffsetWidth(LdSt, BaseOp, Offset, OffsetIsScalable,
  2369. Width, TRI))
  2370. return false;
  2371. BaseOps.push_back(BaseOp);
  2372. return true;
  2373. }
  2374. std::optional<ExtAddrMode>
  2375. AArch64InstrInfo::getAddrModeFromMemoryOp(const MachineInstr &MemI,
  2376. const TargetRegisterInfo *TRI) const {
  2377. const MachineOperand *Base; // Filled with the base operand of MI.
  2378. int64_t Offset; // Filled with the offset of MI.
  2379. bool OffsetIsScalable;
  2380. if (!getMemOperandWithOffset(MemI, Base, Offset, OffsetIsScalable, TRI))
  2381. return std::nullopt;
  2382. if (!Base->isReg())
  2383. return std::nullopt;
  2384. ExtAddrMode AM;
  2385. AM.BaseReg = Base->getReg();
  2386. AM.Displacement = Offset;
  2387. AM.ScaledReg = 0;
  2388. AM.Scale = 0;
  2389. return AM;
  2390. }
  2391. bool AArch64InstrInfo::getMemOperandWithOffsetWidth(
  2392. const MachineInstr &LdSt, const MachineOperand *&BaseOp, int64_t &Offset,
  2393. bool &OffsetIsScalable, unsigned &Width,
  2394. const TargetRegisterInfo *TRI) const {
  2395. assert(LdSt.mayLoadOrStore() && "Expected a memory operation.");
  2396. // Handle only loads/stores with base register followed by immediate offset.
  2397. if (LdSt.getNumExplicitOperands() == 3) {
  2398. // Non-paired instruction (e.g., ldr x1, [x0, #8]).
  2399. if ((!LdSt.getOperand(1).isReg() && !LdSt.getOperand(1).isFI()) ||
  2400. !LdSt.getOperand(2).isImm())
  2401. return false;
  2402. } else if (LdSt.getNumExplicitOperands() == 4) {
  2403. // Paired instruction (e.g., ldp x1, x2, [x0, #8]).
  2404. if (!LdSt.getOperand(1).isReg() ||
  2405. (!LdSt.getOperand(2).isReg() && !LdSt.getOperand(2).isFI()) ||
  2406. !LdSt.getOperand(3).isImm())
  2407. return false;
  2408. } else
  2409. return false;
  2410. // Get the scaling factor for the instruction and set the width for the
  2411. // instruction.
  2412. TypeSize Scale(0U, false);
  2413. int64_t Dummy1, Dummy2;
  2414. // If this returns false, then it's an instruction we don't want to handle.
  2415. if (!getMemOpInfo(LdSt.getOpcode(), Scale, Width, Dummy1, Dummy2))
  2416. return false;
  2417. // Compute the offset. Offset is calculated as the immediate operand
  2418. // multiplied by the scaling factor. Unscaled instructions have scaling factor
  2419. // set to 1.
  2420. if (LdSt.getNumExplicitOperands() == 3) {
  2421. BaseOp = &LdSt.getOperand(1);
  2422. Offset = LdSt.getOperand(2).getImm() * Scale.getKnownMinValue();
  2423. } else {
  2424. assert(LdSt.getNumExplicitOperands() == 4 && "invalid number of operands");
  2425. BaseOp = &LdSt.getOperand(2);
  2426. Offset = LdSt.getOperand(3).getImm() * Scale.getKnownMinValue();
  2427. }
  2428. OffsetIsScalable = Scale.isScalable();
  2429. if (!BaseOp->isReg() && !BaseOp->isFI())
  2430. return false;
  2431. return true;
  2432. }
  2433. MachineOperand &
  2434. AArch64InstrInfo::getMemOpBaseRegImmOfsOffsetOperand(MachineInstr &LdSt) const {
  2435. assert(LdSt.mayLoadOrStore() && "Expected a memory operation.");
  2436. MachineOperand &OfsOp = LdSt.getOperand(LdSt.getNumExplicitOperands() - 1);
  2437. assert(OfsOp.isImm() && "Offset operand wasn't immediate.");
  2438. return OfsOp;
  2439. }
  2440. bool AArch64InstrInfo::getMemOpInfo(unsigned Opcode, TypeSize &Scale,
  2441. unsigned &Width, int64_t &MinOffset,
  2442. int64_t &MaxOffset) {
  2443. const unsigned SVEMaxBytesPerVector = AArch64::SVEMaxBitsPerVector / 8;
  2444. switch (Opcode) {
  2445. // Not a memory operation or something we want to handle.
  2446. default:
  2447. Scale = TypeSize::Fixed(0);
  2448. Width = 0;
  2449. MinOffset = MaxOffset = 0;
  2450. return false;
  2451. case AArch64::STRWpost:
  2452. case AArch64::LDRWpost:
  2453. Width = 32;
  2454. Scale = TypeSize::Fixed(4);
  2455. MinOffset = -256;
  2456. MaxOffset = 255;
  2457. break;
  2458. case AArch64::LDURQi:
  2459. case AArch64::STURQi:
  2460. Width = 16;
  2461. Scale = TypeSize::Fixed(1);
  2462. MinOffset = -256;
  2463. MaxOffset = 255;
  2464. break;
  2465. case AArch64::PRFUMi:
  2466. case AArch64::LDURXi:
  2467. case AArch64::LDURDi:
  2468. case AArch64::STURXi:
  2469. case AArch64::STURDi:
  2470. Width = 8;
  2471. Scale = TypeSize::Fixed(1);
  2472. MinOffset = -256;
  2473. MaxOffset = 255;
  2474. break;
  2475. case AArch64::LDURWi:
  2476. case AArch64::LDURSi:
  2477. case AArch64::LDURSWi:
  2478. case AArch64::STURWi:
  2479. case AArch64::STURSi:
  2480. Width = 4;
  2481. Scale = TypeSize::Fixed(1);
  2482. MinOffset = -256;
  2483. MaxOffset = 255;
  2484. break;
  2485. case AArch64::LDURHi:
  2486. case AArch64::LDURHHi:
  2487. case AArch64::LDURSHXi:
  2488. case AArch64::LDURSHWi:
  2489. case AArch64::STURHi:
  2490. case AArch64::STURHHi:
  2491. Width = 2;
  2492. Scale = TypeSize::Fixed(1);
  2493. MinOffset = -256;
  2494. MaxOffset = 255;
  2495. break;
  2496. case AArch64::LDURBi:
  2497. case AArch64::LDURBBi:
  2498. case AArch64::LDURSBXi:
  2499. case AArch64::LDURSBWi:
  2500. case AArch64::STURBi:
  2501. case AArch64::STURBBi:
  2502. Width = 1;
  2503. Scale = TypeSize::Fixed(1);
  2504. MinOffset = -256;
  2505. MaxOffset = 255;
  2506. break;
  2507. case AArch64::LDPQi:
  2508. case AArch64::LDNPQi:
  2509. case AArch64::STPQi:
  2510. case AArch64::STNPQi:
  2511. Scale = TypeSize::Fixed(16);
  2512. Width = 32;
  2513. MinOffset = -64;
  2514. MaxOffset = 63;
  2515. break;
  2516. case AArch64::LDRQui:
  2517. case AArch64::STRQui:
  2518. Scale = TypeSize::Fixed(16);
  2519. Width = 16;
  2520. MinOffset = 0;
  2521. MaxOffset = 4095;
  2522. break;
  2523. case AArch64::LDPXi:
  2524. case AArch64::LDPDi:
  2525. case AArch64::LDNPXi:
  2526. case AArch64::LDNPDi:
  2527. case AArch64::STPXi:
  2528. case AArch64::STPDi:
  2529. case AArch64::STNPXi:
  2530. case AArch64::STNPDi:
  2531. Scale = TypeSize::Fixed(8);
  2532. Width = 16;
  2533. MinOffset = -64;
  2534. MaxOffset = 63;
  2535. break;
  2536. case AArch64::PRFMui:
  2537. case AArch64::LDRXui:
  2538. case AArch64::LDRDui:
  2539. case AArch64::STRXui:
  2540. case AArch64::STRDui:
  2541. Scale = TypeSize::Fixed(8);
  2542. Width = 8;
  2543. MinOffset = 0;
  2544. MaxOffset = 4095;
  2545. break;
  2546. case AArch64::StoreSwiftAsyncContext:
  2547. // Store is an STRXui, but there might be an ADDXri in the expansion too.
  2548. Scale = TypeSize::Fixed(1);
  2549. Width = 8;
  2550. MinOffset = 0;
  2551. MaxOffset = 4095;
  2552. break;
  2553. case AArch64::LDPWi:
  2554. case AArch64::LDPSi:
  2555. case AArch64::LDNPWi:
  2556. case AArch64::LDNPSi:
  2557. case AArch64::STPWi:
  2558. case AArch64::STPSi:
  2559. case AArch64::STNPWi:
  2560. case AArch64::STNPSi:
  2561. Scale = TypeSize::Fixed(4);
  2562. Width = 8;
  2563. MinOffset = -64;
  2564. MaxOffset = 63;
  2565. break;
  2566. case AArch64::LDRWui:
  2567. case AArch64::LDRSui:
  2568. case AArch64::LDRSWui:
  2569. case AArch64::STRWui:
  2570. case AArch64::STRSui:
  2571. Scale = TypeSize::Fixed(4);
  2572. Width = 4;
  2573. MinOffset = 0;
  2574. MaxOffset = 4095;
  2575. break;
  2576. case AArch64::LDRHui:
  2577. case AArch64::LDRHHui:
  2578. case AArch64::LDRSHWui:
  2579. case AArch64::LDRSHXui:
  2580. case AArch64::STRHui:
  2581. case AArch64::STRHHui:
  2582. Scale = TypeSize::Fixed(2);
  2583. Width = 2;
  2584. MinOffset = 0;
  2585. MaxOffset = 4095;
  2586. break;
  2587. case AArch64::LDRBui:
  2588. case AArch64::LDRBBui:
  2589. case AArch64::LDRSBWui:
  2590. case AArch64::LDRSBXui:
  2591. case AArch64::STRBui:
  2592. case AArch64::STRBBui:
  2593. Scale = TypeSize::Fixed(1);
  2594. Width = 1;
  2595. MinOffset = 0;
  2596. MaxOffset = 4095;
  2597. break;
  2598. case AArch64::STPXpre:
  2599. case AArch64::LDPXpost:
  2600. case AArch64::STPDpre:
  2601. case AArch64::LDPDpost:
  2602. Scale = TypeSize::Fixed(8);
  2603. Width = 8;
  2604. MinOffset = -512;
  2605. MaxOffset = 504;
  2606. break;
  2607. case AArch64::STPQpre:
  2608. case AArch64::LDPQpost:
  2609. Scale = TypeSize::Fixed(16);
  2610. Width = 16;
  2611. MinOffset = -1024;
  2612. MaxOffset = 1008;
  2613. break;
  2614. case AArch64::STRXpre:
  2615. case AArch64::STRDpre:
  2616. case AArch64::LDRXpost:
  2617. case AArch64::LDRDpost:
  2618. Scale = TypeSize::Fixed(1);
  2619. Width = 8;
  2620. MinOffset = -256;
  2621. MaxOffset = 255;
  2622. break;
  2623. case AArch64::STRQpre:
  2624. case AArch64::LDRQpost:
  2625. Scale = TypeSize::Fixed(1);
  2626. Width = 16;
  2627. MinOffset = -256;
  2628. MaxOffset = 255;
  2629. break;
  2630. case AArch64::ADDG:
  2631. Scale = TypeSize::Fixed(16);
  2632. Width = 0;
  2633. MinOffset = 0;
  2634. MaxOffset = 63;
  2635. break;
  2636. case AArch64::TAGPstack:
  2637. Scale = TypeSize::Fixed(16);
  2638. Width = 0;
  2639. // TAGP with a negative offset turns into SUBP, which has a maximum offset
  2640. // of 63 (not 64!).
  2641. MinOffset = -63;
  2642. MaxOffset = 63;
  2643. break;
  2644. case AArch64::LDG:
  2645. case AArch64::STGOffset:
  2646. case AArch64::STZGOffset:
  2647. Scale = TypeSize::Fixed(16);
  2648. Width = 16;
  2649. MinOffset = -256;
  2650. MaxOffset = 255;
  2651. break;
  2652. case AArch64::STR_ZZZZXI:
  2653. case AArch64::LDR_ZZZZXI:
  2654. Scale = TypeSize::Scalable(16);
  2655. Width = SVEMaxBytesPerVector * 4;
  2656. MinOffset = -256;
  2657. MaxOffset = 252;
  2658. break;
  2659. case AArch64::STR_ZZZXI:
  2660. case AArch64::LDR_ZZZXI:
  2661. Scale = TypeSize::Scalable(16);
  2662. Width = SVEMaxBytesPerVector * 3;
  2663. MinOffset = -256;
  2664. MaxOffset = 253;
  2665. break;
  2666. case AArch64::STR_ZZXI:
  2667. case AArch64::LDR_ZZXI:
  2668. Scale = TypeSize::Scalable(16);
  2669. Width = SVEMaxBytesPerVector * 2;
  2670. MinOffset = -256;
  2671. MaxOffset = 254;
  2672. break;
  2673. case AArch64::LDR_PXI:
  2674. case AArch64::STR_PXI:
  2675. Scale = TypeSize::Scalable(2);
  2676. Width = SVEMaxBytesPerVector / 8;
  2677. MinOffset = -256;
  2678. MaxOffset = 255;
  2679. break;
  2680. case AArch64::LDR_ZXI:
  2681. case AArch64::STR_ZXI:
  2682. Scale = TypeSize::Scalable(16);
  2683. Width = SVEMaxBytesPerVector;
  2684. MinOffset = -256;
  2685. MaxOffset = 255;
  2686. break;
  2687. case AArch64::LD1B_IMM:
  2688. case AArch64::LD1H_IMM:
  2689. case AArch64::LD1W_IMM:
  2690. case AArch64::LD1D_IMM:
  2691. case AArch64::LDNT1B_ZRI:
  2692. case AArch64::LDNT1H_ZRI:
  2693. case AArch64::LDNT1W_ZRI:
  2694. case AArch64::LDNT1D_ZRI:
  2695. case AArch64::ST1B_IMM:
  2696. case AArch64::ST1H_IMM:
  2697. case AArch64::ST1W_IMM:
  2698. case AArch64::ST1D_IMM:
  2699. case AArch64::STNT1B_ZRI:
  2700. case AArch64::STNT1H_ZRI:
  2701. case AArch64::STNT1W_ZRI:
  2702. case AArch64::STNT1D_ZRI:
  2703. case AArch64::LDNF1B_IMM:
  2704. case AArch64::LDNF1H_IMM:
  2705. case AArch64::LDNF1W_IMM:
  2706. case AArch64::LDNF1D_IMM:
  2707. // A full vectors worth of data
  2708. // Width = mbytes * elements
  2709. Scale = TypeSize::Scalable(16);
  2710. Width = SVEMaxBytesPerVector;
  2711. MinOffset = -8;
  2712. MaxOffset = 7;
  2713. break;
  2714. case AArch64::LD2B_IMM:
  2715. case AArch64::LD2H_IMM:
  2716. case AArch64::LD2W_IMM:
  2717. case AArch64::LD2D_IMM:
  2718. case AArch64::ST2B_IMM:
  2719. case AArch64::ST2H_IMM:
  2720. case AArch64::ST2W_IMM:
  2721. case AArch64::ST2D_IMM:
  2722. Scale = TypeSize::Scalable(32);
  2723. Width = SVEMaxBytesPerVector * 2;
  2724. MinOffset = -8;
  2725. MaxOffset = 7;
  2726. break;
  2727. case AArch64::LD3B_IMM:
  2728. case AArch64::LD3H_IMM:
  2729. case AArch64::LD3W_IMM:
  2730. case AArch64::LD3D_IMM:
  2731. case AArch64::ST3B_IMM:
  2732. case AArch64::ST3H_IMM:
  2733. case AArch64::ST3W_IMM:
  2734. case AArch64::ST3D_IMM:
  2735. Scale = TypeSize::Scalable(48);
  2736. Width = SVEMaxBytesPerVector * 3;
  2737. MinOffset = -8;
  2738. MaxOffset = 7;
  2739. break;
  2740. case AArch64::LD4B_IMM:
  2741. case AArch64::LD4H_IMM:
  2742. case AArch64::LD4W_IMM:
  2743. case AArch64::LD4D_IMM:
  2744. case AArch64::ST4B_IMM:
  2745. case AArch64::ST4H_IMM:
  2746. case AArch64::ST4W_IMM:
  2747. case AArch64::ST4D_IMM:
  2748. Scale = TypeSize::Scalable(64);
  2749. Width = SVEMaxBytesPerVector * 4;
  2750. MinOffset = -8;
  2751. MaxOffset = 7;
  2752. break;
  2753. case AArch64::LD1B_H_IMM:
  2754. case AArch64::LD1SB_H_IMM:
  2755. case AArch64::LD1H_S_IMM:
  2756. case AArch64::LD1SH_S_IMM:
  2757. case AArch64::LD1W_D_IMM:
  2758. case AArch64::LD1SW_D_IMM:
  2759. case AArch64::ST1B_H_IMM:
  2760. case AArch64::ST1H_S_IMM:
  2761. case AArch64::ST1W_D_IMM:
  2762. case AArch64::LDNF1B_H_IMM:
  2763. case AArch64::LDNF1SB_H_IMM:
  2764. case AArch64::LDNF1H_S_IMM:
  2765. case AArch64::LDNF1SH_S_IMM:
  2766. case AArch64::LDNF1W_D_IMM:
  2767. case AArch64::LDNF1SW_D_IMM:
  2768. // A half vector worth of data
  2769. // Width = mbytes * elements
  2770. Scale = TypeSize::Scalable(8);
  2771. Width = SVEMaxBytesPerVector / 2;
  2772. MinOffset = -8;
  2773. MaxOffset = 7;
  2774. break;
  2775. case AArch64::LD1B_S_IMM:
  2776. case AArch64::LD1SB_S_IMM:
  2777. case AArch64::LD1H_D_IMM:
  2778. case AArch64::LD1SH_D_IMM:
  2779. case AArch64::ST1B_S_IMM:
  2780. case AArch64::ST1H_D_IMM:
  2781. case AArch64::LDNF1B_S_IMM:
  2782. case AArch64::LDNF1SB_S_IMM:
  2783. case AArch64::LDNF1H_D_IMM:
  2784. case AArch64::LDNF1SH_D_IMM:
  2785. // A quarter vector worth of data
  2786. // Width = mbytes * elements
  2787. Scale = TypeSize::Scalable(4);
  2788. Width = SVEMaxBytesPerVector / 4;
  2789. MinOffset = -8;
  2790. MaxOffset = 7;
  2791. break;
  2792. case AArch64::LD1B_D_IMM:
  2793. case AArch64::LD1SB_D_IMM:
  2794. case AArch64::ST1B_D_IMM:
  2795. case AArch64::LDNF1B_D_IMM:
  2796. case AArch64::LDNF1SB_D_IMM:
  2797. // A eighth vector worth of data
  2798. // Width = mbytes * elements
  2799. Scale = TypeSize::Scalable(2);
  2800. Width = SVEMaxBytesPerVector / 8;
  2801. MinOffset = -8;
  2802. MaxOffset = 7;
  2803. break;
  2804. case AArch64::ST2GOffset:
  2805. case AArch64::STZ2GOffset:
  2806. Scale = TypeSize::Fixed(16);
  2807. Width = 32;
  2808. MinOffset = -256;
  2809. MaxOffset = 255;
  2810. break;
  2811. case AArch64::STGPi:
  2812. Scale = TypeSize::Fixed(16);
  2813. Width = 16;
  2814. MinOffset = -64;
  2815. MaxOffset = 63;
  2816. break;
  2817. case AArch64::LD1RB_IMM:
  2818. case AArch64::LD1RB_H_IMM:
  2819. case AArch64::LD1RB_S_IMM:
  2820. case AArch64::LD1RB_D_IMM:
  2821. case AArch64::LD1RSB_H_IMM:
  2822. case AArch64::LD1RSB_S_IMM:
  2823. case AArch64::LD1RSB_D_IMM:
  2824. Scale = TypeSize::Fixed(1);
  2825. Width = 1;
  2826. MinOffset = 0;
  2827. MaxOffset = 63;
  2828. break;
  2829. case AArch64::LD1RH_IMM:
  2830. case AArch64::LD1RH_S_IMM:
  2831. case AArch64::LD1RH_D_IMM:
  2832. case AArch64::LD1RSH_S_IMM:
  2833. case AArch64::LD1RSH_D_IMM:
  2834. Scale = TypeSize::Fixed(2);
  2835. Width = 2;
  2836. MinOffset = 0;
  2837. MaxOffset = 63;
  2838. break;
  2839. case AArch64::LD1RW_IMM:
  2840. case AArch64::LD1RW_D_IMM:
  2841. case AArch64::LD1RSW_IMM:
  2842. Scale = TypeSize::Fixed(4);
  2843. Width = 4;
  2844. MinOffset = 0;
  2845. MaxOffset = 63;
  2846. break;
  2847. case AArch64::LD1RD_IMM:
  2848. Scale = TypeSize::Fixed(8);
  2849. Width = 8;
  2850. MinOffset = 0;
  2851. MaxOffset = 63;
  2852. break;
  2853. }
  2854. return true;
  2855. }
  2856. // Scaling factor for unscaled load or store.
  2857. int AArch64InstrInfo::getMemScale(unsigned Opc) {
  2858. switch (Opc) {
  2859. default:
  2860. llvm_unreachable("Opcode has unknown scale!");
  2861. case AArch64::LDRBBui:
  2862. case AArch64::LDURBBi:
  2863. case AArch64::LDRSBWui:
  2864. case AArch64::LDURSBWi:
  2865. case AArch64::STRBBui:
  2866. case AArch64::STURBBi:
  2867. return 1;
  2868. case AArch64::LDRHHui:
  2869. case AArch64::LDURHHi:
  2870. case AArch64::LDRSHWui:
  2871. case AArch64::LDURSHWi:
  2872. case AArch64::STRHHui:
  2873. case AArch64::STURHHi:
  2874. return 2;
  2875. case AArch64::LDRSui:
  2876. case AArch64::LDURSi:
  2877. case AArch64::LDRSpre:
  2878. case AArch64::LDRSWui:
  2879. case AArch64::LDURSWi:
  2880. case AArch64::LDRWpre:
  2881. case AArch64::LDRWui:
  2882. case AArch64::LDURWi:
  2883. case AArch64::STRSui:
  2884. case AArch64::STURSi:
  2885. case AArch64::STRSpre:
  2886. case AArch64::STRWui:
  2887. case AArch64::STURWi:
  2888. case AArch64::STRWpre:
  2889. case AArch64::LDPSi:
  2890. case AArch64::LDPSWi:
  2891. case AArch64::LDPWi:
  2892. case AArch64::STPSi:
  2893. case AArch64::STPWi:
  2894. return 4;
  2895. case AArch64::LDRDui:
  2896. case AArch64::LDURDi:
  2897. case AArch64::LDRDpre:
  2898. case AArch64::LDRXui:
  2899. case AArch64::LDURXi:
  2900. case AArch64::LDRXpre:
  2901. case AArch64::STRDui:
  2902. case AArch64::STURDi:
  2903. case AArch64::STRDpre:
  2904. case AArch64::STRXui:
  2905. case AArch64::STURXi:
  2906. case AArch64::STRXpre:
  2907. case AArch64::LDPDi:
  2908. case AArch64::LDPXi:
  2909. case AArch64::STPDi:
  2910. case AArch64::STPXi:
  2911. return 8;
  2912. case AArch64::LDRQui:
  2913. case AArch64::LDURQi:
  2914. case AArch64::STRQui:
  2915. case AArch64::STURQi:
  2916. case AArch64::STRQpre:
  2917. case AArch64::LDPQi:
  2918. case AArch64::LDRQpre:
  2919. case AArch64::STPQi:
  2920. case AArch64::STGOffset:
  2921. case AArch64::STZGOffset:
  2922. case AArch64::ST2GOffset:
  2923. case AArch64::STZ2GOffset:
  2924. case AArch64::STGPi:
  2925. return 16;
  2926. }
  2927. }
  2928. bool AArch64InstrInfo::isPreLd(const MachineInstr &MI) {
  2929. switch (MI.getOpcode()) {
  2930. default:
  2931. return false;
  2932. case AArch64::LDRWpre:
  2933. case AArch64::LDRXpre:
  2934. case AArch64::LDRSpre:
  2935. case AArch64::LDRDpre:
  2936. case AArch64::LDRQpre:
  2937. return true;
  2938. }
  2939. }
  2940. bool AArch64InstrInfo::isPreSt(const MachineInstr &MI) {
  2941. switch (MI.getOpcode()) {
  2942. default:
  2943. return false;
  2944. case AArch64::STRWpre:
  2945. case AArch64::STRXpre:
  2946. case AArch64::STRSpre:
  2947. case AArch64::STRDpre:
  2948. case AArch64::STRQpre:
  2949. return true;
  2950. }
  2951. }
  2952. bool AArch64InstrInfo::isPreLdSt(const MachineInstr &MI) {
  2953. return isPreLd(MI) || isPreSt(MI);
  2954. }
  2955. bool AArch64InstrInfo::isPairedLdSt(const MachineInstr &MI) {
  2956. switch (MI.getOpcode()) {
  2957. default:
  2958. return false;
  2959. case AArch64::LDPSi:
  2960. case AArch64::LDPSWi:
  2961. case AArch64::LDPDi:
  2962. case AArch64::LDPQi:
  2963. case AArch64::LDPWi:
  2964. case AArch64::LDPXi:
  2965. case AArch64::STPSi:
  2966. case AArch64::STPDi:
  2967. case AArch64::STPQi:
  2968. case AArch64::STPWi:
  2969. case AArch64::STPXi:
  2970. case AArch64::STGPi:
  2971. return true;
  2972. }
  2973. }
  2974. const MachineOperand &AArch64InstrInfo::getLdStBaseOp(const MachineInstr &MI) {
  2975. unsigned Idx =
  2976. AArch64InstrInfo::isPairedLdSt(MI) || AArch64InstrInfo::isPreLdSt(MI) ? 2
  2977. : 1;
  2978. return MI.getOperand(Idx);
  2979. }
  2980. const MachineOperand &
  2981. AArch64InstrInfo::getLdStOffsetOp(const MachineInstr &MI) {
  2982. unsigned Idx =
  2983. AArch64InstrInfo::isPairedLdSt(MI) || AArch64InstrInfo::isPreLdSt(MI) ? 3
  2984. : 2;
  2985. return MI.getOperand(Idx);
  2986. }
  2987. static const TargetRegisterClass *getRegClass(const MachineInstr &MI,
  2988. Register Reg) {
  2989. if (MI.getParent() == nullptr)
  2990. return nullptr;
  2991. const MachineFunction *MF = MI.getParent()->getParent();
  2992. return MF ? MF->getRegInfo().getRegClassOrNull(Reg) : nullptr;
  2993. }
  2994. bool AArch64InstrInfo::isQForm(const MachineInstr &MI) {
  2995. auto IsQFPR = [&](const MachineOperand &Op) {
  2996. if (!Op.isReg())
  2997. return false;
  2998. auto Reg = Op.getReg();
  2999. if (Reg.isPhysical())
  3000. return AArch64::FPR128RegClass.contains(Reg);
  3001. const TargetRegisterClass *TRC = ::getRegClass(MI, Reg);
  3002. return TRC == &AArch64::FPR128RegClass ||
  3003. TRC == &AArch64::FPR128_loRegClass;
  3004. };
  3005. return llvm::any_of(MI.operands(), IsQFPR);
  3006. }
  3007. bool AArch64InstrInfo::isFpOrNEON(const MachineInstr &MI) {
  3008. auto IsFPR = [&](const MachineOperand &Op) {
  3009. if (!Op.isReg())
  3010. return false;
  3011. auto Reg = Op.getReg();
  3012. if (Reg.isPhysical())
  3013. return AArch64::FPR128RegClass.contains(Reg) ||
  3014. AArch64::FPR64RegClass.contains(Reg) ||
  3015. AArch64::FPR32RegClass.contains(Reg) ||
  3016. AArch64::FPR16RegClass.contains(Reg) ||
  3017. AArch64::FPR8RegClass.contains(Reg);
  3018. const TargetRegisterClass *TRC = ::getRegClass(MI, Reg);
  3019. return TRC == &AArch64::FPR128RegClass ||
  3020. TRC == &AArch64::FPR128_loRegClass ||
  3021. TRC == &AArch64::FPR64RegClass ||
  3022. TRC == &AArch64::FPR64_loRegClass ||
  3023. TRC == &AArch64::FPR32RegClass || TRC == &AArch64::FPR16RegClass ||
  3024. TRC == &AArch64::FPR8RegClass;
  3025. };
  3026. return llvm::any_of(MI.operands(), IsFPR);
  3027. }
  3028. // Scale the unscaled offsets. Returns false if the unscaled offset can't be
  3029. // scaled.
  3030. static bool scaleOffset(unsigned Opc, int64_t &Offset) {
  3031. int Scale = AArch64InstrInfo::getMemScale(Opc);
  3032. // If the byte-offset isn't a multiple of the stride, we can't scale this
  3033. // offset.
  3034. if (Offset % Scale != 0)
  3035. return false;
  3036. // Convert the byte-offset used by unscaled into an "element" offset used
  3037. // by the scaled pair load/store instructions.
  3038. Offset /= Scale;
  3039. return true;
  3040. }
  3041. static bool canPairLdStOpc(unsigned FirstOpc, unsigned SecondOpc) {
  3042. if (FirstOpc == SecondOpc)
  3043. return true;
  3044. // We can also pair sign-ext and zero-ext instructions.
  3045. switch (FirstOpc) {
  3046. default:
  3047. return false;
  3048. case AArch64::LDRWui:
  3049. case AArch64::LDURWi:
  3050. return SecondOpc == AArch64::LDRSWui || SecondOpc == AArch64::LDURSWi;
  3051. case AArch64::LDRSWui:
  3052. case AArch64::LDURSWi:
  3053. return SecondOpc == AArch64::LDRWui || SecondOpc == AArch64::LDURWi;
  3054. }
  3055. // These instructions can't be paired based on their opcodes.
  3056. return false;
  3057. }
  3058. static bool shouldClusterFI(const MachineFrameInfo &MFI, int FI1,
  3059. int64_t Offset1, unsigned Opcode1, int FI2,
  3060. int64_t Offset2, unsigned Opcode2) {
  3061. // Accesses through fixed stack object frame indices may access a different
  3062. // fixed stack slot. Check that the object offsets + offsets match.
  3063. if (MFI.isFixedObjectIndex(FI1) && MFI.isFixedObjectIndex(FI2)) {
  3064. int64_t ObjectOffset1 = MFI.getObjectOffset(FI1);
  3065. int64_t ObjectOffset2 = MFI.getObjectOffset(FI2);
  3066. assert(ObjectOffset1 <= ObjectOffset2 && "Object offsets are not ordered.");
  3067. // Convert to scaled object offsets.
  3068. int Scale1 = AArch64InstrInfo::getMemScale(Opcode1);
  3069. if (ObjectOffset1 % Scale1 != 0)
  3070. return false;
  3071. ObjectOffset1 /= Scale1;
  3072. int Scale2 = AArch64InstrInfo::getMemScale(Opcode2);
  3073. if (ObjectOffset2 % Scale2 != 0)
  3074. return false;
  3075. ObjectOffset2 /= Scale2;
  3076. ObjectOffset1 += Offset1;
  3077. ObjectOffset2 += Offset2;
  3078. return ObjectOffset1 + 1 == ObjectOffset2;
  3079. }
  3080. return FI1 == FI2;
  3081. }
  3082. /// Detect opportunities for ldp/stp formation.
  3083. ///
  3084. /// Only called for LdSt for which getMemOperandWithOffset returns true.
  3085. bool AArch64InstrInfo::shouldClusterMemOps(
  3086. ArrayRef<const MachineOperand *> BaseOps1,
  3087. ArrayRef<const MachineOperand *> BaseOps2, unsigned NumLoads,
  3088. unsigned NumBytes) const {
  3089. assert(BaseOps1.size() == 1 && BaseOps2.size() == 1);
  3090. const MachineOperand &BaseOp1 = *BaseOps1.front();
  3091. const MachineOperand &BaseOp2 = *BaseOps2.front();
  3092. const MachineInstr &FirstLdSt = *BaseOp1.getParent();
  3093. const MachineInstr &SecondLdSt = *BaseOp2.getParent();
  3094. if (BaseOp1.getType() != BaseOp2.getType())
  3095. return false;
  3096. assert((BaseOp1.isReg() || BaseOp1.isFI()) &&
  3097. "Only base registers and frame indices are supported.");
  3098. // Check for both base regs and base FI.
  3099. if (BaseOp1.isReg() && BaseOp1.getReg() != BaseOp2.getReg())
  3100. return false;
  3101. // Only cluster up to a single pair.
  3102. if (NumLoads > 2)
  3103. return false;
  3104. if (!isPairableLdStInst(FirstLdSt) || !isPairableLdStInst(SecondLdSt))
  3105. return false;
  3106. // Can we pair these instructions based on their opcodes?
  3107. unsigned FirstOpc = FirstLdSt.getOpcode();
  3108. unsigned SecondOpc = SecondLdSt.getOpcode();
  3109. if (!canPairLdStOpc(FirstOpc, SecondOpc))
  3110. return false;
  3111. // Can't merge volatiles or load/stores that have a hint to avoid pair
  3112. // formation, for example.
  3113. if (!isCandidateToMergeOrPair(FirstLdSt) ||
  3114. !isCandidateToMergeOrPair(SecondLdSt))
  3115. return false;
  3116. // isCandidateToMergeOrPair guarantees that operand 2 is an immediate.
  3117. int64_t Offset1 = FirstLdSt.getOperand(2).getImm();
  3118. if (hasUnscaledLdStOffset(FirstOpc) && !scaleOffset(FirstOpc, Offset1))
  3119. return false;
  3120. int64_t Offset2 = SecondLdSt.getOperand(2).getImm();
  3121. if (hasUnscaledLdStOffset(SecondOpc) && !scaleOffset(SecondOpc, Offset2))
  3122. return false;
  3123. // Pairwise instructions have a 7-bit signed offset field.
  3124. if (Offset1 > 63 || Offset1 < -64)
  3125. return false;
  3126. // The caller should already have ordered First/SecondLdSt by offset.
  3127. // Note: except for non-equal frame index bases
  3128. if (BaseOp1.isFI()) {
  3129. assert((!BaseOp1.isIdenticalTo(BaseOp2) || Offset1 <= Offset2) &&
  3130. "Caller should have ordered offsets.");
  3131. const MachineFrameInfo &MFI =
  3132. FirstLdSt.getParent()->getParent()->getFrameInfo();
  3133. return shouldClusterFI(MFI, BaseOp1.getIndex(), Offset1, FirstOpc,
  3134. BaseOp2.getIndex(), Offset2, SecondOpc);
  3135. }
  3136. assert(Offset1 <= Offset2 && "Caller should have ordered offsets.");
  3137. return Offset1 + 1 == Offset2;
  3138. }
  3139. static const MachineInstrBuilder &AddSubReg(const MachineInstrBuilder &MIB,
  3140. unsigned Reg, unsigned SubIdx,
  3141. unsigned State,
  3142. const TargetRegisterInfo *TRI) {
  3143. if (!SubIdx)
  3144. return MIB.addReg(Reg, State);
  3145. if (Register::isPhysicalRegister(Reg))
  3146. return MIB.addReg(TRI->getSubReg(Reg, SubIdx), State);
  3147. return MIB.addReg(Reg, State, SubIdx);
  3148. }
  3149. static bool forwardCopyWillClobberTuple(unsigned DestReg, unsigned SrcReg,
  3150. unsigned NumRegs) {
  3151. // We really want the positive remainder mod 32 here, that happens to be
  3152. // easily obtainable with a mask.
  3153. return ((DestReg - SrcReg) & 0x1f) < NumRegs;
  3154. }
  3155. void AArch64InstrInfo::copyPhysRegTuple(MachineBasicBlock &MBB,
  3156. MachineBasicBlock::iterator I,
  3157. const DebugLoc &DL, MCRegister DestReg,
  3158. MCRegister SrcReg, bool KillSrc,
  3159. unsigned Opcode,
  3160. ArrayRef<unsigned> Indices) const {
  3161. assert(Subtarget.hasNEON() && "Unexpected register copy without NEON");
  3162. const TargetRegisterInfo *TRI = &getRegisterInfo();
  3163. uint16_t DestEncoding = TRI->getEncodingValue(DestReg);
  3164. uint16_t SrcEncoding = TRI->getEncodingValue(SrcReg);
  3165. unsigned NumRegs = Indices.size();
  3166. int SubReg = 0, End = NumRegs, Incr = 1;
  3167. if (forwardCopyWillClobberTuple(DestEncoding, SrcEncoding, NumRegs)) {
  3168. SubReg = NumRegs - 1;
  3169. End = -1;
  3170. Incr = -1;
  3171. }
  3172. for (; SubReg != End; SubReg += Incr) {
  3173. const MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(Opcode));
  3174. AddSubReg(MIB, DestReg, Indices[SubReg], RegState::Define, TRI);
  3175. AddSubReg(MIB, SrcReg, Indices[SubReg], 0, TRI);
  3176. AddSubReg(MIB, SrcReg, Indices[SubReg], getKillRegState(KillSrc), TRI);
  3177. }
  3178. }
  3179. void AArch64InstrInfo::copyGPRRegTuple(MachineBasicBlock &MBB,
  3180. MachineBasicBlock::iterator I,
  3181. DebugLoc DL, unsigned DestReg,
  3182. unsigned SrcReg, bool KillSrc,
  3183. unsigned Opcode, unsigned ZeroReg,
  3184. llvm::ArrayRef<unsigned> Indices) const {
  3185. const TargetRegisterInfo *TRI = &getRegisterInfo();
  3186. unsigned NumRegs = Indices.size();
  3187. #ifndef NDEBUG
  3188. uint16_t DestEncoding = TRI->getEncodingValue(DestReg);
  3189. uint16_t SrcEncoding = TRI->getEncodingValue(SrcReg);
  3190. assert(DestEncoding % NumRegs == 0 && SrcEncoding % NumRegs == 0 &&
  3191. "GPR reg sequences should not be able to overlap");
  3192. #endif
  3193. for (unsigned SubReg = 0; SubReg != NumRegs; ++SubReg) {
  3194. const MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(Opcode));
  3195. AddSubReg(MIB, DestReg, Indices[SubReg], RegState::Define, TRI);
  3196. MIB.addReg(ZeroReg);
  3197. AddSubReg(MIB, SrcReg, Indices[SubReg], getKillRegState(KillSrc), TRI);
  3198. MIB.addImm(0);
  3199. }
  3200. }
  3201. void AArch64InstrInfo::copyPhysReg(MachineBasicBlock &MBB,
  3202. MachineBasicBlock::iterator I,
  3203. const DebugLoc &DL, MCRegister DestReg,
  3204. MCRegister SrcReg, bool KillSrc) const {
  3205. if (AArch64::GPR32spRegClass.contains(DestReg) &&
  3206. (AArch64::GPR32spRegClass.contains(SrcReg) || SrcReg == AArch64::WZR)) {
  3207. const TargetRegisterInfo *TRI = &getRegisterInfo();
  3208. if (DestReg == AArch64::WSP || SrcReg == AArch64::WSP) {
  3209. // If either operand is WSP, expand to ADD #0.
  3210. if (Subtarget.hasZeroCycleRegMove()) {
  3211. // Cyclone recognizes "ADD Xd, Xn, #0" as a zero-cycle register move.
  3212. MCRegister DestRegX = TRI->getMatchingSuperReg(
  3213. DestReg, AArch64::sub_32, &AArch64::GPR64spRegClass);
  3214. MCRegister SrcRegX = TRI->getMatchingSuperReg(
  3215. SrcReg, AArch64::sub_32, &AArch64::GPR64spRegClass);
  3216. // This instruction is reading and writing X registers. This may upset
  3217. // the register scavenger and machine verifier, so we need to indicate
  3218. // that we are reading an undefined value from SrcRegX, but a proper
  3219. // value from SrcReg.
  3220. BuildMI(MBB, I, DL, get(AArch64::ADDXri), DestRegX)
  3221. .addReg(SrcRegX, RegState::Undef)
  3222. .addImm(0)
  3223. .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0))
  3224. .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
  3225. } else {
  3226. BuildMI(MBB, I, DL, get(AArch64::ADDWri), DestReg)
  3227. .addReg(SrcReg, getKillRegState(KillSrc))
  3228. .addImm(0)
  3229. .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0));
  3230. }
  3231. } else if (SrcReg == AArch64::WZR && Subtarget.hasZeroCycleZeroingGP()) {
  3232. BuildMI(MBB, I, DL, get(AArch64::MOVZWi), DestReg)
  3233. .addImm(0)
  3234. .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0));
  3235. } else {
  3236. if (Subtarget.hasZeroCycleRegMove()) {
  3237. // Cyclone recognizes "ORR Xd, XZR, Xm" as a zero-cycle register move.
  3238. MCRegister DestRegX = TRI->getMatchingSuperReg(
  3239. DestReg, AArch64::sub_32, &AArch64::GPR64spRegClass);
  3240. MCRegister SrcRegX = TRI->getMatchingSuperReg(
  3241. SrcReg, AArch64::sub_32, &AArch64::GPR64spRegClass);
  3242. // This instruction is reading and writing X registers. This may upset
  3243. // the register scavenger and machine verifier, so we need to indicate
  3244. // that we are reading an undefined value from SrcRegX, but a proper
  3245. // value from SrcReg.
  3246. BuildMI(MBB, I, DL, get(AArch64::ORRXrr), DestRegX)
  3247. .addReg(AArch64::XZR)
  3248. .addReg(SrcRegX, RegState::Undef)
  3249. .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
  3250. } else {
  3251. // Otherwise, expand to ORR WZR.
  3252. BuildMI(MBB, I, DL, get(AArch64::ORRWrr), DestReg)
  3253. .addReg(AArch64::WZR)
  3254. .addReg(SrcReg, getKillRegState(KillSrc));
  3255. }
  3256. }
  3257. return;
  3258. }
  3259. // Copy a Predicate register by ORRing with itself.
  3260. if (AArch64::PPRRegClass.contains(DestReg) &&
  3261. AArch64::PPRRegClass.contains(SrcReg)) {
  3262. assert(Subtarget.hasSVEorSME() && "Unexpected SVE register.");
  3263. BuildMI(MBB, I, DL, get(AArch64::ORR_PPzPP), DestReg)
  3264. .addReg(SrcReg) // Pg
  3265. .addReg(SrcReg)
  3266. .addReg(SrcReg, getKillRegState(KillSrc));
  3267. return;
  3268. }
  3269. // Copy a Z register by ORRing with itself.
  3270. if (AArch64::ZPRRegClass.contains(DestReg) &&
  3271. AArch64::ZPRRegClass.contains(SrcReg)) {
  3272. assert(Subtarget.hasSVEorSME() && "Unexpected SVE register.");
  3273. BuildMI(MBB, I, DL, get(AArch64::ORR_ZZZ), DestReg)
  3274. .addReg(SrcReg)
  3275. .addReg(SrcReg, getKillRegState(KillSrc));
  3276. return;
  3277. }
  3278. // Copy a Z register pair by copying the individual sub-registers.
  3279. if (AArch64::ZPR2RegClass.contains(DestReg) &&
  3280. AArch64::ZPR2RegClass.contains(SrcReg)) {
  3281. assert(Subtarget.hasSVEorSME() && "Unexpected SVE register.");
  3282. static const unsigned Indices[] = {AArch64::zsub0, AArch64::zsub1};
  3283. copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORR_ZZZ,
  3284. Indices);
  3285. return;
  3286. }
  3287. // Copy a Z register triple by copying the individual sub-registers.
  3288. if (AArch64::ZPR3RegClass.contains(DestReg) &&
  3289. AArch64::ZPR3RegClass.contains(SrcReg)) {
  3290. assert(Subtarget.hasSVEorSME() && "Unexpected SVE register.");
  3291. static const unsigned Indices[] = {AArch64::zsub0, AArch64::zsub1,
  3292. AArch64::zsub2};
  3293. copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORR_ZZZ,
  3294. Indices);
  3295. return;
  3296. }
  3297. // Copy a Z register quad by copying the individual sub-registers.
  3298. if (AArch64::ZPR4RegClass.contains(DestReg) &&
  3299. AArch64::ZPR4RegClass.contains(SrcReg)) {
  3300. assert(Subtarget.hasSVEorSME() && "Unexpected SVE register.");
  3301. static const unsigned Indices[] = {AArch64::zsub0, AArch64::zsub1,
  3302. AArch64::zsub2, AArch64::zsub3};
  3303. copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORR_ZZZ,
  3304. Indices);
  3305. return;
  3306. }
  3307. if (AArch64::GPR64spRegClass.contains(DestReg) &&
  3308. (AArch64::GPR64spRegClass.contains(SrcReg) || SrcReg == AArch64::XZR)) {
  3309. if (DestReg == AArch64::SP || SrcReg == AArch64::SP) {
  3310. // If either operand is SP, expand to ADD #0.
  3311. BuildMI(MBB, I, DL, get(AArch64::ADDXri), DestReg)
  3312. .addReg(SrcReg, getKillRegState(KillSrc))
  3313. .addImm(0)
  3314. .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0));
  3315. } else if (SrcReg == AArch64::XZR && Subtarget.hasZeroCycleZeroingGP()) {
  3316. BuildMI(MBB, I, DL, get(AArch64::MOVZXi), DestReg)
  3317. .addImm(0)
  3318. .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0));
  3319. } else {
  3320. // Otherwise, expand to ORR XZR.
  3321. BuildMI(MBB, I, DL, get(AArch64::ORRXrr), DestReg)
  3322. .addReg(AArch64::XZR)
  3323. .addReg(SrcReg, getKillRegState(KillSrc));
  3324. }
  3325. return;
  3326. }
  3327. // Copy a DDDD register quad by copying the individual sub-registers.
  3328. if (AArch64::DDDDRegClass.contains(DestReg) &&
  3329. AArch64::DDDDRegClass.contains(SrcReg)) {
  3330. static const unsigned Indices[] = {AArch64::dsub0, AArch64::dsub1,
  3331. AArch64::dsub2, AArch64::dsub3};
  3332. copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRv8i8,
  3333. Indices);
  3334. return;
  3335. }
  3336. // Copy a DDD register triple by copying the individual sub-registers.
  3337. if (AArch64::DDDRegClass.contains(DestReg) &&
  3338. AArch64::DDDRegClass.contains(SrcReg)) {
  3339. static const unsigned Indices[] = {AArch64::dsub0, AArch64::dsub1,
  3340. AArch64::dsub2};
  3341. copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRv8i8,
  3342. Indices);
  3343. return;
  3344. }
  3345. // Copy a DD register pair by copying the individual sub-registers.
  3346. if (AArch64::DDRegClass.contains(DestReg) &&
  3347. AArch64::DDRegClass.contains(SrcReg)) {
  3348. static const unsigned Indices[] = {AArch64::dsub0, AArch64::dsub1};
  3349. copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRv8i8,
  3350. Indices);
  3351. return;
  3352. }
  3353. // Copy a QQQQ register quad by copying the individual sub-registers.
  3354. if (AArch64::QQQQRegClass.contains(DestReg) &&
  3355. AArch64::QQQQRegClass.contains(SrcReg)) {
  3356. static const unsigned Indices[] = {AArch64::qsub0, AArch64::qsub1,
  3357. AArch64::qsub2, AArch64::qsub3};
  3358. copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRv16i8,
  3359. Indices);
  3360. return;
  3361. }
  3362. // Copy a QQQ register triple by copying the individual sub-registers.
  3363. if (AArch64::QQQRegClass.contains(DestReg) &&
  3364. AArch64::QQQRegClass.contains(SrcReg)) {
  3365. static const unsigned Indices[] = {AArch64::qsub0, AArch64::qsub1,
  3366. AArch64::qsub2};
  3367. copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRv16i8,
  3368. Indices);
  3369. return;
  3370. }
  3371. // Copy a QQ register pair by copying the individual sub-registers.
  3372. if (AArch64::QQRegClass.contains(DestReg) &&
  3373. AArch64::QQRegClass.contains(SrcReg)) {
  3374. static const unsigned Indices[] = {AArch64::qsub0, AArch64::qsub1};
  3375. copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRv16i8,
  3376. Indices);
  3377. return;
  3378. }
  3379. if (AArch64::XSeqPairsClassRegClass.contains(DestReg) &&
  3380. AArch64::XSeqPairsClassRegClass.contains(SrcReg)) {
  3381. static const unsigned Indices[] = {AArch64::sube64, AArch64::subo64};
  3382. copyGPRRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRXrs,
  3383. AArch64::XZR, Indices);
  3384. return;
  3385. }
  3386. if (AArch64::WSeqPairsClassRegClass.contains(DestReg) &&
  3387. AArch64::WSeqPairsClassRegClass.contains(SrcReg)) {
  3388. static const unsigned Indices[] = {AArch64::sube32, AArch64::subo32};
  3389. copyGPRRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRWrs,
  3390. AArch64::WZR, Indices);
  3391. return;
  3392. }
  3393. if (AArch64::FPR128RegClass.contains(DestReg) &&
  3394. AArch64::FPR128RegClass.contains(SrcReg)) {
  3395. if (Subtarget.forceStreamingCompatibleSVE()) {
  3396. BuildMI(MBB, I, DL, get(AArch64::ORR_ZZZ))
  3397. .addReg(AArch64::Z0 + (DestReg - AArch64::Q0), RegState::Define)
  3398. .addReg(AArch64::Z0 + (SrcReg - AArch64::Q0))
  3399. .addReg(AArch64::Z0 + (SrcReg - AArch64::Q0));
  3400. } else if (Subtarget.hasNEON()) {
  3401. BuildMI(MBB, I, DL, get(AArch64::ORRv16i8), DestReg)
  3402. .addReg(SrcReg)
  3403. .addReg(SrcReg, getKillRegState(KillSrc));
  3404. } else {
  3405. BuildMI(MBB, I, DL, get(AArch64::STRQpre))
  3406. .addReg(AArch64::SP, RegState::Define)
  3407. .addReg(SrcReg, getKillRegState(KillSrc))
  3408. .addReg(AArch64::SP)
  3409. .addImm(-16);
  3410. BuildMI(MBB, I, DL, get(AArch64::LDRQpre))
  3411. .addReg(AArch64::SP, RegState::Define)
  3412. .addReg(DestReg, RegState::Define)
  3413. .addReg(AArch64::SP)
  3414. .addImm(16);
  3415. }
  3416. return;
  3417. }
  3418. if (AArch64::FPR64RegClass.contains(DestReg) &&
  3419. AArch64::FPR64RegClass.contains(SrcReg)) {
  3420. BuildMI(MBB, I, DL, get(AArch64::FMOVDr), DestReg)
  3421. .addReg(SrcReg, getKillRegState(KillSrc));
  3422. return;
  3423. }
  3424. if (AArch64::FPR32RegClass.contains(DestReg) &&
  3425. AArch64::FPR32RegClass.contains(SrcReg)) {
  3426. BuildMI(MBB, I, DL, get(AArch64::FMOVSr), DestReg)
  3427. .addReg(SrcReg, getKillRegState(KillSrc));
  3428. return;
  3429. }
  3430. if (AArch64::FPR16RegClass.contains(DestReg) &&
  3431. AArch64::FPR16RegClass.contains(SrcReg)) {
  3432. DestReg =
  3433. RI.getMatchingSuperReg(DestReg, AArch64::hsub, &AArch64::FPR32RegClass);
  3434. SrcReg =
  3435. RI.getMatchingSuperReg(SrcReg, AArch64::hsub, &AArch64::FPR32RegClass);
  3436. BuildMI(MBB, I, DL, get(AArch64::FMOVSr), DestReg)
  3437. .addReg(SrcReg, getKillRegState(KillSrc));
  3438. return;
  3439. }
  3440. if (AArch64::FPR8RegClass.contains(DestReg) &&
  3441. AArch64::FPR8RegClass.contains(SrcReg)) {
  3442. DestReg =
  3443. RI.getMatchingSuperReg(DestReg, AArch64::bsub, &AArch64::FPR32RegClass);
  3444. SrcReg =
  3445. RI.getMatchingSuperReg(SrcReg, AArch64::bsub, &AArch64::FPR32RegClass);
  3446. BuildMI(MBB, I, DL, get(AArch64::FMOVSr), DestReg)
  3447. .addReg(SrcReg, getKillRegState(KillSrc));
  3448. return;
  3449. }
  3450. // Copies between GPR64 and FPR64.
  3451. if (AArch64::FPR64RegClass.contains(DestReg) &&
  3452. AArch64::GPR64RegClass.contains(SrcReg)) {
  3453. BuildMI(MBB, I, DL, get(AArch64::FMOVXDr), DestReg)
  3454. .addReg(SrcReg, getKillRegState(KillSrc));
  3455. return;
  3456. }
  3457. if (AArch64::GPR64RegClass.contains(DestReg) &&
  3458. AArch64::FPR64RegClass.contains(SrcReg)) {
  3459. BuildMI(MBB, I, DL, get(AArch64::FMOVDXr), DestReg)
  3460. .addReg(SrcReg, getKillRegState(KillSrc));
  3461. return;
  3462. }
  3463. // Copies between GPR32 and FPR32.
  3464. if (AArch64::FPR32RegClass.contains(DestReg) &&
  3465. AArch64::GPR32RegClass.contains(SrcReg)) {
  3466. BuildMI(MBB, I, DL, get(AArch64::FMOVWSr), DestReg)
  3467. .addReg(SrcReg, getKillRegState(KillSrc));
  3468. return;
  3469. }
  3470. if (AArch64::GPR32RegClass.contains(DestReg) &&
  3471. AArch64::FPR32RegClass.contains(SrcReg)) {
  3472. BuildMI(MBB, I, DL, get(AArch64::FMOVSWr), DestReg)
  3473. .addReg(SrcReg, getKillRegState(KillSrc));
  3474. return;
  3475. }
  3476. if (DestReg == AArch64::NZCV) {
  3477. assert(AArch64::GPR64RegClass.contains(SrcReg) && "Invalid NZCV copy");
  3478. BuildMI(MBB, I, DL, get(AArch64::MSR))
  3479. .addImm(AArch64SysReg::NZCV)
  3480. .addReg(SrcReg, getKillRegState(KillSrc))
  3481. .addReg(AArch64::NZCV, RegState::Implicit | RegState::Define);
  3482. return;
  3483. }
  3484. if (SrcReg == AArch64::NZCV) {
  3485. assert(AArch64::GPR64RegClass.contains(DestReg) && "Invalid NZCV copy");
  3486. BuildMI(MBB, I, DL, get(AArch64::MRS), DestReg)
  3487. .addImm(AArch64SysReg::NZCV)
  3488. .addReg(AArch64::NZCV, RegState::Implicit | getKillRegState(KillSrc));
  3489. return;
  3490. }
  3491. #ifndef NDEBUG
  3492. const TargetRegisterInfo &TRI = getRegisterInfo();
  3493. errs() << TRI.getRegAsmName(DestReg) << " = COPY "
  3494. << TRI.getRegAsmName(SrcReg) << "\n";
  3495. #endif
  3496. llvm_unreachable("unimplemented reg-to-reg copy");
  3497. }
  3498. static void storeRegPairToStackSlot(const TargetRegisterInfo &TRI,
  3499. MachineBasicBlock &MBB,
  3500. MachineBasicBlock::iterator InsertBefore,
  3501. const MCInstrDesc &MCID,
  3502. Register SrcReg, bool IsKill,
  3503. unsigned SubIdx0, unsigned SubIdx1, int FI,
  3504. MachineMemOperand *MMO) {
  3505. Register SrcReg0 = SrcReg;
  3506. Register SrcReg1 = SrcReg;
  3507. if (SrcReg.isPhysical()) {
  3508. SrcReg0 = TRI.getSubReg(SrcReg, SubIdx0);
  3509. SubIdx0 = 0;
  3510. SrcReg1 = TRI.getSubReg(SrcReg, SubIdx1);
  3511. SubIdx1 = 0;
  3512. }
  3513. BuildMI(MBB, InsertBefore, DebugLoc(), MCID)
  3514. .addReg(SrcReg0, getKillRegState(IsKill), SubIdx0)
  3515. .addReg(SrcReg1, getKillRegState(IsKill), SubIdx1)
  3516. .addFrameIndex(FI)
  3517. .addImm(0)
  3518. .addMemOperand(MMO);
  3519. }
  3520. void AArch64InstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
  3521. MachineBasicBlock::iterator MBBI,
  3522. Register SrcReg, bool isKill, int FI,
  3523. const TargetRegisterClass *RC,
  3524. const TargetRegisterInfo *TRI,
  3525. Register VReg) const {
  3526. MachineFunction &MF = *MBB.getParent();
  3527. MachineFrameInfo &MFI = MF.getFrameInfo();
  3528. MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(MF, FI);
  3529. MachineMemOperand *MMO =
  3530. MF.getMachineMemOperand(PtrInfo, MachineMemOperand::MOStore,
  3531. MFI.getObjectSize(FI), MFI.getObjectAlign(FI));
  3532. unsigned Opc = 0;
  3533. bool Offset = true;
  3534. unsigned StackID = TargetStackID::Default;
  3535. switch (TRI->getSpillSize(*RC)) {
  3536. case 1:
  3537. if (AArch64::FPR8RegClass.hasSubClassEq(RC))
  3538. Opc = AArch64::STRBui;
  3539. break;
  3540. case 2:
  3541. if (AArch64::FPR16RegClass.hasSubClassEq(RC))
  3542. Opc = AArch64::STRHui;
  3543. else if (AArch64::PPRRegClass.hasSubClassEq(RC)) {
  3544. assert(Subtarget.hasSVE() && "Unexpected register store without SVE");
  3545. Opc = AArch64::STR_PXI;
  3546. StackID = TargetStackID::ScalableVector;
  3547. }
  3548. break;
  3549. case 4:
  3550. if (AArch64::GPR32allRegClass.hasSubClassEq(RC)) {
  3551. Opc = AArch64::STRWui;
  3552. if (SrcReg.isVirtual())
  3553. MF.getRegInfo().constrainRegClass(SrcReg, &AArch64::GPR32RegClass);
  3554. else
  3555. assert(SrcReg != AArch64::WSP);
  3556. } else if (AArch64::FPR32RegClass.hasSubClassEq(RC))
  3557. Opc = AArch64::STRSui;
  3558. break;
  3559. case 8:
  3560. if (AArch64::GPR64allRegClass.hasSubClassEq(RC)) {
  3561. Opc = AArch64::STRXui;
  3562. if (SrcReg.isVirtual())
  3563. MF.getRegInfo().constrainRegClass(SrcReg, &AArch64::GPR64RegClass);
  3564. else
  3565. assert(SrcReg != AArch64::SP);
  3566. } else if (AArch64::FPR64RegClass.hasSubClassEq(RC)) {
  3567. Opc = AArch64::STRDui;
  3568. } else if (AArch64::WSeqPairsClassRegClass.hasSubClassEq(RC)) {
  3569. storeRegPairToStackSlot(getRegisterInfo(), MBB, MBBI,
  3570. get(AArch64::STPWi), SrcReg, isKill,
  3571. AArch64::sube32, AArch64::subo32, FI, MMO);
  3572. return;
  3573. }
  3574. break;
  3575. case 16:
  3576. if (AArch64::FPR128RegClass.hasSubClassEq(RC))
  3577. Opc = AArch64::STRQui;
  3578. else if (AArch64::DDRegClass.hasSubClassEq(RC)) {
  3579. assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
  3580. Opc = AArch64::ST1Twov1d;
  3581. Offset = false;
  3582. } else if (AArch64::XSeqPairsClassRegClass.hasSubClassEq(RC)) {
  3583. storeRegPairToStackSlot(getRegisterInfo(), MBB, MBBI,
  3584. get(AArch64::STPXi), SrcReg, isKill,
  3585. AArch64::sube64, AArch64::subo64, FI, MMO);
  3586. return;
  3587. } else if (AArch64::ZPRRegClass.hasSubClassEq(RC)) {
  3588. assert(Subtarget.hasSVE() && "Unexpected register store without SVE");
  3589. Opc = AArch64::STR_ZXI;
  3590. StackID = TargetStackID::ScalableVector;
  3591. }
  3592. break;
  3593. case 24:
  3594. if (AArch64::DDDRegClass.hasSubClassEq(RC)) {
  3595. assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
  3596. Opc = AArch64::ST1Threev1d;
  3597. Offset = false;
  3598. }
  3599. break;
  3600. case 32:
  3601. if (AArch64::DDDDRegClass.hasSubClassEq(RC)) {
  3602. assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
  3603. Opc = AArch64::ST1Fourv1d;
  3604. Offset = false;
  3605. } else if (AArch64::QQRegClass.hasSubClassEq(RC)) {
  3606. assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
  3607. Opc = AArch64::ST1Twov2d;
  3608. Offset = false;
  3609. } else if (AArch64::ZPR2RegClass.hasSubClassEq(RC)) {
  3610. assert(Subtarget.hasSVE() && "Unexpected register store without SVE");
  3611. Opc = AArch64::STR_ZZXI;
  3612. StackID = TargetStackID::ScalableVector;
  3613. }
  3614. break;
  3615. case 48:
  3616. if (AArch64::QQQRegClass.hasSubClassEq(RC)) {
  3617. assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
  3618. Opc = AArch64::ST1Threev2d;
  3619. Offset = false;
  3620. } else if (AArch64::ZPR3RegClass.hasSubClassEq(RC)) {
  3621. assert(Subtarget.hasSVE() && "Unexpected register store without SVE");
  3622. Opc = AArch64::STR_ZZZXI;
  3623. StackID = TargetStackID::ScalableVector;
  3624. }
  3625. break;
  3626. case 64:
  3627. if (AArch64::QQQQRegClass.hasSubClassEq(RC)) {
  3628. assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
  3629. Opc = AArch64::ST1Fourv2d;
  3630. Offset = false;
  3631. } else if (AArch64::ZPR4RegClass.hasSubClassEq(RC)) {
  3632. assert(Subtarget.hasSVE() && "Unexpected register store without SVE");
  3633. Opc = AArch64::STR_ZZZZXI;
  3634. StackID = TargetStackID::ScalableVector;
  3635. }
  3636. break;
  3637. }
  3638. assert(Opc && "Unknown register class");
  3639. MFI.setStackID(FI, StackID);
  3640. const MachineInstrBuilder MI = BuildMI(MBB, MBBI, DebugLoc(), get(Opc))
  3641. .addReg(SrcReg, getKillRegState(isKill))
  3642. .addFrameIndex(FI);
  3643. if (Offset)
  3644. MI.addImm(0);
  3645. MI.addMemOperand(MMO);
  3646. }
  3647. static void loadRegPairFromStackSlot(const TargetRegisterInfo &TRI,
  3648. MachineBasicBlock &MBB,
  3649. MachineBasicBlock::iterator InsertBefore,
  3650. const MCInstrDesc &MCID,
  3651. Register DestReg, unsigned SubIdx0,
  3652. unsigned SubIdx1, int FI,
  3653. MachineMemOperand *MMO) {
  3654. Register DestReg0 = DestReg;
  3655. Register DestReg1 = DestReg;
  3656. bool IsUndef = true;
  3657. if (DestReg.isPhysical()) {
  3658. DestReg0 = TRI.getSubReg(DestReg, SubIdx0);
  3659. SubIdx0 = 0;
  3660. DestReg1 = TRI.getSubReg(DestReg, SubIdx1);
  3661. SubIdx1 = 0;
  3662. IsUndef = false;
  3663. }
  3664. BuildMI(MBB, InsertBefore, DebugLoc(), MCID)
  3665. .addReg(DestReg0, RegState::Define | getUndefRegState(IsUndef), SubIdx0)
  3666. .addReg(DestReg1, RegState::Define | getUndefRegState(IsUndef), SubIdx1)
  3667. .addFrameIndex(FI)
  3668. .addImm(0)
  3669. .addMemOperand(MMO);
  3670. }
  3671. void AArch64InstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
  3672. MachineBasicBlock::iterator MBBI,
  3673. Register DestReg, int FI,
  3674. const TargetRegisterClass *RC,
  3675. const TargetRegisterInfo *TRI,
  3676. Register VReg) const {
  3677. MachineFunction &MF = *MBB.getParent();
  3678. MachineFrameInfo &MFI = MF.getFrameInfo();
  3679. MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(MF, FI);
  3680. MachineMemOperand *MMO =
  3681. MF.getMachineMemOperand(PtrInfo, MachineMemOperand::MOLoad,
  3682. MFI.getObjectSize(FI), MFI.getObjectAlign(FI));
  3683. unsigned Opc = 0;
  3684. bool Offset = true;
  3685. unsigned StackID = TargetStackID::Default;
  3686. switch (TRI->getSpillSize(*RC)) {
  3687. case 1:
  3688. if (AArch64::FPR8RegClass.hasSubClassEq(RC))
  3689. Opc = AArch64::LDRBui;
  3690. break;
  3691. case 2:
  3692. if (AArch64::FPR16RegClass.hasSubClassEq(RC))
  3693. Opc = AArch64::LDRHui;
  3694. else if (AArch64::PPRRegClass.hasSubClassEq(RC)) {
  3695. assert(Subtarget.hasSVE() && "Unexpected register load without SVE");
  3696. Opc = AArch64::LDR_PXI;
  3697. StackID = TargetStackID::ScalableVector;
  3698. }
  3699. break;
  3700. case 4:
  3701. if (AArch64::GPR32allRegClass.hasSubClassEq(RC)) {
  3702. Opc = AArch64::LDRWui;
  3703. if (DestReg.isVirtual())
  3704. MF.getRegInfo().constrainRegClass(DestReg, &AArch64::GPR32RegClass);
  3705. else
  3706. assert(DestReg != AArch64::WSP);
  3707. } else if (AArch64::FPR32RegClass.hasSubClassEq(RC))
  3708. Opc = AArch64::LDRSui;
  3709. break;
  3710. case 8:
  3711. if (AArch64::GPR64allRegClass.hasSubClassEq(RC)) {
  3712. Opc = AArch64::LDRXui;
  3713. if (DestReg.isVirtual())
  3714. MF.getRegInfo().constrainRegClass(DestReg, &AArch64::GPR64RegClass);
  3715. else
  3716. assert(DestReg != AArch64::SP);
  3717. } else if (AArch64::FPR64RegClass.hasSubClassEq(RC)) {
  3718. Opc = AArch64::LDRDui;
  3719. } else if (AArch64::WSeqPairsClassRegClass.hasSubClassEq(RC)) {
  3720. loadRegPairFromStackSlot(getRegisterInfo(), MBB, MBBI,
  3721. get(AArch64::LDPWi), DestReg, AArch64::sube32,
  3722. AArch64::subo32, FI, MMO);
  3723. return;
  3724. }
  3725. break;
  3726. case 16:
  3727. if (AArch64::FPR128RegClass.hasSubClassEq(RC))
  3728. Opc = AArch64::LDRQui;
  3729. else if (AArch64::DDRegClass.hasSubClassEq(RC)) {
  3730. assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
  3731. Opc = AArch64::LD1Twov1d;
  3732. Offset = false;
  3733. } else if (AArch64::XSeqPairsClassRegClass.hasSubClassEq(RC)) {
  3734. loadRegPairFromStackSlot(getRegisterInfo(), MBB, MBBI,
  3735. get(AArch64::LDPXi), DestReg, AArch64::sube64,
  3736. AArch64::subo64, FI, MMO);
  3737. return;
  3738. } else if (AArch64::ZPRRegClass.hasSubClassEq(RC)) {
  3739. assert(Subtarget.hasSVE() && "Unexpected register load without SVE");
  3740. Opc = AArch64::LDR_ZXI;
  3741. StackID = TargetStackID::ScalableVector;
  3742. }
  3743. break;
  3744. case 24:
  3745. if (AArch64::DDDRegClass.hasSubClassEq(RC)) {
  3746. assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
  3747. Opc = AArch64::LD1Threev1d;
  3748. Offset = false;
  3749. }
  3750. break;
  3751. case 32:
  3752. if (AArch64::DDDDRegClass.hasSubClassEq(RC)) {
  3753. assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
  3754. Opc = AArch64::LD1Fourv1d;
  3755. Offset = false;
  3756. } else if (AArch64::QQRegClass.hasSubClassEq(RC)) {
  3757. assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
  3758. Opc = AArch64::LD1Twov2d;
  3759. Offset = false;
  3760. } else if (AArch64::ZPR2RegClass.hasSubClassEq(RC)) {
  3761. assert(Subtarget.hasSVE() && "Unexpected register load without SVE");
  3762. Opc = AArch64::LDR_ZZXI;
  3763. StackID = TargetStackID::ScalableVector;
  3764. }
  3765. break;
  3766. case 48:
  3767. if (AArch64::QQQRegClass.hasSubClassEq(RC)) {
  3768. assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
  3769. Opc = AArch64::LD1Threev2d;
  3770. Offset = false;
  3771. } else if (AArch64::ZPR3RegClass.hasSubClassEq(RC)) {
  3772. assert(Subtarget.hasSVE() && "Unexpected register load without SVE");
  3773. Opc = AArch64::LDR_ZZZXI;
  3774. StackID = TargetStackID::ScalableVector;
  3775. }
  3776. break;
  3777. case 64:
  3778. if (AArch64::QQQQRegClass.hasSubClassEq(RC)) {
  3779. assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
  3780. Opc = AArch64::LD1Fourv2d;
  3781. Offset = false;
  3782. } else if (AArch64::ZPR4RegClass.hasSubClassEq(RC)) {
  3783. assert(Subtarget.hasSVE() && "Unexpected register load without SVE");
  3784. Opc = AArch64::LDR_ZZZZXI;
  3785. StackID = TargetStackID::ScalableVector;
  3786. }
  3787. break;
  3788. }
  3789. assert(Opc && "Unknown register class");
  3790. MFI.setStackID(FI, StackID);
  3791. const MachineInstrBuilder MI = BuildMI(MBB, MBBI, DebugLoc(), get(Opc))
  3792. .addReg(DestReg, getDefRegState(true))
  3793. .addFrameIndex(FI);
  3794. if (Offset)
  3795. MI.addImm(0);
  3796. MI.addMemOperand(MMO);
  3797. }
  3798. bool llvm::isNZCVTouchedInInstructionRange(const MachineInstr &DefMI,
  3799. const MachineInstr &UseMI,
  3800. const TargetRegisterInfo *TRI) {
  3801. return any_of(instructionsWithoutDebug(std::next(DefMI.getIterator()),
  3802. UseMI.getIterator()),
  3803. [TRI](const MachineInstr &I) {
  3804. return I.modifiesRegister(AArch64::NZCV, TRI) ||
  3805. I.readsRegister(AArch64::NZCV, TRI);
  3806. });
  3807. }
  3808. void AArch64InstrInfo::decomposeStackOffsetForDwarfOffsets(
  3809. const StackOffset &Offset, int64_t &ByteSized, int64_t &VGSized) {
  3810. // The smallest scalable element supported by scaled SVE addressing
  3811. // modes are predicates, which are 2 scalable bytes in size. So the scalable
  3812. // byte offset must always be a multiple of 2.
  3813. assert(Offset.getScalable() % 2 == 0 && "Invalid frame offset");
  3814. // VGSized offsets are divided by '2', because the VG register is the
  3815. // the number of 64bit granules as opposed to 128bit vector chunks,
  3816. // which is how the 'n' in e.g. MVT::nxv1i8 is modelled.
  3817. // So, for a stack offset of 16 MVT::nxv1i8's, the size is n x 16 bytes.
  3818. // VG = n * 2 and the dwarf offset must be VG * 8 bytes.
  3819. ByteSized = Offset.getFixed();
  3820. VGSized = Offset.getScalable() / 2;
  3821. }
  3822. /// Returns the offset in parts to which this frame offset can be
  3823. /// decomposed for the purpose of describing a frame offset.
  3824. /// For non-scalable offsets this is simply its byte size.
  3825. void AArch64InstrInfo::decomposeStackOffsetForFrameOffsets(
  3826. const StackOffset &Offset, int64_t &NumBytes, int64_t &NumPredicateVectors,
  3827. int64_t &NumDataVectors) {
  3828. // The smallest scalable element supported by scaled SVE addressing
  3829. // modes are predicates, which are 2 scalable bytes in size. So the scalable
  3830. // byte offset must always be a multiple of 2.
  3831. assert(Offset.getScalable() % 2 == 0 && "Invalid frame offset");
  3832. NumBytes = Offset.getFixed();
  3833. NumDataVectors = 0;
  3834. NumPredicateVectors = Offset.getScalable() / 2;
  3835. // This method is used to get the offsets to adjust the frame offset.
  3836. // If the function requires ADDPL to be used and needs more than two ADDPL
  3837. // instructions, part of the offset is folded into NumDataVectors so that it
  3838. // uses ADDVL for part of it, reducing the number of ADDPL instructions.
  3839. if (NumPredicateVectors % 8 == 0 || NumPredicateVectors < -64 ||
  3840. NumPredicateVectors > 62) {
  3841. NumDataVectors = NumPredicateVectors / 8;
  3842. NumPredicateVectors -= NumDataVectors * 8;
  3843. }
  3844. }
  3845. // Convenience function to create a DWARF expression for
  3846. // Expr + NumBytes + NumVGScaledBytes * AArch64::VG
  3847. static void appendVGScaledOffsetExpr(SmallVectorImpl<char> &Expr, int NumBytes,
  3848. int NumVGScaledBytes, unsigned VG,
  3849. llvm::raw_string_ostream &Comment) {
  3850. uint8_t buffer[16];
  3851. if (NumBytes) {
  3852. Expr.push_back(dwarf::DW_OP_consts);
  3853. Expr.append(buffer, buffer + encodeSLEB128(NumBytes, buffer));
  3854. Expr.push_back((uint8_t)dwarf::DW_OP_plus);
  3855. Comment << (NumBytes < 0 ? " - " : " + ") << std::abs(NumBytes);
  3856. }
  3857. if (NumVGScaledBytes) {
  3858. Expr.push_back((uint8_t)dwarf::DW_OP_consts);
  3859. Expr.append(buffer, buffer + encodeSLEB128(NumVGScaledBytes, buffer));
  3860. Expr.push_back((uint8_t)dwarf::DW_OP_bregx);
  3861. Expr.append(buffer, buffer + encodeULEB128(VG, buffer));
  3862. Expr.push_back(0);
  3863. Expr.push_back((uint8_t)dwarf::DW_OP_mul);
  3864. Expr.push_back((uint8_t)dwarf::DW_OP_plus);
  3865. Comment << (NumVGScaledBytes < 0 ? " - " : " + ")
  3866. << std::abs(NumVGScaledBytes) << " * VG";
  3867. }
  3868. }
  3869. // Creates an MCCFIInstruction:
  3870. // { DW_CFA_def_cfa_expression, ULEB128 (sizeof expr), expr }
  3871. static MCCFIInstruction createDefCFAExpression(const TargetRegisterInfo &TRI,
  3872. unsigned Reg,
  3873. const StackOffset &Offset) {
  3874. int64_t NumBytes, NumVGScaledBytes;
  3875. AArch64InstrInfo::decomposeStackOffsetForDwarfOffsets(Offset, NumBytes,
  3876. NumVGScaledBytes);
  3877. std::string CommentBuffer;
  3878. llvm::raw_string_ostream Comment(CommentBuffer);
  3879. if (Reg == AArch64::SP)
  3880. Comment << "sp";
  3881. else if (Reg == AArch64::FP)
  3882. Comment << "fp";
  3883. else
  3884. Comment << printReg(Reg, &TRI);
  3885. // Build up the expression (Reg + NumBytes + NumVGScaledBytes * AArch64::VG)
  3886. SmallString<64> Expr;
  3887. unsigned DwarfReg = TRI.getDwarfRegNum(Reg, true);
  3888. Expr.push_back((uint8_t)(dwarf::DW_OP_breg0 + DwarfReg));
  3889. Expr.push_back(0);
  3890. appendVGScaledOffsetExpr(Expr, NumBytes, NumVGScaledBytes,
  3891. TRI.getDwarfRegNum(AArch64::VG, true), Comment);
  3892. // Wrap this into DW_CFA_def_cfa.
  3893. SmallString<64> DefCfaExpr;
  3894. DefCfaExpr.push_back(dwarf::DW_CFA_def_cfa_expression);
  3895. uint8_t buffer[16];
  3896. DefCfaExpr.append(buffer, buffer + encodeULEB128(Expr.size(), buffer));
  3897. DefCfaExpr.append(Expr.str());
  3898. return MCCFIInstruction::createEscape(nullptr, DefCfaExpr.str(),
  3899. Comment.str());
  3900. }
  3901. MCCFIInstruction llvm::createDefCFA(const TargetRegisterInfo &TRI,
  3902. unsigned FrameReg, unsigned Reg,
  3903. const StackOffset &Offset,
  3904. bool LastAdjustmentWasScalable) {
  3905. if (Offset.getScalable())
  3906. return createDefCFAExpression(TRI, Reg, Offset);
  3907. if (FrameReg == Reg && !LastAdjustmentWasScalable)
  3908. return MCCFIInstruction::cfiDefCfaOffset(nullptr, int(Offset.getFixed()));
  3909. unsigned DwarfReg = TRI.getDwarfRegNum(Reg, true);
  3910. return MCCFIInstruction::cfiDefCfa(nullptr, DwarfReg, (int)Offset.getFixed());
  3911. }
  3912. MCCFIInstruction llvm::createCFAOffset(const TargetRegisterInfo &TRI,
  3913. unsigned Reg,
  3914. const StackOffset &OffsetFromDefCFA) {
  3915. int64_t NumBytes, NumVGScaledBytes;
  3916. AArch64InstrInfo::decomposeStackOffsetForDwarfOffsets(
  3917. OffsetFromDefCFA, NumBytes, NumVGScaledBytes);
  3918. unsigned DwarfReg = TRI.getDwarfRegNum(Reg, true);
  3919. // Non-scalable offsets can use DW_CFA_offset directly.
  3920. if (!NumVGScaledBytes)
  3921. return MCCFIInstruction::createOffset(nullptr, DwarfReg, NumBytes);
  3922. std::string CommentBuffer;
  3923. llvm::raw_string_ostream Comment(CommentBuffer);
  3924. Comment << printReg(Reg, &TRI) << " @ cfa";
  3925. // Build up expression (NumBytes + NumVGScaledBytes * AArch64::VG)
  3926. SmallString<64> OffsetExpr;
  3927. appendVGScaledOffsetExpr(OffsetExpr, NumBytes, NumVGScaledBytes,
  3928. TRI.getDwarfRegNum(AArch64::VG, true), Comment);
  3929. // Wrap this into DW_CFA_expression
  3930. SmallString<64> CfaExpr;
  3931. CfaExpr.push_back(dwarf::DW_CFA_expression);
  3932. uint8_t buffer[16];
  3933. CfaExpr.append(buffer, buffer + encodeULEB128(DwarfReg, buffer));
  3934. CfaExpr.append(buffer, buffer + encodeULEB128(OffsetExpr.size(), buffer));
  3935. CfaExpr.append(OffsetExpr.str());
  3936. return MCCFIInstruction::createEscape(nullptr, CfaExpr.str(), Comment.str());
  3937. }
  3938. // Helper function to emit a frame offset adjustment from a given
  3939. // pointer (SrcReg), stored into DestReg. This function is explicit
  3940. // in that it requires the opcode.
  3941. static void emitFrameOffsetAdj(MachineBasicBlock &MBB,
  3942. MachineBasicBlock::iterator MBBI,
  3943. const DebugLoc &DL, unsigned DestReg,
  3944. unsigned SrcReg, int64_t Offset, unsigned Opc,
  3945. const TargetInstrInfo *TII,
  3946. MachineInstr::MIFlag Flag, bool NeedsWinCFI,
  3947. bool *HasWinCFI, bool EmitCFAOffset,
  3948. StackOffset CFAOffset, unsigned FrameReg) {
  3949. int Sign = 1;
  3950. unsigned MaxEncoding, ShiftSize;
  3951. switch (Opc) {
  3952. case AArch64::ADDXri:
  3953. case AArch64::ADDSXri:
  3954. case AArch64::SUBXri:
  3955. case AArch64::SUBSXri:
  3956. MaxEncoding = 0xfff;
  3957. ShiftSize = 12;
  3958. break;
  3959. case AArch64::ADDVL_XXI:
  3960. case AArch64::ADDPL_XXI:
  3961. case AArch64::ADDSVL_XXI:
  3962. case AArch64::ADDSPL_XXI:
  3963. MaxEncoding = 31;
  3964. ShiftSize = 0;
  3965. if (Offset < 0) {
  3966. MaxEncoding = 32;
  3967. Sign = -1;
  3968. Offset = -Offset;
  3969. }
  3970. break;
  3971. default:
  3972. llvm_unreachable("Unsupported opcode");
  3973. }
  3974. // `Offset` can be in bytes or in "scalable bytes".
  3975. int VScale = 1;
  3976. if (Opc == AArch64::ADDVL_XXI || Opc == AArch64::ADDSVL_XXI)
  3977. VScale = 16;
  3978. else if (Opc == AArch64::ADDPL_XXI || Opc == AArch64::ADDSPL_XXI)
  3979. VScale = 2;
  3980. // FIXME: If the offset won't fit in 24-bits, compute the offset into a
  3981. // scratch register. If DestReg is a virtual register, use it as the
  3982. // scratch register; otherwise, create a new virtual register (to be
  3983. // replaced by the scavenger at the end of PEI). That case can be optimized
  3984. // slightly if DestReg is SP which is always 16-byte aligned, so the scratch
  3985. // register can be loaded with offset%8 and the add/sub can use an extending
  3986. // instruction with LSL#3.
  3987. // Currently the function handles any offsets but generates a poor sequence
  3988. // of code.
  3989. // assert(Offset < (1 << 24) && "unimplemented reg plus immediate");
  3990. const unsigned MaxEncodableValue = MaxEncoding << ShiftSize;
  3991. Register TmpReg = DestReg;
  3992. if (TmpReg == AArch64::XZR)
  3993. TmpReg = MBB.getParent()->getRegInfo().createVirtualRegister(
  3994. &AArch64::GPR64RegClass);
  3995. do {
  3996. uint64_t ThisVal = std::min<uint64_t>(Offset, MaxEncodableValue);
  3997. unsigned LocalShiftSize = 0;
  3998. if (ThisVal > MaxEncoding) {
  3999. ThisVal = ThisVal >> ShiftSize;
  4000. LocalShiftSize = ShiftSize;
  4001. }
  4002. assert((ThisVal >> ShiftSize) <= MaxEncoding &&
  4003. "Encoding cannot handle value that big");
  4004. Offset -= ThisVal << LocalShiftSize;
  4005. if (Offset == 0)
  4006. TmpReg = DestReg;
  4007. auto MBI = BuildMI(MBB, MBBI, DL, TII->get(Opc), TmpReg)
  4008. .addReg(SrcReg)
  4009. .addImm(Sign * (int)ThisVal);
  4010. if (ShiftSize)
  4011. MBI = MBI.addImm(
  4012. AArch64_AM::getShifterImm(AArch64_AM::LSL, LocalShiftSize));
  4013. MBI = MBI.setMIFlag(Flag);
  4014. auto Change =
  4015. VScale == 1
  4016. ? StackOffset::getFixed(ThisVal << LocalShiftSize)
  4017. : StackOffset::getScalable(VScale * (ThisVal << LocalShiftSize));
  4018. if (Sign == -1 || Opc == AArch64::SUBXri || Opc == AArch64::SUBSXri)
  4019. CFAOffset += Change;
  4020. else
  4021. CFAOffset -= Change;
  4022. if (EmitCFAOffset && DestReg == TmpReg) {
  4023. MachineFunction &MF = *MBB.getParent();
  4024. const TargetSubtargetInfo &STI = MF.getSubtarget();
  4025. const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
  4026. unsigned CFIIndex = MF.addFrameInst(
  4027. createDefCFA(TRI, FrameReg, DestReg, CFAOffset, VScale != 1));
  4028. BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
  4029. .addCFIIndex(CFIIndex)
  4030. .setMIFlags(Flag);
  4031. }
  4032. if (NeedsWinCFI) {
  4033. assert(Sign == 1 && "SEH directives should always have a positive sign");
  4034. int Imm = (int)(ThisVal << LocalShiftSize);
  4035. if ((DestReg == AArch64::FP && SrcReg == AArch64::SP) ||
  4036. (SrcReg == AArch64::FP && DestReg == AArch64::SP)) {
  4037. if (HasWinCFI)
  4038. *HasWinCFI = true;
  4039. if (Imm == 0)
  4040. BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_SetFP)).setMIFlag(Flag);
  4041. else
  4042. BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_AddFP))
  4043. .addImm(Imm)
  4044. .setMIFlag(Flag);
  4045. assert(Offset == 0 && "Expected remaining offset to be zero to "
  4046. "emit a single SEH directive");
  4047. } else if (DestReg == AArch64::SP) {
  4048. if (HasWinCFI)
  4049. *HasWinCFI = true;
  4050. assert(SrcReg == AArch64::SP && "Unexpected SrcReg for SEH_StackAlloc");
  4051. BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_StackAlloc))
  4052. .addImm(Imm)
  4053. .setMIFlag(Flag);
  4054. }
  4055. }
  4056. SrcReg = TmpReg;
  4057. } while (Offset);
  4058. }
  4059. void llvm::emitFrameOffset(MachineBasicBlock &MBB,
  4060. MachineBasicBlock::iterator MBBI, const DebugLoc &DL,
  4061. unsigned DestReg, unsigned SrcReg,
  4062. StackOffset Offset, const TargetInstrInfo *TII,
  4063. MachineInstr::MIFlag Flag, bool SetNZCV,
  4064. bool NeedsWinCFI, bool *HasWinCFI,
  4065. bool EmitCFAOffset, StackOffset CFAOffset,
  4066. unsigned FrameReg) {
  4067. // If a function is marked as arm_locally_streaming, then the runtime value of
  4068. // vscale in the prologue/epilogue is different the runtime value of vscale
  4069. // in the function's body. To avoid having to consider multiple vscales,
  4070. // we can use `addsvl` to allocate any scalable stack-slots, which under
  4071. // most circumstances will be only locals, not callee-save slots.
  4072. const Function &F = MBB.getParent()->getFunction();
  4073. bool UseSVL = F.hasFnAttribute("aarch64_pstate_sm_body");
  4074. int64_t Bytes, NumPredicateVectors, NumDataVectors;
  4075. AArch64InstrInfo::decomposeStackOffsetForFrameOffsets(
  4076. Offset, Bytes, NumPredicateVectors, NumDataVectors);
  4077. // First emit non-scalable frame offsets, or a simple 'mov'.
  4078. if (Bytes || (!Offset && SrcReg != DestReg)) {
  4079. assert((DestReg != AArch64::SP || Bytes % 8 == 0) &&
  4080. "SP increment/decrement not 8-byte aligned");
  4081. unsigned Opc = SetNZCV ? AArch64::ADDSXri : AArch64::ADDXri;
  4082. if (Bytes < 0) {
  4083. Bytes = -Bytes;
  4084. Opc = SetNZCV ? AArch64::SUBSXri : AArch64::SUBXri;
  4085. }
  4086. emitFrameOffsetAdj(MBB, MBBI, DL, DestReg, SrcReg, Bytes, Opc, TII, Flag,
  4087. NeedsWinCFI, HasWinCFI, EmitCFAOffset, CFAOffset,
  4088. FrameReg);
  4089. CFAOffset += (Opc == AArch64::ADDXri || Opc == AArch64::ADDSXri)
  4090. ? StackOffset::getFixed(-Bytes)
  4091. : StackOffset::getFixed(Bytes);
  4092. SrcReg = DestReg;
  4093. FrameReg = DestReg;
  4094. }
  4095. assert(!(SetNZCV && (NumPredicateVectors || NumDataVectors)) &&
  4096. "SetNZCV not supported with SVE vectors");
  4097. assert(!(NeedsWinCFI && (NumPredicateVectors || NumDataVectors)) &&
  4098. "WinCFI not supported with SVE vectors");
  4099. if (NumDataVectors) {
  4100. emitFrameOffsetAdj(MBB, MBBI, DL, DestReg, SrcReg, NumDataVectors,
  4101. UseSVL ? AArch64::ADDSVL_XXI : AArch64::ADDVL_XXI,
  4102. TII, Flag, NeedsWinCFI, nullptr, EmitCFAOffset,
  4103. CFAOffset, FrameReg);
  4104. CFAOffset += StackOffset::getScalable(-NumDataVectors * 16);
  4105. SrcReg = DestReg;
  4106. }
  4107. if (NumPredicateVectors) {
  4108. assert(DestReg != AArch64::SP && "Unaligned access to SP");
  4109. emitFrameOffsetAdj(MBB, MBBI, DL, DestReg, SrcReg, NumPredicateVectors,
  4110. UseSVL ? AArch64::ADDSPL_XXI : AArch64::ADDPL_XXI,
  4111. TII, Flag, NeedsWinCFI, nullptr, EmitCFAOffset,
  4112. CFAOffset, FrameReg);
  4113. }
  4114. }
  4115. MachineInstr *AArch64InstrInfo::foldMemoryOperandImpl(
  4116. MachineFunction &MF, MachineInstr &MI, ArrayRef<unsigned> Ops,
  4117. MachineBasicBlock::iterator InsertPt, int FrameIndex,
  4118. LiveIntervals *LIS, VirtRegMap *VRM) const {
  4119. // This is a bit of a hack. Consider this instruction:
  4120. //
  4121. // %0 = COPY %sp; GPR64all:%0
  4122. //
  4123. // We explicitly chose GPR64all for the virtual register so such a copy might
  4124. // be eliminated by RegisterCoalescer. However, that may not be possible, and
  4125. // %0 may even spill. We can't spill %sp, and since it is in the GPR64all
  4126. // register class, TargetInstrInfo::foldMemoryOperand() is going to try.
  4127. //
  4128. // To prevent that, we are going to constrain the %0 register class here.
  4129. //
  4130. // <rdar://problem/11522048>
  4131. //
  4132. if (MI.isFullCopy()) {
  4133. Register DstReg = MI.getOperand(0).getReg();
  4134. Register SrcReg = MI.getOperand(1).getReg();
  4135. if (SrcReg == AArch64::SP && DstReg.isVirtual()) {
  4136. MF.getRegInfo().constrainRegClass(DstReg, &AArch64::GPR64RegClass);
  4137. return nullptr;
  4138. }
  4139. if (DstReg == AArch64::SP && SrcReg.isVirtual()) {
  4140. MF.getRegInfo().constrainRegClass(SrcReg, &AArch64::GPR64RegClass);
  4141. return nullptr;
  4142. }
  4143. // Nothing can folded with copy from/to NZCV.
  4144. if (SrcReg == AArch64::NZCV || DstReg == AArch64::NZCV)
  4145. return nullptr;
  4146. }
  4147. // Handle the case where a copy is being spilled or filled but the source
  4148. // and destination register class don't match. For example:
  4149. //
  4150. // %0 = COPY %xzr; GPR64common:%0
  4151. //
  4152. // In this case we can still safely fold away the COPY and generate the
  4153. // following spill code:
  4154. //
  4155. // STRXui %xzr, %stack.0
  4156. //
  4157. // This also eliminates spilled cross register class COPYs (e.g. between x and
  4158. // d regs) of the same size. For example:
  4159. //
  4160. // %0 = COPY %1; GPR64:%0, FPR64:%1
  4161. //
  4162. // will be filled as
  4163. //
  4164. // LDRDui %0, fi<#0>
  4165. //
  4166. // instead of
  4167. //
  4168. // LDRXui %Temp, fi<#0>
  4169. // %0 = FMOV %Temp
  4170. //
  4171. if (MI.isCopy() && Ops.size() == 1 &&
  4172. // Make sure we're only folding the explicit COPY defs/uses.
  4173. (Ops[0] == 0 || Ops[0] == 1)) {
  4174. bool IsSpill = Ops[0] == 0;
  4175. bool IsFill = !IsSpill;
  4176. const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
  4177. const MachineRegisterInfo &MRI = MF.getRegInfo();
  4178. MachineBasicBlock &MBB = *MI.getParent();
  4179. const MachineOperand &DstMO = MI.getOperand(0);
  4180. const MachineOperand &SrcMO = MI.getOperand(1);
  4181. Register DstReg = DstMO.getReg();
  4182. Register SrcReg = SrcMO.getReg();
  4183. // This is slightly expensive to compute for physical regs since
  4184. // getMinimalPhysRegClass is slow.
  4185. auto getRegClass = [&](unsigned Reg) {
  4186. return Register::isVirtualRegister(Reg) ? MRI.getRegClass(Reg)
  4187. : TRI.getMinimalPhysRegClass(Reg);
  4188. };
  4189. if (DstMO.getSubReg() == 0 && SrcMO.getSubReg() == 0) {
  4190. assert(TRI.getRegSizeInBits(*getRegClass(DstReg)) ==
  4191. TRI.getRegSizeInBits(*getRegClass(SrcReg)) &&
  4192. "Mismatched register size in non subreg COPY");
  4193. if (IsSpill)
  4194. storeRegToStackSlot(MBB, InsertPt, SrcReg, SrcMO.isKill(), FrameIndex,
  4195. getRegClass(SrcReg), &TRI, Register());
  4196. else
  4197. loadRegFromStackSlot(MBB, InsertPt, DstReg, FrameIndex,
  4198. getRegClass(DstReg), &TRI, Register());
  4199. return &*--InsertPt;
  4200. }
  4201. // Handle cases like spilling def of:
  4202. //
  4203. // %0:sub_32<def,read-undef> = COPY %wzr; GPR64common:%0
  4204. //
  4205. // where the physical register source can be widened and stored to the full
  4206. // virtual reg destination stack slot, in this case producing:
  4207. //
  4208. // STRXui %xzr, %stack.0
  4209. //
  4210. if (IsSpill && DstMO.isUndef() && SrcReg.isPhysical()) {
  4211. assert(SrcMO.getSubReg() == 0 &&
  4212. "Unexpected subreg on physical register");
  4213. const TargetRegisterClass *SpillRC;
  4214. unsigned SpillSubreg;
  4215. switch (DstMO.getSubReg()) {
  4216. default:
  4217. SpillRC = nullptr;
  4218. break;
  4219. case AArch64::sub_32:
  4220. case AArch64::ssub:
  4221. if (AArch64::GPR32RegClass.contains(SrcReg)) {
  4222. SpillRC = &AArch64::GPR64RegClass;
  4223. SpillSubreg = AArch64::sub_32;
  4224. } else if (AArch64::FPR32RegClass.contains(SrcReg)) {
  4225. SpillRC = &AArch64::FPR64RegClass;
  4226. SpillSubreg = AArch64::ssub;
  4227. } else
  4228. SpillRC = nullptr;
  4229. break;
  4230. case AArch64::dsub:
  4231. if (AArch64::FPR64RegClass.contains(SrcReg)) {
  4232. SpillRC = &AArch64::FPR128RegClass;
  4233. SpillSubreg = AArch64::dsub;
  4234. } else
  4235. SpillRC = nullptr;
  4236. break;
  4237. }
  4238. if (SpillRC)
  4239. if (unsigned WidenedSrcReg =
  4240. TRI.getMatchingSuperReg(SrcReg, SpillSubreg, SpillRC)) {
  4241. storeRegToStackSlot(MBB, InsertPt, WidenedSrcReg, SrcMO.isKill(),
  4242. FrameIndex, SpillRC, &TRI, Register());
  4243. return &*--InsertPt;
  4244. }
  4245. }
  4246. // Handle cases like filling use of:
  4247. //
  4248. // %0:sub_32<def,read-undef> = COPY %1; GPR64:%0, GPR32:%1
  4249. //
  4250. // where we can load the full virtual reg source stack slot, into the subreg
  4251. // destination, in this case producing:
  4252. //
  4253. // LDRWui %0:sub_32<def,read-undef>, %stack.0
  4254. //
  4255. if (IsFill && SrcMO.getSubReg() == 0 && DstMO.isUndef()) {
  4256. const TargetRegisterClass *FillRC;
  4257. switch (DstMO.getSubReg()) {
  4258. default:
  4259. FillRC = nullptr;
  4260. break;
  4261. case AArch64::sub_32:
  4262. FillRC = &AArch64::GPR32RegClass;
  4263. break;
  4264. case AArch64::ssub:
  4265. FillRC = &AArch64::FPR32RegClass;
  4266. break;
  4267. case AArch64::dsub:
  4268. FillRC = &AArch64::FPR64RegClass;
  4269. break;
  4270. }
  4271. if (FillRC) {
  4272. assert(TRI.getRegSizeInBits(*getRegClass(SrcReg)) ==
  4273. TRI.getRegSizeInBits(*FillRC) &&
  4274. "Mismatched regclass size on folded subreg COPY");
  4275. loadRegFromStackSlot(MBB, InsertPt, DstReg, FrameIndex, FillRC, &TRI,
  4276. Register());
  4277. MachineInstr &LoadMI = *--InsertPt;
  4278. MachineOperand &LoadDst = LoadMI.getOperand(0);
  4279. assert(LoadDst.getSubReg() == 0 && "unexpected subreg on fill load");
  4280. LoadDst.setSubReg(DstMO.getSubReg());
  4281. LoadDst.setIsUndef();
  4282. return &LoadMI;
  4283. }
  4284. }
  4285. }
  4286. // Cannot fold.
  4287. return nullptr;
  4288. }
  4289. int llvm::isAArch64FrameOffsetLegal(const MachineInstr &MI,
  4290. StackOffset &SOffset,
  4291. bool *OutUseUnscaledOp,
  4292. unsigned *OutUnscaledOp,
  4293. int64_t *EmittableOffset) {
  4294. // Set output values in case of early exit.
  4295. if (EmittableOffset)
  4296. *EmittableOffset = 0;
  4297. if (OutUseUnscaledOp)
  4298. *OutUseUnscaledOp = false;
  4299. if (OutUnscaledOp)
  4300. *OutUnscaledOp = 0;
  4301. // Exit early for structured vector spills/fills as they can't take an
  4302. // immediate offset.
  4303. switch (MI.getOpcode()) {
  4304. default:
  4305. break;
  4306. case AArch64::LD1Twov2d:
  4307. case AArch64::LD1Threev2d:
  4308. case AArch64::LD1Fourv2d:
  4309. case AArch64::LD1Twov1d:
  4310. case AArch64::LD1Threev1d:
  4311. case AArch64::LD1Fourv1d:
  4312. case AArch64::ST1Twov2d:
  4313. case AArch64::ST1Threev2d:
  4314. case AArch64::ST1Fourv2d:
  4315. case AArch64::ST1Twov1d:
  4316. case AArch64::ST1Threev1d:
  4317. case AArch64::ST1Fourv1d:
  4318. case AArch64::ST1i8:
  4319. case AArch64::ST1i16:
  4320. case AArch64::ST1i32:
  4321. case AArch64::ST1i64:
  4322. case AArch64::IRG:
  4323. case AArch64::IRGstack:
  4324. case AArch64::STGloop:
  4325. case AArch64::STZGloop:
  4326. return AArch64FrameOffsetCannotUpdate;
  4327. }
  4328. // Get the min/max offset and the scale.
  4329. TypeSize ScaleValue(0U, false);
  4330. unsigned Width;
  4331. int64_t MinOff, MaxOff;
  4332. if (!AArch64InstrInfo::getMemOpInfo(MI.getOpcode(), ScaleValue, Width, MinOff,
  4333. MaxOff))
  4334. llvm_unreachable("unhandled opcode in isAArch64FrameOffsetLegal");
  4335. // Construct the complete offset.
  4336. bool IsMulVL = ScaleValue.isScalable();
  4337. unsigned Scale = ScaleValue.getKnownMinValue();
  4338. int64_t Offset = IsMulVL ? SOffset.getScalable() : SOffset.getFixed();
  4339. const MachineOperand &ImmOpnd =
  4340. MI.getOperand(AArch64InstrInfo::getLoadStoreImmIdx(MI.getOpcode()));
  4341. Offset += ImmOpnd.getImm() * Scale;
  4342. // If the offset doesn't match the scale, we rewrite the instruction to
  4343. // use the unscaled instruction instead. Likewise, if we have a negative
  4344. // offset and there is an unscaled op to use.
  4345. std::optional<unsigned> UnscaledOp =
  4346. AArch64InstrInfo::getUnscaledLdSt(MI.getOpcode());
  4347. bool useUnscaledOp = UnscaledOp && (Offset % Scale || Offset < 0);
  4348. if (useUnscaledOp &&
  4349. !AArch64InstrInfo::getMemOpInfo(*UnscaledOp, ScaleValue, Width, MinOff,
  4350. MaxOff))
  4351. llvm_unreachable("unhandled opcode in isAArch64FrameOffsetLegal");
  4352. Scale = ScaleValue.getKnownMinValue();
  4353. assert(IsMulVL == ScaleValue.isScalable() &&
  4354. "Unscaled opcode has different value for scalable");
  4355. int64_t Remainder = Offset % Scale;
  4356. assert(!(Remainder && useUnscaledOp) &&
  4357. "Cannot have remainder when using unscaled op");
  4358. assert(MinOff < MaxOff && "Unexpected Min/Max offsets");
  4359. int64_t NewOffset = Offset / Scale;
  4360. if (MinOff <= NewOffset && NewOffset <= MaxOff)
  4361. Offset = Remainder;
  4362. else {
  4363. NewOffset = NewOffset < 0 ? MinOff : MaxOff;
  4364. Offset = Offset - NewOffset * Scale + Remainder;
  4365. }
  4366. if (EmittableOffset)
  4367. *EmittableOffset = NewOffset;
  4368. if (OutUseUnscaledOp)
  4369. *OutUseUnscaledOp = useUnscaledOp;
  4370. if (OutUnscaledOp && UnscaledOp)
  4371. *OutUnscaledOp = *UnscaledOp;
  4372. if (IsMulVL)
  4373. SOffset = StackOffset::get(SOffset.getFixed(), Offset);
  4374. else
  4375. SOffset = StackOffset::get(Offset, SOffset.getScalable());
  4376. return AArch64FrameOffsetCanUpdate |
  4377. (SOffset ? 0 : AArch64FrameOffsetIsLegal);
  4378. }
  4379. bool llvm::rewriteAArch64FrameIndex(MachineInstr &MI, unsigned FrameRegIdx,
  4380. unsigned FrameReg, StackOffset &Offset,
  4381. const AArch64InstrInfo *TII) {
  4382. unsigned Opcode = MI.getOpcode();
  4383. unsigned ImmIdx = FrameRegIdx + 1;
  4384. if (Opcode == AArch64::ADDSXri || Opcode == AArch64::ADDXri) {
  4385. Offset += StackOffset::getFixed(MI.getOperand(ImmIdx).getImm());
  4386. emitFrameOffset(*MI.getParent(), MI, MI.getDebugLoc(),
  4387. MI.getOperand(0).getReg(), FrameReg, Offset, TII,
  4388. MachineInstr::NoFlags, (Opcode == AArch64::ADDSXri));
  4389. MI.eraseFromParent();
  4390. Offset = StackOffset();
  4391. return true;
  4392. }
  4393. int64_t NewOffset;
  4394. unsigned UnscaledOp;
  4395. bool UseUnscaledOp;
  4396. int Status = isAArch64FrameOffsetLegal(MI, Offset, &UseUnscaledOp,
  4397. &UnscaledOp, &NewOffset);
  4398. if (Status & AArch64FrameOffsetCanUpdate) {
  4399. if (Status & AArch64FrameOffsetIsLegal)
  4400. // Replace the FrameIndex with FrameReg.
  4401. MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
  4402. if (UseUnscaledOp)
  4403. MI.setDesc(TII->get(UnscaledOp));
  4404. MI.getOperand(ImmIdx).ChangeToImmediate(NewOffset);
  4405. return !Offset;
  4406. }
  4407. return false;
  4408. }
  4409. MCInst AArch64InstrInfo::getNop() const {
  4410. return MCInstBuilder(AArch64::HINT).addImm(0);
  4411. }
  4412. // AArch64 supports MachineCombiner.
  4413. bool AArch64InstrInfo::useMachineCombiner() const { return true; }
  4414. // True when Opc sets flag
  4415. static bool isCombineInstrSettingFlag(unsigned Opc) {
  4416. switch (Opc) {
  4417. case AArch64::ADDSWrr:
  4418. case AArch64::ADDSWri:
  4419. case AArch64::ADDSXrr:
  4420. case AArch64::ADDSXri:
  4421. case AArch64::SUBSWrr:
  4422. case AArch64::SUBSXrr:
  4423. // Note: MSUB Wd,Wn,Wm,Wi -> Wd = Wi - WnxWm, not Wd=WnxWm - Wi.
  4424. case AArch64::SUBSWri:
  4425. case AArch64::SUBSXri:
  4426. return true;
  4427. default:
  4428. break;
  4429. }
  4430. return false;
  4431. }
  4432. // 32b Opcodes that can be combined with a MUL
  4433. static bool isCombineInstrCandidate32(unsigned Opc) {
  4434. switch (Opc) {
  4435. case AArch64::ADDWrr:
  4436. case AArch64::ADDWri:
  4437. case AArch64::SUBWrr:
  4438. case AArch64::ADDSWrr:
  4439. case AArch64::ADDSWri:
  4440. case AArch64::SUBSWrr:
  4441. // Note: MSUB Wd,Wn,Wm,Wi -> Wd = Wi - WnxWm, not Wd=WnxWm - Wi.
  4442. case AArch64::SUBWri:
  4443. case AArch64::SUBSWri:
  4444. return true;
  4445. default:
  4446. break;
  4447. }
  4448. return false;
  4449. }
  4450. // 64b Opcodes that can be combined with a MUL
  4451. static bool isCombineInstrCandidate64(unsigned Opc) {
  4452. switch (Opc) {
  4453. case AArch64::ADDXrr:
  4454. case AArch64::ADDXri:
  4455. case AArch64::SUBXrr:
  4456. case AArch64::ADDSXrr:
  4457. case AArch64::ADDSXri:
  4458. case AArch64::SUBSXrr:
  4459. // Note: MSUB Wd,Wn,Wm,Wi -> Wd = Wi - WnxWm, not Wd=WnxWm - Wi.
  4460. case AArch64::SUBXri:
  4461. case AArch64::SUBSXri:
  4462. case AArch64::ADDv8i8:
  4463. case AArch64::ADDv16i8:
  4464. case AArch64::ADDv4i16:
  4465. case AArch64::ADDv8i16:
  4466. case AArch64::ADDv2i32:
  4467. case AArch64::ADDv4i32:
  4468. case AArch64::SUBv8i8:
  4469. case AArch64::SUBv16i8:
  4470. case AArch64::SUBv4i16:
  4471. case AArch64::SUBv8i16:
  4472. case AArch64::SUBv2i32:
  4473. case AArch64::SUBv4i32:
  4474. return true;
  4475. default:
  4476. break;
  4477. }
  4478. return false;
  4479. }
  4480. // FP Opcodes that can be combined with a FMUL.
  4481. static bool isCombineInstrCandidateFP(const MachineInstr &Inst) {
  4482. switch (Inst.getOpcode()) {
  4483. default:
  4484. break;
  4485. case AArch64::FADDHrr:
  4486. case AArch64::FADDSrr:
  4487. case AArch64::FADDDrr:
  4488. case AArch64::FADDv4f16:
  4489. case AArch64::FADDv8f16:
  4490. case AArch64::FADDv2f32:
  4491. case AArch64::FADDv2f64:
  4492. case AArch64::FADDv4f32:
  4493. case AArch64::FSUBHrr:
  4494. case AArch64::FSUBSrr:
  4495. case AArch64::FSUBDrr:
  4496. case AArch64::FSUBv4f16:
  4497. case AArch64::FSUBv8f16:
  4498. case AArch64::FSUBv2f32:
  4499. case AArch64::FSUBv2f64:
  4500. case AArch64::FSUBv4f32:
  4501. TargetOptions Options = Inst.getParent()->getParent()->getTarget().Options;
  4502. // We can fuse FADD/FSUB with FMUL, if fusion is either allowed globally by
  4503. // the target options or if FADD/FSUB has the contract fast-math flag.
  4504. return Options.UnsafeFPMath ||
  4505. Options.AllowFPOpFusion == FPOpFusion::Fast ||
  4506. Inst.getFlag(MachineInstr::FmContract);
  4507. return true;
  4508. }
  4509. return false;
  4510. }
  4511. // Opcodes that can be combined with a MUL
  4512. static bool isCombineInstrCandidate(unsigned Opc) {
  4513. return (isCombineInstrCandidate32(Opc) || isCombineInstrCandidate64(Opc));
  4514. }
  4515. //
  4516. // Utility routine that checks if \param MO is defined by an
  4517. // \param CombineOpc instruction in the basic block \param MBB
  4518. static bool canCombine(MachineBasicBlock &MBB, MachineOperand &MO,
  4519. unsigned CombineOpc, unsigned ZeroReg = 0,
  4520. bool CheckZeroReg = false) {
  4521. MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
  4522. MachineInstr *MI = nullptr;
  4523. if (MO.isReg() && MO.getReg().isVirtual())
  4524. MI = MRI.getUniqueVRegDef(MO.getReg());
  4525. // And it needs to be in the trace (otherwise, it won't have a depth).
  4526. if (!MI || MI->getParent() != &MBB || (unsigned)MI->getOpcode() != CombineOpc)
  4527. return false;
  4528. // Must only used by the user we combine with.
  4529. if (!MRI.hasOneNonDBGUse(MI->getOperand(0).getReg()))
  4530. return false;
  4531. if (CheckZeroReg) {
  4532. assert(MI->getNumOperands() >= 4 && MI->getOperand(0).isReg() &&
  4533. MI->getOperand(1).isReg() && MI->getOperand(2).isReg() &&
  4534. MI->getOperand(3).isReg() && "MAdd/MSub must have a least 4 regs");
  4535. // The third input reg must be zero.
  4536. if (MI->getOperand(3).getReg() != ZeroReg)
  4537. return false;
  4538. }
  4539. if (isCombineInstrSettingFlag(CombineOpc) &&
  4540. MI->findRegisterDefOperandIdx(AArch64::NZCV, true) == -1)
  4541. return false;
  4542. return true;
  4543. }
  4544. //
  4545. // Is \param MO defined by an integer multiply and can be combined?
  4546. static bool canCombineWithMUL(MachineBasicBlock &MBB, MachineOperand &MO,
  4547. unsigned MulOpc, unsigned ZeroReg) {
  4548. return canCombine(MBB, MO, MulOpc, ZeroReg, true);
  4549. }
  4550. //
  4551. // Is \param MO defined by a floating-point multiply and can be combined?
  4552. static bool canCombineWithFMUL(MachineBasicBlock &MBB, MachineOperand &MO,
  4553. unsigned MulOpc) {
  4554. return canCombine(MBB, MO, MulOpc);
  4555. }
  4556. // TODO: There are many more machine instruction opcodes to match:
  4557. // 1. Other data types (integer, vectors)
  4558. // 2. Other math / logic operations (xor, or)
  4559. // 3. Other forms of the same operation (intrinsics and other variants)
  4560. bool AArch64InstrInfo::isAssociativeAndCommutative(const MachineInstr &Inst,
  4561. bool Invert) const {
  4562. if (Invert)
  4563. return false;
  4564. switch (Inst.getOpcode()) {
  4565. // == Floating-point types ==
  4566. // -- Floating-point instructions --
  4567. case AArch64::FADDHrr:
  4568. case AArch64::FADDSrr:
  4569. case AArch64::FADDDrr:
  4570. case AArch64::FMULHrr:
  4571. case AArch64::FMULSrr:
  4572. case AArch64::FMULDrr:
  4573. case AArch64::FMULX16:
  4574. case AArch64::FMULX32:
  4575. case AArch64::FMULX64:
  4576. // -- Advanced SIMD instructions --
  4577. case AArch64::FADDv4f16:
  4578. case AArch64::FADDv8f16:
  4579. case AArch64::FADDv2f32:
  4580. case AArch64::FADDv4f32:
  4581. case AArch64::FADDv2f64:
  4582. case AArch64::FMULv4f16:
  4583. case AArch64::FMULv8f16:
  4584. case AArch64::FMULv2f32:
  4585. case AArch64::FMULv4f32:
  4586. case AArch64::FMULv2f64:
  4587. case AArch64::FMULXv4f16:
  4588. case AArch64::FMULXv8f16:
  4589. case AArch64::FMULXv2f32:
  4590. case AArch64::FMULXv4f32:
  4591. case AArch64::FMULXv2f64:
  4592. // -- SVE instructions --
  4593. // Opcodes FMULX_ZZZ_? don't exist because there is no unpredicated FMULX
  4594. // in the SVE instruction set (though there are predicated ones).
  4595. case AArch64::FADD_ZZZ_H:
  4596. case AArch64::FADD_ZZZ_S:
  4597. case AArch64::FADD_ZZZ_D:
  4598. case AArch64::FMUL_ZZZ_H:
  4599. case AArch64::FMUL_ZZZ_S:
  4600. case AArch64::FMUL_ZZZ_D:
  4601. return Inst.getParent()->getParent()->getTarget().Options.UnsafeFPMath ||
  4602. (Inst.getFlag(MachineInstr::MIFlag::FmReassoc) &&
  4603. Inst.getFlag(MachineInstr::MIFlag::FmNsz));
  4604. // == Integer types ==
  4605. // -- Base instructions --
  4606. // Opcodes MULWrr and MULXrr don't exist because
  4607. // `MUL <Wd>, <Wn>, <Wm>` and `MUL <Xd>, <Xn>, <Xm>` are aliases of
  4608. // `MADD <Wd>, <Wn>, <Wm>, WZR` and `MADD <Xd>, <Xn>, <Xm>, XZR` respectively.
  4609. // The machine-combiner does not support three-source-operands machine
  4610. // instruction. So we cannot reassociate MULs.
  4611. case AArch64::ADDWrr:
  4612. case AArch64::ADDXrr:
  4613. case AArch64::ANDWrr:
  4614. case AArch64::ANDXrr:
  4615. case AArch64::ORRWrr:
  4616. case AArch64::ORRXrr:
  4617. case AArch64::EORWrr:
  4618. case AArch64::EORXrr:
  4619. case AArch64::EONWrr:
  4620. case AArch64::EONXrr:
  4621. // -- Advanced SIMD instructions --
  4622. // Opcodes MULv1i64 and MULv2i64 don't exist because there is no 64-bit MUL
  4623. // in the Advanced SIMD instruction set.
  4624. case AArch64::ADDv8i8:
  4625. case AArch64::ADDv16i8:
  4626. case AArch64::ADDv4i16:
  4627. case AArch64::ADDv8i16:
  4628. case AArch64::ADDv2i32:
  4629. case AArch64::ADDv4i32:
  4630. case AArch64::ADDv1i64:
  4631. case AArch64::ADDv2i64:
  4632. case AArch64::MULv8i8:
  4633. case AArch64::MULv16i8:
  4634. case AArch64::MULv4i16:
  4635. case AArch64::MULv8i16:
  4636. case AArch64::MULv2i32:
  4637. case AArch64::MULv4i32:
  4638. case AArch64::ANDv8i8:
  4639. case AArch64::ANDv16i8:
  4640. case AArch64::ORRv8i8:
  4641. case AArch64::ORRv16i8:
  4642. case AArch64::EORv8i8:
  4643. case AArch64::EORv16i8:
  4644. // -- SVE instructions --
  4645. case AArch64::ADD_ZZZ_B:
  4646. case AArch64::ADD_ZZZ_H:
  4647. case AArch64::ADD_ZZZ_S:
  4648. case AArch64::ADD_ZZZ_D:
  4649. case AArch64::MUL_ZZZ_B:
  4650. case AArch64::MUL_ZZZ_H:
  4651. case AArch64::MUL_ZZZ_S:
  4652. case AArch64::MUL_ZZZ_D:
  4653. case AArch64::AND_ZZZ:
  4654. case AArch64::ORR_ZZZ:
  4655. case AArch64::EOR_ZZZ:
  4656. return true;
  4657. default:
  4658. return false;
  4659. }
  4660. }
  4661. /// Find instructions that can be turned into madd.
  4662. static bool getMaddPatterns(MachineInstr &Root,
  4663. SmallVectorImpl<MachineCombinerPattern> &Patterns) {
  4664. unsigned Opc = Root.getOpcode();
  4665. MachineBasicBlock &MBB = *Root.getParent();
  4666. bool Found = false;
  4667. if (!isCombineInstrCandidate(Opc))
  4668. return false;
  4669. if (isCombineInstrSettingFlag(Opc)) {
  4670. int Cmp_NZCV = Root.findRegisterDefOperandIdx(AArch64::NZCV, true);
  4671. // When NZCV is live bail out.
  4672. if (Cmp_NZCV == -1)
  4673. return false;
  4674. unsigned NewOpc = convertToNonFlagSettingOpc(Root);
  4675. // When opcode can't change bail out.
  4676. // CHECKME: do we miss any cases for opcode conversion?
  4677. if (NewOpc == Opc)
  4678. return false;
  4679. Opc = NewOpc;
  4680. }
  4681. auto setFound = [&](int Opcode, int Operand, unsigned ZeroReg,
  4682. MachineCombinerPattern Pattern) {
  4683. if (canCombineWithMUL(MBB, Root.getOperand(Operand), Opcode, ZeroReg)) {
  4684. Patterns.push_back(Pattern);
  4685. Found = true;
  4686. }
  4687. };
  4688. auto setVFound = [&](int Opcode, int Operand, MachineCombinerPattern Pattern) {
  4689. if (canCombine(MBB, Root.getOperand(Operand), Opcode)) {
  4690. Patterns.push_back(Pattern);
  4691. Found = true;
  4692. }
  4693. };
  4694. typedef MachineCombinerPattern MCP;
  4695. switch (Opc) {
  4696. default:
  4697. break;
  4698. case AArch64::ADDWrr:
  4699. assert(Root.getOperand(1).isReg() && Root.getOperand(2).isReg() &&
  4700. "ADDWrr does not have register operands");
  4701. setFound(AArch64::MADDWrrr, 1, AArch64::WZR, MCP::MULADDW_OP1);
  4702. setFound(AArch64::MADDWrrr, 2, AArch64::WZR, MCP::MULADDW_OP2);
  4703. break;
  4704. case AArch64::ADDXrr:
  4705. setFound(AArch64::MADDXrrr, 1, AArch64::XZR, MCP::MULADDX_OP1);
  4706. setFound(AArch64::MADDXrrr, 2, AArch64::XZR, MCP::MULADDX_OP2);
  4707. break;
  4708. case AArch64::SUBWrr:
  4709. setFound(AArch64::MADDWrrr, 1, AArch64::WZR, MCP::MULSUBW_OP1);
  4710. setFound(AArch64::MADDWrrr, 2, AArch64::WZR, MCP::MULSUBW_OP2);
  4711. break;
  4712. case AArch64::SUBXrr:
  4713. setFound(AArch64::MADDXrrr, 1, AArch64::XZR, MCP::MULSUBX_OP1);
  4714. setFound(AArch64::MADDXrrr, 2, AArch64::XZR, MCP::MULSUBX_OP2);
  4715. break;
  4716. case AArch64::ADDWri:
  4717. setFound(AArch64::MADDWrrr, 1, AArch64::WZR, MCP::MULADDWI_OP1);
  4718. break;
  4719. case AArch64::ADDXri:
  4720. setFound(AArch64::MADDXrrr, 1, AArch64::XZR, MCP::MULADDXI_OP1);
  4721. break;
  4722. case AArch64::SUBWri:
  4723. setFound(AArch64::MADDWrrr, 1, AArch64::WZR, MCP::MULSUBWI_OP1);
  4724. break;
  4725. case AArch64::SUBXri:
  4726. setFound(AArch64::MADDXrrr, 1, AArch64::XZR, MCP::MULSUBXI_OP1);
  4727. break;
  4728. case AArch64::ADDv8i8:
  4729. setVFound(AArch64::MULv8i8, 1, MCP::MULADDv8i8_OP1);
  4730. setVFound(AArch64::MULv8i8, 2, MCP::MULADDv8i8_OP2);
  4731. break;
  4732. case AArch64::ADDv16i8:
  4733. setVFound(AArch64::MULv16i8, 1, MCP::MULADDv16i8_OP1);
  4734. setVFound(AArch64::MULv16i8, 2, MCP::MULADDv16i8_OP2);
  4735. break;
  4736. case AArch64::ADDv4i16:
  4737. setVFound(AArch64::MULv4i16, 1, MCP::MULADDv4i16_OP1);
  4738. setVFound(AArch64::MULv4i16, 2, MCP::MULADDv4i16_OP2);
  4739. setVFound(AArch64::MULv4i16_indexed, 1, MCP::MULADDv4i16_indexed_OP1);
  4740. setVFound(AArch64::MULv4i16_indexed, 2, MCP::MULADDv4i16_indexed_OP2);
  4741. break;
  4742. case AArch64::ADDv8i16:
  4743. setVFound(AArch64::MULv8i16, 1, MCP::MULADDv8i16_OP1);
  4744. setVFound(AArch64::MULv8i16, 2, MCP::MULADDv8i16_OP2);
  4745. setVFound(AArch64::MULv8i16_indexed, 1, MCP::MULADDv8i16_indexed_OP1);
  4746. setVFound(AArch64::MULv8i16_indexed, 2, MCP::MULADDv8i16_indexed_OP2);
  4747. break;
  4748. case AArch64::ADDv2i32:
  4749. setVFound(AArch64::MULv2i32, 1, MCP::MULADDv2i32_OP1);
  4750. setVFound(AArch64::MULv2i32, 2, MCP::MULADDv2i32_OP2);
  4751. setVFound(AArch64::MULv2i32_indexed, 1, MCP::MULADDv2i32_indexed_OP1);
  4752. setVFound(AArch64::MULv2i32_indexed, 2, MCP::MULADDv2i32_indexed_OP2);
  4753. break;
  4754. case AArch64::ADDv4i32:
  4755. setVFound(AArch64::MULv4i32, 1, MCP::MULADDv4i32_OP1);
  4756. setVFound(AArch64::MULv4i32, 2, MCP::MULADDv4i32_OP2);
  4757. setVFound(AArch64::MULv4i32_indexed, 1, MCP::MULADDv4i32_indexed_OP1);
  4758. setVFound(AArch64::MULv4i32_indexed, 2, MCP::MULADDv4i32_indexed_OP2);
  4759. break;
  4760. case AArch64::SUBv8i8:
  4761. setVFound(AArch64::MULv8i8, 1, MCP::MULSUBv8i8_OP1);
  4762. setVFound(AArch64::MULv8i8, 2, MCP::MULSUBv8i8_OP2);
  4763. break;
  4764. case AArch64::SUBv16i8:
  4765. setVFound(AArch64::MULv16i8, 1, MCP::MULSUBv16i8_OP1);
  4766. setVFound(AArch64::MULv16i8, 2, MCP::MULSUBv16i8_OP2);
  4767. break;
  4768. case AArch64::SUBv4i16:
  4769. setVFound(AArch64::MULv4i16, 1, MCP::MULSUBv4i16_OP1);
  4770. setVFound(AArch64::MULv4i16, 2, MCP::MULSUBv4i16_OP2);
  4771. setVFound(AArch64::MULv4i16_indexed, 1, MCP::MULSUBv4i16_indexed_OP1);
  4772. setVFound(AArch64::MULv4i16_indexed, 2, MCP::MULSUBv4i16_indexed_OP2);
  4773. break;
  4774. case AArch64::SUBv8i16:
  4775. setVFound(AArch64::MULv8i16, 1, MCP::MULSUBv8i16_OP1);
  4776. setVFound(AArch64::MULv8i16, 2, MCP::MULSUBv8i16_OP2);
  4777. setVFound(AArch64::MULv8i16_indexed, 1, MCP::MULSUBv8i16_indexed_OP1);
  4778. setVFound(AArch64::MULv8i16_indexed, 2, MCP::MULSUBv8i16_indexed_OP2);
  4779. break;
  4780. case AArch64::SUBv2i32:
  4781. setVFound(AArch64::MULv2i32, 1, MCP::MULSUBv2i32_OP1);
  4782. setVFound(AArch64::MULv2i32, 2, MCP::MULSUBv2i32_OP2);
  4783. setVFound(AArch64::MULv2i32_indexed, 1, MCP::MULSUBv2i32_indexed_OP1);
  4784. setVFound(AArch64::MULv2i32_indexed, 2, MCP::MULSUBv2i32_indexed_OP2);
  4785. break;
  4786. case AArch64::SUBv4i32:
  4787. setVFound(AArch64::MULv4i32, 1, MCP::MULSUBv4i32_OP1);
  4788. setVFound(AArch64::MULv4i32, 2, MCP::MULSUBv4i32_OP2);
  4789. setVFound(AArch64::MULv4i32_indexed, 1, MCP::MULSUBv4i32_indexed_OP1);
  4790. setVFound(AArch64::MULv4i32_indexed, 2, MCP::MULSUBv4i32_indexed_OP2);
  4791. break;
  4792. }
  4793. return Found;
  4794. }
  4795. /// Floating-Point Support
  4796. /// Find instructions that can be turned into madd.
  4797. static bool getFMAPatterns(MachineInstr &Root,
  4798. SmallVectorImpl<MachineCombinerPattern> &Patterns) {
  4799. if (!isCombineInstrCandidateFP(Root))
  4800. return false;
  4801. MachineBasicBlock &MBB = *Root.getParent();
  4802. bool Found = false;
  4803. auto Match = [&](int Opcode, int Operand,
  4804. MachineCombinerPattern Pattern) -> bool {
  4805. if (canCombineWithFMUL(MBB, Root.getOperand(Operand), Opcode)) {
  4806. Patterns.push_back(Pattern);
  4807. return true;
  4808. }
  4809. return false;
  4810. };
  4811. typedef MachineCombinerPattern MCP;
  4812. switch (Root.getOpcode()) {
  4813. default:
  4814. assert(false && "Unsupported FP instruction in combiner\n");
  4815. break;
  4816. case AArch64::FADDHrr:
  4817. assert(Root.getOperand(1).isReg() && Root.getOperand(2).isReg() &&
  4818. "FADDHrr does not have register operands");
  4819. Found = Match(AArch64::FMULHrr, 1, MCP::FMULADDH_OP1);
  4820. Found |= Match(AArch64::FMULHrr, 2, MCP::FMULADDH_OP2);
  4821. break;
  4822. case AArch64::FADDSrr:
  4823. assert(Root.getOperand(1).isReg() && Root.getOperand(2).isReg() &&
  4824. "FADDSrr does not have register operands");
  4825. Found |= Match(AArch64::FMULSrr, 1, MCP::FMULADDS_OP1) ||
  4826. Match(AArch64::FMULv1i32_indexed, 1, MCP::FMLAv1i32_indexed_OP1);
  4827. Found |= Match(AArch64::FMULSrr, 2, MCP::FMULADDS_OP2) ||
  4828. Match(AArch64::FMULv1i32_indexed, 2, MCP::FMLAv1i32_indexed_OP2);
  4829. break;
  4830. case AArch64::FADDDrr:
  4831. Found |= Match(AArch64::FMULDrr, 1, MCP::FMULADDD_OP1) ||
  4832. Match(AArch64::FMULv1i64_indexed, 1, MCP::FMLAv1i64_indexed_OP1);
  4833. Found |= Match(AArch64::FMULDrr, 2, MCP::FMULADDD_OP2) ||
  4834. Match(AArch64::FMULv1i64_indexed, 2, MCP::FMLAv1i64_indexed_OP2);
  4835. break;
  4836. case AArch64::FADDv4f16:
  4837. Found |= Match(AArch64::FMULv4i16_indexed, 1, MCP::FMLAv4i16_indexed_OP1) ||
  4838. Match(AArch64::FMULv4f16, 1, MCP::FMLAv4f16_OP1);
  4839. Found |= Match(AArch64::FMULv4i16_indexed, 2, MCP::FMLAv4i16_indexed_OP2) ||
  4840. Match(AArch64::FMULv4f16, 2, MCP::FMLAv4f16_OP2);
  4841. break;
  4842. case AArch64::FADDv8f16:
  4843. Found |= Match(AArch64::FMULv8i16_indexed, 1, MCP::FMLAv8i16_indexed_OP1) ||
  4844. Match(AArch64::FMULv8f16, 1, MCP::FMLAv8f16_OP1);
  4845. Found |= Match(AArch64::FMULv8i16_indexed, 2, MCP::FMLAv8i16_indexed_OP2) ||
  4846. Match(AArch64::FMULv8f16, 2, MCP::FMLAv8f16_OP2);
  4847. break;
  4848. case AArch64::FADDv2f32:
  4849. Found |= Match(AArch64::FMULv2i32_indexed, 1, MCP::FMLAv2i32_indexed_OP1) ||
  4850. Match(AArch64::FMULv2f32, 1, MCP::FMLAv2f32_OP1);
  4851. Found |= Match(AArch64::FMULv2i32_indexed, 2, MCP::FMLAv2i32_indexed_OP2) ||
  4852. Match(AArch64::FMULv2f32, 2, MCP::FMLAv2f32_OP2);
  4853. break;
  4854. case AArch64::FADDv2f64:
  4855. Found |= Match(AArch64::FMULv2i64_indexed, 1, MCP::FMLAv2i64_indexed_OP1) ||
  4856. Match(AArch64::FMULv2f64, 1, MCP::FMLAv2f64_OP1);
  4857. Found |= Match(AArch64::FMULv2i64_indexed, 2, MCP::FMLAv2i64_indexed_OP2) ||
  4858. Match(AArch64::FMULv2f64, 2, MCP::FMLAv2f64_OP2);
  4859. break;
  4860. case AArch64::FADDv4f32:
  4861. Found |= Match(AArch64::FMULv4i32_indexed, 1, MCP::FMLAv4i32_indexed_OP1) ||
  4862. Match(AArch64::FMULv4f32, 1, MCP::FMLAv4f32_OP1);
  4863. Found |= Match(AArch64::FMULv4i32_indexed, 2, MCP::FMLAv4i32_indexed_OP2) ||
  4864. Match(AArch64::FMULv4f32, 2, MCP::FMLAv4f32_OP2);
  4865. break;
  4866. case AArch64::FSUBHrr:
  4867. Found = Match(AArch64::FMULHrr, 1, MCP::FMULSUBH_OP1);
  4868. Found |= Match(AArch64::FMULHrr, 2, MCP::FMULSUBH_OP2);
  4869. Found |= Match(AArch64::FNMULHrr, 1, MCP::FNMULSUBH_OP1);
  4870. break;
  4871. case AArch64::FSUBSrr:
  4872. Found = Match(AArch64::FMULSrr, 1, MCP::FMULSUBS_OP1);
  4873. Found |= Match(AArch64::FMULSrr, 2, MCP::FMULSUBS_OP2) ||
  4874. Match(AArch64::FMULv1i32_indexed, 2, MCP::FMLSv1i32_indexed_OP2);
  4875. Found |= Match(AArch64::FNMULSrr, 1, MCP::FNMULSUBS_OP1);
  4876. break;
  4877. case AArch64::FSUBDrr:
  4878. Found = Match(AArch64::FMULDrr, 1, MCP::FMULSUBD_OP1);
  4879. Found |= Match(AArch64::FMULDrr, 2, MCP::FMULSUBD_OP2) ||
  4880. Match(AArch64::FMULv1i64_indexed, 2, MCP::FMLSv1i64_indexed_OP2);
  4881. Found |= Match(AArch64::FNMULDrr, 1, MCP::FNMULSUBD_OP1);
  4882. break;
  4883. case AArch64::FSUBv4f16:
  4884. Found |= Match(AArch64::FMULv4i16_indexed, 2, MCP::FMLSv4i16_indexed_OP2) ||
  4885. Match(AArch64::FMULv4f16, 2, MCP::FMLSv4f16_OP2);
  4886. Found |= Match(AArch64::FMULv4i16_indexed, 1, MCP::FMLSv4i16_indexed_OP1) ||
  4887. Match(AArch64::FMULv4f16, 1, MCP::FMLSv4f16_OP1);
  4888. break;
  4889. case AArch64::FSUBv8f16:
  4890. Found |= Match(AArch64::FMULv8i16_indexed, 2, MCP::FMLSv8i16_indexed_OP2) ||
  4891. Match(AArch64::FMULv8f16, 2, MCP::FMLSv8f16_OP2);
  4892. Found |= Match(AArch64::FMULv8i16_indexed, 1, MCP::FMLSv8i16_indexed_OP1) ||
  4893. Match(AArch64::FMULv8f16, 1, MCP::FMLSv8f16_OP1);
  4894. break;
  4895. case AArch64::FSUBv2f32:
  4896. Found |= Match(AArch64::FMULv2i32_indexed, 2, MCP::FMLSv2i32_indexed_OP2) ||
  4897. Match(AArch64::FMULv2f32, 2, MCP::FMLSv2f32_OP2);
  4898. Found |= Match(AArch64::FMULv2i32_indexed, 1, MCP::FMLSv2i32_indexed_OP1) ||
  4899. Match(AArch64::FMULv2f32, 1, MCP::FMLSv2f32_OP1);
  4900. break;
  4901. case AArch64::FSUBv2f64:
  4902. Found |= Match(AArch64::FMULv2i64_indexed, 2, MCP::FMLSv2i64_indexed_OP2) ||
  4903. Match(AArch64::FMULv2f64, 2, MCP::FMLSv2f64_OP2);
  4904. Found |= Match(AArch64::FMULv2i64_indexed, 1, MCP::FMLSv2i64_indexed_OP1) ||
  4905. Match(AArch64::FMULv2f64, 1, MCP::FMLSv2f64_OP1);
  4906. break;
  4907. case AArch64::FSUBv4f32:
  4908. Found |= Match(AArch64::FMULv4i32_indexed, 2, MCP::FMLSv4i32_indexed_OP2) ||
  4909. Match(AArch64::FMULv4f32, 2, MCP::FMLSv4f32_OP2);
  4910. Found |= Match(AArch64::FMULv4i32_indexed, 1, MCP::FMLSv4i32_indexed_OP1) ||
  4911. Match(AArch64::FMULv4f32, 1, MCP::FMLSv4f32_OP1);
  4912. break;
  4913. }
  4914. return Found;
  4915. }
  4916. static bool getFMULPatterns(MachineInstr &Root,
  4917. SmallVectorImpl<MachineCombinerPattern> &Patterns) {
  4918. MachineBasicBlock &MBB = *Root.getParent();
  4919. bool Found = false;
  4920. auto Match = [&](unsigned Opcode, int Operand,
  4921. MachineCombinerPattern Pattern) -> bool {
  4922. MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
  4923. MachineOperand &MO = Root.getOperand(Operand);
  4924. MachineInstr *MI = nullptr;
  4925. if (MO.isReg() && MO.getReg().isVirtual())
  4926. MI = MRI.getUniqueVRegDef(MO.getReg());
  4927. // Ignore No-op COPYs in FMUL(COPY(DUP(..)))
  4928. if (MI && MI->getOpcode() == TargetOpcode::COPY &&
  4929. MI->getOperand(1).getReg().isVirtual())
  4930. MI = MRI.getUniqueVRegDef(MI->getOperand(1).getReg());
  4931. if (MI && MI->getOpcode() == Opcode) {
  4932. Patterns.push_back(Pattern);
  4933. return true;
  4934. }
  4935. return false;
  4936. };
  4937. typedef MachineCombinerPattern MCP;
  4938. switch (Root.getOpcode()) {
  4939. default:
  4940. return false;
  4941. case AArch64::FMULv2f32:
  4942. Found = Match(AArch64::DUPv2i32lane, 1, MCP::FMULv2i32_indexed_OP1);
  4943. Found |= Match(AArch64::DUPv2i32lane, 2, MCP::FMULv2i32_indexed_OP2);
  4944. break;
  4945. case AArch64::FMULv2f64:
  4946. Found = Match(AArch64::DUPv2i64lane, 1, MCP::FMULv2i64_indexed_OP1);
  4947. Found |= Match(AArch64::DUPv2i64lane, 2, MCP::FMULv2i64_indexed_OP2);
  4948. break;
  4949. case AArch64::FMULv4f16:
  4950. Found = Match(AArch64::DUPv4i16lane, 1, MCP::FMULv4i16_indexed_OP1);
  4951. Found |= Match(AArch64::DUPv4i16lane, 2, MCP::FMULv4i16_indexed_OP2);
  4952. break;
  4953. case AArch64::FMULv4f32:
  4954. Found = Match(AArch64::DUPv4i32lane, 1, MCP::FMULv4i32_indexed_OP1);
  4955. Found |= Match(AArch64::DUPv4i32lane, 2, MCP::FMULv4i32_indexed_OP2);
  4956. break;
  4957. case AArch64::FMULv8f16:
  4958. Found = Match(AArch64::DUPv8i16lane, 1, MCP::FMULv8i16_indexed_OP1);
  4959. Found |= Match(AArch64::DUPv8i16lane, 2, MCP::FMULv8i16_indexed_OP2);
  4960. break;
  4961. }
  4962. return Found;
  4963. }
  4964. /// Return true when a code sequence can improve throughput. It
  4965. /// should be called only for instructions in loops.
  4966. /// \param Pattern - combiner pattern
  4967. bool AArch64InstrInfo::isThroughputPattern(
  4968. MachineCombinerPattern Pattern) const {
  4969. switch (Pattern) {
  4970. default:
  4971. break;
  4972. case MachineCombinerPattern::FMULADDH_OP1:
  4973. case MachineCombinerPattern::FMULADDH_OP2:
  4974. case MachineCombinerPattern::FMULSUBH_OP1:
  4975. case MachineCombinerPattern::FMULSUBH_OP2:
  4976. case MachineCombinerPattern::FMULADDS_OP1:
  4977. case MachineCombinerPattern::FMULADDS_OP2:
  4978. case MachineCombinerPattern::FMULSUBS_OP1:
  4979. case MachineCombinerPattern::FMULSUBS_OP2:
  4980. case MachineCombinerPattern::FMULADDD_OP1:
  4981. case MachineCombinerPattern::FMULADDD_OP2:
  4982. case MachineCombinerPattern::FMULSUBD_OP1:
  4983. case MachineCombinerPattern::FMULSUBD_OP2:
  4984. case MachineCombinerPattern::FNMULSUBH_OP1:
  4985. case MachineCombinerPattern::FNMULSUBS_OP1:
  4986. case MachineCombinerPattern::FNMULSUBD_OP1:
  4987. case MachineCombinerPattern::FMLAv4i16_indexed_OP1:
  4988. case MachineCombinerPattern::FMLAv4i16_indexed_OP2:
  4989. case MachineCombinerPattern::FMLAv8i16_indexed_OP1:
  4990. case MachineCombinerPattern::FMLAv8i16_indexed_OP2:
  4991. case MachineCombinerPattern::FMLAv1i32_indexed_OP1:
  4992. case MachineCombinerPattern::FMLAv1i32_indexed_OP2:
  4993. case MachineCombinerPattern::FMLAv1i64_indexed_OP1:
  4994. case MachineCombinerPattern::FMLAv1i64_indexed_OP2:
  4995. case MachineCombinerPattern::FMLAv4f16_OP2:
  4996. case MachineCombinerPattern::FMLAv4f16_OP1:
  4997. case MachineCombinerPattern::FMLAv8f16_OP1:
  4998. case MachineCombinerPattern::FMLAv8f16_OP2:
  4999. case MachineCombinerPattern::FMLAv2f32_OP2:
  5000. case MachineCombinerPattern::FMLAv2f32_OP1:
  5001. case MachineCombinerPattern::FMLAv2f64_OP1:
  5002. case MachineCombinerPattern::FMLAv2f64_OP2:
  5003. case MachineCombinerPattern::FMLAv2i32_indexed_OP1:
  5004. case MachineCombinerPattern::FMLAv2i32_indexed_OP2:
  5005. case MachineCombinerPattern::FMLAv2i64_indexed_OP1:
  5006. case MachineCombinerPattern::FMLAv2i64_indexed_OP2:
  5007. case MachineCombinerPattern::FMLAv4f32_OP1:
  5008. case MachineCombinerPattern::FMLAv4f32_OP2:
  5009. case MachineCombinerPattern::FMLAv4i32_indexed_OP1:
  5010. case MachineCombinerPattern::FMLAv4i32_indexed_OP2:
  5011. case MachineCombinerPattern::FMLSv4i16_indexed_OP1:
  5012. case MachineCombinerPattern::FMLSv4i16_indexed_OP2:
  5013. case MachineCombinerPattern::FMLSv8i16_indexed_OP1:
  5014. case MachineCombinerPattern::FMLSv8i16_indexed_OP2:
  5015. case MachineCombinerPattern::FMLSv1i32_indexed_OP2:
  5016. case MachineCombinerPattern::FMLSv1i64_indexed_OP2:
  5017. case MachineCombinerPattern::FMLSv2i32_indexed_OP2:
  5018. case MachineCombinerPattern::FMLSv2i64_indexed_OP2:
  5019. case MachineCombinerPattern::FMLSv4f16_OP1:
  5020. case MachineCombinerPattern::FMLSv4f16_OP2:
  5021. case MachineCombinerPattern::FMLSv8f16_OP1:
  5022. case MachineCombinerPattern::FMLSv8f16_OP2:
  5023. case MachineCombinerPattern::FMLSv2f32_OP2:
  5024. case MachineCombinerPattern::FMLSv2f64_OP2:
  5025. case MachineCombinerPattern::FMLSv4i32_indexed_OP2:
  5026. case MachineCombinerPattern::FMLSv4f32_OP2:
  5027. case MachineCombinerPattern::FMULv2i32_indexed_OP1:
  5028. case MachineCombinerPattern::FMULv2i32_indexed_OP2:
  5029. case MachineCombinerPattern::FMULv2i64_indexed_OP1:
  5030. case MachineCombinerPattern::FMULv2i64_indexed_OP2:
  5031. case MachineCombinerPattern::FMULv4i16_indexed_OP1:
  5032. case MachineCombinerPattern::FMULv4i16_indexed_OP2:
  5033. case MachineCombinerPattern::FMULv4i32_indexed_OP1:
  5034. case MachineCombinerPattern::FMULv4i32_indexed_OP2:
  5035. case MachineCombinerPattern::FMULv8i16_indexed_OP1:
  5036. case MachineCombinerPattern::FMULv8i16_indexed_OP2:
  5037. case MachineCombinerPattern::MULADDv8i8_OP1:
  5038. case MachineCombinerPattern::MULADDv8i8_OP2:
  5039. case MachineCombinerPattern::MULADDv16i8_OP1:
  5040. case MachineCombinerPattern::MULADDv16i8_OP2:
  5041. case MachineCombinerPattern::MULADDv4i16_OP1:
  5042. case MachineCombinerPattern::MULADDv4i16_OP2:
  5043. case MachineCombinerPattern::MULADDv8i16_OP1:
  5044. case MachineCombinerPattern::MULADDv8i16_OP2:
  5045. case MachineCombinerPattern::MULADDv2i32_OP1:
  5046. case MachineCombinerPattern::MULADDv2i32_OP2:
  5047. case MachineCombinerPattern::MULADDv4i32_OP1:
  5048. case MachineCombinerPattern::MULADDv4i32_OP2:
  5049. case MachineCombinerPattern::MULSUBv8i8_OP1:
  5050. case MachineCombinerPattern::MULSUBv8i8_OP2:
  5051. case MachineCombinerPattern::MULSUBv16i8_OP1:
  5052. case MachineCombinerPattern::MULSUBv16i8_OP2:
  5053. case MachineCombinerPattern::MULSUBv4i16_OP1:
  5054. case MachineCombinerPattern::MULSUBv4i16_OP2:
  5055. case MachineCombinerPattern::MULSUBv8i16_OP1:
  5056. case MachineCombinerPattern::MULSUBv8i16_OP2:
  5057. case MachineCombinerPattern::MULSUBv2i32_OP1:
  5058. case MachineCombinerPattern::MULSUBv2i32_OP2:
  5059. case MachineCombinerPattern::MULSUBv4i32_OP1:
  5060. case MachineCombinerPattern::MULSUBv4i32_OP2:
  5061. case MachineCombinerPattern::MULADDv4i16_indexed_OP1:
  5062. case MachineCombinerPattern::MULADDv4i16_indexed_OP2:
  5063. case MachineCombinerPattern::MULADDv8i16_indexed_OP1:
  5064. case MachineCombinerPattern::MULADDv8i16_indexed_OP2:
  5065. case MachineCombinerPattern::MULADDv2i32_indexed_OP1:
  5066. case MachineCombinerPattern::MULADDv2i32_indexed_OP2:
  5067. case MachineCombinerPattern::MULADDv4i32_indexed_OP1:
  5068. case MachineCombinerPattern::MULADDv4i32_indexed_OP2:
  5069. case MachineCombinerPattern::MULSUBv4i16_indexed_OP1:
  5070. case MachineCombinerPattern::MULSUBv4i16_indexed_OP2:
  5071. case MachineCombinerPattern::MULSUBv8i16_indexed_OP1:
  5072. case MachineCombinerPattern::MULSUBv8i16_indexed_OP2:
  5073. case MachineCombinerPattern::MULSUBv2i32_indexed_OP1:
  5074. case MachineCombinerPattern::MULSUBv2i32_indexed_OP2:
  5075. case MachineCombinerPattern::MULSUBv4i32_indexed_OP1:
  5076. case MachineCombinerPattern::MULSUBv4i32_indexed_OP2:
  5077. return true;
  5078. } // end switch (Pattern)
  5079. return false;
  5080. }
  5081. /// Find other MI combine patterns.
  5082. static bool getMiscPatterns(MachineInstr &Root,
  5083. SmallVectorImpl<MachineCombinerPattern> &Patterns)
  5084. {
  5085. // A - (B + C) ==> (A - B) - C or (A - C) - B
  5086. unsigned Opc = Root.getOpcode();
  5087. MachineBasicBlock &MBB = *Root.getParent();
  5088. switch (Opc) {
  5089. case AArch64::SUBWrr:
  5090. case AArch64::SUBSWrr:
  5091. case AArch64::SUBXrr:
  5092. case AArch64::SUBSXrr:
  5093. // Found candidate root.
  5094. break;
  5095. default:
  5096. return false;
  5097. }
  5098. if (isCombineInstrSettingFlag(Opc) &&
  5099. Root.findRegisterDefOperandIdx(AArch64::NZCV, true) == -1)
  5100. return false;
  5101. if (canCombine(MBB, Root.getOperand(2), AArch64::ADDWrr) ||
  5102. canCombine(MBB, Root.getOperand(2), AArch64::ADDSWrr) ||
  5103. canCombine(MBB, Root.getOperand(2), AArch64::ADDXrr) ||
  5104. canCombine(MBB, Root.getOperand(2), AArch64::ADDSXrr)) {
  5105. Patterns.push_back(MachineCombinerPattern::SUBADD_OP1);
  5106. Patterns.push_back(MachineCombinerPattern::SUBADD_OP2);
  5107. return true;
  5108. }
  5109. return false;
  5110. }
  5111. /// Return true when there is potentially a faster code sequence for an
  5112. /// instruction chain ending in \p Root. All potential patterns are listed in
  5113. /// the \p Pattern vector. Pattern should be sorted in priority order since the
  5114. /// pattern evaluator stops checking as soon as it finds a faster sequence.
  5115. bool AArch64InstrInfo::getMachineCombinerPatterns(
  5116. MachineInstr &Root, SmallVectorImpl<MachineCombinerPattern> &Patterns,
  5117. bool DoRegPressureReduce) const {
  5118. // Integer patterns
  5119. if (getMaddPatterns(Root, Patterns))
  5120. return true;
  5121. // Floating point patterns
  5122. if (getFMULPatterns(Root, Patterns))
  5123. return true;
  5124. if (getFMAPatterns(Root, Patterns))
  5125. return true;
  5126. // Other patterns
  5127. if (getMiscPatterns(Root, Patterns))
  5128. return true;
  5129. return TargetInstrInfo::getMachineCombinerPatterns(Root, Patterns,
  5130. DoRegPressureReduce);
  5131. }
  5132. enum class FMAInstKind { Default, Indexed, Accumulator };
  5133. /// genFusedMultiply - Generate fused multiply instructions.
  5134. /// This function supports both integer and floating point instructions.
  5135. /// A typical example:
  5136. /// F|MUL I=A,B,0
  5137. /// F|ADD R,I,C
  5138. /// ==> F|MADD R,A,B,C
  5139. /// \param MF Containing MachineFunction
  5140. /// \param MRI Register information
  5141. /// \param TII Target information
  5142. /// \param Root is the F|ADD instruction
  5143. /// \param [out] InsInstrs is a vector of machine instructions and will
  5144. /// contain the generated madd instruction
  5145. /// \param IdxMulOpd is index of operand in Root that is the result of
  5146. /// the F|MUL. In the example above IdxMulOpd is 1.
  5147. /// \param MaddOpc the opcode fo the f|madd instruction
  5148. /// \param RC Register class of operands
  5149. /// \param kind of fma instruction (addressing mode) to be generated
  5150. /// \param ReplacedAddend is the result register from the instruction
  5151. /// replacing the non-combined operand, if any.
  5152. static MachineInstr *
  5153. genFusedMultiply(MachineFunction &MF, MachineRegisterInfo &MRI,
  5154. const TargetInstrInfo *TII, MachineInstr &Root,
  5155. SmallVectorImpl<MachineInstr *> &InsInstrs, unsigned IdxMulOpd,
  5156. unsigned MaddOpc, const TargetRegisterClass *RC,
  5157. FMAInstKind kind = FMAInstKind::Default,
  5158. const Register *ReplacedAddend = nullptr) {
  5159. assert(IdxMulOpd == 1 || IdxMulOpd == 2);
  5160. unsigned IdxOtherOpd = IdxMulOpd == 1 ? 2 : 1;
  5161. MachineInstr *MUL = MRI.getUniqueVRegDef(Root.getOperand(IdxMulOpd).getReg());
  5162. Register ResultReg = Root.getOperand(0).getReg();
  5163. Register SrcReg0 = MUL->getOperand(1).getReg();
  5164. bool Src0IsKill = MUL->getOperand(1).isKill();
  5165. Register SrcReg1 = MUL->getOperand(2).getReg();
  5166. bool Src1IsKill = MUL->getOperand(2).isKill();
  5167. Register SrcReg2;
  5168. bool Src2IsKill;
  5169. if (ReplacedAddend) {
  5170. // If we just generated a new addend, we must be it's only use.
  5171. SrcReg2 = *ReplacedAddend;
  5172. Src2IsKill = true;
  5173. } else {
  5174. SrcReg2 = Root.getOperand(IdxOtherOpd).getReg();
  5175. Src2IsKill = Root.getOperand(IdxOtherOpd).isKill();
  5176. }
  5177. if (ResultReg.isVirtual())
  5178. MRI.constrainRegClass(ResultReg, RC);
  5179. if (SrcReg0.isVirtual())
  5180. MRI.constrainRegClass(SrcReg0, RC);
  5181. if (SrcReg1.isVirtual())
  5182. MRI.constrainRegClass(SrcReg1, RC);
  5183. if (SrcReg2.isVirtual())
  5184. MRI.constrainRegClass(SrcReg2, RC);
  5185. MachineInstrBuilder MIB;
  5186. if (kind == FMAInstKind::Default)
  5187. MIB = BuildMI(MF, MIMetadata(Root), TII->get(MaddOpc), ResultReg)
  5188. .addReg(SrcReg0, getKillRegState(Src0IsKill))
  5189. .addReg(SrcReg1, getKillRegState(Src1IsKill))
  5190. .addReg(SrcReg2, getKillRegState(Src2IsKill));
  5191. else if (kind == FMAInstKind::Indexed)
  5192. MIB = BuildMI(MF, MIMetadata(Root), TII->get(MaddOpc), ResultReg)
  5193. .addReg(SrcReg2, getKillRegState(Src2IsKill))
  5194. .addReg(SrcReg0, getKillRegState(Src0IsKill))
  5195. .addReg(SrcReg1, getKillRegState(Src1IsKill))
  5196. .addImm(MUL->getOperand(3).getImm());
  5197. else if (kind == FMAInstKind::Accumulator)
  5198. MIB = BuildMI(MF, MIMetadata(Root), TII->get(MaddOpc), ResultReg)
  5199. .addReg(SrcReg2, getKillRegState(Src2IsKill))
  5200. .addReg(SrcReg0, getKillRegState(Src0IsKill))
  5201. .addReg(SrcReg1, getKillRegState(Src1IsKill));
  5202. else
  5203. assert(false && "Invalid FMA instruction kind \n");
  5204. // Insert the MADD (MADD, FMA, FMS, FMLA, FMSL)
  5205. InsInstrs.push_back(MIB);
  5206. return MUL;
  5207. }
  5208. /// Fold (FMUL x (DUP y lane)) into (FMUL_indexed x y lane)
  5209. static MachineInstr *
  5210. genIndexedMultiply(MachineInstr &Root,
  5211. SmallVectorImpl<MachineInstr *> &InsInstrs,
  5212. unsigned IdxDupOp, unsigned MulOpc,
  5213. const TargetRegisterClass *RC, MachineRegisterInfo &MRI) {
  5214. assert(((IdxDupOp == 1) || (IdxDupOp == 2)) &&
  5215. "Invalid index of FMUL operand");
  5216. MachineFunction &MF = *Root.getMF();
  5217. const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
  5218. MachineInstr *Dup =
  5219. MF.getRegInfo().getUniqueVRegDef(Root.getOperand(IdxDupOp).getReg());
  5220. if (Dup->getOpcode() == TargetOpcode::COPY)
  5221. Dup = MRI.getUniqueVRegDef(Dup->getOperand(1).getReg());
  5222. Register DupSrcReg = Dup->getOperand(1).getReg();
  5223. MRI.clearKillFlags(DupSrcReg);
  5224. MRI.constrainRegClass(DupSrcReg, RC);
  5225. unsigned DupSrcLane = Dup->getOperand(2).getImm();
  5226. unsigned IdxMulOp = IdxDupOp == 1 ? 2 : 1;
  5227. MachineOperand &MulOp = Root.getOperand(IdxMulOp);
  5228. Register ResultReg = Root.getOperand(0).getReg();
  5229. MachineInstrBuilder MIB;
  5230. MIB = BuildMI(MF, MIMetadata(Root), TII->get(MulOpc), ResultReg)
  5231. .add(MulOp)
  5232. .addReg(DupSrcReg)
  5233. .addImm(DupSrcLane);
  5234. InsInstrs.push_back(MIB);
  5235. return &Root;
  5236. }
  5237. /// genFusedMultiplyAcc - Helper to generate fused multiply accumulate
  5238. /// instructions.
  5239. ///
  5240. /// \see genFusedMultiply
  5241. static MachineInstr *genFusedMultiplyAcc(
  5242. MachineFunction &MF, MachineRegisterInfo &MRI, const TargetInstrInfo *TII,
  5243. MachineInstr &Root, SmallVectorImpl<MachineInstr *> &InsInstrs,
  5244. unsigned IdxMulOpd, unsigned MaddOpc, const TargetRegisterClass *RC) {
  5245. return genFusedMultiply(MF, MRI, TII, Root, InsInstrs, IdxMulOpd, MaddOpc, RC,
  5246. FMAInstKind::Accumulator);
  5247. }
  5248. /// genNeg - Helper to generate an intermediate negation of the second operand
  5249. /// of Root
  5250. static Register genNeg(MachineFunction &MF, MachineRegisterInfo &MRI,
  5251. const TargetInstrInfo *TII, MachineInstr &Root,
  5252. SmallVectorImpl<MachineInstr *> &InsInstrs,
  5253. DenseMap<unsigned, unsigned> &InstrIdxForVirtReg,
  5254. unsigned MnegOpc, const TargetRegisterClass *RC) {
  5255. Register NewVR = MRI.createVirtualRegister(RC);
  5256. MachineInstrBuilder MIB =
  5257. BuildMI(MF, MIMetadata(Root), TII->get(MnegOpc), NewVR)
  5258. .add(Root.getOperand(2));
  5259. InsInstrs.push_back(MIB);
  5260. assert(InstrIdxForVirtReg.empty());
  5261. InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
  5262. return NewVR;
  5263. }
  5264. /// genFusedMultiplyAccNeg - Helper to generate fused multiply accumulate
  5265. /// instructions with an additional negation of the accumulator
  5266. static MachineInstr *genFusedMultiplyAccNeg(
  5267. MachineFunction &MF, MachineRegisterInfo &MRI, const TargetInstrInfo *TII,
  5268. MachineInstr &Root, SmallVectorImpl<MachineInstr *> &InsInstrs,
  5269. DenseMap<unsigned, unsigned> &InstrIdxForVirtReg, unsigned IdxMulOpd,
  5270. unsigned MaddOpc, unsigned MnegOpc, const TargetRegisterClass *RC) {
  5271. assert(IdxMulOpd == 1);
  5272. Register NewVR =
  5273. genNeg(MF, MRI, TII, Root, InsInstrs, InstrIdxForVirtReg, MnegOpc, RC);
  5274. return genFusedMultiply(MF, MRI, TII, Root, InsInstrs, IdxMulOpd, MaddOpc, RC,
  5275. FMAInstKind::Accumulator, &NewVR);
  5276. }
  5277. /// genFusedMultiplyIdx - Helper to generate fused multiply accumulate
  5278. /// instructions.
  5279. ///
  5280. /// \see genFusedMultiply
  5281. static MachineInstr *genFusedMultiplyIdx(
  5282. MachineFunction &MF, MachineRegisterInfo &MRI, const TargetInstrInfo *TII,
  5283. MachineInstr &Root, SmallVectorImpl<MachineInstr *> &InsInstrs,
  5284. unsigned IdxMulOpd, unsigned MaddOpc, const TargetRegisterClass *RC) {
  5285. return genFusedMultiply(MF, MRI, TII, Root, InsInstrs, IdxMulOpd, MaddOpc, RC,
  5286. FMAInstKind::Indexed);
  5287. }
  5288. /// genFusedMultiplyAccNeg - Helper to generate fused multiply accumulate
  5289. /// instructions with an additional negation of the accumulator
  5290. static MachineInstr *genFusedMultiplyIdxNeg(
  5291. MachineFunction &MF, MachineRegisterInfo &MRI, const TargetInstrInfo *TII,
  5292. MachineInstr &Root, SmallVectorImpl<MachineInstr *> &InsInstrs,
  5293. DenseMap<unsigned, unsigned> &InstrIdxForVirtReg, unsigned IdxMulOpd,
  5294. unsigned MaddOpc, unsigned MnegOpc, const TargetRegisterClass *RC) {
  5295. assert(IdxMulOpd == 1);
  5296. Register NewVR =
  5297. genNeg(MF, MRI, TII, Root, InsInstrs, InstrIdxForVirtReg, MnegOpc, RC);
  5298. return genFusedMultiply(MF, MRI, TII, Root, InsInstrs, IdxMulOpd, MaddOpc, RC,
  5299. FMAInstKind::Indexed, &NewVR);
  5300. }
  5301. /// genMaddR - Generate madd instruction and combine mul and add using
  5302. /// an extra virtual register
  5303. /// Example - an ADD intermediate needs to be stored in a register:
  5304. /// MUL I=A,B,0
  5305. /// ADD R,I,Imm
  5306. /// ==> ORR V, ZR, Imm
  5307. /// ==> MADD R,A,B,V
  5308. /// \param MF Containing MachineFunction
  5309. /// \param MRI Register information
  5310. /// \param TII Target information
  5311. /// \param Root is the ADD instruction
  5312. /// \param [out] InsInstrs is a vector of machine instructions and will
  5313. /// contain the generated madd instruction
  5314. /// \param IdxMulOpd is index of operand in Root that is the result of
  5315. /// the MUL. In the example above IdxMulOpd is 1.
  5316. /// \param MaddOpc the opcode fo the madd instruction
  5317. /// \param VR is a virtual register that holds the value of an ADD operand
  5318. /// (V in the example above).
  5319. /// \param RC Register class of operands
  5320. static MachineInstr *genMaddR(MachineFunction &MF, MachineRegisterInfo &MRI,
  5321. const TargetInstrInfo *TII, MachineInstr &Root,
  5322. SmallVectorImpl<MachineInstr *> &InsInstrs,
  5323. unsigned IdxMulOpd, unsigned MaddOpc, unsigned VR,
  5324. const TargetRegisterClass *RC) {
  5325. assert(IdxMulOpd == 1 || IdxMulOpd == 2);
  5326. MachineInstr *MUL = MRI.getUniqueVRegDef(Root.getOperand(IdxMulOpd).getReg());
  5327. Register ResultReg = Root.getOperand(0).getReg();
  5328. Register SrcReg0 = MUL->getOperand(1).getReg();
  5329. bool Src0IsKill = MUL->getOperand(1).isKill();
  5330. Register SrcReg1 = MUL->getOperand(2).getReg();
  5331. bool Src1IsKill = MUL->getOperand(2).isKill();
  5332. if (ResultReg.isVirtual())
  5333. MRI.constrainRegClass(ResultReg, RC);
  5334. if (SrcReg0.isVirtual())
  5335. MRI.constrainRegClass(SrcReg0, RC);
  5336. if (SrcReg1.isVirtual())
  5337. MRI.constrainRegClass(SrcReg1, RC);
  5338. if (Register::isVirtualRegister(VR))
  5339. MRI.constrainRegClass(VR, RC);
  5340. MachineInstrBuilder MIB =
  5341. BuildMI(MF, MIMetadata(Root), TII->get(MaddOpc), ResultReg)
  5342. .addReg(SrcReg0, getKillRegState(Src0IsKill))
  5343. .addReg(SrcReg1, getKillRegState(Src1IsKill))
  5344. .addReg(VR);
  5345. // Insert the MADD
  5346. InsInstrs.push_back(MIB);
  5347. return MUL;
  5348. }
  5349. /// Do the following transformation
  5350. /// A - (B + C) ==> (A - B) - C
  5351. /// A - (B + C) ==> (A - C) - B
  5352. static void
  5353. genSubAdd2SubSub(MachineFunction &MF, MachineRegisterInfo &MRI,
  5354. const TargetInstrInfo *TII, MachineInstr &Root,
  5355. SmallVectorImpl<MachineInstr *> &InsInstrs,
  5356. SmallVectorImpl<MachineInstr *> &DelInstrs,
  5357. unsigned IdxOpd1,
  5358. DenseMap<unsigned, unsigned> &InstrIdxForVirtReg) {
  5359. assert(IdxOpd1 == 1 || IdxOpd1 == 2);
  5360. unsigned IdxOtherOpd = IdxOpd1 == 1 ? 2 : 1;
  5361. MachineInstr *AddMI = MRI.getUniqueVRegDef(Root.getOperand(2).getReg());
  5362. Register ResultReg = Root.getOperand(0).getReg();
  5363. Register RegA = Root.getOperand(1).getReg();
  5364. bool RegAIsKill = Root.getOperand(1).isKill();
  5365. Register RegB = AddMI->getOperand(IdxOpd1).getReg();
  5366. bool RegBIsKill = AddMI->getOperand(IdxOpd1).isKill();
  5367. Register RegC = AddMI->getOperand(IdxOtherOpd).getReg();
  5368. bool RegCIsKill = AddMI->getOperand(IdxOtherOpd).isKill();
  5369. Register NewVR = MRI.createVirtualRegister(MRI.getRegClass(RegA));
  5370. unsigned Opcode = Root.getOpcode();
  5371. if (Opcode == AArch64::SUBSWrr)
  5372. Opcode = AArch64::SUBWrr;
  5373. else if (Opcode == AArch64::SUBSXrr)
  5374. Opcode = AArch64::SUBXrr;
  5375. else
  5376. assert((Opcode == AArch64::SUBWrr || Opcode == AArch64::SUBXrr) &&
  5377. "Unexpected instruction opcode.");
  5378. MachineInstrBuilder MIB1 =
  5379. BuildMI(MF, MIMetadata(Root), TII->get(Opcode), NewVR)
  5380. .addReg(RegA, getKillRegState(RegAIsKill))
  5381. .addReg(RegB, getKillRegState(RegBIsKill));
  5382. MachineInstrBuilder MIB2 =
  5383. BuildMI(MF, MIMetadata(Root), TII->get(Opcode), ResultReg)
  5384. .addReg(NewVR, getKillRegState(true))
  5385. .addReg(RegC, getKillRegState(RegCIsKill));
  5386. InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
  5387. InsInstrs.push_back(MIB1);
  5388. InsInstrs.push_back(MIB2);
  5389. DelInstrs.push_back(AddMI);
  5390. }
  5391. /// When getMachineCombinerPatterns() finds potential patterns,
  5392. /// this function generates the instructions that could replace the
  5393. /// original code sequence
  5394. void AArch64InstrInfo::genAlternativeCodeSequence(
  5395. MachineInstr &Root, MachineCombinerPattern Pattern,
  5396. SmallVectorImpl<MachineInstr *> &InsInstrs,
  5397. SmallVectorImpl<MachineInstr *> &DelInstrs,
  5398. DenseMap<unsigned, unsigned> &InstrIdxForVirtReg) const {
  5399. MachineBasicBlock &MBB = *Root.getParent();
  5400. MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
  5401. MachineFunction &MF = *MBB.getParent();
  5402. const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
  5403. MachineInstr *MUL = nullptr;
  5404. const TargetRegisterClass *RC;
  5405. unsigned Opc;
  5406. switch (Pattern) {
  5407. default:
  5408. // Reassociate instructions.
  5409. TargetInstrInfo::genAlternativeCodeSequence(Root, Pattern, InsInstrs,
  5410. DelInstrs, InstrIdxForVirtReg);
  5411. return;
  5412. case MachineCombinerPattern::SUBADD_OP1:
  5413. // A - (B + C)
  5414. // ==> (A - B) - C
  5415. genSubAdd2SubSub(MF, MRI, TII, Root, InsInstrs, DelInstrs, 1,
  5416. InstrIdxForVirtReg);
  5417. break;
  5418. case MachineCombinerPattern::SUBADD_OP2:
  5419. // A - (B + C)
  5420. // ==> (A - C) - B
  5421. genSubAdd2SubSub(MF, MRI, TII, Root, InsInstrs, DelInstrs, 2,
  5422. InstrIdxForVirtReg);
  5423. break;
  5424. case MachineCombinerPattern::MULADDW_OP1:
  5425. case MachineCombinerPattern::MULADDX_OP1:
  5426. // MUL I=A,B,0
  5427. // ADD R,I,C
  5428. // ==> MADD R,A,B,C
  5429. // --- Create(MADD);
  5430. if (Pattern == MachineCombinerPattern::MULADDW_OP1) {
  5431. Opc = AArch64::MADDWrrr;
  5432. RC = &AArch64::GPR32RegClass;
  5433. } else {
  5434. Opc = AArch64::MADDXrrr;
  5435. RC = &AArch64::GPR64RegClass;
  5436. }
  5437. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
  5438. break;
  5439. case MachineCombinerPattern::MULADDW_OP2:
  5440. case MachineCombinerPattern::MULADDX_OP2:
  5441. // MUL I=A,B,0
  5442. // ADD R,C,I
  5443. // ==> MADD R,A,B,C
  5444. // --- Create(MADD);
  5445. if (Pattern == MachineCombinerPattern::MULADDW_OP2) {
  5446. Opc = AArch64::MADDWrrr;
  5447. RC = &AArch64::GPR32RegClass;
  5448. } else {
  5449. Opc = AArch64::MADDXrrr;
  5450. RC = &AArch64::GPR64RegClass;
  5451. }
  5452. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
  5453. break;
  5454. case MachineCombinerPattern::MULADDWI_OP1:
  5455. case MachineCombinerPattern::MULADDXI_OP1: {
  5456. // MUL I=A,B,0
  5457. // ADD R,I,Imm
  5458. // ==> MOV V, Imm
  5459. // ==> MADD R,A,B,V
  5460. // --- Create(MADD);
  5461. const TargetRegisterClass *OrrRC;
  5462. unsigned BitSize, OrrOpc, ZeroReg;
  5463. if (Pattern == MachineCombinerPattern::MULADDWI_OP1) {
  5464. OrrOpc = AArch64::ORRWri;
  5465. OrrRC = &AArch64::GPR32spRegClass;
  5466. BitSize = 32;
  5467. ZeroReg = AArch64::WZR;
  5468. Opc = AArch64::MADDWrrr;
  5469. RC = &AArch64::GPR32RegClass;
  5470. } else {
  5471. OrrOpc = AArch64::ORRXri;
  5472. OrrRC = &AArch64::GPR64spRegClass;
  5473. BitSize = 64;
  5474. ZeroReg = AArch64::XZR;
  5475. Opc = AArch64::MADDXrrr;
  5476. RC = &AArch64::GPR64RegClass;
  5477. }
  5478. Register NewVR = MRI.createVirtualRegister(OrrRC);
  5479. uint64_t Imm = Root.getOperand(2).getImm();
  5480. if (Root.getOperand(3).isImm()) {
  5481. unsigned Val = Root.getOperand(3).getImm();
  5482. Imm = Imm << Val;
  5483. }
  5484. uint64_t UImm = SignExtend64(Imm, BitSize);
  5485. // The immediate can be composed via a single instruction.
  5486. SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
  5487. AArch64_IMM::expandMOVImm(UImm, BitSize, Insn);
  5488. if (Insn.size() != 1)
  5489. return;
  5490. auto MovI = Insn.begin();
  5491. MachineInstrBuilder MIB1;
  5492. // MOV is an alias for one of three instructions: movz, movn, and orr.
  5493. if (MovI->Opcode == OrrOpc)
  5494. MIB1 = BuildMI(MF, MIMetadata(Root), TII->get(OrrOpc), NewVR)
  5495. .addReg(ZeroReg)
  5496. .addImm(MovI->Op2);
  5497. else {
  5498. if (BitSize == 32)
  5499. assert((MovI->Opcode == AArch64::MOVNWi ||
  5500. MovI->Opcode == AArch64::MOVZWi) &&
  5501. "Expected opcode");
  5502. else
  5503. assert((MovI->Opcode == AArch64::MOVNXi ||
  5504. MovI->Opcode == AArch64::MOVZXi) &&
  5505. "Expected opcode");
  5506. MIB1 = BuildMI(MF, MIMetadata(Root), TII->get(MovI->Opcode), NewVR)
  5507. .addImm(MovI->Op1)
  5508. .addImm(MovI->Op2);
  5509. }
  5510. InsInstrs.push_back(MIB1);
  5511. InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
  5512. MUL = genMaddR(MF, MRI, TII, Root, InsInstrs, 1, Opc, NewVR, RC);
  5513. break;
  5514. }
  5515. case MachineCombinerPattern::MULSUBW_OP1:
  5516. case MachineCombinerPattern::MULSUBX_OP1: {
  5517. // MUL I=A,B,0
  5518. // SUB R,I, C
  5519. // ==> SUB V, 0, C
  5520. // ==> MADD R,A,B,V // = -C + A*B
  5521. // --- Create(MADD);
  5522. const TargetRegisterClass *SubRC;
  5523. unsigned SubOpc, ZeroReg;
  5524. if (Pattern == MachineCombinerPattern::MULSUBW_OP1) {
  5525. SubOpc = AArch64::SUBWrr;
  5526. SubRC = &AArch64::GPR32spRegClass;
  5527. ZeroReg = AArch64::WZR;
  5528. Opc = AArch64::MADDWrrr;
  5529. RC = &AArch64::GPR32RegClass;
  5530. } else {
  5531. SubOpc = AArch64::SUBXrr;
  5532. SubRC = &AArch64::GPR64spRegClass;
  5533. ZeroReg = AArch64::XZR;
  5534. Opc = AArch64::MADDXrrr;
  5535. RC = &AArch64::GPR64RegClass;
  5536. }
  5537. Register NewVR = MRI.createVirtualRegister(SubRC);
  5538. // SUB NewVR, 0, C
  5539. MachineInstrBuilder MIB1 =
  5540. BuildMI(MF, MIMetadata(Root), TII->get(SubOpc), NewVR)
  5541. .addReg(ZeroReg)
  5542. .add(Root.getOperand(2));
  5543. InsInstrs.push_back(MIB1);
  5544. InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
  5545. MUL = genMaddR(MF, MRI, TII, Root, InsInstrs, 1, Opc, NewVR, RC);
  5546. break;
  5547. }
  5548. case MachineCombinerPattern::MULSUBW_OP2:
  5549. case MachineCombinerPattern::MULSUBX_OP2:
  5550. // MUL I=A,B,0
  5551. // SUB R,C,I
  5552. // ==> MSUB R,A,B,C (computes C - A*B)
  5553. // --- Create(MSUB);
  5554. if (Pattern == MachineCombinerPattern::MULSUBW_OP2) {
  5555. Opc = AArch64::MSUBWrrr;
  5556. RC = &AArch64::GPR32RegClass;
  5557. } else {
  5558. Opc = AArch64::MSUBXrrr;
  5559. RC = &AArch64::GPR64RegClass;
  5560. }
  5561. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
  5562. break;
  5563. case MachineCombinerPattern::MULSUBWI_OP1:
  5564. case MachineCombinerPattern::MULSUBXI_OP1: {
  5565. // MUL I=A,B,0
  5566. // SUB R,I, Imm
  5567. // ==> MOV V, -Imm
  5568. // ==> MADD R,A,B,V // = -Imm + A*B
  5569. // --- Create(MADD);
  5570. const TargetRegisterClass *OrrRC;
  5571. unsigned BitSize, OrrOpc, ZeroReg;
  5572. if (Pattern == MachineCombinerPattern::MULSUBWI_OP1) {
  5573. OrrOpc = AArch64::ORRWri;
  5574. OrrRC = &AArch64::GPR32spRegClass;
  5575. BitSize = 32;
  5576. ZeroReg = AArch64::WZR;
  5577. Opc = AArch64::MADDWrrr;
  5578. RC = &AArch64::GPR32RegClass;
  5579. } else {
  5580. OrrOpc = AArch64::ORRXri;
  5581. OrrRC = &AArch64::GPR64spRegClass;
  5582. BitSize = 64;
  5583. ZeroReg = AArch64::XZR;
  5584. Opc = AArch64::MADDXrrr;
  5585. RC = &AArch64::GPR64RegClass;
  5586. }
  5587. Register NewVR = MRI.createVirtualRegister(OrrRC);
  5588. uint64_t Imm = Root.getOperand(2).getImm();
  5589. if (Root.getOperand(3).isImm()) {
  5590. unsigned Val = Root.getOperand(3).getImm();
  5591. Imm = Imm << Val;
  5592. }
  5593. uint64_t UImm = SignExtend64(-Imm, BitSize);
  5594. // The immediate can be composed via a single instruction.
  5595. SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
  5596. AArch64_IMM::expandMOVImm(UImm, BitSize, Insn);
  5597. if (Insn.size() != 1)
  5598. return;
  5599. auto MovI = Insn.begin();
  5600. MachineInstrBuilder MIB1;
  5601. // MOV is an alias for one of three instructions: movz, movn, and orr.
  5602. if (MovI->Opcode == OrrOpc)
  5603. MIB1 = BuildMI(MF, MIMetadata(Root), TII->get(OrrOpc), NewVR)
  5604. .addReg(ZeroReg)
  5605. .addImm(MovI->Op2);
  5606. else {
  5607. if (BitSize == 32)
  5608. assert((MovI->Opcode == AArch64::MOVNWi ||
  5609. MovI->Opcode == AArch64::MOVZWi) &&
  5610. "Expected opcode");
  5611. else
  5612. assert((MovI->Opcode == AArch64::MOVNXi ||
  5613. MovI->Opcode == AArch64::MOVZXi) &&
  5614. "Expected opcode");
  5615. MIB1 = BuildMI(MF, MIMetadata(Root), TII->get(MovI->Opcode), NewVR)
  5616. .addImm(MovI->Op1)
  5617. .addImm(MovI->Op2);
  5618. }
  5619. InsInstrs.push_back(MIB1);
  5620. InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
  5621. MUL = genMaddR(MF, MRI, TII, Root, InsInstrs, 1, Opc, NewVR, RC);
  5622. break;
  5623. }
  5624. case MachineCombinerPattern::MULADDv8i8_OP1:
  5625. Opc = AArch64::MLAv8i8;
  5626. RC = &AArch64::FPR64RegClass;
  5627. MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
  5628. break;
  5629. case MachineCombinerPattern::MULADDv8i8_OP2:
  5630. Opc = AArch64::MLAv8i8;
  5631. RC = &AArch64::FPR64RegClass;
  5632. MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
  5633. break;
  5634. case MachineCombinerPattern::MULADDv16i8_OP1:
  5635. Opc = AArch64::MLAv16i8;
  5636. RC = &AArch64::FPR128RegClass;
  5637. MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
  5638. break;
  5639. case MachineCombinerPattern::MULADDv16i8_OP2:
  5640. Opc = AArch64::MLAv16i8;
  5641. RC = &AArch64::FPR128RegClass;
  5642. MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
  5643. break;
  5644. case MachineCombinerPattern::MULADDv4i16_OP1:
  5645. Opc = AArch64::MLAv4i16;
  5646. RC = &AArch64::FPR64RegClass;
  5647. MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
  5648. break;
  5649. case MachineCombinerPattern::MULADDv4i16_OP2:
  5650. Opc = AArch64::MLAv4i16;
  5651. RC = &AArch64::FPR64RegClass;
  5652. MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
  5653. break;
  5654. case MachineCombinerPattern::MULADDv8i16_OP1:
  5655. Opc = AArch64::MLAv8i16;
  5656. RC = &AArch64::FPR128RegClass;
  5657. MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
  5658. break;
  5659. case MachineCombinerPattern::MULADDv8i16_OP2:
  5660. Opc = AArch64::MLAv8i16;
  5661. RC = &AArch64::FPR128RegClass;
  5662. MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
  5663. break;
  5664. case MachineCombinerPattern::MULADDv2i32_OP1:
  5665. Opc = AArch64::MLAv2i32;
  5666. RC = &AArch64::FPR64RegClass;
  5667. MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
  5668. break;
  5669. case MachineCombinerPattern::MULADDv2i32_OP2:
  5670. Opc = AArch64::MLAv2i32;
  5671. RC = &AArch64::FPR64RegClass;
  5672. MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
  5673. break;
  5674. case MachineCombinerPattern::MULADDv4i32_OP1:
  5675. Opc = AArch64::MLAv4i32;
  5676. RC = &AArch64::FPR128RegClass;
  5677. MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
  5678. break;
  5679. case MachineCombinerPattern::MULADDv4i32_OP2:
  5680. Opc = AArch64::MLAv4i32;
  5681. RC = &AArch64::FPR128RegClass;
  5682. MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
  5683. break;
  5684. case MachineCombinerPattern::MULSUBv8i8_OP1:
  5685. Opc = AArch64::MLAv8i8;
  5686. RC = &AArch64::FPR64RegClass;
  5687. MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
  5688. InstrIdxForVirtReg, 1, Opc, AArch64::NEGv8i8,
  5689. RC);
  5690. break;
  5691. case MachineCombinerPattern::MULSUBv8i8_OP2:
  5692. Opc = AArch64::MLSv8i8;
  5693. RC = &AArch64::FPR64RegClass;
  5694. MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
  5695. break;
  5696. case MachineCombinerPattern::MULSUBv16i8_OP1:
  5697. Opc = AArch64::MLAv16i8;
  5698. RC = &AArch64::FPR128RegClass;
  5699. MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
  5700. InstrIdxForVirtReg, 1, Opc, AArch64::NEGv16i8,
  5701. RC);
  5702. break;
  5703. case MachineCombinerPattern::MULSUBv16i8_OP2:
  5704. Opc = AArch64::MLSv16i8;
  5705. RC = &AArch64::FPR128RegClass;
  5706. MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
  5707. break;
  5708. case MachineCombinerPattern::MULSUBv4i16_OP1:
  5709. Opc = AArch64::MLAv4i16;
  5710. RC = &AArch64::FPR64RegClass;
  5711. MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
  5712. InstrIdxForVirtReg, 1, Opc, AArch64::NEGv4i16,
  5713. RC);
  5714. break;
  5715. case MachineCombinerPattern::MULSUBv4i16_OP2:
  5716. Opc = AArch64::MLSv4i16;
  5717. RC = &AArch64::FPR64RegClass;
  5718. MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
  5719. break;
  5720. case MachineCombinerPattern::MULSUBv8i16_OP1:
  5721. Opc = AArch64::MLAv8i16;
  5722. RC = &AArch64::FPR128RegClass;
  5723. MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
  5724. InstrIdxForVirtReg, 1, Opc, AArch64::NEGv8i16,
  5725. RC);
  5726. break;
  5727. case MachineCombinerPattern::MULSUBv8i16_OP2:
  5728. Opc = AArch64::MLSv8i16;
  5729. RC = &AArch64::FPR128RegClass;
  5730. MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
  5731. break;
  5732. case MachineCombinerPattern::MULSUBv2i32_OP1:
  5733. Opc = AArch64::MLAv2i32;
  5734. RC = &AArch64::FPR64RegClass;
  5735. MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
  5736. InstrIdxForVirtReg, 1, Opc, AArch64::NEGv2i32,
  5737. RC);
  5738. break;
  5739. case MachineCombinerPattern::MULSUBv2i32_OP2:
  5740. Opc = AArch64::MLSv2i32;
  5741. RC = &AArch64::FPR64RegClass;
  5742. MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
  5743. break;
  5744. case MachineCombinerPattern::MULSUBv4i32_OP1:
  5745. Opc = AArch64::MLAv4i32;
  5746. RC = &AArch64::FPR128RegClass;
  5747. MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
  5748. InstrIdxForVirtReg, 1, Opc, AArch64::NEGv4i32,
  5749. RC);
  5750. break;
  5751. case MachineCombinerPattern::MULSUBv4i32_OP2:
  5752. Opc = AArch64::MLSv4i32;
  5753. RC = &AArch64::FPR128RegClass;
  5754. MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
  5755. break;
  5756. case MachineCombinerPattern::MULADDv4i16_indexed_OP1:
  5757. Opc = AArch64::MLAv4i16_indexed;
  5758. RC = &AArch64::FPR64RegClass;
  5759. MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
  5760. break;
  5761. case MachineCombinerPattern::MULADDv4i16_indexed_OP2:
  5762. Opc = AArch64::MLAv4i16_indexed;
  5763. RC = &AArch64::FPR64RegClass;
  5764. MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
  5765. break;
  5766. case MachineCombinerPattern::MULADDv8i16_indexed_OP1:
  5767. Opc = AArch64::MLAv8i16_indexed;
  5768. RC = &AArch64::FPR128RegClass;
  5769. MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
  5770. break;
  5771. case MachineCombinerPattern::MULADDv8i16_indexed_OP2:
  5772. Opc = AArch64::MLAv8i16_indexed;
  5773. RC = &AArch64::FPR128RegClass;
  5774. MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
  5775. break;
  5776. case MachineCombinerPattern::MULADDv2i32_indexed_OP1:
  5777. Opc = AArch64::MLAv2i32_indexed;
  5778. RC = &AArch64::FPR64RegClass;
  5779. MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
  5780. break;
  5781. case MachineCombinerPattern::MULADDv2i32_indexed_OP2:
  5782. Opc = AArch64::MLAv2i32_indexed;
  5783. RC = &AArch64::FPR64RegClass;
  5784. MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
  5785. break;
  5786. case MachineCombinerPattern::MULADDv4i32_indexed_OP1:
  5787. Opc = AArch64::MLAv4i32_indexed;
  5788. RC = &AArch64::FPR128RegClass;
  5789. MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
  5790. break;
  5791. case MachineCombinerPattern::MULADDv4i32_indexed_OP2:
  5792. Opc = AArch64::MLAv4i32_indexed;
  5793. RC = &AArch64::FPR128RegClass;
  5794. MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
  5795. break;
  5796. case MachineCombinerPattern::MULSUBv4i16_indexed_OP1:
  5797. Opc = AArch64::MLAv4i16_indexed;
  5798. RC = &AArch64::FPR64RegClass;
  5799. MUL = genFusedMultiplyIdxNeg(MF, MRI, TII, Root, InsInstrs,
  5800. InstrIdxForVirtReg, 1, Opc, AArch64::NEGv4i16,
  5801. RC);
  5802. break;
  5803. case MachineCombinerPattern::MULSUBv4i16_indexed_OP2:
  5804. Opc = AArch64::MLSv4i16_indexed;
  5805. RC = &AArch64::FPR64RegClass;
  5806. MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
  5807. break;
  5808. case MachineCombinerPattern::MULSUBv8i16_indexed_OP1:
  5809. Opc = AArch64::MLAv8i16_indexed;
  5810. RC = &AArch64::FPR128RegClass;
  5811. MUL = genFusedMultiplyIdxNeg(MF, MRI, TII, Root, InsInstrs,
  5812. InstrIdxForVirtReg, 1, Opc, AArch64::NEGv8i16,
  5813. RC);
  5814. break;
  5815. case MachineCombinerPattern::MULSUBv8i16_indexed_OP2:
  5816. Opc = AArch64::MLSv8i16_indexed;
  5817. RC = &AArch64::FPR128RegClass;
  5818. MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
  5819. break;
  5820. case MachineCombinerPattern::MULSUBv2i32_indexed_OP1:
  5821. Opc = AArch64::MLAv2i32_indexed;
  5822. RC = &AArch64::FPR64RegClass;
  5823. MUL = genFusedMultiplyIdxNeg(MF, MRI, TII, Root, InsInstrs,
  5824. InstrIdxForVirtReg, 1, Opc, AArch64::NEGv2i32,
  5825. RC);
  5826. break;
  5827. case MachineCombinerPattern::MULSUBv2i32_indexed_OP2:
  5828. Opc = AArch64::MLSv2i32_indexed;
  5829. RC = &AArch64::FPR64RegClass;
  5830. MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
  5831. break;
  5832. case MachineCombinerPattern::MULSUBv4i32_indexed_OP1:
  5833. Opc = AArch64::MLAv4i32_indexed;
  5834. RC = &AArch64::FPR128RegClass;
  5835. MUL = genFusedMultiplyIdxNeg(MF, MRI, TII, Root, InsInstrs,
  5836. InstrIdxForVirtReg, 1, Opc, AArch64::NEGv4i32,
  5837. RC);
  5838. break;
  5839. case MachineCombinerPattern::MULSUBv4i32_indexed_OP2:
  5840. Opc = AArch64::MLSv4i32_indexed;
  5841. RC = &AArch64::FPR128RegClass;
  5842. MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
  5843. break;
  5844. // Floating Point Support
  5845. case MachineCombinerPattern::FMULADDH_OP1:
  5846. Opc = AArch64::FMADDHrrr;
  5847. RC = &AArch64::FPR16RegClass;
  5848. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
  5849. break;
  5850. case MachineCombinerPattern::FMULADDS_OP1:
  5851. Opc = AArch64::FMADDSrrr;
  5852. RC = &AArch64::FPR32RegClass;
  5853. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
  5854. break;
  5855. case MachineCombinerPattern::FMULADDD_OP1:
  5856. Opc = AArch64::FMADDDrrr;
  5857. RC = &AArch64::FPR64RegClass;
  5858. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
  5859. break;
  5860. case MachineCombinerPattern::FMULADDH_OP2:
  5861. Opc = AArch64::FMADDHrrr;
  5862. RC = &AArch64::FPR16RegClass;
  5863. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
  5864. break;
  5865. case MachineCombinerPattern::FMULADDS_OP2:
  5866. Opc = AArch64::FMADDSrrr;
  5867. RC = &AArch64::FPR32RegClass;
  5868. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
  5869. break;
  5870. case MachineCombinerPattern::FMULADDD_OP2:
  5871. Opc = AArch64::FMADDDrrr;
  5872. RC = &AArch64::FPR64RegClass;
  5873. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
  5874. break;
  5875. case MachineCombinerPattern::FMLAv1i32_indexed_OP1:
  5876. Opc = AArch64::FMLAv1i32_indexed;
  5877. RC = &AArch64::FPR32RegClass;
  5878. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
  5879. FMAInstKind::Indexed);
  5880. break;
  5881. case MachineCombinerPattern::FMLAv1i32_indexed_OP2:
  5882. Opc = AArch64::FMLAv1i32_indexed;
  5883. RC = &AArch64::FPR32RegClass;
  5884. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
  5885. FMAInstKind::Indexed);
  5886. break;
  5887. case MachineCombinerPattern::FMLAv1i64_indexed_OP1:
  5888. Opc = AArch64::FMLAv1i64_indexed;
  5889. RC = &AArch64::FPR64RegClass;
  5890. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
  5891. FMAInstKind::Indexed);
  5892. break;
  5893. case MachineCombinerPattern::FMLAv1i64_indexed_OP2:
  5894. Opc = AArch64::FMLAv1i64_indexed;
  5895. RC = &AArch64::FPR64RegClass;
  5896. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
  5897. FMAInstKind::Indexed);
  5898. break;
  5899. case MachineCombinerPattern::FMLAv4i16_indexed_OP1:
  5900. RC = &AArch64::FPR64RegClass;
  5901. Opc = AArch64::FMLAv4i16_indexed;
  5902. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
  5903. FMAInstKind::Indexed);
  5904. break;
  5905. case MachineCombinerPattern::FMLAv4f16_OP1:
  5906. RC = &AArch64::FPR64RegClass;
  5907. Opc = AArch64::FMLAv4f16;
  5908. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
  5909. FMAInstKind::Accumulator);
  5910. break;
  5911. case MachineCombinerPattern::FMLAv4i16_indexed_OP2:
  5912. RC = &AArch64::FPR64RegClass;
  5913. Opc = AArch64::FMLAv4i16_indexed;
  5914. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
  5915. FMAInstKind::Indexed);
  5916. break;
  5917. case MachineCombinerPattern::FMLAv4f16_OP2:
  5918. RC = &AArch64::FPR64RegClass;
  5919. Opc = AArch64::FMLAv4f16;
  5920. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
  5921. FMAInstKind::Accumulator);
  5922. break;
  5923. case MachineCombinerPattern::FMLAv2i32_indexed_OP1:
  5924. case MachineCombinerPattern::FMLAv2f32_OP1:
  5925. RC = &AArch64::FPR64RegClass;
  5926. if (Pattern == MachineCombinerPattern::FMLAv2i32_indexed_OP1) {
  5927. Opc = AArch64::FMLAv2i32_indexed;
  5928. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
  5929. FMAInstKind::Indexed);
  5930. } else {
  5931. Opc = AArch64::FMLAv2f32;
  5932. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
  5933. FMAInstKind::Accumulator);
  5934. }
  5935. break;
  5936. case MachineCombinerPattern::FMLAv2i32_indexed_OP2:
  5937. case MachineCombinerPattern::FMLAv2f32_OP2:
  5938. RC = &AArch64::FPR64RegClass;
  5939. if (Pattern == MachineCombinerPattern::FMLAv2i32_indexed_OP2) {
  5940. Opc = AArch64::FMLAv2i32_indexed;
  5941. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
  5942. FMAInstKind::Indexed);
  5943. } else {
  5944. Opc = AArch64::FMLAv2f32;
  5945. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
  5946. FMAInstKind::Accumulator);
  5947. }
  5948. break;
  5949. case MachineCombinerPattern::FMLAv8i16_indexed_OP1:
  5950. RC = &AArch64::FPR128RegClass;
  5951. Opc = AArch64::FMLAv8i16_indexed;
  5952. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
  5953. FMAInstKind::Indexed);
  5954. break;
  5955. case MachineCombinerPattern::FMLAv8f16_OP1:
  5956. RC = &AArch64::FPR128RegClass;
  5957. Opc = AArch64::FMLAv8f16;
  5958. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
  5959. FMAInstKind::Accumulator);
  5960. break;
  5961. case MachineCombinerPattern::FMLAv8i16_indexed_OP2:
  5962. RC = &AArch64::FPR128RegClass;
  5963. Opc = AArch64::FMLAv8i16_indexed;
  5964. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
  5965. FMAInstKind::Indexed);
  5966. break;
  5967. case MachineCombinerPattern::FMLAv8f16_OP2:
  5968. RC = &AArch64::FPR128RegClass;
  5969. Opc = AArch64::FMLAv8f16;
  5970. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
  5971. FMAInstKind::Accumulator);
  5972. break;
  5973. case MachineCombinerPattern::FMLAv2i64_indexed_OP1:
  5974. case MachineCombinerPattern::FMLAv2f64_OP1:
  5975. RC = &AArch64::FPR128RegClass;
  5976. if (Pattern == MachineCombinerPattern::FMLAv2i64_indexed_OP1) {
  5977. Opc = AArch64::FMLAv2i64_indexed;
  5978. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
  5979. FMAInstKind::Indexed);
  5980. } else {
  5981. Opc = AArch64::FMLAv2f64;
  5982. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
  5983. FMAInstKind::Accumulator);
  5984. }
  5985. break;
  5986. case MachineCombinerPattern::FMLAv2i64_indexed_OP2:
  5987. case MachineCombinerPattern::FMLAv2f64_OP2:
  5988. RC = &AArch64::FPR128RegClass;
  5989. if (Pattern == MachineCombinerPattern::FMLAv2i64_indexed_OP2) {
  5990. Opc = AArch64::FMLAv2i64_indexed;
  5991. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
  5992. FMAInstKind::Indexed);
  5993. } else {
  5994. Opc = AArch64::FMLAv2f64;
  5995. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
  5996. FMAInstKind::Accumulator);
  5997. }
  5998. break;
  5999. case MachineCombinerPattern::FMLAv4i32_indexed_OP1:
  6000. case MachineCombinerPattern::FMLAv4f32_OP1:
  6001. RC = &AArch64::FPR128RegClass;
  6002. if (Pattern == MachineCombinerPattern::FMLAv4i32_indexed_OP1) {
  6003. Opc = AArch64::FMLAv4i32_indexed;
  6004. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
  6005. FMAInstKind::Indexed);
  6006. } else {
  6007. Opc = AArch64::FMLAv4f32;
  6008. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
  6009. FMAInstKind::Accumulator);
  6010. }
  6011. break;
  6012. case MachineCombinerPattern::FMLAv4i32_indexed_OP2:
  6013. case MachineCombinerPattern::FMLAv4f32_OP2:
  6014. RC = &AArch64::FPR128RegClass;
  6015. if (Pattern == MachineCombinerPattern::FMLAv4i32_indexed_OP2) {
  6016. Opc = AArch64::FMLAv4i32_indexed;
  6017. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
  6018. FMAInstKind::Indexed);
  6019. } else {
  6020. Opc = AArch64::FMLAv4f32;
  6021. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
  6022. FMAInstKind::Accumulator);
  6023. }
  6024. break;
  6025. case MachineCombinerPattern::FMULSUBH_OP1:
  6026. Opc = AArch64::FNMSUBHrrr;
  6027. RC = &AArch64::FPR16RegClass;
  6028. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
  6029. break;
  6030. case MachineCombinerPattern::FMULSUBS_OP1:
  6031. Opc = AArch64::FNMSUBSrrr;
  6032. RC = &AArch64::FPR32RegClass;
  6033. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
  6034. break;
  6035. case MachineCombinerPattern::FMULSUBD_OP1:
  6036. Opc = AArch64::FNMSUBDrrr;
  6037. RC = &AArch64::FPR64RegClass;
  6038. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
  6039. break;
  6040. case MachineCombinerPattern::FNMULSUBH_OP1:
  6041. Opc = AArch64::FNMADDHrrr;
  6042. RC = &AArch64::FPR16RegClass;
  6043. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
  6044. break;
  6045. case MachineCombinerPattern::FNMULSUBS_OP1:
  6046. Opc = AArch64::FNMADDSrrr;
  6047. RC = &AArch64::FPR32RegClass;
  6048. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
  6049. break;
  6050. case MachineCombinerPattern::FNMULSUBD_OP1:
  6051. Opc = AArch64::FNMADDDrrr;
  6052. RC = &AArch64::FPR64RegClass;
  6053. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
  6054. break;
  6055. case MachineCombinerPattern::FMULSUBH_OP2:
  6056. Opc = AArch64::FMSUBHrrr;
  6057. RC = &AArch64::FPR16RegClass;
  6058. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
  6059. break;
  6060. case MachineCombinerPattern::FMULSUBS_OP2:
  6061. Opc = AArch64::FMSUBSrrr;
  6062. RC = &AArch64::FPR32RegClass;
  6063. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
  6064. break;
  6065. case MachineCombinerPattern::FMULSUBD_OP2:
  6066. Opc = AArch64::FMSUBDrrr;
  6067. RC = &AArch64::FPR64RegClass;
  6068. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
  6069. break;
  6070. case MachineCombinerPattern::FMLSv1i32_indexed_OP2:
  6071. Opc = AArch64::FMLSv1i32_indexed;
  6072. RC = &AArch64::FPR32RegClass;
  6073. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
  6074. FMAInstKind::Indexed);
  6075. break;
  6076. case MachineCombinerPattern::FMLSv1i64_indexed_OP2:
  6077. Opc = AArch64::FMLSv1i64_indexed;
  6078. RC = &AArch64::FPR64RegClass;
  6079. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
  6080. FMAInstKind::Indexed);
  6081. break;
  6082. case MachineCombinerPattern::FMLSv4f16_OP1:
  6083. case MachineCombinerPattern::FMLSv4i16_indexed_OP1: {
  6084. RC = &AArch64::FPR64RegClass;
  6085. Register NewVR = MRI.createVirtualRegister(RC);
  6086. MachineInstrBuilder MIB1 =
  6087. BuildMI(MF, MIMetadata(Root), TII->get(AArch64::FNEGv4f16), NewVR)
  6088. .add(Root.getOperand(2));
  6089. InsInstrs.push_back(MIB1);
  6090. InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
  6091. if (Pattern == MachineCombinerPattern::FMLSv4f16_OP1) {
  6092. Opc = AArch64::FMLAv4f16;
  6093. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
  6094. FMAInstKind::Accumulator, &NewVR);
  6095. } else {
  6096. Opc = AArch64::FMLAv4i16_indexed;
  6097. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
  6098. FMAInstKind::Indexed, &NewVR);
  6099. }
  6100. break;
  6101. }
  6102. case MachineCombinerPattern::FMLSv4f16_OP2:
  6103. RC = &AArch64::FPR64RegClass;
  6104. Opc = AArch64::FMLSv4f16;
  6105. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
  6106. FMAInstKind::Accumulator);
  6107. break;
  6108. case MachineCombinerPattern::FMLSv4i16_indexed_OP2:
  6109. RC = &AArch64::FPR64RegClass;
  6110. Opc = AArch64::FMLSv4i16_indexed;
  6111. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
  6112. FMAInstKind::Indexed);
  6113. break;
  6114. case MachineCombinerPattern::FMLSv2f32_OP2:
  6115. case MachineCombinerPattern::FMLSv2i32_indexed_OP2:
  6116. RC = &AArch64::FPR64RegClass;
  6117. if (Pattern == MachineCombinerPattern::FMLSv2i32_indexed_OP2) {
  6118. Opc = AArch64::FMLSv2i32_indexed;
  6119. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
  6120. FMAInstKind::Indexed);
  6121. } else {
  6122. Opc = AArch64::FMLSv2f32;
  6123. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
  6124. FMAInstKind::Accumulator);
  6125. }
  6126. break;
  6127. case MachineCombinerPattern::FMLSv8f16_OP1:
  6128. case MachineCombinerPattern::FMLSv8i16_indexed_OP1: {
  6129. RC = &AArch64::FPR128RegClass;
  6130. Register NewVR = MRI.createVirtualRegister(RC);
  6131. MachineInstrBuilder MIB1 =
  6132. BuildMI(MF, MIMetadata(Root), TII->get(AArch64::FNEGv8f16), NewVR)
  6133. .add(Root.getOperand(2));
  6134. InsInstrs.push_back(MIB1);
  6135. InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
  6136. if (Pattern == MachineCombinerPattern::FMLSv8f16_OP1) {
  6137. Opc = AArch64::FMLAv8f16;
  6138. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
  6139. FMAInstKind::Accumulator, &NewVR);
  6140. } else {
  6141. Opc = AArch64::FMLAv8i16_indexed;
  6142. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
  6143. FMAInstKind::Indexed, &NewVR);
  6144. }
  6145. break;
  6146. }
  6147. case MachineCombinerPattern::FMLSv8f16_OP2:
  6148. RC = &AArch64::FPR128RegClass;
  6149. Opc = AArch64::FMLSv8f16;
  6150. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
  6151. FMAInstKind::Accumulator);
  6152. break;
  6153. case MachineCombinerPattern::FMLSv8i16_indexed_OP2:
  6154. RC = &AArch64::FPR128RegClass;
  6155. Opc = AArch64::FMLSv8i16_indexed;
  6156. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
  6157. FMAInstKind::Indexed);
  6158. break;
  6159. case MachineCombinerPattern::FMLSv2f64_OP2:
  6160. case MachineCombinerPattern::FMLSv2i64_indexed_OP2:
  6161. RC = &AArch64::FPR128RegClass;
  6162. if (Pattern == MachineCombinerPattern::FMLSv2i64_indexed_OP2) {
  6163. Opc = AArch64::FMLSv2i64_indexed;
  6164. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
  6165. FMAInstKind::Indexed);
  6166. } else {
  6167. Opc = AArch64::FMLSv2f64;
  6168. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
  6169. FMAInstKind::Accumulator);
  6170. }
  6171. break;
  6172. case MachineCombinerPattern::FMLSv4f32_OP2:
  6173. case MachineCombinerPattern::FMLSv4i32_indexed_OP2:
  6174. RC = &AArch64::FPR128RegClass;
  6175. if (Pattern == MachineCombinerPattern::FMLSv4i32_indexed_OP2) {
  6176. Opc = AArch64::FMLSv4i32_indexed;
  6177. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
  6178. FMAInstKind::Indexed);
  6179. } else {
  6180. Opc = AArch64::FMLSv4f32;
  6181. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
  6182. FMAInstKind::Accumulator);
  6183. }
  6184. break;
  6185. case MachineCombinerPattern::FMLSv2f32_OP1:
  6186. case MachineCombinerPattern::FMLSv2i32_indexed_OP1: {
  6187. RC = &AArch64::FPR64RegClass;
  6188. Register NewVR = MRI.createVirtualRegister(RC);
  6189. MachineInstrBuilder MIB1 =
  6190. BuildMI(MF, MIMetadata(Root), TII->get(AArch64::FNEGv2f32), NewVR)
  6191. .add(Root.getOperand(2));
  6192. InsInstrs.push_back(MIB1);
  6193. InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
  6194. if (Pattern == MachineCombinerPattern::FMLSv2i32_indexed_OP1) {
  6195. Opc = AArch64::FMLAv2i32_indexed;
  6196. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
  6197. FMAInstKind::Indexed, &NewVR);
  6198. } else {
  6199. Opc = AArch64::FMLAv2f32;
  6200. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
  6201. FMAInstKind::Accumulator, &NewVR);
  6202. }
  6203. break;
  6204. }
  6205. case MachineCombinerPattern::FMLSv4f32_OP1:
  6206. case MachineCombinerPattern::FMLSv4i32_indexed_OP1: {
  6207. RC = &AArch64::FPR128RegClass;
  6208. Register NewVR = MRI.createVirtualRegister(RC);
  6209. MachineInstrBuilder MIB1 =
  6210. BuildMI(MF, MIMetadata(Root), TII->get(AArch64::FNEGv4f32), NewVR)
  6211. .add(Root.getOperand(2));
  6212. InsInstrs.push_back(MIB1);
  6213. InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
  6214. if (Pattern == MachineCombinerPattern::FMLSv4i32_indexed_OP1) {
  6215. Opc = AArch64::FMLAv4i32_indexed;
  6216. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
  6217. FMAInstKind::Indexed, &NewVR);
  6218. } else {
  6219. Opc = AArch64::FMLAv4f32;
  6220. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
  6221. FMAInstKind::Accumulator, &NewVR);
  6222. }
  6223. break;
  6224. }
  6225. case MachineCombinerPattern::FMLSv2f64_OP1:
  6226. case MachineCombinerPattern::FMLSv2i64_indexed_OP1: {
  6227. RC = &AArch64::FPR128RegClass;
  6228. Register NewVR = MRI.createVirtualRegister(RC);
  6229. MachineInstrBuilder MIB1 =
  6230. BuildMI(MF, MIMetadata(Root), TII->get(AArch64::FNEGv2f64), NewVR)
  6231. .add(Root.getOperand(2));
  6232. InsInstrs.push_back(MIB1);
  6233. InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
  6234. if (Pattern == MachineCombinerPattern::FMLSv2i64_indexed_OP1) {
  6235. Opc = AArch64::FMLAv2i64_indexed;
  6236. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
  6237. FMAInstKind::Indexed, &NewVR);
  6238. } else {
  6239. Opc = AArch64::FMLAv2f64;
  6240. MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
  6241. FMAInstKind::Accumulator, &NewVR);
  6242. }
  6243. break;
  6244. }
  6245. case MachineCombinerPattern::FMULv2i32_indexed_OP1:
  6246. case MachineCombinerPattern::FMULv2i32_indexed_OP2: {
  6247. unsigned IdxDupOp =
  6248. (Pattern == MachineCombinerPattern::FMULv2i32_indexed_OP1) ? 1 : 2;
  6249. genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv2i32_indexed,
  6250. &AArch64::FPR128RegClass, MRI);
  6251. break;
  6252. }
  6253. case MachineCombinerPattern::FMULv2i64_indexed_OP1:
  6254. case MachineCombinerPattern::FMULv2i64_indexed_OP2: {
  6255. unsigned IdxDupOp =
  6256. (Pattern == MachineCombinerPattern::FMULv2i64_indexed_OP1) ? 1 : 2;
  6257. genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv2i64_indexed,
  6258. &AArch64::FPR128RegClass, MRI);
  6259. break;
  6260. }
  6261. case MachineCombinerPattern::FMULv4i16_indexed_OP1:
  6262. case MachineCombinerPattern::FMULv4i16_indexed_OP2: {
  6263. unsigned IdxDupOp =
  6264. (Pattern == MachineCombinerPattern::FMULv4i16_indexed_OP1) ? 1 : 2;
  6265. genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv4i16_indexed,
  6266. &AArch64::FPR128_loRegClass, MRI);
  6267. break;
  6268. }
  6269. case MachineCombinerPattern::FMULv4i32_indexed_OP1:
  6270. case MachineCombinerPattern::FMULv4i32_indexed_OP2: {
  6271. unsigned IdxDupOp =
  6272. (Pattern == MachineCombinerPattern::FMULv4i32_indexed_OP1) ? 1 : 2;
  6273. genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv4i32_indexed,
  6274. &AArch64::FPR128RegClass, MRI);
  6275. break;
  6276. }
  6277. case MachineCombinerPattern::FMULv8i16_indexed_OP1:
  6278. case MachineCombinerPattern::FMULv8i16_indexed_OP2: {
  6279. unsigned IdxDupOp =
  6280. (Pattern == MachineCombinerPattern::FMULv8i16_indexed_OP1) ? 1 : 2;
  6281. genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv8i16_indexed,
  6282. &AArch64::FPR128_loRegClass, MRI);
  6283. break;
  6284. }
  6285. } // end switch (Pattern)
  6286. // Record MUL and ADD/SUB for deletion
  6287. if (MUL)
  6288. DelInstrs.push_back(MUL);
  6289. DelInstrs.push_back(&Root);
  6290. // Set the flags on the inserted instructions to be the merged flags of the
  6291. // instructions that we have combined.
  6292. uint16_t Flags = Root.getFlags();
  6293. if (MUL)
  6294. Flags = Root.mergeFlagsWith(*MUL);
  6295. for (auto *MI : InsInstrs)
  6296. MI->setFlags(Flags);
  6297. }
  6298. /// Replace csincr-branch sequence by simple conditional branch
  6299. ///
  6300. /// Examples:
  6301. /// 1. \code
  6302. /// csinc w9, wzr, wzr, <condition code>
  6303. /// tbnz w9, #0, 0x44
  6304. /// \endcode
  6305. /// to
  6306. /// \code
  6307. /// b.<inverted condition code>
  6308. /// \endcode
  6309. ///
  6310. /// 2. \code
  6311. /// csinc w9, wzr, wzr, <condition code>
  6312. /// tbz w9, #0, 0x44
  6313. /// \endcode
  6314. /// to
  6315. /// \code
  6316. /// b.<condition code>
  6317. /// \endcode
  6318. ///
  6319. /// Replace compare and branch sequence by TBZ/TBNZ instruction when the
  6320. /// compare's constant operand is power of 2.
  6321. ///
  6322. /// Examples:
  6323. /// \code
  6324. /// and w8, w8, #0x400
  6325. /// cbnz w8, L1
  6326. /// \endcode
  6327. /// to
  6328. /// \code
  6329. /// tbnz w8, #10, L1
  6330. /// \endcode
  6331. ///
  6332. /// \param MI Conditional Branch
  6333. /// \return True when the simple conditional branch is generated
  6334. ///
  6335. bool AArch64InstrInfo::optimizeCondBranch(MachineInstr &MI) const {
  6336. bool IsNegativeBranch = false;
  6337. bool IsTestAndBranch = false;
  6338. unsigned TargetBBInMI = 0;
  6339. switch (MI.getOpcode()) {
  6340. default:
  6341. llvm_unreachable("Unknown branch instruction?");
  6342. case AArch64::Bcc:
  6343. return false;
  6344. case AArch64::CBZW:
  6345. case AArch64::CBZX:
  6346. TargetBBInMI = 1;
  6347. break;
  6348. case AArch64::CBNZW:
  6349. case AArch64::CBNZX:
  6350. TargetBBInMI = 1;
  6351. IsNegativeBranch = true;
  6352. break;
  6353. case AArch64::TBZW:
  6354. case AArch64::TBZX:
  6355. TargetBBInMI = 2;
  6356. IsTestAndBranch = true;
  6357. break;
  6358. case AArch64::TBNZW:
  6359. case AArch64::TBNZX:
  6360. TargetBBInMI = 2;
  6361. IsNegativeBranch = true;
  6362. IsTestAndBranch = true;
  6363. break;
  6364. }
  6365. // So we increment a zero register and test for bits other
  6366. // than bit 0? Conservatively bail out in case the verifier
  6367. // missed this case.
  6368. if (IsTestAndBranch && MI.getOperand(1).getImm())
  6369. return false;
  6370. // Find Definition.
  6371. assert(MI.getParent() && "Incomplete machine instruciton\n");
  6372. MachineBasicBlock *MBB = MI.getParent();
  6373. MachineFunction *MF = MBB->getParent();
  6374. MachineRegisterInfo *MRI = &MF->getRegInfo();
  6375. Register VReg = MI.getOperand(0).getReg();
  6376. if (!VReg.isVirtual())
  6377. return false;
  6378. MachineInstr *DefMI = MRI->getVRegDef(VReg);
  6379. // Look through COPY instructions to find definition.
  6380. while (DefMI->isCopy()) {
  6381. Register CopyVReg = DefMI->getOperand(1).getReg();
  6382. if (!MRI->hasOneNonDBGUse(CopyVReg))
  6383. return false;
  6384. if (!MRI->hasOneDef(CopyVReg))
  6385. return false;
  6386. DefMI = MRI->getVRegDef(CopyVReg);
  6387. }
  6388. switch (DefMI->getOpcode()) {
  6389. default:
  6390. return false;
  6391. // Fold AND into a TBZ/TBNZ if constant operand is power of 2.
  6392. case AArch64::ANDWri:
  6393. case AArch64::ANDXri: {
  6394. if (IsTestAndBranch)
  6395. return false;
  6396. if (DefMI->getParent() != MBB)
  6397. return false;
  6398. if (!MRI->hasOneNonDBGUse(VReg))
  6399. return false;
  6400. bool Is32Bit = (DefMI->getOpcode() == AArch64::ANDWri);
  6401. uint64_t Mask = AArch64_AM::decodeLogicalImmediate(
  6402. DefMI->getOperand(2).getImm(), Is32Bit ? 32 : 64);
  6403. if (!isPowerOf2_64(Mask))
  6404. return false;
  6405. MachineOperand &MO = DefMI->getOperand(1);
  6406. Register NewReg = MO.getReg();
  6407. if (!NewReg.isVirtual())
  6408. return false;
  6409. assert(!MRI->def_empty(NewReg) && "Register must be defined.");
  6410. MachineBasicBlock &RefToMBB = *MBB;
  6411. MachineBasicBlock *TBB = MI.getOperand(1).getMBB();
  6412. DebugLoc DL = MI.getDebugLoc();
  6413. unsigned Imm = Log2_64(Mask);
  6414. unsigned Opc = (Imm < 32)
  6415. ? (IsNegativeBranch ? AArch64::TBNZW : AArch64::TBZW)
  6416. : (IsNegativeBranch ? AArch64::TBNZX : AArch64::TBZX);
  6417. MachineInstr *NewMI = BuildMI(RefToMBB, MI, DL, get(Opc))
  6418. .addReg(NewReg)
  6419. .addImm(Imm)
  6420. .addMBB(TBB);
  6421. // Register lives on to the CBZ now.
  6422. MO.setIsKill(false);
  6423. // For immediate smaller than 32, we need to use the 32-bit
  6424. // variant (W) in all cases. Indeed the 64-bit variant does not
  6425. // allow to encode them.
  6426. // Therefore, if the input register is 64-bit, we need to take the
  6427. // 32-bit sub-part.
  6428. if (!Is32Bit && Imm < 32)
  6429. NewMI->getOperand(0).setSubReg(AArch64::sub_32);
  6430. MI.eraseFromParent();
  6431. return true;
  6432. }
  6433. // Look for CSINC
  6434. case AArch64::CSINCWr:
  6435. case AArch64::CSINCXr: {
  6436. if (!(DefMI->getOperand(1).getReg() == AArch64::WZR &&
  6437. DefMI->getOperand(2).getReg() == AArch64::WZR) &&
  6438. !(DefMI->getOperand(1).getReg() == AArch64::XZR &&
  6439. DefMI->getOperand(2).getReg() == AArch64::XZR))
  6440. return false;
  6441. if (DefMI->findRegisterDefOperandIdx(AArch64::NZCV, true) != -1)
  6442. return false;
  6443. AArch64CC::CondCode CC = (AArch64CC::CondCode)DefMI->getOperand(3).getImm();
  6444. // Convert only when the condition code is not modified between
  6445. // the CSINC and the branch. The CC may be used by other
  6446. // instructions in between.
  6447. if (areCFlagsAccessedBetweenInstrs(DefMI, MI, &getRegisterInfo(), AK_Write))
  6448. return false;
  6449. MachineBasicBlock &RefToMBB = *MBB;
  6450. MachineBasicBlock *TBB = MI.getOperand(TargetBBInMI).getMBB();
  6451. DebugLoc DL = MI.getDebugLoc();
  6452. if (IsNegativeBranch)
  6453. CC = AArch64CC::getInvertedCondCode(CC);
  6454. BuildMI(RefToMBB, MI, DL, get(AArch64::Bcc)).addImm(CC).addMBB(TBB);
  6455. MI.eraseFromParent();
  6456. return true;
  6457. }
  6458. }
  6459. }
  6460. std::pair<unsigned, unsigned>
  6461. AArch64InstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {
  6462. const unsigned Mask = AArch64II::MO_FRAGMENT;
  6463. return std::make_pair(TF & Mask, TF & ~Mask);
  6464. }
  6465. ArrayRef<std::pair<unsigned, const char *>>
  6466. AArch64InstrInfo::getSerializableDirectMachineOperandTargetFlags() const {
  6467. using namespace AArch64II;
  6468. static const std::pair<unsigned, const char *> TargetFlags[] = {
  6469. {MO_PAGE, "aarch64-page"}, {MO_PAGEOFF, "aarch64-pageoff"},
  6470. {MO_G3, "aarch64-g3"}, {MO_G2, "aarch64-g2"},
  6471. {MO_G1, "aarch64-g1"}, {MO_G0, "aarch64-g0"},
  6472. {MO_HI12, "aarch64-hi12"}};
  6473. return ArrayRef(TargetFlags);
  6474. }
  6475. ArrayRef<std::pair<unsigned, const char *>>
  6476. AArch64InstrInfo::getSerializableBitmaskMachineOperandTargetFlags() const {
  6477. using namespace AArch64II;
  6478. static const std::pair<unsigned, const char *> TargetFlags[] = {
  6479. {MO_COFFSTUB, "aarch64-coffstub"},
  6480. {MO_GOT, "aarch64-got"},
  6481. {MO_NC, "aarch64-nc"},
  6482. {MO_S, "aarch64-s"},
  6483. {MO_TLS, "aarch64-tls"},
  6484. {MO_DLLIMPORT, "aarch64-dllimport"},
  6485. {MO_DLLIMPORTAUX, "aarch64-dllimportaux"},
  6486. {MO_PREL, "aarch64-prel"},
  6487. {MO_TAGGED, "aarch64-tagged"}};
  6488. return ArrayRef(TargetFlags);
  6489. }
  6490. ArrayRef<std::pair<MachineMemOperand::Flags, const char *>>
  6491. AArch64InstrInfo::getSerializableMachineMemOperandTargetFlags() const {
  6492. static const std::pair<MachineMemOperand::Flags, const char *> TargetFlags[] =
  6493. {{MOSuppressPair, "aarch64-suppress-pair"},
  6494. {MOStridedAccess, "aarch64-strided-access"}};
  6495. return ArrayRef(TargetFlags);
  6496. }
  6497. /// Constants defining how certain sequences should be outlined.
  6498. /// This encompasses how an outlined function should be called, and what kind of
  6499. /// frame should be emitted for that outlined function.
  6500. ///
  6501. /// \p MachineOutlinerDefault implies that the function should be called with
  6502. /// a save and restore of LR to the stack.
  6503. ///
  6504. /// That is,
  6505. ///
  6506. /// I1 Save LR OUTLINED_FUNCTION:
  6507. /// I2 --> BL OUTLINED_FUNCTION I1
  6508. /// I3 Restore LR I2
  6509. /// I3
  6510. /// RET
  6511. ///
  6512. /// * Call construction overhead: 3 (save + BL + restore)
  6513. /// * Frame construction overhead: 1 (ret)
  6514. /// * Requires stack fixups? Yes
  6515. ///
  6516. /// \p MachineOutlinerTailCall implies that the function is being created from
  6517. /// a sequence of instructions ending in a return.
  6518. ///
  6519. /// That is,
  6520. ///
  6521. /// I1 OUTLINED_FUNCTION:
  6522. /// I2 --> B OUTLINED_FUNCTION I1
  6523. /// RET I2
  6524. /// RET
  6525. ///
  6526. /// * Call construction overhead: 1 (B)
  6527. /// * Frame construction overhead: 0 (Return included in sequence)
  6528. /// * Requires stack fixups? No
  6529. ///
  6530. /// \p MachineOutlinerNoLRSave implies that the function should be called using
  6531. /// a BL instruction, but doesn't require LR to be saved and restored. This
  6532. /// happens when LR is known to be dead.
  6533. ///
  6534. /// That is,
  6535. ///
  6536. /// I1 OUTLINED_FUNCTION:
  6537. /// I2 --> BL OUTLINED_FUNCTION I1
  6538. /// I3 I2
  6539. /// I3
  6540. /// RET
  6541. ///
  6542. /// * Call construction overhead: 1 (BL)
  6543. /// * Frame construction overhead: 1 (RET)
  6544. /// * Requires stack fixups? No
  6545. ///
  6546. /// \p MachineOutlinerThunk implies that the function is being created from
  6547. /// a sequence of instructions ending in a call. The outlined function is
  6548. /// called with a BL instruction, and the outlined function tail-calls the
  6549. /// original call destination.
  6550. ///
  6551. /// That is,
  6552. ///
  6553. /// I1 OUTLINED_FUNCTION:
  6554. /// I2 --> BL OUTLINED_FUNCTION I1
  6555. /// BL f I2
  6556. /// B f
  6557. /// * Call construction overhead: 1 (BL)
  6558. /// * Frame construction overhead: 0
  6559. /// * Requires stack fixups? No
  6560. ///
  6561. /// \p MachineOutlinerRegSave implies that the function should be called with a
  6562. /// save and restore of LR to an available register. This allows us to avoid
  6563. /// stack fixups. Note that this outlining variant is compatible with the
  6564. /// NoLRSave case.
  6565. ///
  6566. /// That is,
  6567. ///
  6568. /// I1 Save LR OUTLINED_FUNCTION:
  6569. /// I2 --> BL OUTLINED_FUNCTION I1
  6570. /// I3 Restore LR I2
  6571. /// I3
  6572. /// RET
  6573. ///
  6574. /// * Call construction overhead: 3 (save + BL + restore)
  6575. /// * Frame construction overhead: 1 (ret)
  6576. /// * Requires stack fixups? No
  6577. enum MachineOutlinerClass {
  6578. MachineOutlinerDefault, /// Emit a save, restore, call, and return.
  6579. MachineOutlinerTailCall, /// Only emit a branch.
  6580. MachineOutlinerNoLRSave, /// Emit a call and return.
  6581. MachineOutlinerThunk, /// Emit a call and tail-call.
  6582. MachineOutlinerRegSave /// Same as default, but save to a register.
  6583. };
  6584. enum MachineOutlinerMBBFlags {
  6585. LRUnavailableSomewhere = 0x2,
  6586. HasCalls = 0x4,
  6587. UnsafeRegsDead = 0x8
  6588. };
  6589. Register
  6590. AArch64InstrInfo::findRegisterToSaveLRTo(outliner::Candidate &C) const {
  6591. MachineFunction *MF = C.getMF();
  6592. const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
  6593. const AArch64RegisterInfo *ARI =
  6594. static_cast<const AArch64RegisterInfo *>(&TRI);
  6595. // Check if there is an available register across the sequence that we can
  6596. // use.
  6597. for (unsigned Reg : AArch64::GPR64RegClass) {
  6598. if (!ARI->isReservedReg(*MF, Reg) &&
  6599. Reg != AArch64::LR && // LR is not reserved, but don't use it.
  6600. Reg != AArch64::X16 && // X16 is not guaranteed to be preserved.
  6601. Reg != AArch64::X17 && // Ditto for X17.
  6602. C.isAvailableAcrossAndOutOfSeq(Reg, TRI) &&
  6603. C.isAvailableInsideSeq(Reg, TRI))
  6604. return Reg;
  6605. }
  6606. return Register();
  6607. }
  6608. static bool
  6609. outliningCandidatesSigningScopeConsensus(const outliner::Candidate &a,
  6610. const outliner::Candidate &b) {
  6611. const auto &MFIa = a.getMF()->getInfo<AArch64FunctionInfo>();
  6612. const auto &MFIb = b.getMF()->getInfo<AArch64FunctionInfo>();
  6613. return MFIa->shouldSignReturnAddress(false) == MFIb->shouldSignReturnAddress(false) &&
  6614. MFIa->shouldSignReturnAddress(true) == MFIb->shouldSignReturnAddress(true);
  6615. }
  6616. static bool
  6617. outliningCandidatesSigningKeyConsensus(const outliner::Candidate &a,
  6618. const outliner::Candidate &b) {
  6619. const auto &MFIa = a.getMF()->getInfo<AArch64FunctionInfo>();
  6620. const auto &MFIb = b.getMF()->getInfo<AArch64FunctionInfo>();
  6621. return MFIa->shouldSignWithBKey() == MFIb->shouldSignWithBKey();
  6622. }
  6623. static bool outliningCandidatesV8_3OpsConsensus(const outliner::Candidate &a,
  6624. const outliner::Candidate &b) {
  6625. const AArch64Subtarget &SubtargetA =
  6626. a.getMF()->getSubtarget<AArch64Subtarget>();
  6627. const AArch64Subtarget &SubtargetB =
  6628. b.getMF()->getSubtarget<AArch64Subtarget>();
  6629. return SubtargetA.hasV8_3aOps() == SubtargetB.hasV8_3aOps();
  6630. }
  6631. outliner::OutlinedFunction AArch64InstrInfo::getOutliningCandidateInfo(
  6632. std::vector<outliner::Candidate> &RepeatedSequenceLocs) const {
  6633. outliner::Candidate &FirstCand = RepeatedSequenceLocs[0];
  6634. unsigned SequenceSize =
  6635. std::accumulate(FirstCand.front(), std::next(FirstCand.back()), 0,
  6636. [this](unsigned Sum, const MachineInstr &MI) {
  6637. return Sum + getInstSizeInBytes(MI);
  6638. });
  6639. unsigned NumBytesToCreateFrame = 0;
  6640. // We only allow outlining for functions having exactly matching return
  6641. // address signing attributes, i.e., all share the same value for the
  6642. // attribute "sign-return-address" and all share the same type of key they
  6643. // are signed with.
  6644. // Additionally we require all functions to simultaniously either support
  6645. // v8.3a features or not. Otherwise an outlined function could get signed
  6646. // using dedicated v8.3 instructions and a call from a function that doesn't
  6647. // support v8.3 instructions would therefore be invalid.
  6648. if (std::adjacent_find(
  6649. RepeatedSequenceLocs.begin(), RepeatedSequenceLocs.end(),
  6650. [](const outliner::Candidate &a, const outliner::Candidate &b) {
  6651. // Return true if a and b are non-equal w.r.t. return address
  6652. // signing or support of v8.3a features
  6653. if (outliningCandidatesSigningScopeConsensus(a, b) &&
  6654. outliningCandidatesSigningKeyConsensus(a, b) &&
  6655. outliningCandidatesV8_3OpsConsensus(a, b)) {
  6656. return false;
  6657. }
  6658. return true;
  6659. }) != RepeatedSequenceLocs.end()) {
  6660. return outliner::OutlinedFunction();
  6661. }
  6662. // Since at this point all candidates agree on their return address signing
  6663. // picking just one is fine. If the candidate functions potentially sign their
  6664. // return addresses, the outlined function should do the same. Note that in
  6665. // the case of "sign-return-address"="non-leaf" this is an assumption: It is
  6666. // not certainly true that the outlined function will have to sign its return
  6667. // address but this decision is made later, when the decision to outline
  6668. // has already been made.
  6669. // The same holds for the number of additional instructions we need: On
  6670. // v8.3a RET can be replaced by RETAA/RETAB and no AUT instruction is
  6671. // necessary. However, at this point we don't know if the outlined function
  6672. // will have a RET instruction so we assume the worst.
  6673. const TargetRegisterInfo &TRI = getRegisterInfo();
  6674. if (FirstCand.getMF()
  6675. ->getInfo<AArch64FunctionInfo>()
  6676. ->shouldSignReturnAddress(true)) {
  6677. // One PAC and one AUT instructions
  6678. NumBytesToCreateFrame += 8;
  6679. // We have to check if sp modifying instructions would get outlined.
  6680. // If so we only allow outlining if sp is unchanged overall, so matching
  6681. // sub and add instructions are okay to outline, all other sp modifications
  6682. // are not
  6683. auto hasIllegalSPModification = [&TRI](outliner::Candidate &C) {
  6684. int SPValue = 0;
  6685. MachineBasicBlock::iterator MBBI = C.front();
  6686. for (;;) {
  6687. if (MBBI->modifiesRegister(AArch64::SP, &TRI)) {
  6688. switch (MBBI->getOpcode()) {
  6689. case AArch64::ADDXri:
  6690. case AArch64::ADDWri:
  6691. assert(MBBI->getNumOperands() == 4 && "Wrong number of operands");
  6692. assert(MBBI->getOperand(2).isImm() &&
  6693. "Expected operand to be immediate");
  6694. assert(MBBI->getOperand(1).isReg() &&
  6695. "Expected operand to be a register");
  6696. // Check if the add just increments sp. If so, we search for
  6697. // matching sub instructions that decrement sp. If not, the
  6698. // modification is illegal
  6699. if (MBBI->getOperand(1).getReg() == AArch64::SP)
  6700. SPValue += MBBI->getOperand(2).getImm();
  6701. else
  6702. return true;
  6703. break;
  6704. case AArch64::SUBXri:
  6705. case AArch64::SUBWri:
  6706. assert(MBBI->getNumOperands() == 4 && "Wrong number of operands");
  6707. assert(MBBI->getOperand(2).isImm() &&
  6708. "Expected operand to be immediate");
  6709. assert(MBBI->getOperand(1).isReg() &&
  6710. "Expected operand to be a register");
  6711. // Check if the sub just decrements sp. If so, we search for
  6712. // matching add instructions that increment sp. If not, the
  6713. // modification is illegal
  6714. if (MBBI->getOperand(1).getReg() == AArch64::SP)
  6715. SPValue -= MBBI->getOperand(2).getImm();
  6716. else
  6717. return true;
  6718. break;
  6719. default:
  6720. return true;
  6721. }
  6722. }
  6723. if (MBBI == C.back())
  6724. break;
  6725. ++MBBI;
  6726. }
  6727. if (SPValue)
  6728. return true;
  6729. return false;
  6730. };
  6731. // Remove candidates with illegal stack modifying instructions
  6732. llvm::erase_if(RepeatedSequenceLocs, hasIllegalSPModification);
  6733. // If the sequence doesn't have enough candidates left, then we're done.
  6734. if (RepeatedSequenceLocs.size() < 2)
  6735. return outliner::OutlinedFunction();
  6736. }
  6737. // Properties about candidate MBBs that hold for all of them.
  6738. unsigned FlagsSetInAll = 0xF;
  6739. // Compute liveness information for each candidate, and set FlagsSetInAll.
  6740. for (outliner::Candidate &C : RepeatedSequenceLocs)
  6741. FlagsSetInAll &= C.Flags;
  6742. // According to the AArch64 Procedure Call Standard, the following are
  6743. // undefined on entry/exit from a function call:
  6744. //
  6745. // * Registers x16, x17, (and thus w16, w17)
  6746. // * Condition codes (and thus the NZCV register)
  6747. //
  6748. // Because if this, we can't outline any sequence of instructions where
  6749. // one
  6750. // of these registers is live into/across it. Thus, we need to delete
  6751. // those
  6752. // candidates.
  6753. auto CantGuaranteeValueAcrossCall = [&TRI](outliner::Candidate &C) {
  6754. // If the unsafe registers in this block are all dead, then we don't need
  6755. // to compute liveness here.
  6756. if (C.Flags & UnsafeRegsDead)
  6757. return false;
  6758. return C.isAnyUnavailableAcrossOrOutOfSeq(
  6759. {AArch64::W16, AArch64::W17, AArch64::NZCV}, TRI);
  6760. };
  6761. // Are there any candidates where those registers are live?
  6762. if (!(FlagsSetInAll & UnsafeRegsDead)) {
  6763. // Erase every candidate that violates the restrictions above. (It could be
  6764. // true that we have viable candidates, so it's not worth bailing out in
  6765. // the case that, say, 1 out of 20 candidates violate the restructions.)
  6766. llvm::erase_if(RepeatedSequenceLocs, CantGuaranteeValueAcrossCall);
  6767. // If the sequence doesn't have enough candidates left, then we're done.
  6768. if (RepeatedSequenceLocs.size() < 2)
  6769. return outliner::OutlinedFunction();
  6770. }
  6771. // At this point, we have only "safe" candidates to outline. Figure out
  6772. // frame + call instruction information.
  6773. unsigned LastInstrOpcode = RepeatedSequenceLocs[0].back()->getOpcode();
  6774. // Helper lambda which sets call information for every candidate.
  6775. auto SetCandidateCallInfo =
  6776. [&RepeatedSequenceLocs](unsigned CallID, unsigned NumBytesForCall) {
  6777. for (outliner::Candidate &C : RepeatedSequenceLocs)
  6778. C.setCallInfo(CallID, NumBytesForCall);
  6779. };
  6780. unsigned FrameID = MachineOutlinerDefault;
  6781. NumBytesToCreateFrame += 4;
  6782. bool HasBTI = any_of(RepeatedSequenceLocs, [](outliner::Candidate &C) {
  6783. return C.getMF()->getInfo<AArch64FunctionInfo>()->branchTargetEnforcement();
  6784. });
  6785. // We check to see if CFI Instructions are present, and if they are
  6786. // we find the number of CFI Instructions in the candidates.
  6787. unsigned CFICount = 0;
  6788. for (auto &I : make_range(RepeatedSequenceLocs[0].front(),
  6789. std::next(RepeatedSequenceLocs[0].back()))) {
  6790. if (I.isCFIInstruction())
  6791. CFICount++;
  6792. }
  6793. // We compare the number of found CFI Instructions to the number of CFI
  6794. // instructions in the parent function for each candidate. We must check this
  6795. // since if we outline one of the CFI instructions in a function, we have to
  6796. // outline them all for correctness. If we do not, the address offsets will be
  6797. // incorrect between the two sections of the program.
  6798. for (outliner::Candidate &C : RepeatedSequenceLocs) {
  6799. std::vector<MCCFIInstruction> CFIInstructions =
  6800. C.getMF()->getFrameInstructions();
  6801. if (CFICount > 0 && CFICount != CFIInstructions.size())
  6802. return outliner::OutlinedFunction();
  6803. }
  6804. // Returns true if an instructions is safe to fix up, false otherwise.
  6805. auto IsSafeToFixup = [this, &TRI](MachineInstr &MI) {
  6806. if (MI.isCall())
  6807. return true;
  6808. if (!MI.modifiesRegister(AArch64::SP, &TRI) &&
  6809. !MI.readsRegister(AArch64::SP, &TRI))
  6810. return true;
  6811. // Any modification of SP will break our code to save/restore LR.
  6812. // FIXME: We could handle some instructions which add a constant
  6813. // offset to SP, with a bit more work.
  6814. if (MI.modifiesRegister(AArch64::SP, &TRI))
  6815. return false;
  6816. // At this point, we have a stack instruction that we might need to
  6817. // fix up. We'll handle it if it's a load or store.
  6818. if (MI.mayLoadOrStore()) {
  6819. const MachineOperand *Base; // Filled with the base operand of MI.
  6820. int64_t Offset; // Filled with the offset of MI.
  6821. bool OffsetIsScalable;
  6822. // Does it allow us to offset the base operand and is the base the
  6823. // register SP?
  6824. if (!getMemOperandWithOffset(MI, Base, Offset, OffsetIsScalable, &TRI) ||
  6825. !Base->isReg() || Base->getReg() != AArch64::SP)
  6826. return false;
  6827. // Fixe-up code below assumes bytes.
  6828. if (OffsetIsScalable)
  6829. return false;
  6830. // Find the minimum/maximum offset for this instruction and check
  6831. // if fixing it up would be in range.
  6832. int64_t MinOffset,
  6833. MaxOffset; // Unscaled offsets for the instruction.
  6834. TypeSize Scale(0U, false); // The scale to multiply the offsets by.
  6835. unsigned DummyWidth;
  6836. getMemOpInfo(MI.getOpcode(), Scale, DummyWidth, MinOffset, MaxOffset);
  6837. Offset += 16; // Update the offset to what it would be if we outlined.
  6838. if (Offset < MinOffset * (int64_t)Scale.getFixedValue() ||
  6839. Offset > MaxOffset * (int64_t)Scale.getFixedValue())
  6840. return false;
  6841. // It's in range, so we can outline it.
  6842. return true;
  6843. }
  6844. // FIXME: Add handling for instructions like "add x0, sp, #8".
  6845. // We can't fix it up, so don't outline it.
  6846. return false;
  6847. };
  6848. // True if it's possible to fix up each stack instruction in this sequence.
  6849. // Important for frames/call variants that modify the stack.
  6850. bool AllStackInstrsSafe = std::all_of(
  6851. FirstCand.front(), std::next(FirstCand.back()), IsSafeToFixup);
  6852. // If the last instruction in any candidate is a terminator, then we should
  6853. // tail call all of the candidates.
  6854. if (RepeatedSequenceLocs[0].back()->isTerminator()) {
  6855. FrameID = MachineOutlinerTailCall;
  6856. NumBytesToCreateFrame = 0;
  6857. SetCandidateCallInfo(MachineOutlinerTailCall, 4);
  6858. }
  6859. else if (LastInstrOpcode == AArch64::BL ||
  6860. ((LastInstrOpcode == AArch64::BLR ||
  6861. LastInstrOpcode == AArch64::BLRNoIP) &&
  6862. !HasBTI)) {
  6863. // FIXME: Do we need to check if the code after this uses the value of LR?
  6864. FrameID = MachineOutlinerThunk;
  6865. NumBytesToCreateFrame = 0;
  6866. SetCandidateCallInfo(MachineOutlinerThunk, 4);
  6867. }
  6868. else {
  6869. // We need to decide how to emit calls + frames. We can always emit the same
  6870. // frame if we don't need to save to the stack. If we have to save to the
  6871. // stack, then we need a different frame.
  6872. unsigned NumBytesNoStackCalls = 0;
  6873. std::vector<outliner::Candidate> CandidatesWithoutStackFixups;
  6874. // Check if we have to save LR.
  6875. for (outliner::Candidate &C : RepeatedSequenceLocs) {
  6876. // If we have a noreturn caller, then we're going to be conservative and
  6877. // say that we have to save LR. If we don't have a ret at the end of the
  6878. // block, then we can't reason about liveness accurately.
  6879. //
  6880. // FIXME: We can probably do better than always disabling this in
  6881. // noreturn functions by fixing up the liveness info.
  6882. bool IsNoReturn =
  6883. C.getMF()->getFunction().hasFnAttribute(Attribute::NoReturn);
  6884. // Is LR available? If so, we don't need a save.
  6885. if (C.isAvailableAcrossAndOutOfSeq(AArch64::LR, TRI) && !IsNoReturn) {
  6886. NumBytesNoStackCalls += 4;
  6887. C.setCallInfo(MachineOutlinerNoLRSave, 4);
  6888. CandidatesWithoutStackFixups.push_back(C);
  6889. }
  6890. // Is an unused register available? If so, we won't modify the stack, so
  6891. // we can outline with the same frame type as those that don't save LR.
  6892. else if (findRegisterToSaveLRTo(C)) {
  6893. NumBytesNoStackCalls += 12;
  6894. C.setCallInfo(MachineOutlinerRegSave, 12);
  6895. CandidatesWithoutStackFixups.push_back(C);
  6896. }
  6897. // Is SP used in the sequence at all? If not, we don't have to modify
  6898. // the stack, so we are guaranteed to get the same frame.
  6899. else if (C.isAvailableInsideSeq(AArch64::SP, TRI)) {
  6900. NumBytesNoStackCalls += 12;
  6901. C.setCallInfo(MachineOutlinerDefault, 12);
  6902. CandidatesWithoutStackFixups.push_back(C);
  6903. }
  6904. // If we outline this, we need to modify the stack. Pretend we don't
  6905. // outline this by saving all of its bytes.
  6906. else {
  6907. NumBytesNoStackCalls += SequenceSize;
  6908. }
  6909. }
  6910. // If there are no places where we have to save LR, then note that we
  6911. // don't have to update the stack. Otherwise, give every candidate the
  6912. // default call type, as long as it's safe to do so.
  6913. if (!AllStackInstrsSafe ||
  6914. NumBytesNoStackCalls <= RepeatedSequenceLocs.size() * 12) {
  6915. RepeatedSequenceLocs = CandidatesWithoutStackFixups;
  6916. FrameID = MachineOutlinerNoLRSave;
  6917. } else {
  6918. SetCandidateCallInfo(MachineOutlinerDefault, 12);
  6919. // Bugzilla ID: 46767
  6920. // TODO: Check if fixing up the stack more than once is safe so we can
  6921. // outline these.
  6922. //
  6923. // An outline resulting in a caller that requires stack fixups at the
  6924. // callsite to a callee that also requires stack fixups can happen when
  6925. // there are no available registers at the candidate callsite for a
  6926. // candidate that itself also has calls.
  6927. //
  6928. // In other words if function_containing_sequence in the following pseudo
  6929. // assembly requires that we save LR at the point of the call, but there
  6930. // are no available registers: in this case we save using SP and as a
  6931. // result the SP offsets requires stack fixups by multiples of 16.
  6932. //
  6933. // function_containing_sequence:
  6934. // ...
  6935. // save LR to SP <- Requires stack instr fixups in OUTLINED_FUNCTION_N
  6936. // call OUTLINED_FUNCTION_N
  6937. // restore LR from SP
  6938. // ...
  6939. //
  6940. // OUTLINED_FUNCTION_N:
  6941. // save LR to SP <- Requires stack instr fixups in OUTLINED_FUNCTION_N
  6942. // ...
  6943. // bl foo
  6944. // restore LR from SP
  6945. // ret
  6946. //
  6947. // Because the code to handle more than one stack fixup does not
  6948. // currently have the proper checks for legality, these cases will assert
  6949. // in the AArch64 MachineOutliner. This is because the code to do this
  6950. // needs more hardening, testing, better checks that generated code is
  6951. // legal, etc and because it is only verified to handle a single pass of
  6952. // stack fixup.
  6953. //
  6954. // The assert happens in AArch64InstrInfo::buildOutlinedFrame to catch
  6955. // these cases until they are known to be handled. Bugzilla 46767 is
  6956. // referenced in comments at the assert site.
  6957. //
  6958. // To avoid asserting (or generating non-legal code on noassert builds)
  6959. // we remove all candidates which would need more than one stack fixup by
  6960. // pruning the cases where the candidate has calls while also having no
  6961. // available LR and having no available general purpose registers to copy
  6962. // LR to (ie one extra stack save/restore).
  6963. //
  6964. if (FlagsSetInAll & MachineOutlinerMBBFlags::HasCalls) {
  6965. erase_if(RepeatedSequenceLocs, [this, &TRI](outliner::Candidate &C) {
  6966. return (std::any_of(
  6967. C.front(), std::next(C.back()),
  6968. [](const MachineInstr &MI) { return MI.isCall(); })) &&
  6969. (!C.isAvailableAcrossAndOutOfSeq(AArch64::LR, TRI) ||
  6970. !findRegisterToSaveLRTo(C));
  6971. });
  6972. }
  6973. }
  6974. // If we dropped all of the candidates, bail out here.
  6975. if (RepeatedSequenceLocs.size() < 2) {
  6976. RepeatedSequenceLocs.clear();
  6977. return outliner::OutlinedFunction();
  6978. }
  6979. }
  6980. // Does every candidate's MBB contain a call? If so, then we might have a call
  6981. // in the range.
  6982. if (FlagsSetInAll & MachineOutlinerMBBFlags::HasCalls) {
  6983. // Check if the range contains a call. These require a save + restore of the
  6984. // link register.
  6985. bool ModStackToSaveLR = false;
  6986. if (std::any_of(FirstCand.front(), FirstCand.back(),
  6987. [](const MachineInstr &MI) { return MI.isCall(); }))
  6988. ModStackToSaveLR = true;
  6989. // Handle the last instruction separately. If this is a tail call, then the
  6990. // last instruction is a call. We don't want to save + restore in this case.
  6991. // However, it could be possible that the last instruction is a call without
  6992. // it being valid to tail call this sequence. We should consider this as
  6993. // well.
  6994. else if (FrameID != MachineOutlinerThunk &&
  6995. FrameID != MachineOutlinerTailCall && FirstCand.back()->isCall())
  6996. ModStackToSaveLR = true;
  6997. if (ModStackToSaveLR) {
  6998. // We can't fix up the stack. Bail out.
  6999. if (!AllStackInstrsSafe) {
  7000. RepeatedSequenceLocs.clear();
  7001. return outliner::OutlinedFunction();
  7002. }
  7003. // Save + restore LR.
  7004. NumBytesToCreateFrame += 8;
  7005. }
  7006. }
  7007. // If we have CFI instructions, we can only outline if the outlined section
  7008. // can be a tail call
  7009. if (FrameID != MachineOutlinerTailCall && CFICount > 0)
  7010. return outliner::OutlinedFunction();
  7011. return outliner::OutlinedFunction(RepeatedSequenceLocs, SequenceSize,
  7012. NumBytesToCreateFrame, FrameID);
  7013. }
  7014. bool AArch64InstrInfo::isFunctionSafeToOutlineFrom(
  7015. MachineFunction &MF, bool OutlineFromLinkOnceODRs) const {
  7016. const Function &F = MF.getFunction();
  7017. // Can F be deduplicated by the linker? If it can, don't outline from it.
  7018. if (!OutlineFromLinkOnceODRs && F.hasLinkOnceODRLinkage())
  7019. return false;
  7020. // Don't outline from functions with section markings; the program could
  7021. // expect that all the code is in the named section.
  7022. // FIXME: Allow outlining from multiple functions with the same section
  7023. // marking.
  7024. if (F.hasSection())
  7025. return false;
  7026. // Outlining from functions with redzones is unsafe since the outliner may
  7027. // modify the stack. Check if hasRedZone is true or unknown; if yes, don't
  7028. // outline from it.
  7029. AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
  7030. if (!AFI || AFI->hasRedZone().value_or(true))
  7031. return false;
  7032. // FIXME: Teach the outliner to generate/handle Windows unwind info.
  7033. if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI())
  7034. return false;
  7035. // It's safe to outline from MF.
  7036. return true;
  7037. }
  7038. bool AArch64InstrInfo::isMBBSafeToOutlineFrom(MachineBasicBlock &MBB,
  7039. unsigned &Flags) const {
  7040. if (!TargetInstrInfo::isMBBSafeToOutlineFrom(MBB, Flags))
  7041. return false;
  7042. // Check if LR is available through all of the MBB. If it's not, then set
  7043. // a flag.
  7044. assert(MBB.getParent()->getRegInfo().tracksLiveness() &&
  7045. "Suitable Machine Function for outlining must track liveness");
  7046. LiveRegUnits LRU(getRegisterInfo());
  7047. for (MachineInstr &MI : llvm::reverse(MBB))
  7048. LRU.accumulate(MI);
  7049. // Check if each of the unsafe registers are available...
  7050. bool W16AvailableInBlock = LRU.available(AArch64::W16);
  7051. bool W17AvailableInBlock = LRU.available(AArch64::W17);
  7052. bool NZCVAvailableInBlock = LRU.available(AArch64::NZCV);
  7053. // If all of these are dead (and not live out), we know we don't have to check
  7054. // them later.
  7055. if (W16AvailableInBlock && W17AvailableInBlock && NZCVAvailableInBlock)
  7056. Flags |= MachineOutlinerMBBFlags::UnsafeRegsDead;
  7057. // Now, add the live outs to the set.
  7058. LRU.addLiveOuts(MBB);
  7059. // If any of these registers is available in the MBB, but also a live out of
  7060. // the block, then we know outlining is unsafe.
  7061. if (W16AvailableInBlock && !LRU.available(AArch64::W16))
  7062. return false;
  7063. if (W17AvailableInBlock && !LRU.available(AArch64::W17))
  7064. return false;
  7065. if (NZCVAvailableInBlock && !LRU.available(AArch64::NZCV))
  7066. return false;
  7067. // Check if there's a call inside this MachineBasicBlock. If there is, then
  7068. // set a flag.
  7069. if (any_of(MBB, [](MachineInstr &MI) { return MI.isCall(); }))
  7070. Flags |= MachineOutlinerMBBFlags::HasCalls;
  7071. MachineFunction *MF = MBB.getParent();
  7072. // In the event that we outline, we may have to save LR. If there is an
  7073. // available register in the MBB, then we'll always save LR there. Check if
  7074. // this is true.
  7075. bool CanSaveLR = false;
  7076. const AArch64RegisterInfo *ARI = static_cast<const AArch64RegisterInfo *>(
  7077. MF->getSubtarget().getRegisterInfo());
  7078. // Check if there is an available register across the sequence that we can
  7079. // use.
  7080. for (unsigned Reg : AArch64::GPR64RegClass) {
  7081. if (!ARI->isReservedReg(*MF, Reg) && Reg != AArch64::LR &&
  7082. Reg != AArch64::X16 && Reg != AArch64::X17 && LRU.available(Reg)) {
  7083. CanSaveLR = true;
  7084. break;
  7085. }
  7086. }
  7087. // Check if we have a register we can save LR to, and if LR was used
  7088. // somewhere. If both of those things are true, then we need to evaluate the
  7089. // safety of outlining stack instructions later.
  7090. if (!CanSaveLR && !LRU.available(AArch64::LR))
  7091. Flags |= MachineOutlinerMBBFlags::LRUnavailableSomewhere;
  7092. return true;
  7093. }
  7094. outliner::InstrType
  7095. AArch64InstrInfo::getOutliningType(MachineBasicBlock::iterator &MIT,
  7096. unsigned Flags) const {
  7097. MachineInstr &MI = *MIT;
  7098. MachineBasicBlock *MBB = MI.getParent();
  7099. MachineFunction *MF = MBB->getParent();
  7100. AArch64FunctionInfo *FuncInfo = MF->getInfo<AArch64FunctionInfo>();
  7101. // Don't outline anything used for return address signing. The outlined
  7102. // function will get signed later if needed
  7103. switch (MI.getOpcode()) {
  7104. case AArch64::PACIASP:
  7105. case AArch64::PACIBSP:
  7106. case AArch64::AUTIASP:
  7107. case AArch64::AUTIBSP:
  7108. case AArch64::RETAA:
  7109. case AArch64::RETAB:
  7110. case AArch64::EMITBKEY:
  7111. return outliner::InstrType::Illegal;
  7112. }
  7113. // Don't outline LOHs.
  7114. if (FuncInfo->getLOHRelated().count(&MI))
  7115. return outliner::InstrType::Illegal;
  7116. // We can only outline these if we will tail call the outlined function, or
  7117. // fix up the CFI offsets. Currently, CFI instructions are outlined only if
  7118. // in a tail call.
  7119. //
  7120. // FIXME: If the proper fixups for the offset are implemented, this should be
  7121. // possible.
  7122. if (MI.isCFIInstruction())
  7123. return outliner::InstrType::Legal;
  7124. // Don't allow debug values to impact outlining type.
  7125. if (MI.isDebugInstr() || MI.isIndirectDebugValue())
  7126. return outliner::InstrType::Invisible;
  7127. // At this point, KILL instructions don't really tell us much so we can go
  7128. // ahead and skip over them.
  7129. if (MI.isKill())
  7130. return outliner::InstrType::Invisible;
  7131. // Is this a terminator for a basic block?
  7132. if (MI.isTerminator()) {
  7133. // Is this the end of a function?
  7134. if (MI.getParent()->succ_empty())
  7135. return outliner::InstrType::Legal;
  7136. // It's not, so don't outline it.
  7137. return outliner::InstrType::Illegal;
  7138. }
  7139. // Make sure none of the operands are un-outlinable.
  7140. for (const MachineOperand &MOP : MI.operands()) {
  7141. if (MOP.isCPI() || MOP.isJTI() || MOP.isCFIIndex() || MOP.isFI() ||
  7142. MOP.isTargetIndex())
  7143. return outliner::InstrType::Illegal;
  7144. // If it uses LR or W30 explicitly, then don't touch it.
  7145. if (MOP.isReg() && !MOP.isImplicit() &&
  7146. (MOP.getReg() == AArch64::LR || MOP.getReg() == AArch64::W30))
  7147. return outliner::InstrType::Illegal;
  7148. }
  7149. // Special cases for instructions that can always be outlined, but will fail
  7150. // the later tests. e.g, ADRPs, which are PC-relative use LR, but can always
  7151. // be outlined because they don't require a *specific* value to be in LR.
  7152. if (MI.getOpcode() == AArch64::ADRP)
  7153. return outliner::InstrType::Legal;
  7154. // If MI is a call we might be able to outline it. We don't want to outline
  7155. // any calls that rely on the position of items on the stack. When we outline
  7156. // something containing a call, we have to emit a save and restore of LR in
  7157. // the outlined function. Currently, this always happens by saving LR to the
  7158. // stack. Thus, if we outline, say, half the parameters for a function call
  7159. // plus the call, then we'll break the callee's expectations for the layout
  7160. // of the stack.
  7161. //
  7162. // FIXME: Allow calls to functions which construct a stack frame, as long
  7163. // as they don't access arguments on the stack.
  7164. // FIXME: Figure out some way to analyze functions defined in other modules.
  7165. // We should be able to compute the memory usage based on the IR calling
  7166. // convention, even if we can't see the definition.
  7167. if (MI.isCall()) {
  7168. // Get the function associated with the call. Look at each operand and find
  7169. // the one that represents the callee and get its name.
  7170. const Function *Callee = nullptr;
  7171. for (const MachineOperand &MOP : MI.operands()) {
  7172. if (MOP.isGlobal()) {
  7173. Callee = dyn_cast<Function>(MOP.getGlobal());
  7174. break;
  7175. }
  7176. }
  7177. // Never outline calls to mcount. There isn't any rule that would require
  7178. // this, but the Linux kernel's "ftrace" feature depends on it.
  7179. if (Callee && Callee->getName() == "\01_mcount")
  7180. return outliner::InstrType::Illegal;
  7181. // If we don't know anything about the callee, assume it depends on the
  7182. // stack layout of the caller. In that case, it's only legal to outline
  7183. // as a tail-call. Explicitly list the call instructions we know about so we
  7184. // don't get unexpected results with call pseudo-instructions.
  7185. auto UnknownCallOutlineType = outliner::InstrType::Illegal;
  7186. if (MI.getOpcode() == AArch64::BLR ||
  7187. MI.getOpcode() == AArch64::BLRNoIP || MI.getOpcode() == AArch64::BL)
  7188. UnknownCallOutlineType = outliner::InstrType::LegalTerminator;
  7189. if (!Callee)
  7190. return UnknownCallOutlineType;
  7191. // We have a function we have information about. Check it if it's something
  7192. // can safely outline.
  7193. MachineFunction *CalleeMF = MF->getMMI().getMachineFunction(*Callee);
  7194. // We don't know what's going on with the callee at all. Don't touch it.
  7195. if (!CalleeMF)
  7196. return UnknownCallOutlineType;
  7197. // Check if we know anything about the callee saves on the function. If we
  7198. // don't, then don't touch it, since that implies that we haven't
  7199. // computed anything about its stack frame yet.
  7200. MachineFrameInfo &MFI = CalleeMF->getFrameInfo();
  7201. if (!MFI.isCalleeSavedInfoValid() || MFI.getStackSize() > 0 ||
  7202. MFI.getNumObjects() > 0)
  7203. return UnknownCallOutlineType;
  7204. // At this point, we can say that CalleeMF ought to not pass anything on the
  7205. // stack. Therefore, we can outline it.
  7206. return outliner::InstrType::Legal;
  7207. }
  7208. // Don't outline positions.
  7209. if (MI.isPosition())
  7210. return outliner::InstrType::Illegal;
  7211. // Don't touch the link register or W30.
  7212. if (MI.readsRegister(AArch64::W30, &getRegisterInfo()) ||
  7213. MI.modifiesRegister(AArch64::W30, &getRegisterInfo()))
  7214. return outliner::InstrType::Illegal;
  7215. // Don't outline BTI instructions, because that will prevent the outlining
  7216. // site from being indirectly callable.
  7217. if (MI.getOpcode() == AArch64::HINT) {
  7218. int64_t Imm = MI.getOperand(0).getImm();
  7219. if (Imm == 32 || Imm == 34 || Imm == 36 || Imm == 38)
  7220. return outliner::InstrType::Illegal;
  7221. }
  7222. return outliner::InstrType::Legal;
  7223. }
  7224. void AArch64InstrInfo::fixupPostOutline(MachineBasicBlock &MBB) const {
  7225. for (MachineInstr &MI : MBB) {
  7226. const MachineOperand *Base;
  7227. unsigned Width;
  7228. int64_t Offset;
  7229. bool OffsetIsScalable;
  7230. // Is this a load or store with an immediate offset with SP as the base?
  7231. if (!MI.mayLoadOrStore() ||
  7232. !getMemOperandWithOffsetWidth(MI, Base, Offset, OffsetIsScalable, Width,
  7233. &RI) ||
  7234. (Base->isReg() && Base->getReg() != AArch64::SP))
  7235. continue;
  7236. // It is, so we have to fix it up.
  7237. TypeSize Scale(0U, false);
  7238. int64_t Dummy1, Dummy2;
  7239. MachineOperand &StackOffsetOperand = getMemOpBaseRegImmOfsOffsetOperand(MI);
  7240. assert(StackOffsetOperand.isImm() && "Stack offset wasn't immediate!");
  7241. getMemOpInfo(MI.getOpcode(), Scale, Width, Dummy1, Dummy2);
  7242. assert(Scale != 0 && "Unexpected opcode!");
  7243. assert(!OffsetIsScalable && "Expected offset to be a byte offset");
  7244. // We've pushed the return address to the stack, so add 16 to the offset.
  7245. // This is safe, since we already checked if it would overflow when we
  7246. // checked if this instruction was legal to outline.
  7247. int64_t NewImm = (Offset + 16) / (int64_t)Scale.getFixedValue();
  7248. StackOffsetOperand.setImm(NewImm);
  7249. }
  7250. }
  7251. static void signOutlinedFunction(MachineFunction &MF, MachineBasicBlock &MBB,
  7252. bool ShouldSignReturnAddr,
  7253. bool ShouldSignReturnAddrWithBKey) {
  7254. if (ShouldSignReturnAddr) {
  7255. MachineBasicBlock::iterator MBBPAC = MBB.begin();
  7256. MachineBasicBlock::iterator MBBAUT = MBB.getFirstTerminator();
  7257. const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
  7258. const TargetInstrInfo *TII = Subtarget.getInstrInfo();
  7259. DebugLoc DL;
  7260. if (MBBAUT != MBB.end())
  7261. DL = MBBAUT->getDebugLoc();
  7262. // At the very beginning of the basic block we insert the following
  7263. // depending on the key type
  7264. //
  7265. // a_key: b_key:
  7266. // PACIASP EMITBKEY
  7267. // CFI_INSTRUCTION PACIBSP
  7268. // CFI_INSTRUCTION
  7269. if (ShouldSignReturnAddrWithBKey) {
  7270. BuildMI(MBB, MBBPAC, DebugLoc(), TII->get(AArch64::EMITBKEY))
  7271. .setMIFlag(MachineInstr::FrameSetup);
  7272. }
  7273. BuildMI(MBB, MBBPAC, DebugLoc(),
  7274. TII->get(ShouldSignReturnAddrWithBKey ? AArch64::PACIBSP
  7275. : AArch64::PACIASP))
  7276. .setMIFlag(MachineInstr::FrameSetup);
  7277. if (MF.getInfo<AArch64FunctionInfo>()->needsDwarfUnwindInfo(MF)) {
  7278. unsigned CFIIndex =
  7279. MF.addFrameInst(MCCFIInstruction::createNegateRAState(nullptr));
  7280. BuildMI(MBB, MBBPAC, DebugLoc(), TII->get(AArch64::CFI_INSTRUCTION))
  7281. .addCFIIndex(CFIIndex)
  7282. .setMIFlags(MachineInstr::FrameSetup);
  7283. }
  7284. // If v8.3a features are available we can replace a RET instruction by
  7285. // RETAA or RETAB and omit the AUT instructions. In this case the
  7286. // DW_CFA_AARCH64_negate_ra_state can't be emitted.
  7287. if (Subtarget.hasPAuth() && MBBAUT != MBB.end() &&
  7288. MBBAUT->getOpcode() == AArch64::RET) {
  7289. BuildMI(MBB, MBBAUT, DL,
  7290. TII->get(ShouldSignReturnAddrWithBKey ? AArch64::RETAB
  7291. : AArch64::RETAA))
  7292. .copyImplicitOps(*MBBAUT);
  7293. MBB.erase(MBBAUT);
  7294. } else {
  7295. BuildMI(MBB, MBBAUT, DL,
  7296. TII->get(ShouldSignReturnAddrWithBKey ? AArch64::AUTIBSP
  7297. : AArch64::AUTIASP))
  7298. .setMIFlag(MachineInstr::FrameDestroy);
  7299. unsigned CFIIndexAuth =
  7300. MF.addFrameInst(MCCFIInstruction::createNegateRAState(nullptr));
  7301. BuildMI(MBB, MBBAUT, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
  7302. .addCFIIndex(CFIIndexAuth)
  7303. .setMIFlags(MachineInstr::FrameDestroy);
  7304. }
  7305. }
  7306. }
  7307. void AArch64InstrInfo::buildOutlinedFrame(
  7308. MachineBasicBlock &MBB, MachineFunction &MF,
  7309. const outliner::OutlinedFunction &OF) const {
  7310. AArch64FunctionInfo *FI = MF.getInfo<AArch64FunctionInfo>();
  7311. if (OF.FrameConstructionID == MachineOutlinerTailCall)
  7312. FI->setOutliningStyle("Tail Call");
  7313. else if (OF.FrameConstructionID == MachineOutlinerThunk) {
  7314. // For thunk outlining, rewrite the last instruction from a call to a
  7315. // tail-call.
  7316. MachineInstr *Call = &*--MBB.instr_end();
  7317. unsigned TailOpcode;
  7318. if (Call->getOpcode() == AArch64::BL) {
  7319. TailOpcode = AArch64::TCRETURNdi;
  7320. } else {
  7321. assert(Call->getOpcode() == AArch64::BLR ||
  7322. Call->getOpcode() == AArch64::BLRNoIP);
  7323. TailOpcode = AArch64::TCRETURNriALL;
  7324. }
  7325. MachineInstr *TC = BuildMI(MF, DebugLoc(), get(TailOpcode))
  7326. .add(Call->getOperand(0))
  7327. .addImm(0);
  7328. MBB.insert(MBB.end(), TC);
  7329. Call->eraseFromParent();
  7330. FI->setOutliningStyle("Thunk");
  7331. }
  7332. bool IsLeafFunction = true;
  7333. // Is there a call in the outlined range?
  7334. auto IsNonTailCall = [](const MachineInstr &MI) {
  7335. return MI.isCall() && !MI.isReturn();
  7336. };
  7337. if (llvm::any_of(MBB.instrs(), IsNonTailCall)) {
  7338. // Fix up the instructions in the range, since we're going to modify the
  7339. // stack.
  7340. // Bugzilla ID: 46767
  7341. // TODO: Check if fixing up twice is safe so we can outline these.
  7342. assert(OF.FrameConstructionID != MachineOutlinerDefault &&
  7343. "Can only fix up stack references once");
  7344. fixupPostOutline(MBB);
  7345. IsLeafFunction = false;
  7346. // LR has to be a live in so that we can save it.
  7347. if (!MBB.isLiveIn(AArch64::LR))
  7348. MBB.addLiveIn(AArch64::LR);
  7349. MachineBasicBlock::iterator It = MBB.begin();
  7350. MachineBasicBlock::iterator Et = MBB.end();
  7351. if (OF.FrameConstructionID == MachineOutlinerTailCall ||
  7352. OF.FrameConstructionID == MachineOutlinerThunk)
  7353. Et = std::prev(MBB.end());
  7354. // Insert a save before the outlined region
  7355. MachineInstr *STRXpre = BuildMI(MF, DebugLoc(), get(AArch64::STRXpre))
  7356. .addReg(AArch64::SP, RegState::Define)
  7357. .addReg(AArch64::LR)
  7358. .addReg(AArch64::SP)
  7359. .addImm(-16);
  7360. It = MBB.insert(It, STRXpre);
  7361. if (MF.getInfo<AArch64FunctionInfo>()->needsDwarfUnwindInfo(MF)) {
  7362. const TargetSubtargetInfo &STI = MF.getSubtarget();
  7363. const MCRegisterInfo *MRI = STI.getRegisterInfo();
  7364. unsigned DwarfReg = MRI->getDwarfRegNum(AArch64::LR, true);
  7365. // Add a CFI saying the stack was moved 16 B down.
  7366. int64_t StackPosEntry =
  7367. MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, 16));
  7368. BuildMI(MBB, It, DebugLoc(), get(AArch64::CFI_INSTRUCTION))
  7369. .addCFIIndex(StackPosEntry)
  7370. .setMIFlags(MachineInstr::FrameSetup);
  7371. // Add a CFI saying that the LR that we want to find is now 16 B higher
  7372. // than before.
  7373. int64_t LRPosEntry = MF.addFrameInst(
  7374. MCCFIInstruction::createOffset(nullptr, DwarfReg, -16));
  7375. BuildMI(MBB, It, DebugLoc(), get(AArch64::CFI_INSTRUCTION))
  7376. .addCFIIndex(LRPosEntry)
  7377. .setMIFlags(MachineInstr::FrameSetup);
  7378. }
  7379. // Insert a restore before the terminator for the function.
  7380. MachineInstr *LDRXpost = BuildMI(MF, DebugLoc(), get(AArch64::LDRXpost))
  7381. .addReg(AArch64::SP, RegState::Define)
  7382. .addReg(AArch64::LR, RegState::Define)
  7383. .addReg(AArch64::SP)
  7384. .addImm(16);
  7385. Et = MBB.insert(Et, LDRXpost);
  7386. }
  7387. // If a bunch of candidates reach this point they must agree on their return
  7388. // address signing. It is therefore enough to just consider the signing
  7389. // behaviour of one of them
  7390. const auto &MFI = *OF.Candidates.front().getMF()->getInfo<AArch64FunctionInfo>();
  7391. bool ShouldSignReturnAddr = MFI.shouldSignReturnAddress(!IsLeafFunction);
  7392. // a_key is the default
  7393. bool ShouldSignReturnAddrWithBKey = MFI.shouldSignWithBKey();
  7394. // If this is a tail call outlined function, then there's already a return.
  7395. if (OF.FrameConstructionID == MachineOutlinerTailCall ||
  7396. OF.FrameConstructionID == MachineOutlinerThunk) {
  7397. signOutlinedFunction(MF, MBB, ShouldSignReturnAddr,
  7398. ShouldSignReturnAddrWithBKey);
  7399. return;
  7400. }
  7401. // It's not a tail call, so we have to insert the return ourselves.
  7402. // LR has to be a live in so that we can return to it.
  7403. if (!MBB.isLiveIn(AArch64::LR))
  7404. MBB.addLiveIn(AArch64::LR);
  7405. MachineInstr *ret = BuildMI(MF, DebugLoc(), get(AArch64::RET))
  7406. .addReg(AArch64::LR);
  7407. MBB.insert(MBB.end(), ret);
  7408. signOutlinedFunction(MF, MBB, ShouldSignReturnAddr,
  7409. ShouldSignReturnAddrWithBKey);
  7410. FI->setOutliningStyle("Function");
  7411. // Did we have to modify the stack by saving the link register?
  7412. if (OF.FrameConstructionID != MachineOutlinerDefault)
  7413. return;
  7414. // We modified the stack.
  7415. // Walk over the basic block and fix up all the stack accesses.
  7416. fixupPostOutline(MBB);
  7417. }
  7418. MachineBasicBlock::iterator AArch64InstrInfo::insertOutlinedCall(
  7419. Module &M, MachineBasicBlock &MBB, MachineBasicBlock::iterator &It,
  7420. MachineFunction &MF, outliner::Candidate &C) const {
  7421. // Are we tail calling?
  7422. if (C.CallConstructionID == MachineOutlinerTailCall) {
  7423. // If yes, then we can just branch to the label.
  7424. It = MBB.insert(It, BuildMI(MF, DebugLoc(), get(AArch64::TCRETURNdi))
  7425. .addGlobalAddress(M.getNamedValue(MF.getName()))
  7426. .addImm(0));
  7427. return It;
  7428. }
  7429. // Are we saving the link register?
  7430. if (C.CallConstructionID == MachineOutlinerNoLRSave ||
  7431. C.CallConstructionID == MachineOutlinerThunk) {
  7432. // No, so just insert the call.
  7433. It = MBB.insert(It, BuildMI(MF, DebugLoc(), get(AArch64::BL))
  7434. .addGlobalAddress(M.getNamedValue(MF.getName())));
  7435. return It;
  7436. }
  7437. // We want to return the spot where we inserted the call.
  7438. MachineBasicBlock::iterator CallPt;
  7439. // Instructions for saving and restoring LR around the call instruction we're
  7440. // going to insert.
  7441. MachineInstr *Save;
  7442. MachineInstr *Restore;
  7443. // Can we save to a register?
  7444. if (C.CallConstructionID == MachineOutlinerRegSave) {
  7445. // FIXME: This logic should be sunk into a target-specific interface so that
  7446. // we don't have to recompute the register.
  7447. Register Reg = findRegisterToSaveLRTo(C);
  7448. assert(Reg && "No callee-saved register available?");
  7449. // LR has to be a live in so that we can save it.
  7450. if (!MBB.isLiveIn(AArch64::LR))
  7451. MBB.addLiveIn(AArch64::LR);
  7452. // Save and restore LR from Reg.
  7453. Save = BuildMI(MF, DebugLoc(), get(AArch64::ORRXrs), Reg)
  7454. .addReg(AArch64::XZR)
  7455. .addReg(AArch64::LR)
  7456. .addImm(0);
  7457. Restore = BuildMI(MF, DebugLoc(), get(AArch64::ORRXrs), AArch64::LR)
  7458. .addReg(AArch64::XZR)
  7459. .addReg(Reg)
  7460. .addImm(0);
  7461. } else {
  7462. // We have the default case. Save and restore from SP.
  7463. Save = BuildMI(MF, DebugLoc(), get(AArch64::STRXpre))
  7464. .addReg(AArch64::SP, RegState::Define)
  7465. .addReg(AArch64::LR)
  7466. .addReg(AArch64::SP)
  7467. .addImm(-16);
  7468. Restore = BuildMI(MF, DebugLoc(), get(AArch64::LDRXpost))
  7469. .addReg(AArch64::SP, RegState::Define)
  7470. .addReg(AArch64::LR, RegState::Define)
  7471. .addReg(AArch64::SP)
  7472. .addImm(16);
  7473. }
  7474. It = MBB.insert(It, Save);
  7475. It++;
  7476. // Insert the call.
  7477. It = MBB.insert(It, BuildMI(MF, DebugLoc(), get(AArch64::BL))
  7478. .addGlobalAddress(M.getNamedValue(MF.getName())));
  7479. CallPt = It;
  7480. It++;
  7481. It = MBB.insert(It, Restore);
  7482. return CallPt;
  7483. }
  7484. bool AArch64InstrInfo::shouldOutlineFromFunctionByDefault(
  7485. MachineFunction &MF) const {
  7486. return MF.getFunction().hasMinSize();
  7487. }
  7488. std::optional<DestSourcePair>
  7489. AArch64InstrInfo::isCopyInstrImpl(const MachineInstr &MI) const {
  7490. // AArch64::ORRWrs and AArch64::ORRXrs with WZR/XZR reg
  7491. // and zero immediate operands used as an alias for mov instruction.
  7492. if (MI.getOpcode() == AArch64::ORRWrs &&
  7493. MI.getOperand(1).getReg() == AArch64::WZR &&
  7494. MI.getOperand(3).getImm() == 0x0) {
  7495. return DestSourcePair{MI.getOperand(0), MI.getOperand(2)};
  7496. }
  7497. if (MI.getOpcode() == AArch64::ORRXrs &&
  7498. MI.getOperand(1).getReg() == AArch64::XZR &&
  7499. MI.getOperand(3).getImm() == 0x0) {
  7500. return DestSourcePair{MI.getOperand(0), MI.getOperand(2)};
  7501. }
  7502. return std::nullopt;
  7503. }
  7504. std::optional<RegImmPair>
  7505. AArch64InstrInfo::isAddImmediate(const MachineInstr &MI, Register Reg) const {
  7506. int Sign = 1;
  7507. int64_t Offset = 0;
  7508. // TODO: Handle cases where Reg is a super- or sub-register of the
  7509. // destination register.
  7510. const MachineOperand &Op0 = MI.getOperand(0);
  7511. if (!Op0.isReg() || Reg != Op0.getReg())
  7512. return std::nullopt;
  7513. switch (MI.getOpcode()) {
  7514. default:
  7515. return std::nullopt;
  7516. case AArch64::SUBWri:
  7517. case AArch64::SUBXri:
  7518. case AArch64::SUBSWri:
  7519. case AArch64::SUBSXri:
  7520. Sign *= -1;
  7521. [[fallthrough]];
  7522. case AArch64::ADDSWri:
  7523. case AArch64::ADDSXri:
  7524. case AArch64::ADDWri:
  7525. case AArch64::ADDXri: {
  7526. // TODO: Third operand can be global address (usually some string).
  7527. if (!MI.getOperand(0).isReg() || !MI.getOperand(1).isReg() ||
  7528. !MI.getOperand(2).isImm())
  7529. return std::nullopt;
  7530. int Shift = MI.getOperand(3).getImm();
  7531. assert((Shift == 0 || Shift == 12) && "Shift can be either 0 or 12");
  7532. Offset = Sign * (MI.getOperand(2).getImm() << Shift);
  7533. }
  7534. }
  7535. return RegImmPair{MI.getOperand(1).getReg(), Offset};
  7536. }
  7537. /// If the given ORR instruction is a copy, and \p DescribedReg overlaps with
  7538. /// the destination register then, if possible, describe the value in terms of
  7539. /// the source register.
  7540. static std::optional<ParamLoadedValue>
  7541. describeORRLoadedValue(const MachineInstr &MI, Register DescribedReg,
  7542. const TargetInstrInfo *TII,
  7543. const TargetRegisterInfo *TRI) {
  7544. auto DestSrc = TII->isCopyInstr(MI);
  7545. if (!DestSrc)
  7546. return std::nullopt;
  7547. Register DestReg = DestSrc->Destination->getReg();
  7548. Register SrcReg = DestSrc->Source->getReg();
  7549. auto Expr = DIExpression::get(MI.getMF()->getFunction().getContext(), {});
  7550. // If the described register is the destination, just return the source.
  7551. if (DestReg == DescribedReg)
  7552. return ParamLoadedValue(MachineOperand::CreateReg(SrcReg, false), Expr);
  7553. // ORRWrs zero-extends to 64-bits, so we need to consider such cases.
  7554. if (MI.getOpcode() == AArch64::ORRWrs &&
  7555. TRI->isSuperRegister(DestReg, DescribedReg))
  7556. return ParamLoadedValue(MachineOperand::CreateReg(SrcReg, false), Expr);
  7557. // We may need to describe the lower part of a ORRXrs move.
  7558. if (MI.getOpcode() == AArch64::ORRXrs &&
  7559. TRI->isSubRegister(DestReg, DescribedReg)) {
  7560. Register SrcSubReg = TRI->getSubReg(SrcReg, AArch64::sub_32);
  7561. return ParamLoadedValue(MachineOperand::CreateReg(SrcSubReg, false), Expr);
  7562. }
  7563. assert(!TRI->isSuperOrSubRegisterEq(DestReg, DescribedReg) &&
  7564. "Unhandled ORR[XW]rs copy case");
  7565. return std::nullopt;
  7566. }
  7567. std::optional<ParamLoadedValue>
  7568. AArch64InstrInfo::describeLoadedValue(const MachineInstr &MI,
  7569. Register Reg) const {
  7570. const MachineFunction *MF = MI.getMF();
  7571. const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
  7572. switch (MI.getOpcode()) {
  7573. case AArch64::MOVZWi:
  7574. case AArch64::MOVZXi: {
  7575. // MOVZWi may be used for producing zero-extended 32-bit immediates in
  7576. // 64-bit parameters, so we need to consider super-registers.
  7577. if (!TRI->isSuperRegisterEq(MI.getOperand(0).getReg(), Reg))
  7578. return std::nullopt;
  7579. if (!MI.getOperand(1).isImm())
  7580. return std::nullopt;
  7581. int64_t Immediate = MI.getOperand(1).getImm();
  7582. int Shift = MI.getOperand(2).getImm();
  7583. return ParamLoadedValue(MachineOperand::CreateImm(Immediate << Shift),
  7584. nullptr);
  7585. }
  7586. case AArch64::ORRWrs:
  7587. case AArch64::ORRXrs:
  7588. return describeORRLoadedValue(MI, Reg, this, TRI);
  7589. }
  7590. return TargetInstrInfo::describeLoadedValue(MI, Reg);
  7591. }
  7592. bool AArch64InstrInfo::isExtendLikelyToBeFolded(
  7593. MachineInstr &ExtMI, MachineRegisterInfo &MRI) const {
  7594. assert(ExtMI.getOpcode() == TargetOpcode::G_SEXT ||
  7595. ExtMI.getOpcode() == TargetOpcode::G_ZEXT ||
  7596. ExtMI.getOpcode() == TargetOpcode::G_ANYEXT);
  7597. // Anyexts are nops.
  7598. if (ExtMI.getOpcode() == TargetOpcode::G_ANYEXT)
  7599. return true;
  7600. Register DefReg = ExtMI.getOperand(0).getReg();
  7601. if (!MRI.hasOneNonDBGUse(DefReg))
  7602. return false;
  7603. // It's likely that a sext/zext as a G_PTR_ADD offset will be folded into an
  7604. // addressing mode.
  7605. auto *UserMI = &*MRI.use_instr_nodbg_begin(DefReg);
  7606. return UserMI->getOpcode() == TargetOpcode::G_PTR_ADD;
  7607. }
  7608. uint64_t AArch64InstrInfo::getElementSizeForOpcode(unsigned Opc) const {
  7609. return get(Opc).TSFlags & AArch64::ElementSizeMask;
  7610. }
  7611. bool AArch64InstrInfo::isPTestLikeOpcode(unsigned Opc) const {
  7612. return get(Opc).TSFlags & AArch64::InstrFlagIsPTestLike;
  7613. }
  7614. bool AArch64InstrInfo::isWhileOpcode(unsigned Opc) const {
  7615. return get(Opc).TSFlags & AArch64::InstrFlagIsWhile;
  7616. }
  7617. unsigned int
  7618. AArch64InstrInfo::getTailDuplicateSize(CodeGenOpt::Level OptLevel) const {
  7619. return OptLevel >= CodeGenOpt::Aggressive ? 6 : 2;
  7620. }
  7621. unsigned llvm::getBLRCallOpcode(const MachineFunction &MF) {
  7622. if (MF.getSubtarget<AArch64Subtarget>().hardenSlsBlr())
  7623. return AArch64::BLRNoIP;
  7624. else
  7625. return AArch64::BLR;
  7626. }
  7627. #define GET_INSTRINFO_HELPERS
  7628. #define GET_INSTRMAP_INFO
  7629. #include "AArch64GenInstrInfo.inc"