AArch64InstructionSelector.cpp 255 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960
  1. //===- AArch64InstructionSelector.cpp ----------------------------*- C++ -*-==//
  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. /// \file
  9. /// This file implements the targeting of the InstructionSelector class for
  10. /// AArch64.
  11. /// \todo This should be generated by TableGen.
  12. //===----------------------------------------------------------------------===//
  13. #include "AArch64GlobalISelUtils.h"
  14. #include "AArch64InstrInfo.h"
  15. #include "AArch64MachineFunctionInfo.h"
  16. #include "AArch64RegisterBankInfo.h"
  17. #include "AArch64RegisterInfo.h"
  18. #include "AArch64Subtarget.h"
  19. #include "AArch64TargetMachine.h"
  20. #include "MCTargetDesc/AArch64AddressingModes.h"
  21. #include "MCTargetDesc/AArch64MCTargetDesc.h"
  22. #include "llvm/BinaryFormat/Dwarf.h"
  23. #include "llvm/CodeGen/GlobalISel/GenericMachineInstrs.h"
  24. #include "llvm/CodeGen/GlobalISel/InstructionSelector.h"
  25. #include "llvm/CodeGen/GlobalISel/InstructionSelectorImpl.h"
  26. #include "llvm/CodeGen/GlobalISel/MIPatternMatch.h"
  27. #include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h"
  28. #include "llvm/CodeGen/GlobalISel/Utils.h"
  29. #include "llvm/CodeGen/MachineBasicBlock.h"
  30. #include "llvm/CodeGen/MachineConstantPool.h"
  31. #include "llvm/CodeGen/MachineFrameInfo.h"
  32. #include "llvm/CodeGen/MachineFunction.h"
  33. #include "llvm/CodeGen/MachineInstr.h"
  34. #include "llvm/CodeGen/MachineInstrBuilder.h"
  35. #include "llvm/CodeGen/MachineMemOperand.h"
  36. #include "llvm/CodeGen/MachineOperand.h"
  37. #include "llvm/CodeGen/MachineRegisterInfo.h"
  38. #include "llvm/CodeGen/TargetOpcodes.h"
  39. #include "llvm/IR/Constants.h"
  40. #include "llvm/IR/DerivedTypes.h"
  41. #include "llvm/IR/Instructions.h"
  42. #include "llvm/IR/IntrinsicsAArch64.h"
  43. #include "llvm/IR/PatternMatch.h"
  44. #include "llvm/IR/Type.h"
  45. #include "llvm/Pass.h"
  46. #include "llvm/Support/Debug.h"
  47. #include "llvm/Support/raw_ostream.h"
  48. #include <optional>
  49. #define DEBUG_TYPE "aarch64-isel"
  50. using namespace llvm;
  51. using namespace MIPatternMatch;
  52. using namespace AArch64GISelUtils;
  53. namespace llvm {
  54. class BlockFrequencyInfo;
  55. class ProfileSummaryInfo;
  56. }
  57. namespace {
  58. #define GET_GLOBALISEL_PREDICATE_BITSET
  59. #include "AArch64GenGlobalISel.inc"
  60. #undef GET_GLOBALISEL_PREDICATE_BITSET
  61. class AArch64InstructionSelector : public InstructionSelector {
  62. public:
  63. AArch64InstructionSelector(const AArch64TargetMachine &TM,
  64. const AArch64Subtarget &STI,
  65. const AArch64RegisterBankInfo &RBI);
  66. bool select(MachineInstr &I) override;
  67. static const char *getName() { return DEBUG_TYPE; }
  68. void setupMF(MachineFunction &MF, GISelKnownBits *KB,
  69. CodeGenCoverage &CoverageInfo, ProfileSummaryInfo *PSI,
  70. BlockFrequencyInfo *BFI) override {
  71. InstructionSelector::setupMF(MF, KB, CoverageInfo, PSI, BFI);
  72. MIB.setMF(MF);
  73. // hasFnAttribute() is expensive to call on every BRCOND selection, so
  74. // cache it here for each run of the selector.
  75. ProduceNonFlagSettingCondBr =
  76. !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening);
  77. MFReturnAddr = Register();
  78. processPHIs(MF);
  79. }
  80. private:
  81. /// tblgen-erated 'select' implementation, used as the initial selector for
  82. /// the patterns that don't require complex C++.
  83. bool selectImpl(MachineInstr &I, CodeGenCoverage &CoverageInfo) const;
  84. // A lowering phase that runs before any selection attempts.
  85. // Returns true if the instruction was modified.
  86. bool preISelLower(MachineInstr &I);
  87. // An early selection function that runs before the selectImpl() call.
  88. bool earlySelect(MachineInstr &I);
  89. // Do some preprocessing of G_PHIs before we begin selection.
  90. void processPHIs(MachineFunction &MF);
  91. bool earlySelectSHL(MachineInstr &I, MachineRegisterInfo &MRI);
  92. /// Eliminate same-sized cross-bank copies into stores before selectImpl().
  93. bool contractCrossBankCopyIntoStore(MachineInstr &I,
  94. MachineRegisterInfo &MRI);
  95. bool convertPtrAddToAdd(MachineInstr &I, MachineRegisterInfo &MRI);
  96. bool selectVaStartAAPCS(MachineInstr &I, MachineFunction &MF,
  97. MachineRegisterInfo &MRI) const;
  98. bool selectVaStartDarwin(MachineInstr &I, MachineFunction &MF,
  99. MachineRegisterInfo &MRI) const;
  100. ///@{
  101. /// Helper functions for selectCompareBranch.
  102. bool selectCompareBranchFedByFCmp(MachineInstr &I, MachineInstr &FCmp,
  103. MachineIRBuilder &MIB) const;
  104. bool selectCompareBranchFedByICmp(MachineInstr &I, MachineInstr &ICmp,
  105. MachineIRBuilder &MIB) const;
  106. bool tryOptCompareBranchFedByICmp(MachineInstr &I, MachineInstr &ICmp,
  107. MachineIRBuilder &MIB) const;
  108. bool tryOptAndIntoCompareBranch(MachineInstr &AndInst, bool Invert,
  109. MachineBasicBlock *DstMBB,
  110. MachineIRBuilder &MIB) const;
  111. ///@}
  112. bool selectCompareBranch(MachineInstr &I, MachineFunction &MF,
  113. MachineRegisterInfo &MRI);
  114. bool selectVectorAshrLshr(MachineInstr &I, MachineRegisterInfo &MRI);
  115. bool selectVectorSHL(MachineInstr &I, MachineRegisterInfo &MRI);
  116. // Helper to generate an equivalent of scalar_to_vector into a new register,
  117. // returned via 'Dst'.
  118. MachineInstr *emitScalarToVector(unsigned EltSize,
  119. const TargetRegisterClass *DstRC,
  120. Register Scalar,
  121. MachineIRBuilder &MIRBuilder) const;
  122. /// Emit a lane insert into \p DstReg, or a new vector register if
  123. /// std::nullopt is provided.
  124. ///
  125. /// The lane inserted into is defined by \p LaneIdx. The vector source
  126. /// register is given by \p SrcReg. The register containing the element is
  127. /// given by \p EltReg.
  128. MachineInstr *emitLaneInsert(std::optional<Register> DstReg, Register SrcReg,
  129. Register EltReg, unsigned LaneIdx,
  130. const RegisterBank &RB,
  131. MachineIRBuilder &MIRBuilder) const;
  132. /// Emit a sequence of instructions representing a constant \p CV for a
  133. /// vector register \p Dst. (E.g. a MOV, or a load from a constant pool.)
  134. ///
  135. /// \returns the last instruction in the sequence on success, and nullptr
  136. /// otherwise.
  137. MachineInstr *emitConstantVector(Register Dst, Constant *CV,
  138. MachineIRBuilder &MIRBuilder,
  139. MachineRegisterInfo &MRI);
  140. bool selectInsertElt(MachineInstr &I, MachineRegisterInfo &MRI);
  141. bool tryOptConstantBuildVec(MachineInstr &MI, LLT DstTy,
  142. MachineRegisterInfo &MRI);
  143. /// \returns true if a G_BUILD_VECTOR instruction \p MI can be selected as a
  144. /// SUBREG_TO_REG.
  145. bool tryOptBuildVecToSubregToReg(MachineInstr &MI, MachineRegisterInfo &MRI);
  146. bool selectBuildVector(MachineInstr &I, MachineRegisterInfo &MRI);
  147. bool selectMergeValues(MachineInstr &I, MachineRegisterInfo &MRI);
  148. bool selectUnmergeValues(MachineInstr &I, MachineRegisterInfo &MRI);
  149. bool selectShuffleVector(MachineInstr &I, MachineRegisterInfo &MRI);
  150. bool selectExtractElt(MachineInstr &I, MachineRegisterInfo &MRI);
  151. bool selectConcatVectors(MachineInstr &I, MachineRegisterInfo &MRI);
  152. bool selectSplitVectorUnmerge(MachineInstr &I, MachineRegisterInfo &MRI);
  153. /// Helper function to select vector load intrinsics like
  154. /// @llvm.aarch64.neon.ld2.*, @llvm.aarch64.neon.ld4.*, etc.
  155. /// \p Opc is the opcode that the selected instruction should use.
  156. /// \p NumVecs is the number of vector destinations for the instruction.
  157. /// \p I is the original G_INTRINSIC_W_SIDE_EFFECTS instruction.
  158. bool selectVectorLoadIntrinsic(unsigned Opc, unsigned NumVecs,
  159. MachineInstr &I);
  160. bool selectIntrinsicWithSideEffects(MachineInstr &I,
  161. MachineRegisterInfo &MRI);
  162. bool selectIntrinsic(MachineInstr &I, MachineRegisterInfo &MRI);
  163. bool selectVectorICmp(MachineInstr &I, MachineRegisterInfo &MRI);
  164. bool selectIntrinsicTrunc(MachineInstr &I, MachineRegisterInfo &MRI) const;
  165. bool selectIntrinsicRound(MachineInstr &I, MachineRegisterInfo &MRI) const;
  166. bool selectJumpTable(MachineInstr &I, MachineRegisterInfo &MRI);
  167. bool selectBrJT(MachineInstr &I, MachineRegisterInfo &MRI);
  168. bool selectTLSGlobalValue(MachineInstr &I, MachineRegisterInfo &MRI);
  169. bool selectReduction(MachineInstr &I, MachineRegisterInfo &MRI);
  170. bool selectMOPS(MachineInstr &I, MachineRegisterInfo &MRI);
  171. bool selectUSMovFromExtend(MachineInstr &I, MachineRegisterInfo &MRI);
  172. unsigned emitConstantPoolEntry(const Constant *CPVal,
  173. MachineFunction &MF) const;
  174. MachineInstr *emitLoadFromConstantPool(const Constant *CPVal,
  175. MachineIRBuilder &MIRBuilder) const;
  176. // Emit a vector concat operation.
  177. MachineInstr *emitVectorConcat(std::optional<Register> Dst, Register Op1,
  178. Register Op2,
  179. MachineIRBuilder &MIRBuilder) const;
  180. // Emit an integer compare between LHS and RHS, which checks for Predicate.
  181. MachineInstr *emitIntegerCompare(MachineOperand &LHS, MachineOperand &RHS,
  182. MachineOperand &Predicate,
  183. MachineIRBuilder &MIRBuilder) const;
  184. /// Emit a floating point comparison between \p LHS and \p RHS.
  185. /// \p Pred if given is the intended predicate to use.
  186. MachineInstr *
  187. emitFPCompare(Register LHS, Register RHS, MachineIRBuilder &MIRBuilder,
  188. std::optional<CmpInst::Predicate> = std::nullopt) const;
  189. MachineInstr *
  190. emitInstr(unsigned Opcode, std::initializer_list<llvm::DstOp> DstOps,
  191. std::initializer_list<llvm::SrcOp> SrcOps,
  192. MachineIRBuilder &MIRBuilder,
  193. const ComplexRendererFns &RenderFns = std::nullopt) const;
  194. /// Helper function to emit an add or sub instruction.
  195. ///
  196. /// \p AddrModeAndSizeToOpcode must contain each of the opcode variants above
  197. /// in a specific order.
  198. ///
  199. /// Below is an example of the expected input to \p AddrModeAndSizeToOpcode.
  200. ///
  201. /// \code
  202. /// const std::array<std::array<unsigned, 2>, 4> Table {
  203. /// {{AArch64::ADDXri, AArch64::ADDWri},
  204. /// {AArch64::ADDXrs, AArch64::ADDWrs},
  205. /// {AArch64::ADDXrr, AArch64::ADDWrr},
  206. /// {AArch64::SUBXri, AArch64::SUBWri},
  207. /// {AArch64::ADDXrx, AArch64::ADDWrx}}};
  208. /// \endcode
  209. ///
  210. /// Each row in the table corresponds to a different addressing mode. Each
  211. /// column corresponds to a different register size.
  212. ///
  213. /// \attention Rows must be structured as follows:
  214. /// - Row 0: The ri opcode variants
  215. /// - Row 1: The rs opcode variants
  216. /// - Row 2: The rr opcode variants
  217. /// - Row 3: The ri opcode variants for negative immediates
  218. /// - Row 4: The rx opcode variants
  219. ///
  220. /// \attention Columns must be structured as follows:
  221. /// - Column 0: The 64-bit opcode variants
  222. /// - Column 1: The 32-bit opcode variants
  223. ///
  224. /// \p Dst is the destination register of the binop to emit.
  225. /// \p LHS is the left-hand operand of the binop to emit.
  226. /// \p RHS is the right-hand operand of the binop to emit.
  227. MachineInstr *emitAddSub(
  228. const std::array<std::array<unsigned, 2>, 5> &AddrModeAndSizeToOpcode,
  229. Register Dst, MachineOperand &LHS, MachineOperand &RHS,
  230. MachineIRBuilder &MIRBuilder) const;
  231. MachineInstr *emitADD(Register DefReg, MachineOperand &LHS,
  232. MachineOperand &RHS,
  233. MachineIRBuilder &MIRBuilder) const;
  234. MachineInstr *emitADDS(Register Dst, MachineOperand &LHS, MachineOperand &RHS,
  235. MachineIRBuilder &MIRBuilder) const;
  236. MachineInstr *emitSUBS(Register Dst, MachineOperand &LHS, MachineOperand &RHS,
  237. MachineIRBuilder &MIRBuilder) const;
  238. MachineInstr *emitCMN(MachineOperand &LHS, MachineOperand &RHS,
  239. MachineIRBuilder &MIRBuilder) const;
  240. MachineInstr *emitTST(MachineOperand &LHS, MachineOperand &RHS,
  241. MachineIRBuilder &MIRBuilder) const;
  242. MachineInstr *emitSelect(Register Dst, Register LHS, Register RHS,
  243. AArch64CC::CondCode CC,
  244. MachineIRBuilder &MIRBuilder) const;
  245. MachineInstr *emitExtractVectorElt(std::optional<Register> DstReg,
  246. const RegisterBank &DstRB, LLT ScalarTy,
  247. Register VecReg, unsigned LaneIdx,
  248. MachineIRBuilder &MIRBuilder) const;
  249. MachineInstr *emitCSINC(Register Dst, Register Src1, Register Src2,
  250. AArch64CC::CondCode Pred,
  251. MachineIRBuilder &MIRBuilder) const;
  252. /// Emit a CSet for a FP compare.
  253. ///
  254. /// \p Dst is expected to be a 32-bit scalar register.
  255. MachineInstr *emitCSetForFCmp(Register Dst, CmpInst::Predicate Pred,
  256. MachineIRBuilder &MIRBuilder) const;
  257. /// Emit the overflow op for \p Opcode.
  258. ///
  259. /// \p Opcode is expected to be an overflow op's opcode, e.g. G_UADDO,
  260. /// G_USUBO, etc.
  261. std::pair<MachineInstr *, AArch64CC::CondCode>
  262. emitOverflowOp(unsigned Opcode, Register Dst, MachineOperand &LHS,
  263. MachineOperand &RHS, MachineIRBuilder &MIRBuilder) const;
  264. /// Emit expression as a conjunction (a series of CCMP/CFCMP ops).
  265. /// In some cases this is even possible with OR operations in the expression.
  266. MachineInstr *emitConjunction(Register Val, AArch64CC::CondCode &OutCC,
  267. MachineIRBuilder &MIB) const;
  268. MachineInstr *emitConditionalComparison(Register LHS, Register RHS,
  269. CmpInst::Predicate CC,
  270. AArch64CC::CondCode Predicate,
  271. AArch64CC::CondCode OutCC,
  272. MachineIRBuilder &MIB) const;
  273. MachineInstr *emitConjunctionRec(Register Val, AArch64CC::CondCode &OutCC,
  274. bool Negate, Register CCOp,
  275. AArch64CC::CondCode Predicate,
  276. MachineIRBuilder &MIB) const;
  277. /// Emit a TB(N)Z instruction which tests \p Bit in \p TestReg.
  278. /// \p IsNegative is true if the test should be "not zero".
  279. /// This will also optimize the test bit instruction when possible.
  280. MachineInstr *emitTestBit(Register TestReg, uint64_t Bit, bool IsNegative,
  281. MachineBasicBlock *DstMBB,
  282. MachineIRBuilder &MIB) const;
  283. /// Emit a CB(N)Z instruction which branches to \p DestMBB.
  284. MachineInstr *emitCBZ(Register CompareReg, bool IsNegative,
  285. MachineBasicBlock *DestMBB,
  286. MachineIRBuilder &MIB) const;
  287. // Equivalent to the i32shift_a and friends from AArch64InstrInfo.td.
  288. // We use these manually instead of using the importer since it doesn't
  289. // support SDNodeXForm.
  290. ComplexRendererFns selectShiftA_32(const MachineOperand &Root) const;
  291. ComplexRendererFns selectShiftB_32(const MachineOperand &Root) const;
  292. ComplexRendererFns selectShiftA_64(const MachineOperand &Root) const;
  293. ComplexRendererFns selectShiftB_64(const MachineOperand &Root) const;
  294. ComplexRendererFns select12BitValueWithLeftShift(uint64_t Immed) const;
  295. ComplexRendererFns selectArithImmed(MachineOperand &Root) const;
  296. ComplexRendererFns selectNegArithImmed(MachineOperand &Root) const;
  297. ComplexRendererFns selectAddrModeUnscaled(MachineOperand &Root,
  298. unsigned Size) const;
  299. ComplexRendererFns selectAddrModeUnscaled8(MachineOperand &Root) const {
  300. return selectAddrModeUnscaled(Root, 1);
  301. }
  302. ComplexRendererFns selectAddrModeUnscaled16(MachineOperand &Root) const {
  303. return selectAddrModeUnscaled(Root, 2);
  304. }
  305. ComplexRendererFns selectAddrModeUnscaled32(MachineOperand &Root) const {
  306. return selectAddrModeUnscaled(Root, 4);
  307. }
  308. ComplexRendererFns selectAddrModeUnscaled64(MachineOperand &Root) const {
  309. return selectAddrModeUnscaled(Root, 8);
  310. }
  311. ComplexRendererFns selectAddrModeUnscaled128(MachineOperand &Root) const {
  312. return selectAddrModeUnscaled(Root, 16);
  313. }
  314. /// Helper to try to fold in a GISEL_ADD_LOW into an immediate, to be used
  315. /// from complex pattern matchers like selectAddrModeIndexed().
  316. ComplexRendererFns tryFoldAddLowIntoImm(MachineInstr &RootDef, unsigned Size,
  317. MachineRegisterInfo &MRI) const;
  318. ComplexRendererFns selectAddrModeIndexed(MachineOperand &Root,
  319. unsigned Size) const;
  320. template <int Width>
  321. ComplexRendererFns selectAddrModeIndexed(MachineOperand &Root) const {
  322. return selectAddrModeIndexed(Root, Width / 8);
  323. }
  324. bool isWorthFoldingIntoExtendedReg(MachineInstr &MI,
  325. const MachineRegisterInfo &MRI) const;
  326. ComplexRendererFns
  327. selectAddrModeShiftedExtendXReg(MachineOperand &Root,
  328. unsigned SizeInBytes) const;
  329. /// Returns a \p ComplexRendererFns which contains a base, offset, and whether
  330. /// or not a shift + extend should be folded into an addressing mode. Returns
  331. /// None when this is not profitable or possible.
  332. ComplexRendererFns
  333. selectExtendedSHL(MachineOperand &Root, MachineOperand &Base,
  334. MachineOperand &Offset, unsigned SizeInBytes,
  335. bool WantsExt) const;
  336. ComplexRendererFns selectAddrModeRegisterOffset(MachineOperand &Root) const;
  337. ComplexRendererFns selectAddrModeXRO(MachineOperand &Root,
  338. unsigned SizeInBytes) const;
  339. template <int Width>
  340. ComplexRendererFns selectAddrModeXRO(MachineOperand &Root) const {
  341. return selectAddrModeXRO(Root, Width / 8);
  342. }
  343. ComplexRendererFns selectAddrModeWRO(MachineOperand &Root,
  344. unsigned SizeInBytes) const;
  345. template <int Width>
  346. ComplexRendererFns selectAddrModeWRO(MachineOperand &Root) const {
  347. return selectAddrModeWRO(Root, Width / 8);
  348. }
  349. ComplexRendererFns selectShiftedRegister(MachineOperand &Root,
  350. bool AllowROR = false) const;
  351. ComplexRendererFns selectArithShiftedRegister(MachineOperand &Root) const {
  352. return selectShiftedRegister(Root);
  353. }
  354. ComplexRendererFns selectLogicalShiftedRegister(MachineOperand &Root) const {
  355. return selectShiftedRegister(Root, true);
  356. }
  357. /// Given an extend instruction, determine the correct shift-extend type for
  358. /// that instruction.
  359. ///
  360. /// If the instruction is going to be used in a load or store, pass
  361. /// \p IsLoadStore = true.
  362. AArch64_AM::ShiftExtendType
  363. getExtendTypeForInst(MachineInstr &MI, MachineRegisterInfo &MRI,
  364. bool IsLoadStore = false) const;
  365. /// Move \p Reg to \p RC if \p Reg is not already on \p RC.
  366. ///
  367. /// \returns Either \p Reg if no change was necessary, or the new register
  368. /// created by moving \p Reg.
  369. ///
  370. /// Note: This uses emitCopy right now.
  371. Register moveScalarRegClass(Register Reg, const TargetRegisterClass &RC,
  372. MachineIRBuilder &MIB) const;
  373. ComplexRendererFns selectArithExtendedRegister(MachineOperand &Root) const;
  374. void renderTruncImm(MachineInstrBuilder &MIB, const MachineInstr &MI,
  375. int OpIdx = -1) const;
  376. void renderLogicalImm32(MachineInstrBuilder &MIB, const MachineInstr &I,
  377. int OpIdx = -1) const;
  378. void renderLogicalImm64(MachineInstrBuilder &MIB, const MachineInstr &I,
  379. int OpIdx = -1) const;
  380. void renderFPImm16(MachineInstrBuilder &MIB, const MachineInstr &MI,
  381. int OpIdx = -1) const;
  382. void renderFPImm32(MachineInstrBuilder &MIB, const MachineInstr &MI,
  383. int OpIdx = -1) const;
  384. void renderFPImm64(MachineInstrBuilder &MIB, const MachineInstr &MI,
  385. int OpIdx = -1) const;
  386. void renderFPImm32SIMDModImmType4(MachineInstrBuilder &MIB,
  387. const MachineInstr &MI,
  388. int OpIdx = -1) const;
  389. // Materialize a GlobalValue or BlockAddress using a movz+movk sequence.
  390. void materializeLargeCMVal(MachineInstr &I, const Value *V, unsigned OpFlags);
  391. // Optimization methods.
  392. bool tryOptSelect(GSelect &Sel);
  393. bool tryOptSelectConjunction(GSelect &Sel, MachineInstr &CondMI);
  394. MachineInstr *tryFoldIntegerCompare(MachineOperand &LHS, MachineOperand &RHS,
  395. MachineOperand &Predicate,
  396. MachineIRBuilder &MIRBuilder) const;
  397. /// Return true if \p MI is a load or store of \p NumBytes bytes.
  398. bool isLoadStoreOfNumBytes(const MachineInstr &MI, unsigned NumBytes) const;
  399. /// Returns true if \p MI is guaranteed to have the high-half of a 64-bit
  400. /// register zeroed out. In other words, the result of MI has been explicitly
  401. /// zero extended.
  402. bool isDef32(const MachineInstr &MI) const;
  403. const AArch64TargetMachine &TM;
  404. const AArch64Subtarget &STI;
  405. const AArch64InstrInfo &TII;
  406. const AArch64RegisterInfo &TRI;
  407. const AArch64RegisterBankInfo &RBI;
  408. bool ProduceNonFlagSettingCondBr = false;
  409. // Some cached values used during selection.
  410. // We use LR as a live-in register, and we keep track of it here as it can be
  411. // clobbered by calls.
  412. Register MFReturnAddr;
  413. MachineIRBuilder MIB;
  414. #define GET_GLOBALISEL_PREDICATES_DECL
  415. #include "AArch64GenGlobalISel.inc"
  416. #undef GET_GLOBALISEL_PREDICATES_DECL
  417. // We declare the temporaries used by selectImpl() in the class to minimize the
  418. // cost of constructing placeholder values.
  419. #define GET_GLOBALISEL_TEMPORARIES_DECL
  420. #include "AArch64GenGlobalISel.inc"
  421. #undef GET_GLOBALISEL_TEMPORARIES_DECL
  422. };
  423. } // end anonymous namespace
  424. #define GET_GLOBALISEL_IMPL
  425. #include "AArch64GenGlobalISel.inc"
  426. #undef GET_GLOBALISEL_IMPL
  427. AArch64InstructionSelector::AArch64InstructionSelector(
  428. const AArch64TargetMachine &TM, const AArch64Subtarget &STI,
  429. const AArch64RegisterBankInfo &RBI)
  430. : TM(TM), STI(STI), TII(*STI.getInstrInfo()), TRI(*STI.getRegisterInfo()),
  431. RBI(RBI),
  432. #define GET_GLOBALISEL_PREDICATES_INIT
  433. #include "AArch64GenGlobalISel.inc"
  434. #undef GET_GLOBALISEL_PREDICATES_INIT
  435. #define GET_GLOBALISEL_TEMPORARIES_INIT
  436. #include "AArch64GenGlobalISel.inc"
  437. #undef GET_GLOBALISEL_TEMPORARIES_INIT
  438. {
  439. }
  440. // FIXME: This should be target-independent, inferred from the types declared
  441. // for each class in the bank.
  442. //
  443. /// Given a register bank, and a type, return the smallest register class that
  444. /// can represent that combination.
  445. static const TargetRegisterClass *
  446. getRegClassForTypeOnBank(LLT Ty, const RegisterBank &RB,
  447. bool GetAllRegSet = false) {
  448. if (RB.getID() == AArch64::GPRRegBankID) {
  449. if (Ty.getSizeInBits() <= 32)
  450. return GetAllRegSet ? &AArch64::GPR32allRegClass
  451. : &AArch64::GPR32RegClass;
  452. if (Ty.getSizeInBits() == 64)
  453. return GetAllRegSet ? &AArch64::GPR64allRegClass
  454. : &AArch64::GPR64RegClass;
  455. if (Ty.getSizeInBits() == 128)
  456. return &AArch64::XSeqPairsClassRegClass;
  457. return nullptr;
  458. }
  459. if (RB.getID() == AArch64::FPRRegBankID) {
  460. switch (Ty.getSizeInBits()) {
  461. case 8:
  462. return &AArch64::FPR8RegClass;
  463. case 16:
  464. return &AArch64::FPR16RegClass;
  465. case 32:
  466. return &AArch64::FPR32RegClass;
  467. case 64:
  468. return &AArch64::FPR64RegClass;
  469. case 128:
  470. return &AArch64::FPR128RegClass;
  471. }
  472. return nullptr;
  473. }
  474. return nullptr;
  475. }
  476. /// Given a register bank, and size in bits, return the smallest register class
  477. /// that can represent that combination.
  478. static const TargetRegisterClass *
  479. getMinClassForRegBank(const RegisterBank &RB, unsigned SizeInBits,
  480. bool GetAllRegSet = false) {
  481. unsigned RegBankID = RB.getID();
  482. if (RegBankID == AArch64::GPRRegBankID) {
  483. if (SizeInBits <= 32)
  484. return GetAllRegSet ? &AArch64::GPR32allRegClass
  485. : &AArch64::GPR32RegClass;
  486. if (SizeInBits == 64)
  487. return GetAllRegSet ? &AArch64::GPR64allRegClass
  488. : &AArch64::GPR64RegClass;
  489. if (SizeInBits == 128)
  490. return &AArch64::XSeqPairsClassRegClass;
  491. }
  492. if (RegBankID == AArch64::FPRRegBankID) {
  493. switch (SizeInBits) {
  494. default:
  495. return nullptr;
  496. case 8:
  497. return &AArch64::FPR8RegClass;
  498. case 16:
  499. return &AArch64::FPR16RegClass;
  500. case 32:
  501. return &AArch64::FPR32RegClass;
  502. case 64:
  503. return &AArch64::FPR64RegClass;
  504. case 128:
  505. return &AArch64::FPR128RegClass;
  506. }
  507. }
  508. return nullptr;
  509. }
  510. /// Returns the correct subregister to use for a given register class.
  511. static bool getSubRegForClass(const TargetRegisterClass *RC,
  512. const TargetRegisterInfo &TRI, unsigned &SubReg) {
  513. switch (TRI.getRegSizeInBits(*RC)) {
  514. case 8:
  515. SubReg = AArch64::bsub;
  516. break;
  517. case 16:
  518. SubReg = AArch64::hsub;
  519. break;
  520. case 32:
  521. if (RC != &AArch64::FPR32RegClass)
  522. SubReg = AArch64::sub_32;
  523. else
  524. SubReg = AArch64::ssub;
  525. break;
  526. case 64:
  527. SubReg = AArch64::dsub;
  528. break;
  529. default:
  530. LLVM_DEBUG(
  531. dbgs() << "Couldn't find appropriate subregister for register class.");
  532. return false;
  533. }
  534. return true;
  535. }
  536. /// Returns the minimum size the given register bank can hold.
  537. static unsigned getMinSizeForRegBank(const RegisterBank &RB) {
  538. switch (RB.getID()) {
  539. case AArch64::GPRRegBankID:
  540. return 32;
  541. case AArch64::FPRRegBankID:
  542. return 8;
  543. default:
  544. llvm_unreachable("Tried to get minimum size for unknown register bank.");
  545. }
  546. }
  547. /// Create a REG_SEQUENCE instruction using the registers in \p Regs.
  548. /// Helper function for functions like createDTuple and createQTuple.
  549. ///
  550. /// \p RegClassIDs - The list of register class IDs available for some tuple of
  551. /// a scalar class. E.g. QQRegClassID, QQQRegClassID, QQQQRegClassID. This is
  552. /// expected to contain between 2 and 4 tuple classes.
  553. ///
  554. /// \p SubRegs - The list of subregister classes associated with each register
  555. /// class ID in \p RegClassIDs. E.g., QQRegClassID should use the qsub0
  556. /// subregister class. The index of each subregister class is expected to
  557. /// correspond with the index of each register class.
  558. ///
  559. /// \returns Either the destination register of REG_SEQUENCE instruction that
  560. /// was created, or the 0th element of \p Regs if \p Regs contains a single
  561. /// element.
  562. static Register createTuple(ArrayRef<Register> Regs,
  563. const unsigned RegClassIDs[],
  564. const unsigned SubRegs[], MachineIRBuilder &MIB) {
  565. unsigned NumRegs = Regs.size();
  566. if (NumRegs == 1)
  567. return Regs[0];
  568. assert(NumRegs >= 2 && NumRegs <= 4 &&
  569. "Only support between two and 4 registers in a tuple!");
  570. const TargetRegisterInfo *TRI = MIB.getMF().getSubtarget().getRegisterInfo();
  571. auto *DesiredClass = TRI->getRegClass(RegClassIDs[NumRegs - 2]);
  572. auto RegSequence =
  573. MIB.buildInstr(TargetOpcode::REG_SEQUENCE, {DesiredClass}, {});
  574. for (unsigned I = 0, E = Regs.size(); I < E; ++I) {
  575. RegSequence.addUse(Regs[I]);
  576. RegSequence.addImm(SubRegs[I]);
  577. }
  578. return RegSequence.getReg(0);
  579. }
  580. /// Create a tuple of D-registers using the registers in \p Regs.
  581. static Register createDTuple(ArrayRef<Register> Regs, MachineIRBuilder &MIB) {
  582. static const unsigned RegClassIDs[] = {
  583. AArch64::DDRegClassID, AArch64::DDDRegClassID, AArch64::DDDDRegClassID};
  584. static const unsigned SubRegs[] = {AArch64::dsub0, AArch64::dsub1,
  585. AArch64::dsub2, AArch64::dsub3};
  586. return createTuple(Regs, RegClassIDs, SubRegs, MIB);
  587. }
  588. /// Create a tuple of Q-registers using the registers in \p Regs.
  589. static Register createQTuple(ArrayRef<Register> Regs, MachineIRBuilder &MIB) {
  590. static const unsigned RegClassIDs[] = {
  591. AArch64::QQRegClassID, AArch64::QQQRegClassID, AArch64::QQQQRegClassID};
  592. static const unsigned SubRegs[] = {AArch64::qsub0, AArch64::qsub1,
  593. AArch64::qsub2, AArch64::qsub3};
  594. return createTuple(Regs, RegClassIDs, SubRegs, MIB);
  595. }
  596. static std::optional<uint64_t> getImmedFromMO(const MachineOperand &Root) {
  597. auto &MI = *Root.getParent();
  598. auto &MBB = *MI.getParent();
  599. auto &MF = *MBB.getParent();
  600. auto &MRI = MF.getRegInfo();
  601. uint64_t Immed;
  602. if (Root.isImm())
  603. Immed = Root.getImm();
  604. else if (Root.isCImm())
  605. Immed = Root.getCImm()->getZExtValue();
  606. else if (Root.isReg()) {
  607. auto ValAndVReg =
  608. getIConstantVRegValWithLookThrough(Root.getReg(), MRI, true);
  609. if (!ValAndVReg)
  610. return std::nullopt;
  611. Immed = ValAndVReg->Value.getSExtValue();
  612. } else
  613. return std::nullopt;
  614. return Immed;
  615. }
  616. /// Check whether \p I is a currently unsupported binary operation:
  617. /// - it has an unsized type
  618. /// - an operand is not a vreg
  619. /// - all operands are not in the same bank
  620. /// These are checks that should someday live in the verifier, but right now,
  621. /// these are mostly limitations of the aarch64 selector.
  622. static bool unsupportedBinOp(const MachineInstr &I,
  623. const AArch64RegisterBankInfo &RBI,
  624. const MachineRegisterInfo &MRI,
  625. const AArch64RegisterInfo &TRI) {
  626. LLT Ty = MRI.getType(I.getOperand(0).getReg());
  627. if (!Ty.isValid()) {
  628. LLVM_DEBUG(dbgs() << "Generic binop register should be typed\n");
  629. return true;
  630. }
  631. const RegisterBank *PrevOpBank = nullptr;
  632. for (auto &MO : I.operands()) {
  633. // FIXME: Support non-register operands.
  634. if (!MO.isReg()) {
  635. LLVM_DEBUG(dbgs() << "Generic inst non-reg operands are unsupported\n");
  636. return true;
  637. }
  638. // FIXME: Can generic operations have physical registers operands? If
  639. // so, this will need to be taught about that, and we'll need to get the
  640. // bank out of the minimal class for the register.
  641. // Either way, this needs to be documented (and possibly verified).
  642. if (!MO.getReg().isVirtual()) {
  643. LLVM_DEBUG(dbgs() << "Generic inst has physical register operand\n");
  644. return true;
  645. }
  646. const RegisterBank *OpBank = RBI.getRegBank(MO.getReg(), MRI, TRI);
  647. if (!OpBank) {
  648. LLVM_DEBUG(dbgs() << "Generic register has no bank or class\n");
  649. return true;
  650. }
  651. if (PrevOpBank && OpBank != PrevOpBank) {
  652. LLVM_DEBUG(dbgs() << "Generic inst operands have different banks\n");
  653. return true;
  654. }
  655. PrevOpBank = OpBank;
  656. }
  657. return false;
  658. }
  659. /// Select the AArch64 opcode for the basic binary operation \p GenericOpc
  660. /// (such as G_OR or G_SDIV), appropriate for the register bank \p RegBankID
  661. /// and of size \p OpSize.
  662. /// \returns \p GenericOpc if the combination is unsupported.
  663. static unsigned selectBinaryOp(unsigned GenericOpc, unsigned RegBankID,
  664. unsigned OpSize) {
  665. switch (RegBankID) {
  666. case AArch64::GPRRegBankID:
  667. if (OpSize == 32) {
  668. switch (GenericOpc) {
  669. case TargetOpcode::G_SHL:
  670. return AArch64::LSLVWr;
  671. case TargetOpcode::G_LSHR:
  672. return AArch64::LSRVWr;
  673. case TargetOpcode::G_ASHR:
  674. return AArch64::ASRVWr;
  675. default:
  676. return GenericOpc;
  677. }
  678. } else if (OpSize == 64) {
  679. switch (GenericOpc) {
  680. case TargetOpcode::G_PTR_ADD:
  681. return AArch64::ADDXrr;
  682. case TargetOpcode::G_SHL:
  683. return AArch64::LSLVXr;
  684. case TargetOpcode::G_LSHR:
  685. return AArch64::LSRVXr;
  686. case TargetOpcode::G_ASHR:
  687. return AArch64::ASRVXr;
  688. default:
  689. return GenericOpc;
  690. }
  691. }
  692. break;
  693. case AArch64::FPRRegBankID:
  694. switch (OpSize) {
  695. case 32:
  696. switch (GenericOpc) {
  697. case TargetOpcode::G_FADD:
  698. return AArch64::FADDSrr;
  699. case TargetOpcode::G_FSUB:
  700. return AArch64::FSUBSrr;
  701. case TargetOpcode::G_FMUL:
  702. return AArch64::FMULSrr;
  703. case TargetOpcode::G_FDIV:
  704. return AArch64::FDIVSrr;
  705. default:
  706. return GenericOpc;
  707. }
  708. case 64:
  709. switch (GenericOpc) {
  710. case TargetOpcode::G_FADD:
  711. return AArch64::FADDDrr;
  712. case TargetOpcode::G_FSUB:
  713. return AArch64::FSUBDrr;
  714. case TargetOpcode::G_FMUL:
  715. return AArch64::FMULDrr;
  716. case TargetOpcode::G_FDIV:
  717. return AArch64::FDIVDrr;
  718. case TargetOpcode::G_OR:
  719. return AArch64::ORRv8i8;
  720. default:
  721. return GenericOpc;
  722. }
  723. }
  724. break;
  725. }
  726. return GenericOpc;
  727. }
  728. /// Select the AArch64 opcode for the G_LOAD or G_STORE operation \p GenericOpc,
  729. /// appropriate for the (value) register bank \p RegBankID and of memory access
  730. /// size \p OpSize. This returns the variant with the base+unsigned-immediate
  731. /// addressing mode (e.g., LDRXui).
  732. /// \returns \p GenericOpc if the combination is unsupported.
  733. static unsigned selectLoadStoreUIOp(unsigned GenericOpc, unsigned RegBankID,
  734. unsigned OpSize) {
  735. const bool isStore = GenericOpc == TargetOpcode::G_STORE;
  736. switch (RegBankID) {
  737. case AArch64::GPRRegBankID:
  738. switch (OpSize) {
  739. case 8:
  740. return isStore ? AArch64::STRBBui : AArch64::LDRBBui;
  741. case 16:
  742. return isStore ? AArch64::STRHHui : AArch64::LDRHHui;
  743. case 32:
  744. return isStore ? AArch64::STRWui : AArch64::LDRWui;
  745. case 64:
  746. return isStore ? AArch64::STRXui : AArch64::LDRXui;
  747. }
  748. break;
  749. case AArch64::FPRRegBankID:
  750. switch (OpSize) {
  751. case 8:
  752. return isStore ? AArch64::STRBui : AArch64::LDRBui;
  753. case 16:
  754. return isStore ? AArch64::STRHui : AArch64::LDRHui;
  755. case 32:
  756. return isStore ? AArch64::STRSui : AArch64::LDRSui;
  757. case 64:
  758. return isStore ? AArch64::STRDui : AArch64::LDRDui;
  759. case 128:
  760. return isStore ? AArch64::STRQui : AArch64::LDRQui;
  761. }
  762. break;
  763. }
  764. return GenericOpc;
  765. }
  766. /// Helper function for selectCopy. Inserts a subregister copy from \p SrcReg
  767. /// to \p *To.
  768. ///
  769. /// E.g "To = COPY SrcReg:SubReg"
  770. static bool copySubReg(MachineInstr &I, MachineRegisterInfo &MRI,
  771. const RegisterBankInfo &RBI, Register SrcReg,
  772. const TargetRegisterClass *To, unsigned SubReg) {
  773. assert(SrcReg.isValid() && "Expected a valid source register?");
  774. assert(To && "Destination register class cannot be null");
  775. assert(SubReg && "Expected a valid subregister");
  776. MachineIRBuilder MIB(I);
  777. auto SubRegCopy =
  778. MIB.buildInstr(TargetOpcode::COPY, {To}, {}).addReg(SrcReg, 0, SubReg);
  779. MachineOperand &RegOp = I.getOperand(1);
  780. RegOp.setReg(SubRegCopy.getReg(0));
  781. // It's possible that the destination register won't be constrained. Make
  782. // sure that happens.
  783. if (!I.getOperand(0).getReg().isPhysical())
  784. RBI.constrainGenericRegister(I.getOperand(0).getReg(), *To, MRI);
  785. return true;
  786. }
  787. /// Helper function to get the source and destination register classes for a
  788. /// copy. Returns a std::pair containing the source register class for the
  789. /// copy, and the destination register class for the copy. If a register class
  790. /// cannot be determined, then it will be nullptr.
  791. static std::pair<const TargetRegisterClass *, const TargetRegisterClass *>
  792. getRegClassesForCopy(MachineInstr &I, const TargetInstrInfo &TII,
  793. MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI,
  794. const RegisterBankInfo &RBI) {
  795. Register DstReg = I.getOperand(0).getReg();
  796. Register SrcReg = I.getOperand(1).getReg();
  797. const RegisterBank &DstRegBank = *RBI.getRegBank(DstReg, MRI, TRI);
  798. const RegisterBank &SrcRegBank = *RBI.getRegBank(SrcReg, MRI, TRI);
  799. unsigned DstSize = RBI.getSizeInBits(DstReg, MRI, TRI);
  800. unsigned SrcSize = RBI.getSizeInBits(SrcReg, MRI, TRI);
  801. // Special casing for cross-bank copies of s1s. We can technically represent
  802. // a 1-bit value with any size of register. The minimum size for a GPR is 32
  803. // bits. So, we need to put the FPR on 32 bits as well.
  804. //
  805. // FIXME: I'm not sure if this case holds true outside of copies. If it does,
  806. // then we can pull it into the helpers that get the appropriate class for a
  807. // register bank. Or make a new helper that carries along some constraint
  808. // information.
  809. if (SrcRegBank != DstRegBank && (DstSize == 1 && SrcSize == 1))
  810. SrcSize = DstSize = 32;
  811. return {getMinClassForRegBank(SrcRegBank, SrcSize, true),
  812. getMinClassForRegBank(DstRegBank, DstSize, true)};
  813. }
  814. // FIXME: We need some sort of API in RBI/TRI to allow generic code to
  815. // constrain operands of simple instructions given a TargetRegisterClass
  816. // and LLT
  817. static bool selectDebugInstr(MachineInstr &I, MachineRegisterInfo &MRI,
  818. const RegisterBankInfo &RBI) {
  819. for (MachineOperand &MO : I.operands()) {
  820. if (!MO.isReg())
  821. continue;
  822. Register Reg = MO.getReg();
  823. if (!Reg)
  824. continue;
  825. if (Reg.isPhysical())
  826. continue;
  827. LLT Ty = MRI.getType(Reg);
  828. const RegClassOrRegBank &RegClassOrBank = MRI.getRegClassOrRegBank(Reg);
  829. const TargetRegisterClass *RC =
  830. RegClassOrBank.dyn_cast<const TargetRegisterClass *>();
  831. if (!RC) {
  832. const RegisterBank &RB = *RegClassOrBank.get<const RegisterBank *>();
  833. RC = getRegClassForTypeOnBank(Ty, RB);
  834. if (!RC) {
  835. LLVM_DEBUG(
  836. dbgs() << "Warning: DBG_VALUE operand has unexpected size/bank\n");
  837. break;
  838. }
  839. }
  840. RBI.constrainGenericRegister(Reg, *RC, MRI);
  841. }
  842. return true;
  843. }
  844. static bool selectCopy(MachineInstr &I, const TargetInstrInfo &TII,
  845. MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI,
  846. const RegisterBankInfo &RBI) {
  847. Register DstReg = I.getOperand(0).getReg();
  848. Register SrcReg = I.getOperand(1).getReg();
  849. const RegisterBank &DstRegBank = *RBI.getRegBank(DstReg, MRI, TRI);
  850. const RegisterBank &SrcRegBank = *RBI.getRegBank(SrcReg, MRI, TRI);
  851. // Find the correct register classes for the source and destination registers.
  852. const TargetRegisterClass *SrcRC;
  853. const TargetRegisterClass *DstRC;
  854. std::tie(SrcRC, DstRC) = getRegClassesForCopy(I, TII, MRI, TRI, RBI);
  855. if (!DstRC) {
  856. LLVM_DEBUG(dbgs() << "Unexpected dest size "
  857. << RBI.getSizeInBits(DstReg, MRI, TRI) << '\n');
  858. return false;
  859. }
  860. // Is this a copy? If so, then we may need to insert a subregister copy.
  861. if (I.isCopy()) {
  862. // Yes. Check if there's anything to fix up.
  863. if (!SrcRC) {
  864. LLVM_DEBUG(dbgs() << "Couldn't determine source register class\n");
  865. return false;
  866. }
  867. unsigned SrcSize = TRI.getRegSizeInBits(*SrcRC);
  868. unsigned DstSize = TRI.getRegSizeInBits(*DstRC);
  869. unsigned SubReg;
  870. // If the source bank doesn't support a subregister copy small enough,
  871. // then we first need to copy to the destination bank.
  872. if (getMinSizeForRegBank(SrcRegBank) > DstSize) {
  873. const TargetRegisterClass *DstTempRC =
  874. getMinClassForRegBank(DstRegBank, SrcSize, /* GetAllRegSet */ true);
  875. getSubRegForClass(DstRC, TRI, SubReg);
  876. MachineIRBuilder MIB(I);
  877. auto Copy = MIB.buildCopy({DstTempRC}, {SrcReg});
  878. copySubReg(I, MRI, RBI, Copy.getReg(0), DstRC, SubReg);
  879. } else if (SrcSize > DstSize) {
  880. // If the source register is bigger than the destination we need to
  881. // perform a subregister copy.
  882. const TargetRegisterClass *SubRegRC =
  883. getMinClassForRegBank(SrcRegBank, DstSize, /* GetAllRegSet */ true);
  884. getSubRegForClass(SubRegRC, TRI, SubReg);
  885. copySubReg(I, MRI, RBI, SrcReg, DstRC, SubReg);
  886. } else if (DstSize > SrcSize) {
  887. // If the destination register is bigger than the source we need to do
  888. // a promotion using SUBREG_TO_REG.
  889. const TargetRegisterClass *PromotionRC =
  890. getMinClassForRegBank(SrcRegBank, DstSize, /* GetAllRegSet */ true);
  891. getSubRegForClass(SrcRC, TRI, SubReg);
  892. Register PromoteReg = MRI.createVirtualRegister(PromotionRC);
  893. BuildMI(*I.getParent(), I, I.getDebugLoc(),
  894. TII.get(AArch64::SUBREG_TO_REG), PromoteReg)
  895. .addImm(0)
  896. .addUse(SrcReg)
  897. .addImm(SubReg);
  898. MachineOperand &RegOp = I.getOperand(1);
  899. RegOp.setReg(PromoteReg);
  900. }
  901. // If the destination is a physical register, then there's nothing to
  902. // change, so we're done.
  903. if (DstReg.isPhysical())
  904. return true;
  905. }
  906. // No need to constrain SrcReg. It will get constrained when we hit another
  907. // of its use or its defs. Copies do not have constraints.
  908. if (!RBI.constrainGenericRegister(DstReg, *DstRC, MRI)) {
  909. LLVM_DEBUG(dbgs() << "Failed to constrain " << TII.getName(I.getOpcode())
  910. << " operand\n");
  911. return false;
  912. }
  913. // If this a GPR ZEXT that we want to just reduce down into a copy.
  914. // The sizes will be mismatched with the source < 32b but that's ok.
  915. if (I.getOpcode() == TargetOpcode::G_ZEXT) {
  916. I.setDesc(TII.get(AArch64::COPY));
  917. assert(SrcRegBank.getID() == AArch64::GPRRegBankID);
  918. return selectCopy(I, TII, MRI, TRI, RBI);
  919. }
  920. I.setDesc(TII.get(AArch64::COPY));
  921. return true;
  922. }
  923. static unsigned selectFPConvOpc(unsigned GenericOpc, LLT DstTy, LLT SrcTy) {
  924. if (!DstTy.isScalar() || !SrcTy.isScalar())
  925. return GenericOpc;
  926. const unsigned DstSize = DstTy.getSizeInBits();
  927. const unsigned SrcSize = SrcTy.getSizeInBits();
  928. switch (DstSize) {
  929. case 32:
  930. switch (SrcSize) {
  931. case 32:
  932. switch (GenericOpc) {
  933. case TargetOpcode::G_SITOFP:
  934. return AArch64::SCVTFUWSri;
  935. case TargetOpcode::G_UITOFP:
  936. return AArch64::UCVTFUWSri;
  937. case TargetOpcode::G_FPTOSI:
  938. return AArch64::FCVTZSUWSr;
  939. case TargetOpcode::G_FPTOUI:
  940. return AArch64::FCVTZUUWSr;
  941. default:
  942. return GenericOpc;
  943. }
  944. case 64:
  945. switch (GenericOpc) {
  946. case TargetOpcode::G_SITOFP:
  947. return AArch64::SCVTFUXSri;
  948. case TargetOpcode::G_UITOFP:
  949. return AArch64::UCVTFUXSri;
  950. case TargetOpcode::G_FPTOSI:
  951. return AArch64::FCVTZSUWDr;
  952. case TargetOpcode::G_FPTOUI:
  953. return AArch64::FCVTZUUWDr;
  954. default:
  955. return GenericOpc;
  956. }
  957. default:
  958. return GenericOpc;
  959. }
  960. case 64:
  961. switch (SrcSize) {
  962. case 32:
  963. switch (GenericOpc) {
  964. case TargetOpcode::G_SITOFP:
  965. return AArch64::SCVTFUWDri;
  966. case TargetOpcode::G_UITOFP:
  967. return AArch64::UCVTFUWDri;
  968. case TargetOpcode::G_FPTOSI:
  969. return AArch64::FCVTZSUXSr;
  970. case TargetOpcode::G_FPTOUI:
  971. return AArch64::FCVTZUUXSr;
  972. default:
  973. return GenericOpc;
  974. }
  975. case 64:
  976. switch (GenericOpc) {
  977. case TargetOpcode::G_SITOFP:
  978. return AArch64::SCVTFUXDri;
  979. case TargetOpcode::G_UITOFP:
  980. return AArch64::UCVTFUXDri;
  981. case TargetOpcode::G_FPTOSI:
  982. return AArch64::FCVTZSUXDr;
  983. case TargetOpcode::G_FPTOUI:
  984. return AArch64::FCVTZUUXDr;
  985. default:
  986. return GenericOpc;
  987. }
  988. default:
  989. return GenericOpc;
  990. }
  991. default:
  992. return GenericOpc;
  993. };
  994. return GenericOpc;
  995. }
  996. MachineInstr *
  997. AArch64InstructionSelector::emitSelect(Register Dst, Register True,
  998. Register False, AArch64CC::CondCode CC,
  999. MachineIRBuilder &MIB) const {
  1000. MachineRegisterInfo &MRI = *MIB.getMRI();
  1001. assert(RBI.getRegBank(False, MRI, TRI)->getID() ==
  1002. RBI.getRegBank(True, MRI, TRI)->getID() &&
  1003. "Expected both select operands to have the same regbank?");
  1004. LLT Ty = MRI.getType(True);
  1005. if (Ty.isVector())
  1006. return nullptr;
  1007. const unsigned Size = Ty.getSizeInBits();
  1008. assert((Size == 32 || Size == 64) &&
  1009. "Expected 32 bit or 64 bit select only?");
  1010. const bool Is32Bit = Size == 32;
  1011. if (RBI.getRegBank(True, MRI, TRI)->getID() != AArch64::GPRRegBankID) {
  1012. unsigned Opc = Is32Bit ? AArch64::FCSELSrrr : AArch64::FCSELDrrr;
  1013. auto FCSel = MIB.buildInstr(Opc, {Dst}, {True, False}).addImm(CC);
  1014. constrainSelectedInstRegOperands(*FCSel, TII, TRI, RBI);
  1015. return &*FCSel;
  1016. }
  1017. // By default, we'll try and emit a CSEL.
  1018. unsigned Opc = Is32Bit ? AArch64::CSELWr : AArch64::CSELXr;
  1019. bool Optimized = false;
  1020. auto TryFoldBinOpIntoSelect = [&Opc, Is32Bit, &CC, &MRI,
  1021. &Optimized](Register &Reg, Register &OtherReg,
  1022. bool Invert) {
  1023. if (Optimized)
  1024. return false;
  1025. // Attempt to fold:
  1026. //
  1027. // %sub = G_SUB 0, %x
  1028. // %select = G_SELECT cc, %reg, %sub
  1029. //
  1030. // Into:
  1031. // %select = CSNEG %reg, %x, cc
  1032. Register MatchReg;
  1033. if (mi_match(Reg, MRI, m_Neg(m_Reg(MatchReg)))) {
  1034. Opc = Is32Bit ? AArch64::CSNEGWr : AArch64::CSNEGXr;
  1035. Reg = MatchReg;
  1036. if (Invert) {
  1037. CC = AArch64CC::getInvertedCondCode(CC);
  1038. std::swap(Reg, OtherReg);
  1039. }
  1040. return true;
  1041. }
  1042. // Attempt to fold:
  1043. //
  1044. // %xor = G_XOR %x, -1
  1045. // %select = G_SELECT cc, %reg, %xor
  1046. //
  1047. // Into:
  1048. // %select = CSINV %reg, %x, cc
  1049. if (mi_match(Reg, MRI, m_Not(m_Reg(MatchReg)))) {
  1050. Opc = Is32Bit ? AArch64::CSINVWr : AArch64::CSINVXr;
  1051. Reg = MatchReg;
  1052. if (Invert) {
  1053. CC = AArch64CC::getInvertedCondCode(CC);
  1054. std::swap(Reg, OtherReg);
  1055. }
  1056. return true;
  1057. }
  1058. // Attempt to fold:
  1059. //
  1060. // %add = G_ADD %x, 1
  1061. // %select = G_SELECT cc, %reg, %add
  1062. //
  1063. // Into:
  1064. // %select = CSINC %reg, %x, cc
  1065. if (mi_match(Reg, MRI,
  1066. m_any_of(m_GAdd(m_Reg(MatchReg), m_SpecificICst(1)),
  1067. m_GPtrAdd(m_Reg(MatchReg), m_SpecificICst(1))))) {
  1068. Opc = Is32Bit ? AArch64::CSINCWr : AArch64::CSINCXr;
  1069. Reg = MatchReg;
  1070. if (Invert) {
  1071. CC = AArch64CC::getInvertedCondCode(CC);
  1072. std::swap(Reg, OtherReg);
  1073. }
  1074. return true;
  1075. }
  1076. return false;
  1077. };
  1078. // Helper lambda which tries to use CSINC/CSINV for the instruction when its
  1079. // true/false values are constants.
  1080. // FIXME: All of these patterns already exist in tablegen. We should be
  1081. // able to import these.
  1082. auto TryOptSelectCst = [&Opc, &True, &False, &CC, Is32Bit, &MRI,
  1083. &Optimized]() {
  1084. if (Optimized)
  1085. return false;
  1086. auto TrueCst = getIConstantVRegValWithLookThrough(True, MRI);
  1087. auto FalseCst = getIConstantVRegValWithLookThrough(False, MRI);
  1088. if (!TrueCst && !FalseCst)
  1089. return false;
  1090. Register ZReg = Is32Bit ? AArch64::WZR : AArch64::XZR;
  1091. if (TrueCst && FalseCst) {
  1092. int64_t T = TrueCst->Value.getSExtValue();
  1093. int64_t F = FalseCst->Value.getSExtValue();
  1094. if (T == 0 && F == 1) {
  1095. // G_SELECT cc, 0, 1 -> CSINC zreg, zreg, cc
  1096. Opc = Is32Bit ? AArch64::CSINCWr : AArch64::CSINCXr;
  1097. True = ZReg;
  1098. False = ZReg;
  1099. return true;
  1100. }
  1101. if (T == 0 && F == -1) {
  1102. // G_SELECT cc 0, -1 -> CSINV zreg, zreg cc
  1103. Opc = Is32Bit ? AArch64::CSINVWr : AArch64::CSINVXr;
  1104. True = ZReg;
  1105. False = ZReg;
  1106. return true;
  1107. }
  1108. }
  1109. if (TrueCst) {
  1110. int64_t T = TrueCst->Value.getSExtValue();
  1111. if (T == 1) {
  1112. // G_SELECT cc, 1, f -> CSINC f, zreg, inv_cc
  1113. Opc = Is32Bit ? AArch64::CSINCWr : AArch64::CSINCXr;
  1114. True = False;
  1115. False = ZReg;
  1116. CC = AArch64CC::getInvertedCondCode(CC);
  1117. return true;
  1118. }
  1119. if (T == -1) {
  1120. // G_SELECT cc, -1, f -> CSINV f, zreg, inv_cc
  1121. Opc = Is32Bit ? AArch64::CSINVWr : AArch64::CSINVXr;
  1122. True = False;
  1123. False = ZReg;
  1124. CC = AArch64CC::getInvertedCondCode(CC);
  1125. return true;
  1126. }
  1127. }
  1128. if (FalseCst) {
  1129. int64_t F = FalseCst->Value.getSExtValue();
  1130. if (F == 1) {
  1131. // G_SELECT cc, t, 1 -> CSINC t, zreg, cc
  1132. Opc = Is32Bit ? AArch64::CSINCWr : AArch64::CSINCXr;
  1133. False = ZReg;
  1134. return true;
  1135. }
  1136. if (F == -1) {
  1137. // G_SELECT cc, t, -1 -> CSINC t, zreg, cc
  1138. Opc = Is32Bit ? AArch64::CSINVWr : AArch64::CSINVXr;
  1139. False = ZReg;
  1140. return true;
  1141. }
  1142. }
  1143. return false;
  1144. };
  1145. Optimized |= TryFoldBinOpIntoSelect(False, True, /*Invert = */ false);
  1146. Optimized |= TryFoldBinOpIntoSelect(True, False, /*Invert = */ true);
  1147. Optimized |= TryOptSelectCst();
  1148. auto SelectInst = MIB.buildInstr(Opc, {Dst}, {True, False}).addImm(CC);
  1149. constrainSelectedInstRegOperands(*SelectInst, TII, TRI, RBI);
  1150. return &*SelectInst;
  1151. }
  1152. static AArch64CC::CondCode changeICMPPredToAArch64CC(CmpInst::Predicate P) {
  1153. switch (P) {
  1154. default:
  1155. llvm_unreachable("Unknown condition code!");
  1156. case CmpInst::ICMP_NE:
  1157. return AArch64CC::NE;
  1158. case CmpInst::ICMP_EQ:
  1159. return AArch64CC::EQ;
  1160. case CmpInst::ICMP_SGT:
  1161. return AArch64CC::GT;
  1162. case CmpInst::ICMP_SGE:
  1163. return AArch64CC::GE;
  1164. case CmpInst::ICMP_SLT:
  1165. return AArch64CC::LT;
  1166. case CmpInst::ICMP_SLE:
  1167. return AArch64CC::LE;
  1168. case CmpInst::ICMP_UGT:
  1169. return AArch64CC::HI;
  1170. case CmpInst::ICMP_UGE:
  1171. return AArch64CC::HS;
  1172. case CmpInst::ICMP_ULT:
  1173. return AArch64CC::LO;
  1174. case CmpInst::ICMP_ULE:
  1175. return AArch64CC::LS;
  1176. }
  1177. }
  1178. /// changeFPCCToORAArch64CC - Convert an IR fp condition code to an AArch64 CC.
  1179. static void changeFPCCToORAArch64CC(CmpInst::Predicate CC,
  1180. AArch64CC::CondCode &CondCode,
  1181. AArch64CC::CondCode &CondCode2) {
  1182. CondCode2 = AArch64CC::AL;
  1183. switch (CC) {
  1184. default:
  1185. llvm_unreachable("Unknown FP condition!");
  1186. case CmpInst::FCMP_OEQ:
  1187. CondCode = AArch64CC::EQ;
  1188. break;
  1189. case CmpInst::FCMP_OGT:
  1190. CondCode = AArch64CC::GT;
  1191. break;
  1192. case CmpInst::FCMP_OGE:
  1193. CondCode = AArch64CC::GE;
  1194. break;
  1195. case CmpInst::FCMP_OLT:
  1196. CondCode = AArch64CC::MI;
  1197. break;
  1198. case CmpInst::FCMP_OLE:
  1199. CondCode = AArch64CC::LS;
  1200. break;
  1201. case CmpInst::FCMP_ONE:
  1202. CondCode = AArch64CC::MI;
  1203. CondCode2 = AArch64CC::GT;
  1204. break;
  1205. case CmpInst::FCMP_ORD:
  1206. CondCode = AArch64CC::VC;
  1207. break;
  1208. case CmpInst::FCMP_UNO:
  1209. CondCode = AArch64CC::VS;
  1210. break;
  1211. case CmpInst::FCMP_UEQ:
  1212. CondCode = AArch64CC::EQ;
  1213. CondCode2 = AArch64CC::VS;
  1214. break;
  1215. case CmpInst::FCMP_UGT:
  1216. CondCode = AArch64CC::HI;
  1217. break;
  1218. case CmpInst::FCMP_UGE:
  1219. CondCode = AArch64CC::PL;
  1220. break;
  1221. case CmpInst::FCMP_ULT:
  1222. CondCode = AArch64CC::LT;
  1223. break;
  1224. case CmpInst::FCMP_ULE:
  1225. CondCode = AArch64CC::LE;
  1226. break;
  1227. case CmpInst::FCMP_UNE:
  1228. CondCode = AArch64CC::NE;
  1229. break;
  1230. }
  1231. }
  1232. /// Convert an IR fp condition code to an AArch64 CC.
  1233. /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
  1234. /// should be AND'ed instead of OR'ed.
  1235. static void changeFPCCToANDAArch64CC(CmpInst::Predicate CC,
  1236. AArch64CC::CondCode &CondCode,
  1237. AArch64CC::CondCode &CondCode2) {
  1238. CondCode2 = AArch64CC::AL;
  1239. switch (CC) {
  1240. default:
  1241. changeFPCCToORAArch64CC(CC, CondCode, CondCode2);
  1242. assert(CondCode2 == AArch64CC::AL);
  1243. break;
  1244. case CmpInst::FCMP_ONE:
  1245. // (a one b)
  1246. // == ((a olt b) || (a ogt b))
  1247. // == ((a ord b) && (a une b))
  1248. CondCode = AArch64CC::VC;
  1249. CondCode2 = AArch64CC::NE;
  1250. break;
  1251. case CmpInst::FCMP_UEQ:
  1252. // (a ueq b)
  1253. // == ((a uno b) || (a oeq b))
  1254. // == ((a ule b) && (a uge b))
  1255. CondCode = AArch64CC::PL;
  1256. CondCode2 = AArch64CC::LE;
  1257. break;
  1258. }
  1259. }
  1260. /// Return a register which can be used as a bit to test in a TB(N)Z.
  1261. static Register getTestBitReg(Register Reg, uint64_t &Bit, bool &Invert,
  1262. MachineRegisterInfo &MRI) {
  1263. assert(Reg.isValid() && "Expected valid register!");
  1264. bool HasZext = false;
  1265. while (MachineInstr *MI = getDefIgnoringCopies(Reg, MRI)) {
  1266. unsigned Opc = MI->getOpcode();
  1267. if (!MI->getOperand(0).isReg() ||
  1268. !MRI.hasOneNonDBGUse(MI->getOperand(0).getReg()))
  1269. break;
  1270. // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits.
  1271. //
  1272. // (tbz (trunc x), b) -> (tbz x, b) is always safe, because the bit number
  1273. // on the truncated x is the same as the bit number on x.
  1274. if (Opc == TargetOpcode::G_ANYEXT || Opc == TargetOpcode::G_ZEXT ||
  1275. Opc == TargetOpcode::G_TRUNC) {
  1276. if (Opc == TargetOpcode::G_ZEXT)
  1277. HasZext = true;
  1278. Register NextReg = MI->getOperand(1).getReg();
  1279. // Did we find something worth folding?
  1280. if (!NextReg.isValid() || !MRI.hasOneNonDBGUse(NextReg))
  1281. break;
  1282. // NextReg is worth folding. Keep looking.
  1283. Reg = NextReg;
  1284. continue;
  1285. }
  1286. // Attempt to find a suitable operation with a constant on one side.
  1287. std::optional<uint64_t> C;
  1288. Register TestReg;
  1289. switch (Opc) {
  1290. default:
  1291. break;
  1292. case TargetOpcode::G_AND:
  1293. case TargetOpcode::G_XOR: {
  1294. TestReg = MI->getOperand(1).getReg();
  1295. Register ConstantReg = MI->getOperand(2).getReg();
  1296. auto VRegAndVal = getIConstantVRegValWithLookThrough(ConstantReg, MRI);
  1297. if (!VRegAndVal) {
  1298. // AND commutes, check the other side for a constant.
  1299. // FIXME: Can we canonicalize the constant so that it's always on the
  1300. // same side at some point earlier?
  1301. std::swap(ConstantReg, TestReg);
  1302. VRegAndVal = getIConstantVRegValWithLookThrough(ConstantReg, MRI);
  1303. }
  1304. if (VRegAndVal) {
  1305. if (HasZext)
  1306. C = VRegAndVal->Value.getZExtValue();
  1307. else
  1308. C = VRegAndVal->Value.getSExtValue();
  1309. }
  1310. break;
  1311. }
  1312. case TargetOpcode::G_ASHR:
  1313. case TargetOpcode::G_LSHR:
  1314. case TargetOpcode::G_SHL: {
  1315. TestReg = MI->getOperand(1).getReg();
  1316. auto VRegAndVal =
  1317. getIConstantVRegValWithLookThrough(MI->getOperand(2).getReg(), MRI);
  1318. if (VRegAndVal)
  1319. C = VRegAndVal->Value.getSExtValue();
  1320. break;
  1321. }
  1322. }
  1323. // Didn't find a constant or viable register. Bail out of the loop.
  1324. if (!C || !TestReg.isValid())
  1325. break;
  1326. // We found a suitable instruction with a constant. Check to see if we can
  1327. // walk through the instruction.
  1328. Register NextReg;
  1329. unsigned TestRegSize = MRI.getType(TestReg).getSizeInBits();
  1330. switch (Opc) {
  1331. default:
  1332. break;
  1333. case TargetOpcode::G_AND:
  1334. // (tbz (and x, m), b) -> (tbz x, b) when the b-th bit of m is set.
  1335. if ((*C >> Bit) & 1)
  1336. NextReg = TestReg;
  1337. break;
  1338. case TargetOpcode::G_SHL:
  1339. // (tbz (shl x, c), b) -> (tbz x, b-c) when b-c is positive and fits in
  1340. // the type of the register.
  1341. if (*C <= Bit && (Bit - *C) < TestRegSize) {
  1342. NextReg = TestReg;
  1343. Bit = Bit - *C;
  1344. }
  1345. break;
  1346. case TargetOpcode::G_ASHR:
  1347. // (tbz (ashr x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits
  1348. // in x
  1349. NextReg = TestReg;
  1350. Bit = Bit + *C;
  1351. if (Bit >= TestRegSize)
  1352. Bit = TestRegSize - 1;
  1353. break;
  1354. case TargetOpcode::G_LSHR:
  1355. // (tbz (lshr x, c), b) -> (tbz x, b+c) when b + c is < # bits in x
  1356. if ((Bit + *C) < TestRegSize) {
  1357. NextReg = TestReg;
  1358. Bit = Bit + *C;
  1359. }
  1360. break;
  1361. case TargetOpcode::G_XOR:
  1362. // We can walk through a G_XOR by inverting whether we use tbz/tbnz when
  1363. // appropriate.
  1364. //
  1365. // e.g. If x' = xor x, c, and the b-th bit is set in c then
  1366. //
  1367. // tbz x', b -> tbnz x, b
  1368. //
  1369. // Because x' only has the b-th bit set if x does not.
  1370. if ((*C >> Bit) & 1)
  1371. Invert = !Invert;
  1372. NextReg = TestReg;
  1373. break;
  1374. }
  1375. // Check if we found anything worth folding.
  1376. if (!NextReg.isValid())
  1377. return Reg;
  1378. Reg = NextReg;
  1379. }
  1380. return Reg;
  1381. }
  1382. MachineInstr *AArch64InstructionSelector::emitTestBit(
  1383. Register TestReg, uint64_t Bit, bool IsNegative, MachineBasicBlock *DstMBB,
  1384. MachineIRBuilder &MIB) const {
  1385. assert(TestReg.isValid());
  1386. assert(ProduceNonFlagSettingCondBr &&
  1387. "Cannot emit TB(N)Z with speculation tracking!");
  1388. MachineRegisterInfo &MRI = *MIB.getMRI();
  1389. // Attempt to optimize the test bit by walking over instructions.
  1390. TestReg = getTestBitReg(TestReg, Bit, IsNegative, MRI);
  1391. LLT Ty = MRI.getType(TestReg);
  1392. unsigned Size = Ty.getSizeInBits();
  1393. assert(!Ty.isVector() && "Expected a scalar!");
  1394. assert(Bit < 64 && "Bit is too large!");
  1395. // When the test register is a 64-bit register, we have to narrow to make
  1396. // TBNZW work.
  1397. bool UseWReg = Bit < 32;
  1398. unsigned NecessarySize = UseWReg ? 32 : 64;
  1399. if (Size != NecessarySize)
  1400. TestReg = moveScalarRegClass(
  1401. TestReg, UseWReg ? AArch64::GPR32RegClass : AArch64::GPR64RegClass,
  1402. MIB);
  1403. static const unsigned OpcTable[2][2] = {{AArch64::TBZX, AArch64::TBNZX},
  1404. {AArch64::TBZW, AArch64::TBNZW}};
  1405. unsigned Opc = OpcTable[UseWReg][IsNegative];
  1406. auto TestBitMI =
  1407. MIB.buildInstr(Opc).addReg(TestReg).addImm(Bit).addMBB(DstMBB);
  1408. constrainSelectedInstRegOperands(*TestBitMI, TII, TRI, RBI);
  1409. return &*TestBitMI;
  1410. }
  1411. bool AArch64InstructionSelector::tryOptAndIntoCompareBranch(
  1412. MachineInstr &AndInst, bool Invert, MachineBasicBlock *DstMBB,
  1413. MachineIRBuilder &MIB) const {
  1414. assert(AndInst.getOpcode() == TargetOpcode::G_AND && "Expected G_AND only?");
  1415. // Given something like this:
  1416. //
  1417. // %x = ...Something...
  1418. // %one = G_CONSTANT i64 1
  1419. // %zero = G_CONSTANT i64 0
  1420. // %and = G_AND %x, %one
  1421. // %cmp = G_ICMP intpred(ne), %and, %zero
  1422. // %cmp_trunc = G_TRUNC %cmp
  1423. // G_BRCOND %cmp_trunc, %bb.3
  1424. //
  1425. // We want to try and fold the AND into the G_BRCOND and produce either a
  1426. // TBNZ (when we have intpred(ne)) or a TBZ (when we have intpred(eq)).
  1427. //
  1428. // In this case, we'd get
  1429. //
  1430. // TBNZ %x %bb.3
  1431. //
  1432. // Check if the AND has a constant on its RHS which we can use as a mask.
  1433. // If it's a power of 2, then it's the same as checking a specific bit.
  1434. // (e.g, ANDing with 8 == ANDing with 000...100 == testing if bit 3 is set)
  1435. auto MaybeBit = getIConstantVRegValWithLookThrough(
  1436. AndInst.getOperand(2).getReg(), *MIB.getMRI());
  1437. if (!MaybeBit)
  1438. return false;
  1439. int32_t Bit = MaybeBit->Value.exactLogBase2();
  1440. if (Bit < 0)
  1441. return false;
  1442. Register TestReg = AndInst.getOperand(1).getReg();
  1443. // Emit a TB(N)Z.
  1444. emitTestBit(TestReg, Bit, Invert, DstMBB, MIB);
  1445. return true;
  1446. }
  1447. MachineInstr *AArch64InstructionSelector::emitCBZ(Register CompareReg,
  1448. bool IsNegative,
  1449. MachineBasicBlock *DestMBB,
  1450. MachineIRBuilder &MIB) const {
  1451. assert(ProduceNonFlagSettingCondBr && "CBZ does not set flags!");
  1452. MachineRegisterInfo &MRI = *MIB.getMRI();
  1453. assert(RBI.getRegBank(CompareReg, MRI, TRI)->getID() ==
  1454. AArch64::GPRRegBankID &&
  1455. "Expected GPRs only?");
  1456. auto Ty = MRI.getType(CompareReg);
  1457. unsigned Width = Ty.getSizeInBits();
  1458. assert(!Ty.isVector() && "Expected scalar only?");
  1459. assert(Width <= 64 && "Expected width to be at most 64?");
  1460. static const unsigned OpcTable[2][2] = {{AArch64::CBZW, AArch64::CBZX},
  1461. {AArch64::CBNZW, AArch64::CBNZX}};
  1462. unsigned Opc = OpcTable[IsNegative][Width == 64];
  1463. auto BranchMI = MIB.buildInstr(Opc, {}, {CompareReg}).addMBB(DestMBB);
  1464. constrainSelectedInstRegOperands(*BranchMI, TII, TRI, RBI);
  1465. return &*BranchMI;
  1466. }
  1467. bool AArch64InstructionSelector::selectCompareBranchFedByFCmp(
  1468. MachineInstr &I, MachineInstr &FCmp, MachineIRBuilder &MIB) const {
  1469. assert(FCmp.getOpcode() == TargetOpcode::G_FCMP);
  1470. assert(I.getOpcode() == TargetOpcode::G_BRCOND);
  1471. // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
  1472. // totally clean. Some of them require two branches to implement.
  1473. auto Pred = (CmpInst::Predicate)FCmp.getOperand(1).getPredicate();
  1474. emitFPCompare(FCmp.getOperand(2).getReg(), FCmp.getOperand(3).getReg(), MIB,
  1475. Pred);
  1476. AArch64CC::CondCode CC1, CC2;
  1477. changeFCMPPredToAArch64CC(static_cast<CmpInst::Predicate>(Pred), CC1, CC2);
  1478. MachineBasicBlock *DestMBB = I.getOperand(1).getMBB();
  1479. MIB.buildInstr(AArch64::Bcc, {}, {}).addImm(CC1).addMBB(DestMBB);
  1480. if (CC2 != AArch64CC::AL)
  1481. MIB.buildInstr(AArch64::Bcc, {}, {}).addImm(CC2).addMBB(DestMBB);
  1482. I.eraseFromParent();
  1483. return true;
  1484. }
  1485. bool AArch64InstructionSelector::tryOptCompareBranchFedByICmp(
  1486. MachineInstr &I, MachineInstr &ICmp, MachineIRBuilder &MIB) const {
  1487. assert(ICmp.getOpcode() == TargetOpcode::G_ICMP);
  1488. assert(I.getOpcode() == TargetOpcode::G_BRCOND);
  1489. // Attempt to optimize the G_BRCOND + G_ICMP into a TB(N)Z/CB(N)Z.
  1490. //
  1491. // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z
  1492. // instructions will not be produced, as they are conditional branch
  1493. // instructions that do not set flags.
  1494. if (!ProduceNonFlagSettingCondBr)
  1495. return false;
  1496. MachineRegisterInfo &MRI = *MIB.getMRI();
  1497. MachineBasicBlock *DestMBB = I.getOperand(1).getMBB();
  1498. auto Pred =
  1499. static_cast<CmpInst::Predicate>(ICmp.getOperand(1).getPredicate());
  1500. Register LHS = ICmp.getOperand(2).getReg();
  1501. Register RHS = ICmp.getOperand(3).getReg();
  1502. // We're allowed to emit a TB(N)Z/CB(N)Z. Try to do that.
  1503. auto VRegAndVal = getIConstantVRegValWithLookThrough(RHS, MRI);
  1504. MachineInstr *AndInst = getOpcodeDef(TargetOpcode::G_AND, LHS, MRI);
  1505. // When we can emit a TB(N)Z, prefer that.
  1506. //
  1507. // Handle non-commutative condition codes first.
  1508. // Note that we don't want to do this when we have a G_AND because it can
  1509. // become a tst. The tst will make the test bit in the TB(N)Z redundant.
  1510. if (VRegAndVal && !AndInst) {
  1511. int64_t C = VRegAndVal->Value.getSExtValue();
  1512. // When we have a greater-than comparison, we can just test if the msb is
  1513. // zero.
  1514. if (C == -1 && Pred == CmpInst::ICMP_SGT) {
  1515. uint64_t Bit = MRI.getType(LHS).getSizeInBits() - 1;
  1516. emitTestBit(LHS, Bit, /*IsNegative = */ false, DestMBB, MIB);
  1517. I.eraseFromParent();
  1518. return true;
  1519. }
  1520. // When we have a less than comparison, we can just test if the msb is not
  1521. // zero.
  1522. if (C == 0 && Pred == CmpInst::ICMP_SLT) {
  1523. uint64_t Bit = MRI.getType(LHS).getSizeInBits() - 1;
  1524. emitTestBit(LHS, Bit, /*IsNegative = */ true, DestMBB, MIB);
  1525. I.eraseFromParent();
  1526. return true;
  1527. }
  1528. // Inversely, if we have a signed greater-than-or-equal comparison to zero,
  1529. // we can test if the msb is zero.
  1530. if (C == 0 && Pred == CmpInst::ICMP_SGE) {
  1531. uint64_t Bit = MRI.getType(LHS).getSizeInBits() - 1;
  1532. emitTestBit(LHS, Bit, /*IsNegative = */ false, DestMBB, MIB);
  1533. I.eraseFromParent();
  1534. return true;
  1535. }
  1536. }
  1537. // Attempt to handle commutative condition codes. Right now, that's only
  1538. // eq/ne.
  1539. if (ICmpInst::isEquality(Pred)) {
  1540. if (!VRegAndVal) {
  1541. std::swap(RHS, LHS);
  1542. VRegAndVal = getIConstantVRegValWithLookThrough(RHS, MRI);
  1543. AndInst = getOpcodeDef(TargetOpcode::G_AND, LHS, MRI);
  1544. }
  1545. if (VRegAndVal && VRegAndVal->Value == 0) {
  1546. // If there's a G_AND feeding into this branch, try to fold it away by
  1547. // emitting a TB(N)Z instead.
  1548. //
  1549. // Note: If we have LT, then it *is* possible to fold, but it wouldn't be
  1550. // beneficial. When we have an AND and LT, we need a TST/ANDS, so folding
  1551. // would be redundant.
  1552. if (AndInst &&
  1553. tryOptAndIntoCompareBranch(
  1554. *AndInst, /*Invert = */ Pred == CmpInst::ICMP_NE, DestMBB, MIB)) {
  1555. I.eraseFromParent();
  1556. return true;
  1557. }
  1558. // Otherwise, try to emit a CB(N)Z instead.
  1559. auto LHSTy = MRI.getType(LHS);
  1560. if (!LHSTy.isVector() && LHSTy.getSizeInBits() <= 64) {
  1561. emitCBZ(LHS, /*IsNegative = */ Pred == CmpInst::ICMP_NE, DestMBB, MIB);
  1562. I.eraseFromParent();
  1563. return true;
  1564. }
  1565. }
  1566. }
  1567. return false;
  1568. }
  1569. bool AArch64InstructionSelector::selectCompareBranchFedByICmp(
  1570. MachineInstr &I, MachineInstr &ICmp, MachineIRBuilder &MIB) const {
  1571. assert(ICmp.getOpcode() == TargetOpcode::G_ICMP);
  1572. assert(I.getOpcode() == TargetOpcode::G_BRCOND);
  1573. if (tryOptCompareBranchFedByICmp(I, ICmp, MIB))
  1574. return true;
  1575. // Couldn't optimize. Emit a compare + a Bcc.
  1576. MachineBasicBlock *DestMBB = I.getOperand(1).getMBB();
  1577. auto PredOp = ICmp.getOperand(1);
  1578. emitIntegerCompare(ICmp.getOperand(2), ICmp.getOperand(3), PredOp, MIB);
  1579. const AArch64CC::CondCode CC = changeICMPPredToAArch64CC(
  1580. static_cast<CmpInst::Predicate>(PredOp.getPredicate()));
  1581. MIB.buildInstr(AArch64::Bcc, {}, {}).addImm(CC).addMBB(DestMBB);
  1582. I.eraseFromParent();
  1583. return true;
  1584. }
  1585. bool AArch64InstructionSelector::selectCompareBranch(
  1586. MachineInstr &I, MachineFunction &MF, MachineRegisterInfo &MRI) {
  1587. Register CondReg = I.getOperand(0).getReg();
  1588. MachineInstr *CCMI = MRI.getVRegDef(CondReg);
  1589. // Try to select the G_BRCOND using whatever is feeding the condition if
  1590. // possible.
  1591. unsigned CCMIOpc = CCMI->getOpcode();
  1592. if (CCMIOpc == TargetOpcode::G_FCMP)
  1593. return selectCompareBranchFedByFCmp(I, *CCMI, MIB);
  1594. if (CCMIOpc == TargetOpcode::G_ICMP)
  1595. return selectCompareBranchFedByICmp(I, *CCMI, MIB);
  1596. // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z
  1597. // instructions will not be produced, as they are conditional branch
  1598. // instructions that do not set flags.
  1599. if (ProduceNonFlagSettingCondBr) {
  1600. emitTestBit(CondReg, /*Bit = */ 0, /*IsNegative = */ true,
  1601. I.getOperand(1).getMBB(), MIB);
  1602. I.eraseFromParent();
  1603. return true;
  1604. }
  1605. // Can't emit TB(N)Z/CB(N)Z. Emit a tst + bcc instead.
  1606. auto TstMI =
  1607. MIB.buildInstr(AArch64::ANDSWri, {LLT::scalar(32)}, {CondReg}).addImm(1);
  1608. constrainSelectedInstRegOperands(*TstMI, TII, TRI, RBI);
  1609. auto Bcc = MIB.buildInstr(AArch64::Bcc)
  1610. .addImm(AArch64CC::EQ)
  1611. .addMBB(I.getOperand(1).getMBB());
  1612. I.eraseFromParent();
  1613. return constrainSelectedInstRegOperands(*Bcc, TII, TRI, RBI);
  1614. }
  1615. /// Returns the element immediate value of a vector shift operand if found.
  1616. /// This needs to detect a splat-like operation, e.g. a G_BUILD_VECTOR.
  1617. static std::optional<int64_t> getVectorShiftImm(Register Reg,
  1618. MachineRegisterInfo &MRI) {
  1619. assert(MRI.getType(Reg).isVector() && "Expected a *vector* shift operand");
  1620. MachineInstr *OpMI = MRI.getVRegDef(Reg);
  1621. return getAArch64VectorSplatScalar(*OpMI, MRI);
  1622. }
  1623. /// Matches and returns the shift immediate value for a SHL instruction given
  1624. /// a shift operand.
  1625. static std::optional<int64_t> getVectorSHLImm(LLT SrcTy, Register Reg,
  1626. MachineRegisterInfo &MRI) {
  1627. std::optional<int64_t> ShiftImm = getVectorShiftImm(Reg, MRI);
  1628. if (!ShiftImm)
  1629. return std::nullopt;
  1630. // Check the immediate is in range for a SHL.
  1631. int64_t Imm = *ShiftImm;
  1632. if (Imm < 0)
  1633. return std::nullopt;
  1634. switch (SrcTy.getElementType().getSizeInBits()) {
  1635. default:
  1636. LLVM_DEBUG(dbgs() << "Unhandled element type for vector shift");
  1637. return std::nullopt;
  1638. case 8:
  1639. if (Imm > 7)
  1640. return std::nullopt;
  1641. break;
  1642. case 16:
  1643. if (Imm > 15)
  1644. return std::nullopt;
  1645. break;
  1646. case 32:
  1647. if (Imm > 31)
  1648. return std::nullopt;
  1649. break;
  1650. case 64:
  1651. if (Imm > 63)
  1652. return std::nullopt;
  1653. break;
  1654. }
  1655. return Imm;
  1656. }
  1657. bool AArch64InstructionSelector::selectVectorSHL(MachineInstr &I,
  1658. MachineRegisterInfo &MRI) {
  1659. assert(I.getOpcode() == TargetOpcode::G_SHL);
  1660. Register DstReg = I.getOperand(0).getReg();
  1661. const LLT Ty = MRI.getType(DstReg);
  1662. Register Src1Reg = I.getOperand(1).getReg();
  1663. Register Src2Reg = I.getOperand(2).getReg();
  1664. if (!Ty.isVector())
  1665. return false;
  1666. // Check if we have a vector of constants on RHS that we can select as the
  1667. // immediate form.
  1668. std::optional<int64_t> ImmVal = getVectorSHLImm(Ty, Src2Reg, MRI);
  1669. unsigned Opc = 0;
  1670. if (Ty == LLT::fixed_vector(2, 64)) {
  1671. Opc = ImmVal ? AArch64::SHLv2i64_shift : AArch64::USHLv2i64;
  1672. } else if (Ty == LLT::fixed_vector(4, 32)) {
  1673. Opc = ImmVal ? AArch64::SHLv4i32_shift : AArch64::USHLv4i32;
  1674. } else if (Ty == LLT::fixed_vector(2, 32)) {
  1675. Opc = ImmVal ? AArch64::SHLv2i32_shift : AArch64::USHLv2i32;
  1676. } else if (Ty == LLT::fixed_vector(4, 16)) {
  1677. Opc = ImmVal ? AArch64::SHLv4i16_shift : AArch64::USHLv4i16;
  1678. } else if (Ty == LLT::fixed_vector(8, 16)) {
  1679. Opc = ImmVal ? AArch64::SHLv8i16_shift : AArch64::USHLv8i16;
  1680. } else if (Ty == LLT::fixed_vector(16, 8)) {
  1681. Opc = ImmVal ? AArch64::SHLv16i8_shift : AArch64::USHLv16i8;
  1682. } else if (Ty == LLT::fixed_vector(8, 8)) {
  1683. Opc = ImmVal ? AArch64::SHLv8i8_shift : AArch64::USHLv8i8;
  1684. } else {
  1685. LLVM_DEBUG(dbgs() << "Unhandled G_SHL type");
  1686. return false;
  1687. }
  1688. auto Shl = MIB.buildInstr(Opc, {DstReg}, {Src1Reg});
  1689. if (ImmVal)
  1690. Shl.addImm(*ImmVal);
  1691. else
  1692. Shl.addUse(Src2Reg);
  1693. constrainSelectedInstRegOperands(*Shl, TII, TRI, RBI);
  1694. I.eraseFromParent();
  1695. return true;
  1696. }
  1697. bool AArch64InstructionSelector::selectVectorAshrLshr(
  1698. MachineInstr &I, MachineRegisterInfo &MRI) {
  1699. assert(I.getOpcode() == TargetOpcode::G_ASHR ||
  1700. I.getOpcode() == TargetOpcode::G_LSHR);
  1701. Register DstReg = I.getOperand(0).getReg();
  1702. const LLT Ty = MRI.getType(DstReg);
  1703. Register Src1Reg = I.getOperand(1).getReg();
  1704. Register Src2Reg = I.getOperand(2).getReg();
  1705. if (!Ty.isVector())
  1706. return false;
  1707. bool IsASHR = I.getOpcode() == TargetOpcode::G_ASHR;
  1708. // We expect the immediate case to be lowered in the PostLegalCombiner to
  1709. // AArch64ISD::VASHR or AArch64ISD::VLSHR equivalents.
  1710. // There is not a shift right register instruction, but the shift left
  1711. // register instruction takes a signed value, where negative numbers specify a
  1712. // right shift.
  1713. unsigned Opc = 0;
  1714. unsigned NegOpc = 0;
  1715. const TargetRegisterClass *RC =
  1716. getRegClassForTypeOnBank(Ty, RBI.getRegBank(AArch64::FPRRegBankID));
  1717. if (Ty == LLT::fixed_vector(2, 64)) {
  1718. Opc = IsASHR ? AArch64::SSHLv2i64 : AArch64::USHLv2i64;
  1719. NegOpc = AArch64::NEGv2i64;
  1720. } else if (Ty == LLT::fixed_vector(4, 32)) {
  1721. Opc = IsASHR ? AArch64::SSHLv4i32 : AArch64::USHLv4i32;
  1722. NegOpc = AArch64::NEGv4i32;
  1723. } else if (Ty == LLT::fixed_vector(2, 32)) {
  1724. Opc = IsASHR ? AArch64::SSHLv2i32 : AArch64::USHLv2i32;
  1725. NegOpc = AArch64::NEGv2i32;
  1726. } else if (Ty == LLT::fixed_vector(4, 16)) {
  1727. Opc = IsASHR ? AArch64::SSHLv4i16 : AArch64::USHLv4i16;
  1728. NegOpc = AArch64::NEGv4i16;
  1729. } else if (Ty == LLT::fixed_vector(8, 16)) {
  1730. Opc = IsASHR ? AArch64::SSHLv8i16 : AArch64::USHLv8i16;
  1731. NegOpc = AArch64::NEGv8i16;
  1732. } else if (Ty == LLT::fixed_vector(16, 8)) {
  1733. Opc = IsASHR ? AArch64::SSHLv16i8 : AArch64::USHLv16i8;
  1734. NegOpc = AArch64::NEGv16i8;
  1735. } else if (Ty == LLT::fixed_vector(8, 8)) {
  1736. Opc = IsASHR ? AArch64::SSHLv8i8 : AArch64::USHLv8i8;
  1737. NegOpc = AArch64::NEGv8i8;
  1738. } else {
  1739. LLVM_DEBUG(dbgs() << "Unhandled G_ASHR type");
  1740. return false;
  1741. }
  1742. auto Neg = MIB.buildInstr(NegOpc, {RC}, {Src2Reg});
  1743. constrainSelectedInstRegOperands(*Neg, TII, TRI, RBI);
  1744. auto SShl = MIB.buildInstr(Opc, {DstReg}, {Src1Reg, Neg});
  1745. constrainSelectedInstRegOperands(*SShl, TII, TRI, RBI);
  1746. I.eraseFromParent();
  1747. return true;
  1748. }
  1749. bool AArch64InstructionSelector::selectVaStartAAPCS(
  1750. MachineInstr &I, MachineFunction &MF, MachineRegisterInfo &MRI) const {
  1751. return false;
  1752. }
  1753. bool AArch64InstructionSelector::selectVaStartDarwin(
  1754. MachineInstr &I, MachineFunction &MF, MachineRegisterInfo &MRI) const {
  1755. AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
  1756. Register ListReg = I.getOperand(0).getReg();
  1757. Register ArgsAddrReg = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
  1758. auto MIB =
  1759. BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(AArch64::ADDXri))
  1760. .addDef(ArgsAddrReg)
  1761. .addFrameIndex(FuncInfo->getVarArgsStackIndex())
  1762. .addImm(0)
  1763. .addImm(0);
  1764. constrainSelectedInstRegOperands(*MIB, TII, TRI, RBI);
  1765. MIB = BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(AArch64::STRXui))
  1766. .addUse(ArgsAddrReg)
  1767. .addUse(ListReg)
  1768. .addImm(0)
  1769. .addMemOperand(*I.memoperands_begin());
  1770. constrainSelectedInstRegOperands(*MIB, TII, TRI, RBI);
  1771. I.eraseFromParent();
  1772. return true;
  1773. }
  1774. void AArch64InstructionSelector::materializeLargeCMVal(
  1775. MachineInstr &I, const Value *V, unsigned OpFlags) {
  1776. MachineBasicBlock &MBB = *I.getParent();
  1777. MachineFunction &MF = *MBB.getParent();
  1778. MachineRegisterInfo &MRI = MF.getRegInfo();
  1779. auto MovZ = MIB.buildInstr(AArch64::MOVZXi, {&AArch64::GPR64RegClass}, {});
  1780. MovZ->addOperand(MF, I.getOperand(1));
  1781. MovZ->getOperand(1).setTargetFlags(OpFlags | AArch64II::MO_G0 |
  1782. AArch64II::MO_NC);
  1783. MovZ->addOperand(MF, MachineOperand::CreateImm(0));
  1784. constrainSelectedInstRegOperands(*MovZ, TII, TRI, RBI);
  1785. auto BuildMovK = [&](Register SrcReg, unsigned char Flags, unsigned Offset,
  1786. Register ForceDstReg) {
  1787. Register DstReg = ForceDstReg
  1788. ? ForceDstReg
  1789. : MRI.createVirtualRegister(&AArch64::GPR64RegClass);
  1790. auto MovI = MIB.buildInstr(AArch64::MOVKXi).addDef(DstReg).addUse(SrcReg);
  1791. if (auto *GV = dyn_cast<GlobalValue>(V)) {
  1792. MovI->addOperand(MF, MachineOperand::CreateGA(
  1793. GV, MovZ->getOperand(1).getOffset(), Flags));
  1794. } else {
  1795. MovI->addOperand(
  1796. MF, MachineOperand::CreateBA(cast<BlockAddress>(V),
  1797. MovZ->getOperand(1).getOffset(), Flags));
  1798. }
  1799. MovI->addOperand(MF, MachineOperand::CreateImm(Offset));
  1800. constrainSelectedInstRegOperands(*MovI, TII, TRI, RBI);
  1801. return DstReg;
  1802. };
  1803. Register DstReg = BuildMovK(MovZ.getReg(0),
  1804. AArch64II::MO_G1 | AArch64II::MO_NC, 16, 0);
  1805. DstReg = BuildMovK(DstReg, AArch64II::MO_G2 | AArch64II::MO_NC, 32, 0);
  1806. BuildMovK(DstReg, AArch64II::MO_G3, 48, I.getOperand(0).getReg());
  1807. }
  1808. bool AArch64InstructionSelector::preISelLower(MachineInstr &I) {
  1809. MachineBasicBlock &MBB = *I.getParent();
  1810. MachineFunction &MF = *MBB.getParent();
  1811. MachineRegisterInfo &MRI = MF.getRegInfo();
  1812. switch (I.getOpcode()) {
  1813. case TargetOpcode::G_STORE: {
  1814. bool Changed = contractCrossBankCopyIntoStore(I, MRI);
  1815. MachineOperand &SrcOp = I.getOperand(0);
  1816. if (MRI.getType(SrcOp.getReg()).isPointer()) {
  1817. // Allow matching with imported patterns for stores of pointers. Unlike
  1818. // G_LOAD/G_PTR_ADD, we may not have selected all users. So, emit a copy
  1819. // and constrain.
  1820. auto Copy = MIB.buildCopy(LLT::scalar(64), SrcOp);
  1821. Register NewSrc = Copy.getReg(0);
  1822. SrcOp.setReg(NewSrc);
  1823. RBI.constrainGenericRegister(NewSrc, AArch64::GPR64RegClass, MRI);
  1824. Changed = true;
  1825. }
  1826. return Changed;
  1827. }
  1828. case TargetOpcode::G_PTR_ADD:
  1829. return convertPtrAddToAdd(I, MRI);
  1830. case TargetOpcode::G_LOAD: {
  1831. // For scalar loads of pointers, we try to convert the dest type from p0
  1832. // to s64 so that our imported patterns can match. Like with the G_PTR_ADD
  1833. // conversion, this should be ok because all users should have been
  1834. // selected already, so the type doesn't matter for them.
  1835. Register DstReg = I.getOperand(0).getReg();
  1836. const LLT DstTy = MRI.getType(DstReg);
  1837. if (!DstTy.isPointer())
  1838. return false;
  1839. MRI.setType(DstReg, LLT::scalar(64));
  1840. return true;
  1841. }
  1842. case AArch64::G_DUP: {
  1843. // Convert the type from p0 to s64 to help selection.
  1844. LLT DstTy = MRI.getType(I.getOperand(0).getReg());
  1845. if (!DstTy.getElementType().isPointer())
  1846. return false;
  1847. auto NewSrc = MIB.buildCopy(LLT::scalar(64), I.getOperand(1).getReg());
  1848. MRI.setType(I.getOperand(0).getReg(),
  1849. DstTy.changeElementType(LLT::scalar(64)));
  1850. MRI.setRegClass(NewSrc.getReg(0), &AArch64::GPR64RegClass);
  1851. I.getOperand(1).setReg(NewSrc.getReg(0));
  1852. return true;
  1853. }
  1854. case TargetOpcode::G_UITOFP:
  1855. case TargetOpcode::G_SITOFP: {
  1856. // If both source and destination regbanks are FPR, then convert the opcode
  1857. // to G_SITOF so that the importer can select it to an fpr variant.
  1858. // Otherwise, it ends up matching an fpr/gpr variant and adding a cross-bank
  1859. // copy.
  1860. Register SrcReg = I.getOperand(1).getReg();
  1861. LLT SrcTy = MRI.getType(SrcReg);
  1862. LLT DstTy = MRI.getType(I.getOperand(0).getReg());
  1863. if (SrcTy.isVector() || SrcTy.getSizeInBits() != DstTy.getSizeInBits())
  1864. return false;
  1865. if (RBI.getRegBank(SrcReg, MRI, TRI)->getID() == AArch64::FPRRegBankID) {
  1866. if (I.getOpcode() == TargetOpcode::G_SITOFP)
  1867. I.setDesc(TII.get(AArch64::G_SITOF));
  1868. else
  1869. I.setDesc(TII.get(AArch64::G_UITOF));
  1870. return true;
  1871. }
  1872. return false;
  1873. }
  1874. default:
  1875. return false;
  1876. }
  1877. }
  1878. /// This lowering tries to look for G_PTR_ADD instructions and then converts
  1879. /// them to a standard G_ADD with a COPY on the source.
  1880. ///
  1881. /// The motivation behind this is to expose the add semantics to the imported
  1882. /// tablegen patterns. We shouldn't need to check for uses being loads/stores,
  1883. /// because the selector works bottom up, uses before defs. By the time we
  1884. /// end up trying to select a G_PTR_ADD, we should have already attempted to
  1885. /// fold this into addressing modes and were therefore unsuccessful.
  1886. bool AArch64InstructionSelector::convertPtrAddToAdd(
  1887. MachineInstr &I, MachineRegisterInfo &MRI) {
  1888. assert(I.getOpcode() == TargetOpcode::G_PTR_ADD && "Expected G_PTR_ADD");
  1889. Register DstReg = I.getOperand(0).getReg();
  1890. Register AddOp1Reg = I.getOperand(1).getReg();
  1891. const LLT PtrTy = MRI.getType(DstReg);
  1892. if (PtrTy.getAddressSpace() != 0)
  1893. return false;
  1894. const LLT CastPtrTy =
  1895. PtrTy.isVector() ? LLT::fixed_vector(2, 64) : LLT::scalar(64);
  1896. auto PtrToInt = MIB.buildPtrToInt(CastPtrTy, AddOp1Reg);
  1897. // Set regbanks on the registers.
  1898. if (PtrTy.isVector())
  1899. MRI.setRegBank(PtrToInt.getReg(0), RBI.getRegBank(AArch64::FPRRegBankID));
  1900. else
  1901. MRI.setRegBank(PtrToInt.getReg(0), RBI.getRegBank(AArch64::GPRRegBankID));
  1902. // Now turn the %dst(p0) = G_PTR_ADD %base, off into:
  1903. // %dst(intty) = G_ADD %intbase, off
  1904. I.setDesc(TII.get(TargetOpcode::G_ADD));
  1905. MRI.setType(DstReg, CastPtrTy);
  1906. I.getOperand(1).setReg(PtrToInt.getReg(0));
  1907. if (!select(*PtrToInt)) {
  1908. LLVM_DEBUG(dbgs() << "Failed to select G_PTRTOINT in convertPtrAddToAdd");
  1909. return false;
  1910. }
  1911. // Also take the opportunity here to try to do some optimization.
  1912. // Try to convert this into a G_SUB if the offset is a 0-x negate idiom.
  1913. Register NegatedReg;
  1914. if (!mi_match(I.getOperand(2).getReg(), MRI, m_Neg(m_Reg(NegatedReg))))
  1915. return true;
  1916. I.getOperand(2).setReg(NegatedReg);
  1917. I.setDesc(TII.get(TargetOpcode::G_SUB));
  1918. return true;
  1919. }
  1920. bool AArch64InstructionSelector::earlySelectSHL(MachineInstr &I,
  1921. MachineRegisterInfo &MRI) {
  1922. // We try to match the immediate variant of LSL, which is actually an alias
  1923. // for a special case of UBFM. Otherwise, we fall back to the imported
  1924. // selector which will match the register variant.
  1925. assert(I.getOpcode() == TargetOpcode::G_SHL && "unexpected op");
  1926. const auto &MO = I.getOperand(2);
  1927. auto VRegAndVal = getIConstantVRegVal(MO.getReg(), MRI);
  1928. if (!VRegAndVal)
  1929. return false;
  1930. const LLT DstTy = MRI.getType(I.getOperand(0).getReg());
  1931. if (DstTy.isVector())
  1932. return false;
  1933. bool Is64Bit = DstTy.getSizeInBits() == 64;
  1934. auto Imm1Fn = Is64Bit ? selectShiftA_64(MO) : selectShiftA_32(MO);
  1935. auto Imm2Fn = Is64Bit ? selectShiftB_64(MO) : selectShiftB_32(MO);
  1936. if (!Imm1Fn || !Imm2Fn)
  1937. return false;
  1938. auto NewI =
  1939. MIB.buildInstr(Is64Bit ? AArch64::UBFMXri : AArch64::UBFMWri,
  1940. {I.getOperand(0).getReg()}, {I.getOperand(1).getReg()});
  1941. for (auto &RenderFn : *Imm1Fn)
  1942. RenderFn(NewI);
  1943. for (auto &RenderFn : *Imm2Fn)
  1944. RenderFn(NewI);
  1945. I.eraseFromParent();
  1946. return constrainSelectedInstRegOperands(*NewI, TII, TRI, RBI);
  1947. }
  1948. bool AArch64InstructionSelector::contractCrossBankCopyIntoStore(
  1949. MachineInstr &I, MachineRegisterInfo &MRI) {
  1950. assert(I.getOpcode() == TargetOpcode::G_STORE && "Expected G_STORE");
  1951. // If we're storing a scalar, it doesn't matter what register bank that
  1952. // scalar is on. All that matters is the size.
  1953. //
  1954. // So, if we see something like this (with a 32-bit scalar as an example):
  1955. //
  1956. // %x:gpr(s32) = ... something ...
  1957. // %y:fpr(s32) = COPY %x:gpr(s32)
  1958. // G_STORE %y:fpr(s32)
  1959. //
  1960. // We can fix this up into something like this:
  1961. //
  1962. // G_STORE %x:gpr(s32)
  1963. //
  1964. // And then continue the selection process normally.
  1965. Register DefDstReg = getSrcRegIgnoringCopies(I.getOperand(0).getReg(), MRI);
  1966. if (!DefDstReg.isValid())
  1967. return false;
  1968. LLT DefDstTy = MRI.getType(DefDstReg);
  1969. Register StoreSrcReg = I.getOperand(0).getReg();
  1970. LLT StoreSrcTy = MRI.getType(StoreSrcReg);
  1971. // If we get something strange like a physical register, then we shouldn't
  1972. // go any further.
  1973. if (!DefDstTy.isValid())
  1974. return false;
  1975. // Are the source and dst types the same size?
  1976. if (DefDstTy.getSizeInBits() != StoreSrcTy.getSizeInBits())
  1977. return false;
  1978. if (RBI.getRegBank(StoreSrcReg, MRI, TRI) ==
  1979. RBI.getRegBank(DefDstReg, MRI, TRI))
  1980. return false;
  1981. // We have a cross-bank copy, which is entering a store. Let's fold it.
  1982. I.getOperand(0).setReg(DefDstReg);
  1983. return true;
  1984. }
  1985. bool AArch64InstructionSelector::earlySelect(MachineInstr &I) {
  1986. assert(I.getParent() && "Instruction should be in a basic block!");
  1987. assert(I.getParent()->getParent() && "Instruction should be in a function!");
  1988. MachineBasicBlock &MBB = *I.getParent();
  1989. MachineFunction &MF = *MBB.getParent();
  1990. MachineRegisterInfo &MRI = MF.getRegInfo();
  1991. switch (I.getOpcode()) {
  1992. case AArch64::G_DUP: {
  1993. // Before selecting a DUP instruction, check if it is better selected as a
  1994. // MOV or load from a constant pool.
  1995. Register Src = I.getOperand(1).getReg();
  1996. auto ValAndVReg = getIConstantVRegValWithLookThrough(Src, MRI);
  1997. if (!ValAndVReg)
  1998. return false;
  1999. LLVMContext &Ctx = MF.getFunction().getContext();
  2000. Register Dst = I.getOperand(0).getReg();
  2001. auto *CV = ConstantDataVector::getSplat(
  2002. MRI.getType(Dst).getNumElements(),
  2003. ConstantInt::get(Type::getIntNTy(Ctx, MRI.getType(Src).getSizeInBits()),
  2004. ValAndVReg->Value));
  2005. if (!emitConstantVector(Dst, CV, MIB, MRI))
  2006. return false;
  2007. I.eraseFromParent();
  2008. return true;
  2009. }
  2010. case TargetOpcode::G_SEXT:
  2011. // Check for i64 sext(i32 vector_extract) prior to tablegen to select SMOV
  2012. // over a normal extend.
  2013. if (selectUSMovFromExtend(I, MRI))
  2014. return true;
  2015. return false;
  2016. case TargetOpcode::G_BR:
  2017. return false;
  2018. case TargetOpcode::G_SHL:
  2019. return earlySelectSHL(I, MRI);
  2020. case TargetOpcode::G_CONSTANT: {
  2021. bool IsZero = false;
  2022. if (I.getOperand(1).isCImm())
  2023. IsZero = I.getOperand(1).getCImm()->getZExtValue() == 0;
  2024. else if (I.getOperand(1).isImm())
  2025. IsZero = I.getOperand(1).getImm() == 0;
  2026. if (!IsZero)
  2027. return false;
  2028. Register DefReg = I.getOperand(0).getReg();
  2029. LLT Ty = MRI.getType(DefReg);
  2030. if (Ty.getSizeInBits() == 64) {
  2031. I.getOperand(1).ChangeToRegister(AArch64::XZR, false);
  2032. RBI.constrainGenericRegister(DefReg, AArch64::GPR64RegClass, MRI);
  2033. } else if (Ty.getSizeInBits() == 32) {
  2034. I.getOperand(1).ChangeToRegister(AArch64::WZR, false);
  2035. RBI.constrainGenericRegister(DefReg, AArch64::GPR32RegClass, MRI);
  2036. } else
  2037. return false;
  2038. I.setDesc(TII.get(TargetOpcode::COPY));
  2039. return true;
  2040. }
  2041. case TargetOpcode::G_ADD: {
  2042. // Check if this is being fed by a G_ICMP on either side.
  2043. //
  2044. // (cmp pred, x, y) + z
  2045. //
  2046. // In the above case, when the cmp is true, we increment z by 1. So, we can
  2047. // fold the add into the cset for the cmp by using cinc.
  2048. //
  2049. // FIXME: This would probably be a lot nicer in PostLegalizerLowering.
  2050. Register AddDst = I.getOperand(0).getReg();
  2051. Register AddLHS = I.getOperand(1).getReg();
  2052. Register AddRHS = I.getOperand(2).getReg();
  2053. // Only handle scalars.
  2054. LLT Ty = MRI.getType(AddLHS);
  2055. if (Ty.isVector())
  2056. return false;
  2057. // Since G_ICMP is modeled as ADDS/SUBS/ANDS, we can handle 32 bits or 64
  2058. // bits.
  2059. unsigned Size = Ty.getSizeInBits();
  2060. if (Size != 32 && Size != 64)
  2061. return false;
  2062. auto MatchCmp = [&](Register Reg) -> MachineInstr * {
  2063. if (!MRI.hasOneNonDBGUse(Reg))
  2064. return nullptr;
  2065. // If the LHS of the add is 32 bits, then we want to fold a 32-bit
  2066. // compare.
  2067. if (Size == 32)
  2068. return getOpcodeDef(TargetOpcode::G_ICMP, Reg, MRI);
  2069. // We model scalar compares using 32-bit destinations right now.
  2070. // If it's a 64-bit compare, it'll have 64-bit sources.
  2071. Register ZExt;
  2072. if (!mi_match(Reg, MRI,
  2073. m_OneNonDBGUse(m_GZExt(m_OneNonDBGUse(m_Reg(ZExt))))))
  2074. return nullptr;
  2075. auto *Cmp = getOpcodeDef(TargetOpcode::G_ICMP, ZExt, MRI);
  2076. if (!Cmp ||
  2077. MRI.getType(Cmp->getOperand(2).getReg()).getSizeInBits() != 64)
  2078. return nullptr;
  2079. return Cmp;
  2080. };
  2081. // Try to match
  2082. // z + (cmp pred, x, y)
  2083. MachineInstr *Cmp = MatchCmp(AddRHS);
  2084. if (!Cmp) {
  2085. // (cmp pred, x, y) + z
  2086. std::swap(AddLHS, AddRHS);
  2087. Cmp = MatchCmp(AddRHS);
  2088. if (!Cmp)
  2089. return false;
  2090. }
  2091. auto &PredOp = Cmp->getOperand(1);
  2092. auto Pred = static_cast<CmpInst::Predicate>(PredOp.getPredicate());
  2093. const AArch64CC::CondCode InvCC =
  2094. changeICMPPredToAArch64CC(CmpInst::getInversePredicate(Pred));
  2095. MIB.setInstrAndDebugLoc(I);
  2096. emitIntegerCompare(/*LHS=*/Cmp->getOperand(2),
  2097. /*RHS=*/Cmp->getOperand(3), PredOp, MIB);
  2098. emitCSINC(/*Dst=*/AddDst, /*Src =*/AddLHS, /*Src2=*/AddLHS, InvCC, MIB);
  2099. I.eraseFromParent();
  2100. return true;
  2101. }
  2102. case TargetOpcode::G_OR: {
  2103. // Look for operations that take the lower `Width=Size-ShiftImm` bits of
  2104. // `ShiftSrc` and insert them into the upper `Width` bits of `MaskSrc` via
  2105. // shifting and masking that we can replace with a BFI (encoded as a BFM).
  2106. Register Dst = I.getOperand(0).getReg();
  2107. LLT Ty = MRI.getType(Dst);
  2108. if (!Ty.isScalar())
  2109. return false;
  2110. unsigned Size = Ty.getSizeInBits();
  2111. if (Size != 32 && Size != 64)
  2112. return false;
  2113. Register ShiftSrc;
  2114. int64_t ShiftImm;
  2115. Register MaskSrc;
  2116. int64_t MaskImm;
  2117. if (!mi_match(
  2118. Dst, MRI,
  2119. m_GOr(m_OneNonDBGUse(m_GShl(m_Reg(ShiftSrc), m_ICst(ShiftImm))),
  2120. m_OneNonDBGUse(m_GAnd(m_Reg(MaskSrc), m_ICst(MaskImm))))))
  2121. return false;
  2122. if (ShiftImm > Size || ((1ULL << ShiftImm) - 1ULL) != uint64_t(MaskImm))
  2123. return false;
  2124. int64_t Immr = Size - ShiftImm;
  2125. int64_t Imms = Size - ShiftImm - 1;
  2126. unsigned Opc = Size == 32 ? AArch64::BFMWri : AArch64::BFMXri;
  2127. emitInstr(Opc, {Dst}, {MaskSrc, ShiftSrc, Immr, Imms}, MIB);
  2128. I.eraseFromParent();
  2129. return true;
  2130. }
  2131. case TargetOpcode::G_FENCE: {
  2132. if (I.getOperand(1).getImm() == 0)
  2133. BuildMI(MBB, I, MIMetadata(I), TII.get(TargetOpcode::MEMBARRIER));
  2134. else
  2135. BuildMI(MBB, I, MIMetadata(I), TII.get(AArch64::DMB))
  2136. .addImm(I.getOperand(0).getImm() == 4 ? 0x9 : 0xb);
  2137. I.eraseFromParent();
  2138. return true;
  2139. }
  2140. default:
  2141. return false;
  2142. }
  2143. }
  2144. bool AArch64InstructionSelector::select(MachineInstr &I) {
  2145. assert(I.getParent() && "Instruction should be in a basic block!");
  2146. assert(I.getParent()->getParent() && "Instruction should be in a function!");
  2147. MachineBasicBlock &MBB = *I.getParent();
  2148. MachineFunction &MF = *MBB.getParent();
  2149. MachineRegisterInfo &MRI = MF.getRegInfo();
  2150. const AArch64Subtarget *Subtarget = &MF.getSubtarget<AArch64Subtarget>();
  2151. if (Subtarget->requiresStrictAlign()) {
  2152. // We don't support this feature yet.
  2153. LLVM_DEBUG(dbgs() << "AArch64 GISel does not support strict-align yet\n");
  2154. return false;
  2155. }
  2156. MIB.setInstrAndDebugLoc(I);
  2157. unsigned Opcode = I.getOpcode();
  2158. // G_PHI requires same handling as PHI
  2159. if (!I.isPreISelOpcode() || Opcode == TargetOpcode::G_PHI) {
  2160. // Certain non-generic instructions also need some special handling.
  2161. if (Opcode == TargetOpcode::LOAD_STACK_GUARD)
  2162. return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
  2163. if (Opcode == TargetOpcode::PHI || Opcode == TargetOpcode::G_PHI) {
  2164. const Register DefReg = I.getOperand(0).getReg();
  2165. const LLT DefTy = MRI.getType(DefReg);
  2166. const RegClassOrRegBank &RegClassOrBank =
  2167. MRI.getRegClassOrRegBank(DefReg);
  2168. const TargetRegisterClass *DefRC
  2169. = RegClassOrBank.dyn_cast<const TargetRegisterClass *>();
  2170. if (!DefRC) {
  2171. if (!DefTy.isValid()) {
  2172. LLVM_DEBUG(dbgs() << "PHI operand has no type, not a gvreg?\n");
  2173. return false;
  2174. }
  2175. const RegisterBank &RB = *RegClassOrBank.get<const RegisterBank *>();
  2176. DefRC = getRegClassForTypeOnBank(DefTy, RB);
  2177. if (!DefRC) {
  2178. LLVM_DEBUG(dbgs() << "PHI operand has unexpected size/bank\n");
  2179. return false;
  2180. }
  2181. }
  2182. I.setDesc(TII.get(TargetOpcode::PHI));
  2183. return RBI.constrainGenericRegister(DefReg, *DefRC, MRI);
  2184. }
  2185. if (I.isCopy())
  2186. return selectCopy(I, TII, MRI, TRI, RBI);
  2187. if (I.isDebugInstr())
  2188. return selectDebugInstr(I, MRI, RBI);
  2189. return true;
  2190. }
  2191. if (I.getNumOperands() != I.getNumExplicitOperands()) {
  2192. LLVM_DEBUG(
  2193. dbgs() << "Generic instruction has unexpected implicit operands\n");
  2194. return false;
  2195. }
  2196. // Try to do some lowering before we start instruction selecting. These
  2197. // lowerings are purely transformations on the input G_MIR and so selection
  2198. // must continue after any modification of the instruction.
  2199. if (preISelLower(I)) {
  2200. Opcode = I.getOpcode(); // The opcode may have been modified, refresh it.
  2201. }
  2202. // There may be patterns where the importer can't deal with them optimally,
  2203. // but does select it to a suboptimal sequence so our custom C++ selection
  2204. // code later never has a chance to work on it. Therefore, we have an early
  2205. // selection attempt here to give priority to certain selection routines
  2206. // over the imported ones.
  2207. if (earlySelect(I))
  2208. return true;
  2209. if (selectImpl(I, *CoverageInfo))
  2210. return true;
  2211. LLT Ty =
  2212. I.getOperand(0).isReg() ? MRI.getType(I.getOperand(0).getReg()) : LLT{};
  2213. switch (Opcode) {
  2214. case TargetOpcode::G_SBFX:
  2215. case TargetOpcode::G_UBFX: {
  2216. static const unsigned OpcTable[2][2] = {
  2217. {AArch64::UBFMWri, AArch64::UBFMXri},
  2218. {AArch64::SBFMWri, AArch64::SBFMXri}};
  2219. bool IsSigned = Opcode == TargetOpcode::G_SBFX;
  2220. unsigned Size = Ty.getSizeInBits();
  2221. unsigned Opc = OpcTable[IsSigned][Size == 64];
  2222. auto Cst1 =
  2223. getIConstantVRegValWithLookThrough(I.getOperand(2).getReg(), MRI);
  2224. assert(Cst1 && "Should have gotten a constant for src 1?");
  2225. auto Cst2 =
  2226. getIConstantVRegValWithLookThrough(I.getOperand(3).getReg(), MRI);
  2227. assert(Cst2 && "Should have gotten a constant for src 2?");
  2228. auto LSB = Cst1->Value.getZExtValue();
  2229. auto Width = Cst2->Value.getZExtValue();
  2230. auto BitfieldInst =
  2231. MIB.buildInstr(Opc, {I.getOperand(0)}, {I.getOperand(1)})
  2232. .addImm(LSB)
  2233. .addImm(LSB + Width - 1);
  2234. I.eraseFromParent();
  2235. return constrainSelectedInstRegOperands(*BitfieldInst, TII, TRI, RBI);
  2236. }
  2237. case TargetOpcode::G_BRCOND:
  2238. return selectCompareBranch(I, MF, MRI);
  2239. case TargetOpcode::G_BRINDIRECT: {
  2240. I.setDesc(TII.get(AArch64::BR));
  2241. return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
  2242. }
  2243. case TargetOpcode::G_BRJT:
  2244. return selectBrJT(I, MRI);
  2245. case AArch64::G_ADD_LOW: {
  2246. // This op may have been separated from it's ADRP companion by the localizer
  2247. // or some other code motion pass. Given that many CPUs will try to
  2248. // macro fuse these operations anyway, select this into a MOVaddr pseudo
  2249. // which will later be expanded into an ADRP+ADD pair after scheduling.
  2250. MachineInstr *BaseMI = MRI.getVRegDef(I.getOperand(1).getReg());
  2251. if (BaseMI->getOpcode() != AArch64::ADRP) {
  2252. I.setDesc(TII.get(AArch64::ADDXri));
  2253. I.addOperand(MachineOperand::CreateImm(0));
  2254. return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
  2255. }
  2256. assert(TM.getCodeModel() == CodeModel::Small &&
  2257. "Expected small code model");
  2258. auto Op1 = BaseMI->getOperand(1);
  2259. auto Op2 = I.getOperand(2);
  2260. auto MovAddr = MIB.buildInstr(AArch64::MOVaddr, {I.getOperand(0)}, {})
  2261. .addGlobalAddress(Op1.getGlobal(), Op1.getOffset(),
  2262. Op1.getTargetFlags())
  2263. .addGlobalAddress(Op2.getGlobal(), Op2.getOffset(),
  2264. Op2.getTargetFlags());
  2265. I.eraseFromParent();
  2266. return constrainSelectedInstRegOperands(*MovAddr, TII, TRI, RBI);
  2267. }
  2268. case TargetOpcode::G_BSWAP: {
  2269. // Handle vector types for G_BSWAP directly.
  2270. Register DstReg = I.getOperand(0).getReg();
  2271. LLT DstTy = MRI.getType(DstReg);
  2272. // We should only get vector types here; everything else is handled by the
  2273. // importer right now.
  2274. if (!DstTy.isVector() || DstTy.getSizeInBits() > 128) {
  2275. LLVM_DEBUG(dbgs() << "Dst type for G_BSWAP currently unsupported.\n");
  2276. return false;
  2277. }
  2278. // Only handle 4 and 2 element vectors for now.
  2279. // TODO: 16-bit elements.
  2280. unsigned NumElts = DstTy.getNumElements();
  2281. if (NumElts != 4 && NumElts != 2) {
  2282. LLVM_DEBUG(dbgs() << "Unsupported number of elements for G_BSWAP.\n");
  2283. return false;
  2284. }
  2285. // Choose the correct opcode for the supported types. Right now, that's
  2286. // v2s32, v4s32, and v2s64.
  2287. unsigned Opc = 0;
  2288. unsigned EltSize = DstTy.getElementType().getSizeInBits();
  2289. if (EltSize == 32)
  2290. Opc = (DstTy.getNumElements() == 2) ? AArch64::REV32v8i8
  2291. : AArch64::REV32v16i8;
  2292. else if (EltSize == 64)
  2293. Opc = AArch64::REV64v16i8;
  2294. // We should always get something by the time we get here...
  2295. assert(Opc != 0 && "Didn't get an opcode for G_BSWAP?");
  2296. I.setDesc(TII.get(Opc));
  2297. return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
  2298. }
  2299. case TargetOpcode::G_FCONSTANT:
  2300. case TargetOpcode::G_CONSTANT: {
  2301. const bool isFP = Opcode == TargetOpcode::G_FCONSTANT;
  2302. const LLT s8 = LLT::scalar(8);
  2303. const LLT s16 = LLT::scalar(16);
  2304. const LLT s32 = LLT::scalar(32);
  2305. const LLT s64 = LLT::scalar(64);
  2306. const LLT s128 = LLT::scalar(128);
  2307. const LLT p0 = LLT::pointer(0, 64);
  2308. const Register DefReg = I.getOperand(0).getReg();
  2309. const LLT DefTy = MRI.getType(DefReg);
  2310. const unsigned DefSize = DefTy.getSizeInBits();
  2311. const RegisterBank &RB = *RBI.getRegBank(DefReg, MRI, TRI);
  2312. // FIXME: Redundant check, but even less readable when factored out.
  2313. if (isFP) {
  2314. if (Ty != s16 && Ty != s32 && Ty != s64 && Ty != s128) {
  2315. LLVM_DEBUG(dbgs() << "Unable to materialize FP " << Ty
  2316. << " constant, expected: " << s16 << " or " << s32
  2317. << " or " << s64 << " or " << s128 << '\n');
  2318. return false;
  2319. }
  2320. if (RB.getID() != AArch64::FPRRegBankID) {
  2321. LLVM_DEBUG(dbgs() << "Unable to materialize FP " << Ty
  2322. << " constant on bank: " << RB
  2323. << ", expected: FPR\n");
  2324. return false;
  2325. }
  2326. // The case when we have 0.0 is covered by tablegen. Reject it here so we
  2327. // can be sure tablegen works correctly and isn't rescued by this code.
  2328. // 0.0 is not covered by tablegen for FP128. So we will handle this
  2329. // scenario in the code here.
  2330. if (DefSize != 128 && I.getOperand(1).getFPImm()->isExactlyValue(0.0))
  2331. return false;
  2332. } else {
  2333. // s32 and s64 are covered by tablegen.
  2334. if (Ty != p0 && Ty != s8 && Ty != s16) {
  2335. LLVM_DEBUG(dbgs() << "Unable to materialize integer " << Ty
  2336. << " constant, expected: " << s32 << ", " << s64
  2337. << ", or " << p0 << '\n');
  2338. return false;
  2339. }
  2340. if (RB.getID() != AArch64::GPRRegBankID) {
  2341. LLVM_DEBUG(dbgs() << "Unable to materialize integer " << Ty
  2342. << " constant on bank: " << RB
  2343. << ", expected: GPR\n");
  2344. return false;
  2345. }
  2346. }
  2347. if (isFP) {
  2348. const TargetRegisterClass &FPRRC = *getRegClassForTypeOnBank(DefTy, RB);
  2349. // For 16, 64, and 128b values, emit a constant pool load.
  2350. switch (DefSize) {
  2351. default:
  2352. llvm_unreachable("Unexpected destination size for G_FCONSTANT?");
  2353. case 32:
  2354. // For s32, use a cp load if we have optsize/minsize.
  2355. if (!shouldOptForSize(&MF))
  2356. break;
  2357. [[fallthrough]];
  2358. case 16:
  2359. case 64:
  2360. case 128: {
  2361. auto *FPImm = I.getOperand(1).getFPImm();
  2362. auto *LoadMI = emitLoadFromConstantPool(FPImm, MIB);
  2363. if (!LoadMI) {
  2364. LLVM_DEBUG(dbgs() << "Failed to load double constant pool entry\n");
  2365. return false;
  2366. }
  2367. MIB.buildCopy({DefReg}, {LoadMI->getOperand(0).getReg()});
  2368. I.eraseFromParent();
  2369. return RBI.constrainGenericRegister(DefReg, FPRRC, MRI);
  2370. }
  2371. }
  2372. // Either emit a FMOV, or emit a copy to emit a normal mov.
  2373. assert(DefSize == 32 &&
  2374. "Expected constant pool loads for all sizes other than 32!");
  2375. const Register DefGPRReg =
  2376. MRI.createVirtualRegister(&AArch64::GPR32RegClass);
  2377. MachineOperand &RegOp = I.getOperand(0);
  2378. RegOp.setReg(DefGPRReg);
  2379. MIB.setInsertPt(MIB.getMBB(), std::next(I.getIterator()));
  2380. MIB.buildCopy({DefReg}, {DefGPRReg});
  2381. if (!RBI.constrainGenericRegister(DefReg, FPRRC, MRI)) {
  2382. LLVM_DEBUG(dbgs() << "Failed to constrain G_FCONSTANT def operand\n");
  2383. return false;
  2384. }
  2385. MachineOperand &ImmOp = I.getOperand(1);
  2386. // FIXME: Is going through int64_t always correct?
  2387. ImmOp.ChangeToImmediate(
  2388. ImmOp.getFPImm()->getValueAPF().bitcastToAPInt().getZExtValue());
  2389. } else if (I.getOperand(1).isCImm()) {
  2390. uint64_t Val = I.getOperand(1).getCImm()->getZExtValue();
  2391. I.getOperand(1).ChangeToImmediate(Val);
  2392. } else if (I.getOperand(1).isImm()) {
  2393. uint64_t Val = I.getOperand(1).getImm();
  2394. I.getOperand(1).ChangeToImmediate(Val);
  2395. }
  2396. const unsigned MovOpc =
  2397. DefSize == 64 ? AArch64::MOVi64imm : AArch64::MOVi32imm;
  2398. I.setDesc(TII.get(MovOpc));
  2399. constrainSelectedInstRegOperands(I, TII, TRI, RBI);
  2400. return true;
  2401. }
  2402. case TargetOpcode::G_EXTRACT: {
  2403. Register DstReg = I.getOperand(0).getReg();
  2404. Register SrcReg = I.getOperand(1).getReg();
  2405. LLT SrcTy = MRI.getType(SrcReg);
  2406. LLT DstTy = MRI.getType(DstReg);
  2407. (void)DstTy;
  2408. unsigned SrcSize = SrcTy.getSizeInBits();
  2409. if (SrcTy.getSizeInBits() > 64) {
  2410. // This should be an extract of an s128, which is like a vector extract.
  2411. if (SrcTy.getSizeInBits() != 128)
  2412. return false;
  2413. // Only support extracting 64 bits from an s128 at the moment.
  2414. if (DstTy.getSizeInBits() != 64)
  2415. return false;
  2416. unsigned Offset = I.getOperand(2).getImm();
  2417. if (Offset % 64 != 0)
  2418. return false;
  2419. // Check we have the right regbank always.
  2420. const RegisterBank &SrcRB = *RBI.getRegBank(SrcReg, MRI, TRI);
  2421. const RegisterBank &DstRB = *RBI.getRegBank(DstReg, MRI, TRI);
  2422. assert(SrcRB.getID() == DstRB.getID() && "Wrong extract regbank!");
  2423. if (SrcRB.getID() == AArch64::GPRRegBankID) {
  2424. auto NewI =
  2425. MIB.buildInstr(TargetOpcode::COPY, {DstReg}, {})
  2426. .addUse(SrcReg, 0,
  2427. Offset == 0 ? AArch64::sube64 : AArch64::subo64);
  2428. constrainOperandRegClass(MF, TRI, MRI, TII, RBI, *NewI,
  2429. AArch64::GPR64RegClass, NewI->getOperand(0));
  2430. I.eraseFromParent();
  2431. return true;
  2432. }
  2433. // Emit the same code as a vector extract.
  2434. // Offset must be a multiple of 64.
  2435. unsigned LaneIdx = Offset / 64;
  2436. MachineInstr *Extract = emitExtractVectorElt(
  2437. DstReg, DstRB, LLT::scalar(64), SrcReg, LaneIdx, MIB);
  2438. if (!Extract)
  2439. return false;
  2440. I.eraseFromParent();
  2441. return true;
  2442. }
  2443. I.setDesc(TII.get(SrcSize == 64 ? AArch64::UBFMXri : AArch64::UBFMWri));
  2444. MachineInstrBuilder(MF, I).addImm(I.getOperand(2).getImm() +
  2445. Ty.getSizeInBits() - 1);
  2446. if (SrcSize < 64) {
  2447. assert(SrcSize == 32 && DstTy.getSizeInBits() == 16 &&
  2448. "unexpected G_EXTRACT types");
  2449. return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
  2450. }
  2451. DstReg = MRI.createGenericVirtualRegister(LLT::scalar(64));
  2452. MIB.setInsertPt(MIB.getMBB(), std::next(I.getIterator()));
  2453. MIB.buildInstr(TargetOpcode::COPY, {I.getOperand(0).getReg()}, {})
  2454. .addReg(DstReg, 0, AArch64::sub_32);
  2455. RBI.constrainGenericRegister(I.getOperand(0).getReg(),
  2456. AArch64::GPR32RegClass, MRI);
  2457. I.getOperand(0).setReg(DstReg);
  2458. return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
  2459. }
  2460. case TargetOpcode::G_INSERT: {
  2461. LLT SrcTy = MRI.getType(I.getOperand(2).getReg());
  2462. LLT DstTy = MRI.getType(I.getOperand(0).getReg());
  2463. unsigned DstSize = DstTy.getSizeInBits();
  2464. // Larger inserts are vectors, same-size ones should be something else by
  2465. // now (split up or turned into COPYs).
  2466. if (Ty.getSizeInBits() > 64 || SrcTy.getSizeInBits() > 32)
  2467. return false;
  2468. I.setDesc(TII.get(DstSize == 64 ? AArch64::BFMXri : AArch64::BFMWri));
  2469. unsigned LSB = I.getOperand(3).getImm();
  2470. unsigned Width = MRI.getType(I.getOperand(2).getReg()).getSizeInBits();
  2471. I.getOperand(3).setImm((DstSize - LSB) % DstSize);
  2472. MachineInstrBuilder(MF, I).addImm(Width - 1);
  2473. if (DstSize < 64) {
  2474. assert(DstSize == 32 && SrcTy.getSizeInBits() == 16 &&
  2475. "unexpected G_INSERT types");
  2476. return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
  2477. }
  2478. Register SrcReg = MRI.createGenericVirtualRegister(LLT::scalar(64));
  2479. BuildMI(MBB, I.getIterator(), I.getDebugLoc(),
  2480. TII.get(AArch64::SUBREG_TO_REG))
  2481. .addDef(SrcReg)
  2482. .addImm(0)
  2483. .addUse(I.getOperand(2).getReg())
  2484. .addImm(AArch64::sub_32);
  2485. RBI.constrainGenericRegister(I.getOperand(2).getReg(),
  2486. AArch64::GPR32RegClass, MRI);
  2487. I.getOperand(2).setReg(SrcReg);
  2488. return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
  2489. }
  2490. case TargetOpcode::G_FRAME_INDEX: {
  2491. // allocas and G_FRAME_INDEX are only supported in addrspace(0).
  2492. if (Ty != LLT::pointer(0, 64)) {
  2493. LLVM_DEBUG(dbgs() << "G_FRAME_INDEX pointer has type: " << Ty
  2494. << ", expected: " << LLT::pointer(0, 64) << '\n');
  2495. return false;
  2496. }
  2497. I.setDesc(TII.get(AArch64::ADDXri));
  2498. // MOs for a #0 shifted immediate.
  2499. I.addOperand(MachineOperand::CreateImm(0));
  2500. I.addOperand(MachineOperand::CreateImm(0));
  2501. return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
  2502. }
  2503. case TargetOpcode::G_GLOBAL_VALUE: {
  2504. auto GV = I.getOperand(1).getGlobal();
  2505. if (GV->isThreadLocal())
  2506. return selectTLSGlobalValue(I, MRI);
  2507. unsigned OpFlags = STI.ClassifyGlobalReference(GV, TM);
  2508. if (OpFlags & AArch64II::MO_GOT) {
  2509. I.setDesc(TII.get(AArch64::LOADgot));
  2510. I.getOperand(1).setTargetFlags(OpFlags);
  2511. } else if (TM.getCodeModel() == CodeModel::Large) {
  2512. // Materialize the global using movz/movk instructions.
  2513. materializeLargeCMVal(I, GV, OpFlags);
  2514. I.eraseFromParent();
  2515. return true;
  2516. } else if (TM.getCodeModel() == CodeModel::Tiny) {
  2517. I.setDesc(TII.get(AArch64::ADR));
  2518. I.getOperand(1).setTargetFlags(OpFlags);
  2519. } else {
  2520. I.setDesc(TII.get(AArch64::MOVaddr));
  2521. I.getOperand(1).setTargetFlags(OpFlags | AArch64II::MO_PAGE);
  2522. MachineInstrBuilder MIB(MF, I);
  2523. MIB.addGlobalAddress(GV, I.getOperand(1).getOffset(),
  2524. OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
  2525. }
  2526. return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
  2527. }
  2528. case TargetOpcode::G_ZEXTLOAD:
  2529. case TargetOpcode::G_LOAD:
  2530. case TargetOpcode::G_STORE: {
  2531. GLoadStore &LdSt = cast<GLoadStore>(I);
  2532. bool IsZExtLoad = I.getOpcode() == TargetOpcode::G_ZEXTLOAD;
  2533. LLT PtrTy = MRI.getType(LdSt.getPointerReg());
  2534. if (PtrTy != LLT::pointer(0, 64)) {
  2535. LLVM_DEBUG(dbgs() << "Load/Store pointer has type: " << PtrTy
  2536. << ", expected: " << LLT::pointer(0, 64) << '\n');
  2537. return false;
  2538. }
  2539. uint64_t MemSizeInBytes = LdSt.getMemSize();
  2540. unsigned MemSizeInBits = LdSt.getMemSizeInBits();
  2541. AtomicOrdering Order = LdSt.getMMO().getSuccessOrdering();
  2542. // Need special instructions for atomics that affect ordering.
  2543. if (Order != AtomicOrdering::NotAtomic &&
  2544. Order != AtomicOrdering::Unordered &&
  2545. Order != AtomicOrdering::Monotonic) {
  2546. assert(!isa<GZExtLoad>(LdSt));
  2547. if (MemSizeInBytes > 64)
  2548. return false;
  2549. if (isa<GLoad>(LdSt)) {
  2550. static constexpr unsigned LDAPROpcodes[] = {
  2551. AArch64::LDAPRB, AArch64::LDAPRH, AArch64::LDAPRW, AArch64::LDAPRX};
  2552. static constexpr unsigned LDAROpcodes[] = {
  2553. AArch64::LDARB, AArch64::LDARH, AArch64::LDARW, AArch64::LDARX};
  2554. ArrayRef<unsigned> Opcodes =
  2555. STI.hasRCPC() && Order != AtomicOrdering::SequentiallyConsistent
  2556. ? LDAPROpcodes
  2557. : LDAROpcodes;
  2558. I.setDesc(TII.get(Opcodes[Log2_32(MemSizeInBytes)]));
  2559. } else {
  2560. static constexpr unsigned Opcodes[] = {AArch64::STLRB, AArch64::STLRH,
  2561. AArch64::STLRW, AArch64::STLRX};
  2562. Register ValReg = LdSt.getReg(0);
  2563. if (MRI.getType(ValReg).getSizeInBits() == 64 && MemSizeInBits != 64) {
  2564. // Emit a subreg copy of 32 bits.
  2565. Register NewVal = MRI.createVirtualRegister(&AArch64::GPR32RegClass);
  2566. MIB.buildInstr(TargetOpcode::COPY, {NewVal}, {})
  2567. .addReg(I.getOperand(0).getReg(), 0, AArch64::sub_32);
  2568. I.getOperand(0).setReg(NewVal);
  2569. }
  2570. I.setDesc(TII.get(Opcodes[Log2_32(MemSizeInBytes)]));
  2571. }
  2572. constrainSelectedInstRegOperands(I, TII, TRI, RBI);
  2573. return true;
  2574. }
  2575. #ifndef NDEBUG
  2576. const Register PtrReg = LdSt.getPointerReg();
  2577. const RegisterBank &PtrRB = *RBI.getRegBank(PtrReg, MRI, TRI);
  2578. // Check that the pointer register is valid.
  2579. assert(PtrRB.getID() == AArch64::GPRRegBankID &&
  2580. "Load/Store pointer operand isn't a GPR");
  2581. assert(MRI.getType(PtrReg).isPointer() &&
  2582. "Load/Store pointer operand isn't a pointer");
  2583. #endif
  2584. const Register ValReg = LdSt.getReg(0);
  2585. const LLT ValTy = MRI.getType(ValReg);
  2586. const RegisterBank &RB = *RBI.getRegBank(ValReg, MRI, TRI);
  2587. // The code below doesn't support truncating stores, so we need to split it
  2588. // again.
  2589. if (isa<GStore>(LdSt) && ValTy.getSizeInBits() > MemSizeInBits) {
  2590. unsigned SubReg;
  2591. LLT MemTy = LdSt.getMMO().getMemoryType();
  2592. auto *RC = getRegClassForTypeOnBank(MemTy, RB);
  2593. if (!getSubRegForClass(RC, TRI, SubReg))
  2594. return false;
  2595. // Generate a subreg copy.
  2596. auto Copy = MIB.buildInstr(TargetOpcode::COPY, {MemTy}, {})
  2597. .addReg(ValReg, 0, SubReg)
  2598. .getReg(0);
  2599. RBI.constrainGenericRegister(Copy, *RC, MRI);
  2600. LdSt.getOperand(0).setReg(Copy);
  2601. } else if (isa<GLoad>(LdSt) && ValTy.getSizeInBits() > MemSizeInBits) {
  2602. // If this is an any-extending load from the FPR bank, split it into a regular
  2603. // load + extend.
  2604. if (RB.getID() == AArch64::FPRRegBankID) {
  2605. unsigned SubReg;
  2606. LLT MemTy = LdSt.getMMO().getMemoryType();
  2607. auto *RC = getRegClassForTypeOnBank(MemTy, RB);
  2608. if (!getSubRegForClass(RC, TRI, SubReg))
  2609. return false;
  2610. Register OldDst = LdSt.getReg(0);
  2611. Register NewDst =
  2612. MRI.createGenericVirtualRegister(LdSt.getMMO().getMemoryType());
  2613. LdSt.getOperand(0).setReg(NewDst);
  2614. MRI.setRegBank(NewDst, RB);
  2615. // Generate a SUBREG_TO_REG to extend it.
  2616. MIB.setInsertPt(MIB.getMBB(), std::next(LdSt.getIterator()));
  2617. MIB.buildInstr(AArch64::SUBREG_TO_REG, {OldDst}, {})
  2618. .addImm(0)
  2619. .addUse(NewDst)
  2620. .addImm(SubReg);
  2621. auto SubRegRC = getRegClassForTypeOnBank(MRI.getType(OldDst), RB);
  2622. RBI.constrainGenericRegister(OldDst, *SubRegRC, MRI);
  2623. MIB.setInstr(LdSt);
  2624. }
  2625. }
  2626. // Helper lambda for partially selecting I. Either returns the original
  2627. // instruction with an updated opcode, or a new instruction.
  2628. auto SelectLoadStoreAddressingMode = [&]() -> MachineInstr * {
  2629. bool IsStore = isa<GStore>(I);
  2630. const unsigned NewOpc =
  2631. selectLoadStoreUIOp(I.getOpcode(), RB.getID(), MemSizeInBits);
  2632. if (NewOpc == I.getOpcode())
  2633. return nullptr;
  2634. // Check if we can fold anything into the addressing mode.
  2635. auto AddrModeFns =
  2636. selectAddrModeIndexed(I.getOperand(1), MemSizeInBytes);
  2637. if (!AddrModeFns) {
  2638. // Can't fold anything. Use the original instruction.
  2639. I.setDesc(TII.get(NewOpc));
  2640. I.addOperand(MachineOperand::CreateImm(0));
  2641. return &I;
  2642. }
  2643. // Folded something. Create a new instruction and return it.
  2644. auto NewInst = MIB.buildInstr(NewOpc, {}, {}, I.getFlags());
  2645. Register CurValReg = I.getOperand(0).getReg();
  2646. IsStore ? NewInst.addUse(CurValReg) : NewInst.addDef(CurValReg);
  2647. NewInst.cloneMemRefs(I);
  2648. for (auto &Fn : *AddrModeFns)
  2649. Fn(NewInst);
  2650. I.eraseFromParent();
  2651. return &*NewInst;
  2652. };
  2653. MachineInstr *LoadStore = SelectLoadStoreAddressingMode();
  2654. if (!LoadStore)
  2655. return false;
  2656. // If we're storing a 0, use WZR/XZR.
  2657. if (Opcode == TargetOpcode::G_STORE) {
  2658. auto CVal = getIConstantVRegValWithLookThrough(
  2659. LoadStore->getOperand(0).getReg(), MRI);
  2660. if (CVal && CVal->Value == 0) {
  2661. switch (LoadStore->getOpcode()) {
  2662. case AArch64::STRWui:
  2663. case AArch64::STRHHui:
  2664. case AArch64::STRBBui:
  2665. LoadStore->getOperand(0).setReg(AArch64::WZR);
  2666. break;
  2667. case AArch64::STRXui:
  2668. LoadStore->getOperand(0).setReg(AArch64::XZR);
  2669. break;
  2670. }
  2671. }
  2672. }
  2673. if (IsZExtLoad) {
  2674. // The zextload from a smaller type to i32 should be handled by the
  2675. // importer.
  2676. if (MRI.getType(LoadStore->getOperand(0).getReg()).getSizeInBits() != 64)
  2677. return false;
  2678. // If we have a ZEXTLOAD then change the load's type to be a narrower reg
  2679. // and zero_extend with SUBREG_TO_REG.
  2680. Register LdReg = MRI.createVirtualRegister(&AArch64::GPR32RegClass);
  2681. Register DstReg = LoadStore->getOperand(0).getReg();
  2682. LoadStore->getOperand(0).setReg(LdReg);
  2683. MIB.setInsertPt(MIB.getMBB(), std::next(LoadStore->getIterator()));
  2684. MIB.buildInstr(AArch64::SUBREG_TO_REG, {DstReg}, {})
  2685. .addImm(0)
  2686. .addUse(LdReg)
  2687. .addImm(AArch64::sub_32);
  2688. constrainSelectedInstRegOperands(*LoadStore, TII, TRI, RBI);
  2689. return RBI.constrainGenericRegister(DstReg, AArch64::GPR64allRegClass,
  2690. MRI);
  2691. }
  2692. return constrainSelectedInstRegOperands(*LoadStore, TII, TRI, RBI);
  2693. }
  2694. case TargetOpcode::G_SMULH:
  2695. case TargetOpcode::G_UMULH: {
  2696. // Reject the various things we don't support yet.
  2697. if (unsupportedBinOp(I, RBI, MRI, TRI))
  2698. return false;
  2699. const Register DefReg = I.getOperand(0).getReg();
  2700. const RegisterBank &RB = *RBI.getRegBank(DefReg, MRI, TRI);
  2701. if (RB.getID() != AArch64::GPRRegBankID) {
  2702. LLVM_DEBUG(dbgs() << "G_[SU]MULH on bank: " << RB << ", expected: GPR\n");
  2703. return false;
  2704. }
  2705. if (Ty != LLT::scalar(64)) {
  2706. LLVM_DEBUG(dbgs() << "G_[SU]MULH has type: " << Ty
  2707. << ", expected: " << LLT::scalar(64) << '\n');
  2708. return false;
  2709. }
  2710. unsigned NewOpc = I.getOpcode() == TargetOpcode::G_SMULH ? AArch64::SMULHrr
  2711. : AArch64::UMULHrr;
  2712. I.setDesc(TII.get(NewOpc));
  2713. // Now that we selected an opcode, we need to constrain the register
  2714. // operands to use appropriate classes.
  2715. return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
  2716. }
  2717. case TargetOpcode::G_LSHR:
  2718. case TargetOpcode::G_ASHR:
  2719. if (MRI.getType(I.getOperand(0).getReg()).isVector())
  2720. return selectVectorAshrLshr(I, MRI);
  2721. [[fallthrough]];
  2722. case TargetOpcode::G_SHL:
  2723. if (Opcode == TargetOpcode::G_SHL &&
  2724. MRI.getType(I.getOperand(0).getReg()).isVector())
  2725. return selectVectorSHL(I, MRI);
  2726. // These shifts were legalized to have 64 bit shift amounts because we
  2727. // want to take advantage of the selection patterns that assume the
  2728. // immediates are s64s, however, selectBinaryOp will assume both operands
  2729. // will have the same bit size.
  2730. {
  2731. Register SrcReg = I.getOperand(1).getReg();
  2732. Register ShiftReg = I.getOperand(2).getReg();
  2733. const LLT ShiftTy = MRI.getType(ShiftReg);
  2734. const LLT SrcTy = MRI.getType(SrcReg);
  2735. if (!SrcTy.isVector() && SrcTy.getSizeInBits() == 32 &&
  2736. ShiftTy.getSizeInBits() == 64) {
  2737. assert(!ShiftTy.isVector() && "unexpected vector shift ty");
  2738. // Insert a subregister copy to implement a 64->32 trunc
  2739. auto Trunc = MIB.buildInstr(TargetOpcode::COPY, {SrcTy}, {})
  2740. .addReg(ShiftReg, 0, AArch64::sub_32);
  2741. MRI.setRegBank(Trunc.getReg(0), RBI.getRegBank(AArch64::GPRRegBankID));
  2742. I.getOperand(2).setReg(Trunc.getReg(0));
  2743. }
  2744. }
  2745. [[fallthrough]];
  2746. case TargetOpcode::G_OR: {
  2747. // Reject the various things we don't support yet.
  2748. if (unsupportedBinOp(I, RBI, MRI, TRI))
  2749. return false;
  2750. const unsigned OpSize = Ty.getSizeInBits();
  2751. const Register DefReg = I.getOperand(0).getReg();
  2752. const RegisterBank &RB = *RBI.getRegBank(DefReg, MRI, TRI);
  2753. const unsigned NewOpc = selectBinaryOp(I.getOpcode(), RB.getID(), OpSize);
  2754. if (NewOpc == I.getOpcode())
  2755. return false;
  2756. I.setDesc(TII.get(NewOpc));
  2757. // FIXME: Should the type be always reset in setDesc?
  2758. // Now that we selected an opcode, we need to constrain the register
  2759. // operands to use appropriate classes.
  2760. return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
  2761. }
  2762. case TargetOpcode::G_PTR_ADD: {
  2763. emitADD(I.getOperand(0).getReg(), I.getOperand(1), I.getOperand(2), MIB);
  2764. I.eraseFromParent();
  2765. return true;
  2766. }
  2767. case TargetOpcode::G_SADDO:
  2768. case TargetOpcode::G_UADDO:
  2769. case TargetOpcode::G_SSUBO:
  2770. case TargetOpcode::G_USUBO: {
  2771. // Emit the operation and get the correct condition code.
  2772. auto OpAndCC = emitOverflowOp(Opcode, I.getOperand(0).getReg(),
  2773. I.getOperand(2), I.getOperand(3), MIB);
  2774. // Now, put the overflow result in the register given by the first operand
  2775. // to the overflow op. CSINC increments the result when the predicate is
  2776. // false, so to get the increment when it's true, we need to use the
  2777. // inverse. In this case, we want to increment when carry is set.
  2778. Register ZReg = AArch64::WZR;
  2779. emitCSINC(/*Dst=*/I.getOperand(1).getReg(), /*Src1=*/ZReg, /*Src2=*/ZReg,
  2780. getInvertedCondCode(OpAndCC.second), MIB);
  2781. I.eraseFromParent();
  2782. return true;
  2783. }
  2784. case TargetOpcode::G_PTRMASK: {
  2785. Register MaskReg = I.getOperand(2).getReg();
  2786. std::optional<int64_t> MaskVal = getIConstantVRegSExtVal(MaskReg, MRI);
  2787. // TODO: Implement arbitrary cases
  2788. if (!MaskVal || !isShiftedMask_64(*MaskVal))
  2789. return false;
  2790. uint64_t Mask = *MaskVal;
  2791. I.setDesc(TII.get(AArch64::ANDXri));
  2792. I.getOperand(2).ChangeToImmediate(
  2793. AArch64_AM::encodeLogicalImmediate(Mask, 64));
  2794. return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
  2795. }
  2796. case TargetOpcode::G_PTRTOINT:
  2797. case TargetOpcode::G_TRUNC: {
  2798. const LLT DstTy = MRI.getType(I.getOperand(0).getReg());
  2799. const LLT SrcTy = MRI.getType(I.getOperand(1).getReg());
  2800. const Register DstReg = I.getOperand(0).getReg();
  2801. const Register SrcReg = I.getOperand(1).getReg();
  2802. const RegisterBank &DstRB = *RBI.getRegBank(DstReg, MRI, TRI);
  2803. const RegisterBank &SrcRB = *RBI.getRegBank(SrcReg, MRI, TRI);
  2804. if (DstRB.getID() != SrcRB.getID()) {
  2805. LLVM_DEBUG(
  2806. dbgs() << "G_TRUNC/G_PTRTOINT input/output on different banks\n");
  2807. return false;
  2808. }
  2809. if (DstRB.getID() == AArch64::GPRRegBankID) {
  2810. const TargetRegisterClass *DstRC = getRegClassForTypeOnBank(DstTy, DstRB);
  2811. if (!DstRC)
  2812. return false;
  2813. const TargetRegisterClass *SrcRC = getRegClassForTypeOnBank(SrcTy, SrcRB);
  2814. if (!SrcRC)
  2815. return false;
  2816. if (!RBI.constrainGenericRegister(SrcReg, *SrcRC, MRI) ||
  2817. !RBI.constrainGenericRegister(DstReg, *DstRC, MRI)) {
  2818. LLVM_DEBUG(dbgs() << "Failed to constrain G_TRUNC/G_PTRTOINT\n");
  2819. return false;
  2820. }
  2821. if (DstRC == SrcRC) {
  2822. // Nothing to be done
  2823. } else if (Opcode == TargetOpcode::G_TRUNC && DstTy == LLT::scalar(32) &&
  2824. SrcTy == LLT::scalar(64)) {
  2825. llvm_unreachable("TableGen can import this case");
  2826. return false;
  2827. } else if (DstRC == &AArch64::GPR32RegClass &&
  2828. SrcRC == &AArch64::GPR64RegClass) {
  2829. I.getOperand(1).setSubReg(AArch64::sub_32);
  2830. } else {
  2831. LLVM_DEBUG(
  2832. dbgs() << "Unhandled mismatched classes in G_TRUNC/G_PTRTOINT\n");
  2833. return false;
  2834. }
  2835. I.setDesc(TII.get(TargetOpcode::COPY));
  2836. return true;
  2837. } else if (DstRB.getID() == AArch64::FPRRegBankID) {
  2838. if (DstTy == LLT::fixed_vector(4, 16) &&
  2839. SrcTy == LLT::fixed_vector(4, 32)) {
  2840. I.setDesc(TII.get(AArch64::XTNv4i16));
  2841. constrainSelectedInstRegOperands(I, TII, TRI, RBI);
  2842. return true;
  2843. }
  2844. if (!SrcTy.isVector() && SrcTy.getSizeInBits() == 128) {
  2845. MachineInstr *Extract = emitExtractVectorElt(
  2846. DstReg, DstRB, LLT::scalar(DstTy.getSizeInBits()), SrcReg, 0, MIB);
  2847. if (!Extract)
  2848. return false;
  2849. I.eraseFromParent();
  2850. return true;
  2851. }
  2852. // We might have a vector G_PTRTOINT, in which case just emit a COPY.
  2853. if (Opcode == TargetOpcode::G_PTRTOINT) {
  2854. assert(DstTy.isVector() && "Expected an FPR ptrtoint to be a vector");
  2855. I.setDesc(TII.get(TargetOpcode::COPY));
  2856. return selectCopy(I, TII, MRI, TRI, RBI);
  2857. }
  2858. }
  2859. return false;
  2860. }
  2861. case TargetOpcode::G_ANYEXT: {
  2862. if (selectUSMovFromExtend(I, MRI))
  2863. return true;
  2864. const Register DstReg = I.getOperand(0).getReg();
  2865. const Register SrcReg = I.getOperand(1).getReg();
  2866. const RegisterBank &RBDst = *RBI.getRegBank(DstReg, MRI, TRI);
  2867. if (RBDst.getID() != AArch64::GPRRegBankID) {
  2868. LLVM_DEBUG(dbgs() << "G_ANYEXT on bank: " << RBDst
  2869. << ", expected: GPR\n");
  2870. return false;
  2871. }
  2872. const RegisterBank &RBSrc = *RBI.getRegBank(SrcReg, MRI, TRI);
  2873. if (RBSrc.getID() != AArch64::GPRRegBankID) {
  2874. LLVM_DEBUG(dbgs() << "G_ANYEXT on bank: " << RBSrc
  2875. << ", expected: GPR\n");
  2876. return false;
  2877. }
  2878. const unsigned DstSize = MRI.getType(DstReg).getSizeInBits();
  2879. if (DstSize == 0) {
  2880. LLVM_DEBUG(dbgs() << "G_ANYEXT operand has no size, not a gvreg?\n");
  2881. return false;
  2882. }
  2883. if (DstSize != 64 && DstSize > 32) {
  2884. LLVM_DEBUG(dbgs() << "G_ANYEXT to size: " << DstSize
  2885. << ", expected: 32 or 64\n");
  2886. return false;
  2887. }
  2888. // At this point G_ANYEXT is just like a plain COPY, but we need
  2889. // to explicitly form the 64-bit value if any.
  2890. if (DstSize > 32) {
  2891. Register ExtSrc = MRI.createVirtualRegister(&AArch64::GPR64allRegClass);
  2892. BuildMI(MBB, I, I.getDebugLoc(), TII.get(AArch64::SUBREG_TO_REG))
  2893. .addDef(ExtSrc)
  2894. .addImm(0)
  2895. .addUse(SrcReg)
  2896. .addImm(AArch64::sub_32);
  2897. I.getOperand(1).setReg(ExtSrc);
  2898. }
  2899. return selectCopy(I, TII, MRI, TRI, RBI);
  2900. }
  2901. case TargetOpcode::G_ZEXT:
  2902. case TargetOpcode::G_SEXT_INREG:
  2903. case TargetOpcode::G_SEXT: {
  2904. if (selectUSMovFromExtend(I, MRI))
  2905. return true;
  2906. unsigned Opcode = I.getOpcode();
  2907. const bool IsSigned = Opcode != TargetOpcode::G_ZEXT;
  2908. const Register DefReg = I.getOperand(0).getReg();
  2909. Register SrcReg = I.getOperand(1).getReg();
  2910. const LLT DstTy = MRI.getType(DefReg);
  2911. const LLT SrcTy = MRI.getType(SrcReg);
  2912. unsigned DstSize = DstTy.getSizeInBits();
  2913. unsigned SrcSize = SrcTy.getSizeInBits();
  2914. // SEXT_INREG has the same src reg size as dst, the size of the value to be
  2915. // extended is encoded in the imm.
  2916. if (Opcode == TargetOpcode::G_SEXT_INREG)
  2917. SrcSize = I.getOperand(2).getImm();
  2918. if (DstTy.isVector())
  2919. return false; // Should be handled by imported patterns.
  2920. assert((*RBI.getRegBank(DefReg, MRI, TRI)).getID() ==
  2921. AArch64::GPRRegBankID &&
  2922. "Unexpected ext regbank");
  2923. MachineInstr *ExtI;
  2924. // First check if we're extending the result of a load which has a dest type
  2925. // smaller than 32 bits, then this zext is redundant. GPR32 is the smallest
  2926. // GPR register on AArch64 and all loads which are smaller automatically
  2927. // zero-extend the upper bits. E.g.
  2928. // %v(s8) = G_LOAD %p, :: (load 1)
  2929. // %v2(s32) = G_ZEXT %v(s8)
  2930. if (!IsSigned) {
  2931. auto *LoadMI = getOpcodeDef(TargetOpcode::G_LOAD, SrcReg, MRI);
  2932. bool IsGPR =
  2933. RBI.getRegBank(SrcReg, MRI, TRI)->getID() == AArch64::GPRRegBankID;
  2934. if (LoadMI && IsGPR) {
  2935. const MachineMemOperand *MemOp = *LoadMI->memoperands_begin();
  2936. unsigned BytesLoaded = MemOp->getSize();
  2937. if (BytesLoaded < 4 && SrcTy.getSizeInBytes() == BytesLoaded)
  2938. return selectCopy(I, TII, MRI, TRI, RBI);
  2939. }
  2940. // For the 32-bit -> 64-bit case, we can emit a mov (ORRWrs)
  2941. // + SUBREG_TO_REG.
  2942. if (IsGPR && SrcSize == 32 && DstSize == 64) {
  2943. Register SubregToRegSrc =
  2944. MRI.createVirtualRegister(&AArch64::GPR32RegClass);
  2945. const Register ZReg = AArch64::WZR;
  2946. MIB.buildInstr(AArch64::ORRWrs, {SubregToRegSrc}, {ZReg, SrcReg})
  2947. .addImm(0);
  2948. MIB.buildInstr(AArch64::SUBREG_TO_REG, {DefReg}, {})
  2949. .addImm(0)
  2950. .addUse(SubregToRegSrc)
  2951. .addImm(AArch64::sub_32);
  2952. if (!RBI.constrainGenericRegister(DefReg, AArch64::GPR64RegClass,
  2953. MRI)) {
  2954. LLVM_DEBUG(dbgs() << "Failed to constrain G_ZEXT destination\n");
  2955. return false;
  2956. }
  2957. if (!RBI.constrainGenericRegister(SrcReg, AArch64::GPR32RegClass,
  2958. MRI)) {
  2959. LLVM_DEBUG(dbgs() << "Failed to constrain G_ZEXT source\n");
  2960. return false;
  2961. }
  2962. I.eraseFromParent();
  2963. return true;
  2964. }
  2965. }
  2966. if (DstSize == 64) {
  2967. if (Opcode != TargetOpcode::G_SEXT_INREG) {
  2968. // FIXME: Can we avoid manually doing this?
  2969. if (!RBI.constrainGenericRegister(SrcReg, AArch64::GPR32RegClass,
  2970. MRI)) {
  2971. LLVM_DEBUG(dbgs() << "Failed to constrain " << TII.getName(Opcode)
  2972. << " operand\n");
  2973. return false;
  2974. }
  2975. SrcReg = MIB.buildInstr(AArch64::SUBREG_TO_REG,
  2976. {&AArch64::GPR64RegClass}, {})
  2977. .addImm(0)
  2978. .addUse(SrcReg)
  2979. .addImm(AArch64::sub_32)
  2980. .getReg(0);
  2981. }
  2982. ExtI = MIB.buildInstr(IsSigned ? AArch64::SBFMXri : AArch64::UBFMXri,
  2983. {DefReg}, {SrcReg})
  2984. .addImm(0)
  2985. .addImm(SrcSize - 1);
  2986. } else if (DstSize <= 32) {
  2987. ExtI = MIB.buildInstr(IsSigned ? AArch64::SBFMWri : AArch64::UBFMWri,
  2988. {DefReg}, {SrcReg})
  2989. .addImm(0)
  2990. .addImm(SrcSize - 1);
  2991. } else {
  2992. return false;
  2993. }
  2994. constrainSelectedInstRegOperands(*ExtI, TII, TRI, RBI);
  2995. I.eraseFromParent();
  2996. return true;
  2997. }
  2998. case TargetOpcode::G_SITOFP:
  2999. case TargetOpcode::G_UITOFP:
  3000. case TargetOpcode::G_FPTOSI:
  3001. case TargetOpcode::G_FPTOUI: {
  3002. const LLT DstTy = MRI.getType(I.getOperand(0).getReg()),
  3003. SrcTy = MRI.getType(I.getOperand(1).getReg());
  3004. const unsigned NewOpc = selectFPConvOpc(Opcode, DstTy, SrcTy);
  3005. if (NewOpc == Opcode)
  3006. return false;
  3007. I.setDesc(TII.get(NewOpc));
  3008. constrainSelectedInstRegOperands(I, TII, TRI, RBI);
  3009. I.setFlags(MachineInstr::NoFPExcept);
  3010. return true;
  3011. }
  3012. case TargetOpcode::G_FREEZE:
  3013. return selectCopy(I, TII, MRI, TRI, RBI);
  3014. case TargetOpcode::G_INTTOPTR:
  3015. // The importer is currently unable to import pointer types since they
  3016. // didn't exist in SelectionDAG.
  3017. return selectCopy(I, TII, MRI, TRI, RBI);
  3018. case TargetOpcode::G_BITCAST:
  3019. // Imported SelectionDAG rules can handle every bitcast except those that
  3020. // bitcast from a type to the same type. Ideally, these shouldn't occur
  3021. // but we might not run an optimizer that deletes them. The other exception
  3022. // is bitcasts involving pointer types, as SelectionDAG has no knowledge
  3023. // of them.
  3024. return selectCopy(I, TII, MRI, TRI, RBI);
  3025. case TargetOpcode::G_SELECT: {
  3026. auto &Sel = cast<GSelect>(I);
  3027. const Register CondReg = Sel.getCondReg();
  3028. const Register TReg = Sel.getTrueReg();
  3029. const Register FReg = Sel.getFalseReg();
  3030. if (tryOptSelect(Sel))
  3031. return true;
  3032. // Make sure to use an unused vreg instead of wzr, so that the peephole
  3033. // optimizations will be able to optimize these.
  3034. Register DeadVReg = MRI.createVirtualRegister(&AArch64::GPR32RegClass);
  3035. auto TstMI = MIB.buildInstr(AArch64::ANDSWri, {DeadVReg}, {CondReg})
  3036. .addImm(AArch64_AM::encodeLogicalImmediate(1, 32));
  3037. constrainSelectedInstRegOperands(*TstMI, TII, TRI, RBI);
  3038. if (!emitSelect(Sel.getReg(0), TReg, FReg, AArch64CC::NE, MIB))
  3039. return false;
  3040. Sel.eraseFromParent();
  3041. return true;
  3042. }
  3043. case TargetOpcode::G_ICMP: {
  3044. if (Ty.isVector())
  3045. return selectVectorICmp(I, MRI);
  3046. if (Ty != LLT::scalar(32)) {
  3047. LLVM_DEBUG(dbgs() << "G_ICMP result has type: " << Ty
  3048. << ", expected: " << LLT::scalar(32) << '\n');
  3049. return false;
  3050. }
  3051. auto Pred = static_cast<CmpInst::Predicate>(I.getOperand(1).getPredicate());
  3052. const AArch64CC::CondCode InvCC =
  3053. changeICMPPredToAArch64CC(CmpInst::getInversePredicate(Pred));
  3054. emitIntegerCompare(I.getOperand(2), I.getOperand(3), I.getOperand(1), MIB);
  3055. emitCSINC(/*Dst=*/I.getOperand(0).getReg(), /*Src1=*/AArch64::WZR,
  3056. /*Src2=*/AArch64::WZR, InvCC, MIB);
  3057. I.eraseFromParent();
  3058. return true;
  3059. }
  3060. case TargetOpcode::G_FCMP: {
  3061. CmpInst::Predicate Pred =
  3062. static_cast<CmpInst::Predicate>(I.getOperand(1).getPredicate());
  3063. if (!emitFPCompare(I.getOperand(2).getReg(), I.getOperand(3).getReg(), MIB,
  3064. Pred) ||
  3065. !emitCSetForFCmp(I.getOperand(0).getReg(), Pred, MIB))
  3066. return false;
  3067. I.eraseFromParent();
  3068. return true;
  3069. }
  3070. case TargetOpcode::G_VASTART:
  3071. return STI.isTargetDarwin() ? selectVaStartDarwin(I, MF, MRI)
  3072. : selectVaStartAAPCS(I, MF, MRI);
  3073. case TargetOpcode::G_INTRINSIC:
  3074. return selectIntrinsic(I, MRI);
  3075. case TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS:
  3076. return selectIntrinsicWithSideEffects(I, MRI);
  3077. case TargetOpcode::G_IMPLICIT_DEF: {
  3078. I.setDesc(TII.get(TargetOpcode::IMPLICIT_DEF));
  3079. const LLT DstTy = MRI.getType(I.getOperand(0).getReg());
  3080. const Register DstReg = I.getOperand(0).getReg();
  3081. const RegisterBank &DstRB = *RBI.getRegBank(DstReg, MRI, TRI);
  3082. const TargetRegisterClass *DstRC = getRegClassForTypeOnBank(DstTy, DstRB);
  3083. RBI.constrainGenericRegister(DstReg, *DstRC, MRI);
  3084. return true;
  3085. }
  3086. case TargetOpcode::G_BLOCK_ADDR: {
  3087. if (TM.getCodeModel() == CodeModel::Large) {
  3088. materializeLargeCMVal(I, I.getOperand(1).getBlockAddress(), 0);
  3089. I.eraseFromParent();
  3090. return true;
  3091. } else {
  3092. I.setDesc(TII.get(AArch64::MOVaddrBA));
  3093. auto MovMI = BuildMI(MBB, I, I.getDebugLoc(), TII.get(AArch64::MOVaddrBA),
  3094. I.getOperand(0).getReg())
  3095. .addBlockAddress(I.getOperand(1).getBlockAddress(),
  3096. /* Offset */ 0, AArch64II::MO_PAGE)
  3097. .addBlockAddress(
  3098. I.getOperand(1).getBlockAddress(), /* Offset */ 0,
  3099. AArch64II::MO_NC | AArch64II::MO_PAGEOFF);
  3100. I.eraseFromParent();
  3101. return constrainSelectedInstRegOperands(*MovMI, TII, TRI, RBI);
  3102. }
  3103. }
  3104. case AArch64::G_DUP: {
  3105. // When the scalar of G_DUP is an s8/s16 gpr, they can't be selected by
  3106. // imported patterns. Do it manually here. Avoiding generating s16 gpr is
  3107. // difficult because at RBS we may end up pessimizing the fpr case if we
  3108. // decided to add an anyextend to fix this. Manual selection is the most
  3109. // robust solution for now.
  3110. if (RBI.getRegBank(I.getOperand(1).getReg(), MRI, TRI)->getID() !=
  3111. AArch64::GPRRegBankID)
  3112. return false; // We expect the fpr regbank case to be imported.
  3113. LLT VecTy = MRI.getType(I.getOperand(0).getReg());
  3114. if (VecTy == LLT::fixed_vector(8, 8))
  3115. I.setDesc(TII.get(AArch64::DUPv8i8gpr));
  3116. else if (VecTy == LLT::fixed_vector(16, 8))
  3117. I.setDesc(TII.get(AArch64::DUPv16i8gpr));
  3118. else if (VecTy == LLT::fixed_vector(4, 16))
  3119. I.setDesc(TII.get(AArch64::DUPv4i16gpr));
  3120. else if (VecTy == LLT::fixed_vector(8, 16))
  3121. I.setDesc(TII.get(AArch64::DUPv8i16gpr));
  3122. else
  3123. return false;
  3124. return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
  3125. }
  3126. case TargetOpcode::G_INTRINSIC_TRUNC:
  3127. return selectIntrinsicTrunc(I, MRI);
  3128. case TargetOpcode::G_INTRINSIC_ROUND:
  3129. return selectIntrinsicRound(I, MRI);
  3130. case TargetOpcode::G_BUILD_VECTOR:
  3131. return selectBuildVector(I, MRI);
  3132. case TargetOpcode::G_MERGE_VALUES:
  3133. return selectMergeValues(I, MRI);
  3134. case TargetOpcode::G_UNMERGE_VALUES:
  3135. return selectUnmergeValues(I, MRI);
  3136. case TargetOpcode::G_SHUFFLE_VECTOR:
  3137. return selectShuffleVector(I, MRI);
  3138. case TargetOpcode::G_EXTRACT_VECTOR_ELT:
  3139. return selectExtractElt(I, MRI);
  3140. case TargetOpcode::G_INSERT_VECTOR_ELT:
  3141. return selectInsertElt(I, MRI);
  3142. case TargetOpcode::G_CONCAT_VECTORS:
  3143. return selectConcatVectors(I, MRI);
  3144. case TargetOpcode::G_JUMP_TABLE:
  3145. return selectJumpTable(I, MRI);
  3146. case TargetOpcode::G_VECREDUCE_FADD:
  3147. case TargetOpcode::G_VECREDUCE_ADD:
  3148. return selectReduction(I, MRI);
  3149. case TargetOpcode::G_MEMCPY:
  3150. case TargetOpcode::G_MEMCPY_INLINE:
  3151. case TargetOpcode::G_MEMMOVE:
  3152. case TargetOpcode::G_MEMSET:
  3153. assert(STI.hasMOPS() && "Shouldn't get here without +mops feature");
  3154. return selectMOPS(I, MRI);
  3155. }
  3156. return false;
  3157. }
  3158. bool AArch64InstructionSelector::selectReduction(MachineInstr &I,
  3159. MachineRegisterInfo &MRI) {
  3160. Register VecReg = I.getOperand(1).getReg();
  3161. LLT VecTy = MRI.getType(VecReg);
  3162. if (I.getOpcode() == TargetOpcode::G_VECREDUCE_ADD) {
  3163. // For <2 x i32> ADDPv2i32 generates an FPR64 value, so we need to emit
  3164. // a subregister copy afterwards.
  3165. if (VecTy == LLT::fixed_vector(2, 32)) {
  3166. Register DstReg = I.getOperand(0).getReg();
  3167. auto AddP = MIB.buildInstr(AArch64::ADDPv2i32, {&AArch64::FPR64RegClass},
  3168. {VecReg, VecReg});
  3169. auto Copy = MIB.buildInstr(TargetOpcode::COPY, {DstReg}, {})
  3170. .addReg(AddP.getReg(0), 0, AArch64::ssub)
  3171. .getReg(0);
  3172. RBI.constrainGenericRegister(Copy, AArch64::FPR32RegClass, MRI);
  3173. I.eraseFromParent();
  3174. return constrainSelectedInstRegOperands(*AddP, TII, TRI, RBI);
  3175. }
  3176. unsigned Opc = 0;
  3177. if (VecTy == LLT::fixed_vector(16, 8))
  3178. Opc = AArch64::ADDVv16i8v;
  3179. else if (VecTy == LLT::fixed_vector(8, 16))
  3180. Opc = AArch64::ADDVv8i16v;
  3181. else if (VecTy == LLT::fixed_vector(4, 32))
  3182. Opc = AArch64::ADDVv4i32v;
  3183. else if (VecTy == LLT::fixed_vector(2, 64))
  3184. Opc = AArch64::ADDPv2i64p;
  3185. else {
  3186. LLVM_DEBUG(dbgs() << "Unhandled type for add reduction");
  3187. return false;
  3188. }
  3189. I.setDesc(TII.get(Opc));
  3190. return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
  3191. }
  3192. if (I.getOpcode() == TargetOpcode::G_VECREDUCE_FADD) {
  3193. unsigned Opc = 0;
  3194. if (VecTy == LLT::fixed_vector(2, 32))
  3195. Opc = AArch64::FADDPv2i32p;
  3196. else if (VecTy == LLT::fixed_vector(2, 64))
  3197. Opc = AArch64::FADDPv2i64p;
  3198. else {
  3199. LLVM_DEBUG(dbgs() << "Unhandled type for fadd reduction");
  3200. return false;
  3201. }
  3202. I.setDesc(TII.get(Opc));
  3203. return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
  3204. }
  3205. return false;
  3206. }
  3207. bool AArch64InstructionSelector::selectMOPS(MachineInstr &GI,
  3208. MachineRegisterInfo &MRI) {
  3209. unsigned Mopcode;
  3210. switch (GI.getOpcode()) {
  3211. case TargetOpcode::G_MEMCPY:
  3212. case TargetOpcode::G_MEMCPY_INLINE:
  3213. Mopcode = AArch64::MOPSMemoryCopyPseudo;
  3214. break;
  3215. case TargetOpcode::G_MEMMOVE:
  3216. Mopcode = AArch64::MOPSMemoryMovePseudo;
  3217. break;
  3218. case TargetOpcode::G_MEMSET:
  3219. // For tagged memset see llvm.aarch64.mops.memset.tag
  3220. Mopcode = AArch64::MOPSMemorySetPseudo;
  3221. break;
  3222. }
  3223. auto &DstPtr = GI.getOperand(0);
  3224. auto &SrcOrVal = GI.getOperand(1);
  3225. auto &Size = GI.getOperand(2);
  3226. // Create copies of the registers that can be clobbered.
  3227. const Register DstPtrCopy = MRI.cloneVirtualRegister(DstPtr.getReg());
  3228. const Register SrcValCopy = MRI.cloneVirtualRegister(SrcOrVal.getReg());
  3229. const Register SizeCopy = MRI.cloneVirtualRegister(Size.getReg());
  3230. const bool IsSet = Mopcode == AArch64::MOPSMemorySetPseudo;
  3231. const auto &SrcValRegClass =
  3232. IsSet ? AArch64::GPR64RegClass : AArch64::GPR64commonRegClass;
  3233. // Constrain to specific registers
  3234. RBI.constrainGenericRegister(DstPtrCopy, AArch64::GPR64commonRegClass, MRI);
  3235. RBI.constrainGenericRegister(SrcValCopy, SrcValRegClass, MRI);
  3236. RBI.constrainGenericRegister(SizeCopy, AArch64::GPR64RegClass, MRI);
  3237. MIB.buildCopy(DstPtrCopy, DstPtr);
  3238. MIB.buildCopy(SrcValCopy, SrcOrVal);
  3239. MIB.buildCopy(SizeCopy, Size);
  3240. // New instruction uses the copied registers because it must update them.
  3241. // The defs are not used since they don't exist in G_MEM*. They are still
  3242. // tied.
  3243. // Note: order of operands is different from G_MEMSET, G_MEMCPY, G_MEMMOVE
  3244. Register DefDstPtr = MRI.createVirtualRegister(&AArch64::GPR64commonRegClass);
  3245. Register DefSize = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
  3246. if (IsSet) {
  3247. MIB.buildInstr(Mopcode, {DefDstPtr, DefSize},
  3248. {DstPtrCopy, SizeCopy, SrcValCopy});
  3249. } else {
  3250. Register DefSrcPtr = MRI.createVirtualRegister(&SrcValRegClass);
  3251. MIB.buildInstr(Mopcode, {DefDstPtr, DefSrcPtr, DefSize},
  3252. {DstPtrCopy, SrcValCopy, SizeCopy});
  3253. }
  3254. GI.eraseFromParent();
  3255. return true;
  3256. }
  3257. bool AArch64InstructionSelector::selectBrJT(MachineInstr &I,
  3258. MachineRegisterInfo &MRI) {
  3259. assert(I.getOpcode() == TargetOpcode::G_BRJT && "Expected G_BRJT");
  3260. Register JTAddr = I.getOperand(0).getReg();
  3261. unsigned JTI = I.getOperand(1).getIndex();
  3262. Register Index = I.getOperand(2).getReg();
  3263. Register TargetReg = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
  3264. Register ScratchReg = MRI.createVirtualRegister(&AArch64::GPR64spRegClass);
  3265. MF->getInfo<AArch64FunctionInfo>()->setJumpTableEntryInfo(JTI, 4, nullptr);
  3266. auto JumpTableInst = MIB.buildInstr(AArch64::JumpTableDest32,
  3267. {TargetReg, ScratchReg}, {JTAddr, Index})
  3268. .addJumpTableIndex(JTI);
  3269. // Build the indirect branch.
  3270. MIB.buildInstr(AArch64::BR, {}, {TargetReg});
  3271. I.eraseFromParent();
  3272. return constrainSelectedInstRegOperands(*JumpTableInst, TII, TRI, RBI);
  3273. }
  3274. bool AArch64InstructionSelector::selectJumpTable(MachineInstr &I,
  3275. MachineRegisterInfo &MRI) {
  3276. assert(I.getOpcode() == TargetOpcode::G_JUMP_TABLE && "Expected jump table");
  3277. assert(I.getOperand(1).isJTI() && "Jump table op should have a JTI!");
  3278. Register DstReg = I.getOperand(0).getReg();
  3279. unsigned JTI = I.getOperand(1).getIndex();
  3280. // We generate a MOVaddrJT which will get expanded to an ADRP + ADD later.
  3281. auto MovMI =
  3282. MIB.buildInstr(AArch64::MOVaddrJT, {DstReg}, {})
  3283. .addJumpTableIndex(JTI, AArch64II::MO_PAGE)
  3284. .addJumpTableIndex(JTI, AArch64II::MO_NC | AArch64II::MO_PAGEOFF);
  3285. I.eraseFromParent();
  3286. return constrainSelectedInstRegOperands(*MovMI, TII, TRI, RBI);
  3287. }
  3288. bool AArch64InstructionSelector::selectTLSGlobalValue(
  3289. MachineInstr &I, MachineRegisterInfo &MRI) {
  3290. if (!STI.isTargetMachO())
  3291. return false;
  3292. MachineFunction &MF = *I.getParent()->getParent();
  3293. MF.getFrameInfo().setAdjustsStack(true);
  3294. const auto &GlobalOp = I.getOperand(1);
  3295. assert(GlobalOp.getOffset() == 0 &&
  3296. "Shouldn't have an offset on TLS globals!");
  3297. const GlobalValue &GV = *GlobalOp.getGlobal();
  3298. auto LoadGOT =
  3299. MIB.buildInstr(AArch64::LOADgot, {&AArch64::GPR64commonRegClass}, {})
  3300. .addGlobalAddress(&GV, 0, AArch64II::MO_TLS);
  3301. auto Load = MIB.buildInstr(AArch64::LDRXui, {&AArch64::GPR64commonRegClass},
  3302. {LoadGOT.getReg(0)})
  3303. .addImm(0);
  3304. MIB.buildCopy(Register(AArch64::X0), LoadGOT.getReg(0));
  3305. // TLS calls preserve all registers except those that absolutely must be
  3306. // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
  3307. // silly).
  3308. MIB.buildInstr(getBLRCallOpcode(MF), {}, {Load})
  3309. .addUse(AArch64::X0, RegState::Implicit)
  3310. .addDef(AArch64::X0, RegState::Implicit)
  3311. .addRegMask(TRI.getTLSCallPreservedMask());
  3312. MIB.buildCopy(I.getOperand(0).getReg(), Register(AArch64::X0));
  3313. RBI.constrainGenericRegister(I.getOperand(0).getReg(), AArch64::GPR64RegClass,
  3314. MRI);
  3315. I.eraseFromParent();
  3316. return true;
  3317. }
  3318. bool AArch64InstructionSelector::selectIntrinsicTrunc(
  3319. MachineInstr &I, MachineRegisterInfo &MRI) const {
  3320. const LLT SrcTy = MRI.getType(I.getOperand(0).getReg());
  3321. // Select the correct opcode.
  3322. unsigned Opc = 0;
  3323. if (!SrcTy.isVector()) {
  3324. switch (SrcTy.getSizeInBits()) {
  3325. default:
  3326. case 16:
  3327. Opc = AArch64::FRINTZHr;
  3328. break;
  3329. case 32:
  3330. Opc = AArch64::FRINTZSr;
  3331. break;
  3332. case 64:
  3333. Opc = AArch64::FRINTZDr;
  3334. break;
  3335. }
  3336. } else {
  3337. unsigned NumElts = SrcTy.getNumElements();
  3338. switch (SrcTy.getElementType().getSizeInBits()) {
  3339. default:
  3340. break;
  3341. case 16:
  3342. if (NumElts == 4)
  3343. Opc = AArch64::FRINTZv4f16;
  3344. else if (NumElts == 8)
  3345. Opc = AArch64::FRINTZv8f16;
  3346. break;
  3347. case 32:
  3348. if (NumElts == 2)
  3349. Opc = AArch64::FRINTZv2f32;
  3350. else if (NumElts == 4)
  3351. Opc = AArch64::FRINTZv4f32;
  3352. break;
  3353. case 64:
  3354. if (NumElts == 2)
  3355. Opc = AArch64::FRINTZv2f64;
  3356. break;
  3357. }
  3358. }
  3359. if (!Opc) {
  3360. // Didn't get an opcode above, bail.
  3361. LLVM_DEBUG(dbgs() << "Unsupported type for G_INTRINSIC_TRUNC!\n");
  3362. return false;
  3363. }
  3364. // Legalization would have set us up perfectly for this; we just need to
  3365. // set the opcode and move on.
  3366. I.setDesc(TII.get(Opc));
  3367. return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
  3368. }
  3369. bool AArch64InstructionSelector::selectIntrinsicRound(
  3370. MachineInstr &I, MachineRegisterInfo &MRI) const {
  3371. const LLT SrcTy = MRI.getType(I.getOperand(0).getReg());
  3372. // Select the correct opcode.
  3373. unsigned Opc = 0;
  3374. if (!SrcTy.isVector()) {
  3375. switch (SrcTy.getSizeInBits()) {
  3376. default:
  3377. case 16:
  3378. Opc = AArch64::FRINTAHr;
  3379. break;
  3380. case 32:
  3381. Opc = AArch64::FRINTASr;
  3382. break;
  3383. case 64:
  3384. Opc = AArch64::FRINTADr;
  3385. break;
  3386. }
  3387. } else {
  3388. unsigned NumElts = SrcTy.getNumElements();
  3389. switch (SrcTy.getElementType().getSizeInBits()) {
  3390. default:
  3391. break;
  3392. case 16:
  3393. if (NumElts == 4)
  3394. Opc = AArch64::FRINTAv4f16;
  3395. else if (NumElts == 8)
  3396. Opc = AArch64::FRINTAv8f16;
  3397. break;
  3398. case 32:
  3399. if (NumElts == 2)
  3400. Opc = AArch64::FRINTAv2f32;
  3401. else if (NumElts == 4)
  3402. Opc = AArch64::FRINTAv4f32;
  3403. break;
  3404. case 64:
  3405. if (NumElts == 2)
  3406. Opc = AArch64::FRINTAv2f64;
  3407. break;
  3408. }
  3409. }
  3410. if (!Opc) {
  3411. // Didn't get an opcode above, bail.
  3412. LLVM_DEBUG(dbgs() << "Unsupported type for G_INTRINSIC_ROUND!\n");
  3413. return false;
  3414. }
  3415. // Legalization would have set us up perfectly for this; we just need to
  3416. // set the opcode and move on.
  3417. I.setDesc(TII.get(Opc));
  3418. return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
  3419. }
  3420. bool AArch64InstructionSelector::selectVectorICmp(
  3421. MachineInstr &I, MachineRegisterInfo &MRI) {
  3422. Register DstReg = I.getOperand(0).getReg();
  3423. LLT DstTy = MRI.getType(DstReg);
  3424. Register SrcReg = I.getOperand(2).getReg();
  3425. Register Src2Reg = I.getOperand(3).getReg();
  3426. LLT SrcTy = MRI.getType(SrcReg);
  3427. unsigned SrcEltSize = SrcTy.getElementType().getSizeInBits();
  3428. unsigned NumElts = DstTy.getNumElements();
  3429. // First index is element size, 0 == 8b, 1 == 16b, 2 == 32b, 3 == 64b
  3430. // Second index is num elts, 0 == v2, 1 == v4, 2 == v8, 3 == v16
  3431. // Third index is cc opcode:
  3432. // 0 == eq
  3433. // 1 == ugt
  3434. // 2 == uge
  3435. // 3 == ult
  3436. // 4 == ule
  3437. // 5 == sgt
  3438. // 6 == sge
  3439. // 7 == slt
  3440. // 8 == sle
  3441. // ne is done by negating 'eq' result.
  3442. // This table below assumes that for some comparisons the operands will be
  3443. // commuted.
  3444. // ult op == commute + ugt op
  3445. // ule op == commute + uge op
  3446. // slt op == commute + sgt op
  3447. // sle op == commute + sge op
  3448. unsigned PredIdx = 0;
  3449. bool SwapOperands = false;
  3450. CmpInst::Predicate Pred = (CmpInst::Predicate)I.getOperand(1).getPredicate();
  3451. switch (Pred) {
  3452. case CmpInst::ICMP_NE:
  3453. case CmpInst::ICMP_EQ:
  3454. PredIdx = 0;
  3455. break;
  3456. case CmpInst::ICMP_UGT:
  3457. PredIdx = 1;
  3458. break;
  3459. case CmpInst::ICMP_UGE:
  3460. PredIdx = 2;
  3461. break;
  3462. case CmpInst::ICMP_ULT:
  3463. PredIdx = 3;
  3464. SwapOperands = true;
  3465. break;
  3466. case CmpInst::ICMP_ULE:
  3467. PredIdx = 4;
  3468. SwapOperands = true;
  3469. break;
  3470. case CmpInst::ICMP_SGT:
  3471. PredIdx = 5;
  3472. break;
  3473. case CmpInst::ICMP_SGE:
  3474. PredIdx = 6;
  3475. break;
  3476. case CmpInst::ICMP_SLT:
  3477. PredIdx = 7;
  3478. SwapOperands = true;
  3479. break;
  3480. case CmpInst::ICMP_SLE:
  3481. PredIdx = 8;
  3482. SwapOperands = true;
  3483. break;
  3484. default:
  3485. llvm_unreachable("Unhandled icmp predicate");
  3486. return false;
  3487. }
  3488. // This table obviously should be tablegen'd when we have our GISel native
  3489. // tablegen selector.
  3490. static const unsigned OpcTable[4][4][9] = {
  3491. {
  3492. {0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
  3493. 0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
  3494. 0 /* invalid */},
  3495. {0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
  3496. 0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
  3497. 0 /* invalid */},
  3498. {AArch64::CMEQv8i8, AArch64::CMHIv8i8, AArch64::CMHSv8i8,
  3499. AArch64::CMHIv8i8, AArch64::CMHSv8i8, AArch64::CMGTv8i8,
  3500. AArch64::CMGEv8i8, AArch64::CMGTv8i8, AArch64::CMGEv8i8},
  3501. {AArch64::CMEQv16i8, AArch64::CMHIv16i8, AArch64::CMHSv16i8,
  3502. AArch64::CMHIv16i8, AArch64::CMHSv16i8, AArch64::CMGTv16i8,
  3503. AArch64::CMGEv16i8, AArch64::CMGTv16i8, AArch64::CMGEv16i8}
  3504. },
  3505. {
  3506. {0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
  3507. 0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
  3508. 0 /* invalid */},
  3509. {AArch64::CMEQv4i16, AArch64::CMHIv4i16, AArch64::CMHSv4i16,
  3510. AArch64::CMHIv4i16, AArch64::CMHSv4i16, AArch64::CMGTv4i16,
  3511. AArch64::CMGEv4i16, AArch64::CMGTv4i16, AArch64::CMGEv4i16},
  3512. {AArch64::CMEQv8i16, AArch64::CMHIv8i16, AArch64::CMHSv8i16,
  3513. AArch64::CMHIv8i16, AArch64::CMHSv8i16, AArch64::CMGTv8i16,
  3514. AArch64::CMGEv8i16, AArch64::CMGTv8i16, AArch64::CMGEv8i16},
  3515. {0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
  3516. 0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
  3517. 0 /* invalid */}
  3518. },
  3519. {
  3520. {AArch64::CMEQv2i32, AArch64::CMHIv2i32, AArch64::CMHSv2i32,
  3521. AArch64::CMHIv2i32, AArch64::CMHSv2i32, AArch64::CMGTv2i32,
  3522. AArch64::CMGEv2i32, AArch64::CMGTv2i32, AArch64::CMGEv2i32},
  3523. {AArch64::CMEQv4i32, AArch64::CMHIv4i32, AArch64::CMHSv4i32,
  3524. AArch64::CMHIv4i32, AArch64::CMHSv4i32, AArch64::CMGTv4i32,
  3525. AArch64::CMGEv4i32, AArch64::CMGTv4i32, AArch64::CMGEv4i32},
  3526. {0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
  3527. 0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
  3528. 0 /* invalid */},
  3529. {0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
  3530. 0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
  3531. 0 /* invalid */}
  3532. },
  3533. {
  3534. {AArch64::CMEQv2i64, AArch64::CMHIv2i64, AArch64::CMHSv2i64,
  3535. AArch64::CMHIv2i64, AArch64::CMHSv2i64, AArch64::CMGTv2i64,
  3536. AArch64::CMGEv2i64, AArch64::CMGTv2i64, AArch64::CMGEv2i64},
  3537. {0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
  3538. 0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
  3539. 0 /* invalid */},
  3540. {0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
  3541. 0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
  3542. 0 /* invalid */},
  3543. {0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
  3544. 0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
  3545. 0 /* invalid */}
  3546. },
  3547. };
  3548. unsigned EltIdx = Log2_32(SrcEltSize / 8);
  3549. unsigned NumEltsIdx = Log2_32(NumElts / 2);
  3550. unsigned Opc = OpcTable[EltIdx][NumEltsIdx][PredIdx];
  3551. if (!Opc) {
  3552. LLVM_DEBUG(dbgs() << "Could not map G_ICMP to cmp opcode");
  3553. return false;
  3554. }
  3555. const RegisterBank &VecRB = *RBI.getRegBank(SrcReg, MRI, TRI);
  3556. const TargetRegisterClass *SrcRC =
  3557. getRegClassForTypeOnBank(SrcTy, VecRB, true);
  3558. if (!SrcRC) {
  3559. LLVM_DEBUG(dbgs() << "Could not determine source register class.\n");
  3560. return false;
  3561. }
  3562. unsigned NotOpc = Pred == ICmpInst::ICMP_NE ? AArch64::NOTv8i8 : 0;
  3563. if (SrcTy.getSizeInBits() == 128)
  3564. NotOpc = NotOpc ? AArch64::NOTv16i8 : 0;
  3565. if (SwapOperands)
  3566. std::swap(SrcReg, Src2Reg);
  3567. auto Cmp = MIB.buildInstr(Opc, {SrcRC}, {SrcReg, Src2Reg});
  3568. constrainSelectedInstRegOperands(*Cmp, TII, TRI, RBI);
  3569. // Invert if we had a 'ne' cc.
  3570. if (NotOpc) {
  3571. Cmp = MIB.buildInstr(NotOpc, {DstReg}, {Cmp});
  3572. constrainSelectedInstRegOperands(*Cmp, TII, TRI, RBI);
  3573. } else {
  3574. MIB.buildCopy(DstReg, Cmp.getReg(0));
  3575. }
  3576. RBI.constrainGenericRegister(DstReg, *SrcRC, MRI);
  3577. I.eraseFromParent();
  3578. return true;
  3579. }
  3580. MachineInstr *AArch64InstructionSelector::emitScalarToVector(
  3581. unsigned EltSize, const TargetRegisterClass *DstRC, Register Scalar,
  3582. MachineIRBuilder &MIRBuilder) const {
  3583. auto Undef = MIRBuilder.buildInstr(TargetOpcode::IMPLICIT_DEF, {DstRC}, {});
  3584. auto BuildFn = [&](unsigned SubregIndex) {
  3585. auto Ins =
  3586. MIRBuilder
  3587. .buildInstr(TargetOpcode::INSERT_SUBREG, {DstRC}, {Undef, Scalar})
  3588. .addImm(SubregIndex);
  3589. constrainSelectedInstRegOperands(*Undef, TII, TRI, RBI);
  3590. constrainSelectedInstRegOperands(*Ins, TII, TRI, RBI);
  3591. return &*Ins;
  3592. };
  3593. switch (EltSize) {
  3594. case 16:
  3595. return BuildFn(AArch64::hsub);
  3596. case 32:
  3597. return BuildFn(AArch64::ssub);
  3598. case 64:
  3599. return BuildFn(AArch64::dsub);
  3600. default:
  3601. return nullptr;
  3602. }
  3603. }
  3604. bool AArch64InstructionSelector::selectMergeValues(
  3605. MachineInstr &I, MachineRegisterInfo &MRI) {
  3606. assert(I.getOpcode() == TargetOpcode::G_MERGE_VALUES && "unexpected opcode");
  3607. const LLT DstTy = MRI.getType(I.getOperand(0).getReg());
  3608. const LLT SrcTy = MRI.getType(I.getOperand(1).getReg());
  3609. assert(!DstTy.isVector() && !SrcTy.isVector() && "invalid merge operation");
  3610. const RegisterBank &RB = *RBI.getRegBank(I.getOperand(1).getReg(), MRI, TRI);
  3611. if (I.getNumOperands() != 3)
  3612. return false;
  3613. // Merging 2 s64s into an s128.
  3614. if (DstTy == LLT::scalar(128)) {
  3615. if (SrcTy.getSizeInBits() != 64)
  3616. return false;
  3617. Register DstReg = I.getOperand(0).getReg();
  3618. Register Src1Reg = I.getOperand(1).getReg();
  3619. Register Src2Reg = I.getOperand(2).getReg();
  3620. auto Tmp = MIB.buildInstr(TargetOpcode::IMPLICIT_DEF, {DstTy}, {});
  3621. MachineInstr *InsMI = emitLaneInsert(std::nullopt, Tmp.getReg(0), Src1Reg,
  3622. /* LaneIdx */ 0, RB, MIB);
  3623. if (!InsMI)
  3624. return false;
  3625. MachineInstr *Ins2MI = emitLaneInsert(DstReg, InsMI->getOperand(0).getReg(),
  3626. Src2Reg, /* LaneIdx */ 1, RB, MIB);
  3627. if (!Ins2MI)
  3628. return false;
  3629. constrainSelectedInstRegOperands(*InsMI, TII, TRI, RBI);
  3630. constrainSelectedInstRegOperands(*Ins2MI, TII, TRI, RBI);
  3631. I.eraseFromParent();
  3632. return true;
  3633. }
  3634. if (RB.getID() != AArch64::GPRRegBankID)
  3635. return false;
  3636. if (DstTy.getSizeInBits() != 64 || SrcTy.getSizeInBits() != 32)
  3637. return false;
  3638. auto *DstRC = &AArch64::GPR64RegClass;
  3639. Register SubToRegDef = MRI.createVirtualRegister(DstRC);
  3640. MachineInstr &SubRegMI = *BuildMI(*I.getParent(), I, I.getDebugLoc(),
  3641. TII.get(TargetOpcode::SUBREG_TO_REG))
  3642. .addDef(SubToRegDef)
  3643. .addImm(0)
  3644. .addUse(I.getOperand(1).getReg())
  3645. .addImm(AArch64::sub_32);
  3646. Register SubToRegDef2 = MRI.createVirtualRegister(DstRC);
  3647. // Need to anyext the second scalar before we can use bfm
  3648. MachineInstr &SubRegMI2 = *BuildMI(*I.getParent(), I, I.getDebugLoc(),
  3649. TII.get(TargetOpcode::SUBREG_TO_REG))
  3650. .addDef(SubToRegDef2)
  3651. .addImm(0)
  3652. .addUse(I.getOperand(2).getReg())
  3653. .addImm(AArch64::sub_32);
  3654. MachineInstr &BFM =
  3655. *BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(AArch64::BFMXri))
  3656. .addDef(I.getOperand(0).getReg())
  3657. .addUse(SubToRegDef)
  3658. .addUse(SubToRegDef2)
  3659. .addImm(32)
  3660. .addImm(31);
  3661. constrainSelectedInstRegOperands(SubRegMI, TII, TRI, RBI);
  3662. constrainSelectedInstRegOperands(SubRegMI2, TII, TRI, RBI);
  3663. constrainSelectedInstRegOperands(BFM, TII, TRI, RBI);
  3664. I.eraseFromParent();
  3665. return true;
  3666. }
  3667. static bool getLaneCopyOpcode(unsigned &CopyOpc, unsigned &ExtractSubReg,
  3668. const unsigned EltSize) {
  3669. // Choose a lane copy opcode and subregister based off of the size of the
  3670. // vector's elements.
  3671. switch (EltSize) {
  3672. case 8:
  3673. CopyOpc = AArch64::DUPi8;
  3674. ExtractSubReg = AArch64::bsub;
  3675. break;
  3676. case 16:
  3677. CopyOpc = AArch64::DUPi16;
  3678. ExtractSubReg = AArch64::hsub;
  3679. break;
  3680. case 32:
  3681. CopyOpc = AArch64::DUPi32;
  3682. ExtractSubReg = AArch64::ssub;
  3683. break;
  3684. case 64:
  3685. CopyOpc = AArch64::DUPi64;
  3686. ExtractSubReg = AArch64::dsub;
  3687. break;
  3688. default:
  3689. // Unknown size, bail out.
  3690. LLVM_DEBUG(dbgs() << "Elt size '" << EltSize << "' unsupported.\n");
  3691. return false;
  3692. }
  3693. return true;
  3694. }
  3695. MachineInstr *AArch64InstructionSelector::emitExtractVectorElt(
  3696. std::optional<Register> DstReg, const RegisterBank &DstRB, LLT ScalarTy,
  3697. Register VecReg, unsigned LaneIdx, MachineIRBuilder &MIRBuilder) const {
  3698. MachineRegisterInfo &MRI = *MIRBuilder.getMRI();
  3699. unsigned CopyOpc = 0;
  3700. unsigned ExtractSubReg = 0;
  3701. if (!getLaneCopyOpcode(CopyOpc, ExtractSubReg, ScalarTy.getSizeInBits())) {
  3702. LLVM_DEBUG(
  3703. dbgs() << "Couldn't determine lane copy opcode for instruction.\n");
  3704. return nullptr;
  3705. }
  3706. const TargetRegisterClass *DstRC =
  3707. getRegClassForTypeOnBank(ScalarTy, DstRB, true);
  3708. if (!DstRC) {
  3709. LLVM_DEBUG(dbgs() << "Could not determine destination register class.\n");
  3710. return nullptr;
  3711. }
  3712. const RegisterBank &VecRB = *RBI.getRegBank(VecReg, MRI, TRI);
  3713. const LLT &VecTy = MRI.getType(VecReg);
  3714. const TargetRegisterClass *VecRC =
  3715. getRegClassForTypeOnBank(VecTy, VecRB, true);
  3716. if (!VecRC) {
  3717. LLVM_DEBUG(dbgs() << "Could not determine source register class.\n");
  3718. return nullptr;
  3719. }
  3720. // The register that we're going to copy into.
  3721. Register InsertReg = VecReg;
  3722. if (!DstReg)
  3723. DstReg = MRI.createVirtualRegister(DstRC);
  3724. // If the lane index is 0, we just use a subregister COPY.
  3725. if (LaneIdx == 0) {
  3726. auto Copy = MIRBuilder.buildInstr(TargetOpcode::COPY, {*DstReg}, {})
  3727. .addReg(VecReg, 0, ExtractSubReg);
  3728. RBI.constrainGenericRegister(*DstReg, *DstRC, MRI);
  3729. return &*Copy;
  3730. }
  3731. // Lane copies require 128-bit wide registers. If we're dealing with an
  3732. // unpacked vector, then we need to move up to that width. Insert an implicit
  3733. // def and a subregister insert to get us there.
  3734. if (VecTy.getSizeInBits() != 128) {
  3735. MachineInstr *ScalarToVector = emitScalarToVector(
  3736. VecTy.getSizeInBits(), &AArch64::FPR128RegClass, VecReg, MIRBuilder);
  3737. if (!ScalarToVector)
  3738. return nullptr;
  3739. InsertReg = ScalarToVector->getOperand(0).getReg();
  3740. }
  3741. MachineInstr *LaneCopyMI =
  3742. MIRBuilder.buildInstr(CopyOpc, {*DstReg}, {InsertReg}).addImm(LaneIdx);
  3743. constrainSelectedInstRegOperands(*LaneCopyMI, TII, TRI, RBI);
  3744. // Make sure that we actually constrain the initial copy.
  3745. RBI.constrainGenericRegister(*DstReg, *DstRC, MRI);
  3746. return LaneCopyMI;
  3747. }
  3748. bool AArch64InstructionSelector::selectExtractElt(
  3749. MachineInstr &I, MachineRegisterInfo &MRI) {
  3750. assert(I.getOpcode() == TargetOpcode::G_EXTRACT_VECTOR_ELT &&
  3751. "unexpected opcode!");
  3752. Register DstReg = I.getOperand(0).getReg();
  3753. const LLT NarrowTy = MRI.getType(DstReg);
  3754. const Register SrcReg = I.getOperand(1).getReg();
  3755. const LLT WideTy = MRI.getType(SrcReg);
  3756. (void)WideTy;
  3757. assert(WideTy.getSizeInBits() >= NarrowTy.getSizeInBits() &&
  3758. "source register size too small!");
  3759. assert(!NarrowTy.isVector() && "cannot extract vector into vector!");
  3760. // Need the lane index to determine the correct copy opcode.
  3761. MachineOperand &LaneIdxOp = I.getOperand(2);
  3762. assert(LaneIdxOp.isReg() && "Lane index operand was not a register?");
  3763. if (RBI.getRegBank(DstReg, MRI, TRI)->getID() != AArch64::FPRRegBankID) {
  3764. LLVM_DEBUG(dbgs() << "Cannot extract into GPR.\n");
  3765. return false;
  3766. }
  3767. // Find the index to extract from.
  3768. auto VRegAndVal = getIConstantVRegValWithLookThrough(LaneIdxOp.getReg(), MRI);
  3769. if (!VRegAndVal)
  3770. return false;
  3771. unsigned LaneIdx = VRegAndVal->Value.getSExtValue();
  3772. const RegisterBank &DstRB = *RBI.getRegBank(DstReg, MRI, TRI);
  3773. MachineInstr *Extract = emitExtractVectorElt(DstReg, DstRB, NarrowTy, SrcReg,
  3774. LaneIdx, MIB);
  3775. if (!Extract)
  3776. return false;
  3777. I.eraseFromParent();
  3778. return true;
  3779. }
  3780. bool AArch64InstructionSelector::selectSplitVectorUnmerge(
  3781. MachineInstr &I, MachineRegisterInfo &MRI) {
  3782. unsigned NumElts = I.getNumOperands() - 1;
  3783. Register SrcReg = I.getOperand(NumElts).getReg();
  3784. const LLT NarrowTy = MRI.getType(I.getOperand(0).getReg());
  3785. const LLT SrcTy = MRI.getType(SrcReg);
  3786. assert(NarrowTy.isVector() && "Expected an unmerge into vectors");
  3787. if (SrcTy.getSizeInBits() > 128) {
  3788. LLVM_DEBUG(dbgs() << "Unexpected vector type for vec split unmerge");
  3789. return false;
  3790. }
  3791. // We implement a split vector operation by treating the sub-vectors as
  3792. // scalars and extracting them.
  3793. const RegisterBank &DstRB =
  3794. *RBI.getRegBank(I.getOperand(0).getReg(), MRI, TRI);
  3795. for (unsigned OpIdx = 0; OpIdx < NumElts; ++OpIdx) {
  3796. Register Dst = I.getOperand(OpIdx).getReg();
  3797. MachineInstr *Extract =
  3798. emitExtractVectorElt(Dst, DstRB, NarrowTy, SrcReg, OpIdx, MIB);
  3799. if (!Extract)
  3800. return false;
  3801. }
  3802. I.eraseFromParent();
  3803. return true;
  3804. }
  3805. bool AArch64InstructionSelector::selectUnmergeValues(MachineInstr &I,
  3806. MachineRegisterInfo &MRI) {
  3807. assert(I.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
  3808. "unexpected opcode");
  3809. // TODO: Handle unmerging into GPRs and from scalars to scalars.
  3810. if (RBI.getRegBank(I.getOperand(0).getReg(), MRI, TRI)->getID() !=
  3811. AArch64::FPRRegBankID ||
  3812. RBI.getRegBank(I.getOperand(1).getReg(), MRI, TRI)->getID() !=
  3813. AArch64::FPRRegBankID) {
  3814. LLVM_DEBUG(dbgs() << "Unmerging vector-to-gpr and scalar-to-scalar "
  3815. "currently unsupported.\n");
  3816. return false;
  3817. }
  3818. // The last operand is the vector source register, and every other operand is
  3819. // a register to unpack into.
  3820. unsigned NumElts = I.getNumOperands() - 1;
  3821. Register SrcReg = I.getOperand(NumElts).getReg();
  3822. const LLT NarrowTy = MRI.getType(I.getOperand(0).getReg());
  3823. const LLT WideTy = MRI.getType(SrcReg);
  3824. (void)WideTy;
  3825. assert((WideTy.isVector() || WideTy.getSizeInBits() == 128) &&
  3826. "can only unmerge from vector or s128 types!");
  3827. assert(WideTy.getSizeInBits() > NarrowTy.getSizeInBits() &&
  3828. "source register size too small!");
  3829. if (!NarrowTy.isScalar())
  3830. return selectSplitVectorUnmerge(I, MRI);
  3831. // Choose a lane copy opcode and subregister based off of the size of the
  3832. // vector's elements.
  3833. unsigned CopyOpc = 0;
  3834. unsigned ExtractSubReg = 0;
  3835. if (!getLaneCopyOpcode(CopyOpc, ExtractSubReg, NarrowTy.getSizeInBits()))
  3836. return false;
  3837. // Set up for the lane copies.
  3838. MachineBasicBlock &MBB = *I.getParent();
  3839. // Stores the registers we'll be copying from.
  3840. SmallVector<Register, 4> InsertRegs;
  3841. // We'll use the first register twice, so we only need NumElts-1 registers.
  3842. unsigned NumInsertRegs = NumElts - 1;
  3843. // If our elements fit into exactly 128 bits, then we can copy from the source
  3844. // directly. Otherwise, we need to do a bit of setup with some subregister
  3845. // inserts.
  3846. if (NarrowTy.getSizeInBits() * NumElts == 128) {
  3847. InsertRegs = SmallVector<Register, 4>(NumInsertRegs, SrcReg);
  3848. } else {
  3849. // No. We have to perform subregister inserts. For each insert, create an
  3850. // implicit def and a subregister insert, and save the register we create.
  3851. const TargetRegisterClass *RC = getRegClassForTypeOnBank(
  3852. LLT::fixed_vector(NumElts, WideTy.getScalarSizeInBits()),
  3853. *RBI.getRegBank(SrcReg, MRI, TRI));
  3854. unsigned SubReg = 0;
  3855. bool Found = getSubRegForClass(RC, TRI, SubReg);
  3856. (void)Found;
  3857. assert(Found && "expected to find last operand's subeg idx");
  3858. for (unsigned Idx = 0; Idx < NumInsertRegs; ++Idx) {
  3859. Register ImpDefReg = MRI.createVirtualRegister(&AArch64::FPR128RegClass);
  3860. MachineInstr &ImpDefMI =
  3861. *BuildMI(MBB, I, I.getDebugLoc(), TII.get(TargetOpcode::IMPLICIT_DEF),
  3862. ImpDefReg);
  3863. // Now, create the subregister insert from SrcReg.
  3864. Register InsertReg = MRI.createVirtualRegister(&AArch64::FPR128RegClass);
  3865. MachineInstr &InsMI =
  3866. *BuildMI(MBB, I, I.getDebugLoc(),
  3867. TII.get(TargetOpcode::INSERT_SUBREG), InsertReg)
  3868. .addUse(ImpDefReg)
  3869. .addUse(SrcReg)
  3870. .addImm(SubReg);
  3871. constrainSelectedInstRegOperands(ImpDefMI, TII, TRI, RBI);
  3872. constrainSelectedInstRegOperands(InsMI, TII, TRI, RBI);
  3873. // Save the register so that we can copy from it after.
  3874. InsertRegs.push_back(InsertReg);
  3875. }
  3876. }
  3877. // Now that we've created any necessary subregister inserts, we can
  3878. // create the copies.
  3879. //
  3880. // Perform the first copy separately as a subregister copy.
  3881. Register CopyTo = I.getOperand(0).getReg();
  3882. auto FirstCopy = MIB.buildInstr(TargetOpcode::COPY, {CopyTo}, {})
  3883. .addReg(InsertRegs[0], 0, ExtractSubReg);
  3884. constrainSelectedInstRegOperands(*FirstCopy, TII, TRI, RBI);
  3885. // Now, perform the remaining copies as vector lane copies.
  3886. unsigned LaneIdx = 1;
  3887. for (Register InsReg : InsertRegs) {
  3888. Register CopyTo = I.getOperand(LaneIdx).getReg();
  3889. MachineInstr &CopyInst =
  3890. *BuildMI(MBB, I, I.getDebugLoc(), TII.get(CopyOpc), CopyTo)
  3891. .addUse(InsReg)
  3892. .addImm(LaneIdx);
  3893. constrainSelectedInstRegOperands(CopyInst, TII, TRI, RBI);
  3894. ++LaneIdx;
  3895. }
  3896. // Separately constrain the first copy's destination. Because of the
  3897. // limitation in constrainOperandRegClass, we can't guarantee that this will
  3898. // actually be constrained. So, do it ourselves using the second operand.
  3899. const TargetRegisterClass *RC =
  3900. MRI.getRegClassOrNull(I.getOperand(1).getReg());
  3901. if (!RC) {
  3902. LLVM_DEBUG(dbgs() << "Couldn't constrain copy destination.\n");
  3903. return false;
  3904. }
  3905. RBI.constrainGenericRegister(CopyTo, *RC, MRI);
  3906. I.eraseFromParent();
  3907. return true;
  3908. }
  3909. bool AArch64InstructionSelector::selectConcatVectors(
  3910. MachineInstr &I, MachineRegisterInfo &MRI) {
  3911. assert(I.getOpcode() == TargetOpcode::G_CONCAT_VECTORS &&
  3912. "Unexpected opcode");
  3913. Register Dst = I.getOperand(0).getReg();
  3914. Register Op1 = I.getOperand(1).getReg();
  3915. Register Op2 = I.getOperand(2).getReg();
  3916. MachineInstr *ConcatMI = emitVectorConcat(Dst, Op1, Op2, MIB);
  3917. if (!ConcatMI)
  3918. return false;
  3919. I.eraseFromParent();
  3920. return true;
  3921. }
  3922. unsigned
  3923. AArch64InstructionSelector::emitConstantPoolEntry(const Constant *CPVal,
  3924. MachineFunction &MF) const {
  3925. Type *CPTy = CPVal->getType();
  3926. Align Alignment = MF.getDataLayout().getPrefTypeAlign(CPTy);
  3927. MachineConstantPool *MCP = MF.getConstantPool();
  3928. return MCP->getConstantPoolIndex(CPVal, Alignment);
  3929. }
  3930. MachineInstr *AArch64InstructionSelector::emitLoadFromConstantPool(
  3931. const Constant *CPVal, MachineIRBuilder &MIRBuilder) const {
  3932. auto &MF = MIRBuilder.getMF();
  3933. unsigned CPIdx = emitConstantPoolEntry(CPVal, MF);
  3934. auto Adrp =
  3935. MIRBuilder.buildInstr(AArch64::ADRP, {&AArch64::GPR64RegClass}, {})
  3936. .addConstantPoolIndex(CPIdx, 0, AArch64II::MO_PAGE);
  3937. MachineInstr *LoadMI = nullptr;
  3938. MachinePointerInfo PtrInfo = MachinePointerInfo::getConstantPool(MF);
  3939. unsigned Size = MIRBuilder.getDataLayout().getTypeStoreSize(CPVal->getType());
  3940. switch (Size) {
  3941. case 16:
  3942. LoadMI =
  3943. &*MIRBuilder
  3944. .buildInstr(AArch64::LDRQui, {&AArch64::FPR128RegClass}, {Adrp})
  3945. .addConstantPoolIndex(CPIdx, 0,
  3946. AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
  3947. break;
  3948. case 8:
  3949. LoadMI =
  3950. &*MIRBuilder
  3951. .buildInstr(AArch64::LDRDui, {&AArch64::FPR64RegClass}, {Adrp})
  3952. .addConstantPoolIndex(CPIdx, 0,
  3953. AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
  3954. break;
  3955. case 4:
  3956. LoadMI =
  3957. &*MIRBuilder
  3958. .buildInstr(AArch64::LDRSui, {&AArch64::FPR32RegClass}, {Adrp})
  3959. .addConstantPoolIndex(CPIdx, 0,
  3960. AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
  3961. break;
  3962. case 2:
  3963. LoadMI =
  3964. &*MIRBuilder
  3965. .buildInstr(AArch64::LDRHui, {&AArch64::FPR16RegClass}, {Adrp})
  3966. .addConstantPoolIndex(CPIdx, 0,
  3967. AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
  3968. break;
  3969. default:
  3970. LLVM_DEBUG(dbgs() << "Could not load from constant pool of type "
  3971. << *CPVal->getType());
  3972. return nullptr;
  3973. }
  3974. LoadMI->addMemOperand(MF, MF.getMachineMemOperand(PtrInfo,
  3975. MachineMemOperand::MOLoad,
  3976. Size, Align(Size)));
  3977. constrainSelectedInstRegOperands(*Adrp, TII, TRI, RBI);
  3978. constrainSelectedInstRegOperands(*LoadMI, TII, TRI, RBI);
  3979. return LoadMI;
  3980. }
  3981. /// Return an <Opcode, SubregIndex> pair to do an vector elt insert of a given
  3982. /// size and RB.
  3983. static std::pair<unsigned, unsigned>
  3984. getInsertVecEltOpInfo(const RegisterBank &RB, unsigned EltSize) {
  3985. unsigned Opc, SubregIdx;
  3986. if (RB.getID() == AArch64::GPRRegBankID) {
  3987. if (EltSize == 16) {
  3988. Opc = AArch64::INSvi16gpr;
  3989. SubregIdx = AArch64::ssub;
  3990. } else if (EltSize == 32) {
  3991. Opc = AArch64::INSvi32gpr;
  3992. SubregIdx = AArch64::ssub;
  3993. } else if (EltSize == 64) {
  3994. Opc = AArch64::INSvi64gpr;
  3995. SubregIdx = AArch64::dsub;
  3996. } else {
  3997. llvm_unreachable("invalid elt size!");
  3998. }
  3999. } else {
  4000. if (EltSize == 8) {
  4001. Opc = AArch64::INSvi8lane;
  4002. SubregIdx = AArch64::bsub;
  4003. } else if (EltSize == 16) {
  4004. Opc = AArch64::INSvi16lane;
  4005. SubregIdx = AArch64::hsub;
  4006. } else if (EltSize == 32) {
  4007. Opc = AArch64::INSvi32lane;
  4008. SubregIdx = AArch64::ssub;
  4009. } else if (EltSize == 64) {
  4010. Opc = AArch64::INSvi64lane;
  4011. SubregIdx = AArch64::dsub;
  4012. } else {
  4013. llvm_unreachable("invalid elt size!");
  4014. }
  4015. }
  4016. return std::make_pair(Opc, SubregIdx);
  4017. }
  4018. MachineInstr *AArch64InstructionSelector::emitInstr(
  4019. unsigned Opcode, std::initializer_list<llvm::DstOp> DstOps,
  4020. std::initializer_list<llvm::SrcOp> SrcOps, MachineIRBuilder &MIRBuilder,
  4021. const ComplexRendererFns &RenderFns) const {
  4022. assert(Opcode && "Expected an opcode?");
  4023. assert(!isPreISelGenericOpcode(Opcode) &&
  4024. "Function should only be used to produce selected instructions!");
  4025. auto MI = MIRBuilder.buildInstr(Opcode, DstOps, SrcOps);
  4026. if (RenderFns)
  4027. for (auto &Fn : *RenderFns)
  4028. Fn(MI);
  4029. constrainSelectedInstRegOperands(*MI, TII, TRI, RBI);
  4030. return &*MI;
  4031. }
  4032. MachineInstr *AArch64InstructionSelector::emitAddSub(
  4033. const std::array<std::array<unsigned, 2>, 5> &AddrModeAndSizeToOpcode,
  4034. Register Dst, MachineOperand &LHS, MachineOperand &RHS,
  4035. MachineIRBuilder &MIRBuilder) const {
  4036. MachineRegisterInfo &MRI = MIRBuilder.getMF().getRegInfo();
  4037. assert(LHS.isReg() && RHS.isReg() && "Expected register operands?");
  4038. auto Ty = MRI.getType(LHS.getReg());
  4039. assert(!Ty.isVector() && "Expected a scalar or pointer?");
  4040. unsigned Size = Ty.getSizeInBits();
  4041. assert((Size == 32 || Size == 64) && "Expected a 32-bit or 64-bit type only");
  4042. bool Is32Bit = Size == 32;
  4043. // INSTRri form with positive arithmetic immediate.
  4044. if (auto Fns = selectArithImmed(RHS))
  4045. return emitInstr(AddrModeAndSizeToOpcode[0][Is32Bit], {Dst}, {LHS},
  4046. MIRBuilder, Fns);
  4047. // INSTRri form with negative arithmetic immediate.
  4048. if (auto Fns = selectNegArithImmed(RHS))
  4049. return emitInstr(AddrModeAndSizeToOpcode[3][Is32Bit], {Dst}, {LHS},
  4050. MIRBuilder, Fns);
  4051. // INSTRrx form.
  4052. if (auto Fns = selectArithExtendedRegister(RHS))
  4053. return emitInstr(AddrModeAndSizeToOpcode[4][Is32Bit], {Dst}, {LHS},
  4054. MIRBuilder, Fns);
  4055. // INSTRrs form.
  4056. if (auto Fns = selectShiftedRegister(RHS))
  4057. return emitInstr(AddrModeAndSizeToOpcode[1][Is32Bit], {Dst}, {LHS},
  4058. MIRBuilder, Fns);
  4059. return emitInstr(AddrModeAndSizeToOpcode[2][Is32Bit], {Dst}, {LHS, RHS},
  4060. MIRBuilder);
  4061. }
  4062. MachineInstr *
  4063. AArch64InstructionSelector::emitADD(Register DefReg, MachineOperand &LHS,
  4064. MachineOperand &RHS,
  4065. MachineIRBuilder &MIRBuilder) const {
  4066. const std::array<std::array<unsigned, 2>, 5> OpcTable{
  4067. {{AArch64::ADDXri, AArch64::ADDWri},
  4068. {AArch64::ADDXrs, AArch64::ADDWrs},
  4069. {AArch64::ADDXrr, AArch64::ADDWrr},
  4070. {AArch64::SUBXri, AArch64::SUBWri},
  4071. {AArch64::ADDXrx, AArch64::ADDWrx}}};
  4072. return emitAddSub(OpcTable, DefReg, LHS, RHS, MIRBuilder);
  4073. }
  4074. MachineInstr *
  4075. AArch64InstructionSelector::emitADDS(Register Dst, MachineOperand &LHS,
  4076. MachineOperand &RHS,
  4077. MachineIRBuilder &MIRBuilder) const {
  4078. const std::array<std::array<unsigned, 2>, 5> OpcTable{
  4079. {{AArch64::ADDSXri, AArch64::ADDSWri},
  4080. {AArch64::ADDSXrs, AArch64::ADDSWrs},
  4081. {AArch64::ADDSXrr, AArch64::ADDSWrr},
  4082. {AArch64::SUBSXri, AArch64::SUBSWri},
  4083. {AArch64::ADDSXrx, AArch64::ADDSWrx}}};
  4084. return emitAddSub(OpcTable, Dst, LHS, RHS, MIRBuilder);
  4085. }
  4086. MachineInstr *
  4087. AArch64InstructionSelector::emitSUBS(Register Dst, MachineOperand &LHS,
  4088. MachineOperand &RHS,
  4089. MachineIRBuilder &MIRBuilder) const {
  4090. const std::array<std::array<unsigned, 2>, 5> OpcTable{
  4091. {{AArch64::SUBSXri, AArch64::SUBSWri},
  4092. {AArch64::SUBSXrs, AArch64::SUBSWrs},
  4093. {AArch64::SUBSXrr, AArch64::SUBSWrr},
  4094. {AArch64::ADDSXri, AArch64::ADDSWri},
  4095. {AArch64::SUBSXrx, AArch64::SUBSWrx}}};
  4096. return emitAddSub(OpcTable, Dst, LHS, RHS, MIRBuilder);
  4097. }
  4098. MachineInstr *
  4099. AArch64InstructionSelector::emitCMN(MachineOperand &LHS, MachineOperand &RHS,
  4100. MachineIRBuilder &MIRBuilder) const {
  4101. MachineRegisterInfo &MRI = MIRBuilder.getMF().getRegInfo();
  4102. bool Is32Bit = (MRI.getType(LHS.getReg()).getSizeInBits() == 32);
  4103. auto RC = Is32Bit ? &AArch64::GPR32RegClass : &AArch64::GPR64RegClass;
  4104. return emitADDS(MRI.createVirtualRegister(RC), LHS, RHS, MIRBuilder);
  4105. }
  4106. MachineInstr *
  4107. AArch64InstructionSelector::emitTST(MachineOperand &LHS, MachineOperand &RHS,
  4108. MachineIRBuilder &MIRBuilder) const {
  4109. assert(LHS.isReg() && RHS.isReg() && "Expected register operands?");
  4110. MachineRegisterInfo &MRI = MIRBuilder.getMF().getRegInfo();
  4111. LLT Ty = MRI.getType(LHS.getReg());
  4112. unsigned RegSize = Ty.getSizeInBits();
  4113. bool Is32Bit = (RegSize == 32);
  4114. const unsigned OpcTable[3][2] = {{AArch64::ANDSXri, AArch64::ANDSWri},
  4115. {AArch64::ANDSXrs, AArch64::ANDSWrs},
  4116. {AArch64::ANDSXrr, AArch64::ANDSWrr}};
  4117. // ANDS needs a logical immediate for its immediate form. Check if we can
  4118. // fold one in.
  4119. if (auto ValAndVReg = getIConstantVRegValWithLookThrough(RHS.getReg(), MRI)) {
  4120. int64_t Imm = ValAndVReg->Value.getSExtValue();
  4121. if (AArch64_AM::isLogicalImmediate(Imm, RegSize)) {
  4122. auto TstMI = MIRBuilder.buildInstr(OpcTable[0][Is32Bit], {Ty}, {LHS});
  4123. TstMI.addImm(AArch64_AM::encodeLogicalImmediate(Imm, RegSize));
  4124. constrainSelectedInstRegOperands(*TstMI, TII, TRI, RBI);
  4125. return &*TstMI;
  4126. }
  4127. }
  4128. if (auto Fns = selectLogicalShiftedRegister(RHS))
  4129. return emitInstr(OpcTable[1][Is32Bit], {Ty}, {LHS}, MIRBuilder, Fns);
  4130. return emitInstr(OpcTable[2][Is32Bit], {Ty}, {LHS, RHS}, MIRBuilder);
  4131. }
  4132. MachineInstr *AArch64InstructionSelector::emitIntegerCompare(
  4133. MachineOperand &LHS, MachineOperand &RHS, MachineOperand &Predicate,
  4134. MachineIRBuilder &MIRBuilder) const {
  4135. assert(LHS.isReg() && RHS.isReg() && "Expected LHS and RHS to be registers!");
  4136. assert(Predicate.isPredicate() && "Expected predicate?");
  4137. MachineRegisterInfo &MRI = MIRBuilder.getMF().getRegInfo();
  4138. LLT CmpTy = MRI.getType(LHS.getReg());
  4139. assert(!CmpTy.isVector() && "Expected scalar or pointer");
  4140. unsigned Size = CmpTy.getSizeInBits();
  4141. (void)Size;
  4142. assert((Size == 32 || Size == 64) && "Expected a 32-bit or 64-bit LHS/RHS?");
  4143. // Fold the compare into a cmn or tst if possible.
  4144. if (auto FoldCmp = tryFoldIntegerCompare(LHS, RHS, Predicate, MIRBuilder))
  4145. return FoldCmp;
  4146. auto Dst = MRI.cloneVirtualRegister(LHS.getReg());
  4147. return emitSUBS(Dst, LHS, RHS, MIRBuilder);
  4148. }
  4149. MachineInstr *AArch64InstructionSelector::emitCSetForFCmp(
  4150. Register Dst, CmpInst::Predicate Pred, MachineIRBuilder &MIRBuilder) const {
  4151. MachineRegisterInfo &MRI = *MIRBuilder.getMRI();
  4152. #ifndef NDEBUG
  4153. LLT Ty = MRI.getType(Dst);
  4154. assert(!Ty.isVector() && Ty.getSizeInBits() == 32 &&
  4155. "Expected a 32-bit scalar register?");
  4156. #endif
  4157. const Register ZReg = AArch64::WZR;
  4158. AArch64CC::CondCode CC1, CC2;
  4159. changeFCMPPredToAArch64CC(Pred, CC1, CC2);
  4160. auto InvCC1 = AArch64CC::getInvertedCondCode(CC1);
  4161. if (CC2 == AArch64CC::AL)
  4162. return emitCSINC(/*Dst=*/Dst, /*Src1=*/ZReg, /*Src2=*/ZReg, InvCC1,
  4163. MIRBuilder);
  4164. const TargetRegisterClass *RC = &AArch64::GPR32RegClass;
  4165. Register Def1Reg = MRI.createVirtualRegister(RC);
  4166. Register Def2Reg = MRI.createVirtualRegister(RC);
  4167. auto InvCC2 = AArch64CC::getInvertedCondCode(CC2);
  4168. emitCSINC(/*Dst=*/Def1Reg, /*Src1=*/ZReg, /*Src2=*/ZReg, InvCC1, MIRBuilder);
  4169. emitCSINC(/*Dst=*/Def2Reg, /*Src1=*/ZReg, /*Src2=*/ZReg, InvCC2, MIRBuilder);
  4170. auto OrMI = MIRBuilder.buildInstr(AArch64::ORRWrr, {Dst}, {Def1Reg, Def2Reg});
  4171. constrainSelectedInstRegOperands(*OrMI, TII, TRI, RBI);
  4172. return &*OrMI;
  4173. }
  4174. MachineInstr *AArch64InstructionSelector::emitFPCompare(
  4175. Register LHS, Register RHS, MachineIRBuilder &MIRBuilder,
  4176. std::optional<CmpInst::Predicate> Pred) const {
  4177. MachineRegisterInfo &MRI = *MIRBuilder.getMRI();
  4178. LLT Ty = MRI.getType(LHS);
  4179. if (Ty.isVector())
  4180. return nullptr;
  4181. unsigned OpSize = Ty.getSizeInBits();
  4182. if (OpSize != 32 && OpSize != 64)
  4183. return nullptr;
  4184. // If this is a compare against +0.0, then we don't have
  4185. // to explicitly materialize a constant.
  4186. const ConstantFP *FPImm = getConstantFPVRegVal(RHS, MRI);
  4187. bool ShouldUseImm = FPImm && (FPImm->isZero() && !FPImm->isNegative());
  4188. auto IsEqualityPred = [](CmpInst::Predicate P) {
  4189. return P == CmpInst::FCMP_OEQ || P == CmpInst::FCMP_ONE ||
  4190. P == CmpInst::FCMP_UEQ || P == CmpInst::FCMP_UNE;
  4191. };
  4192. if (!ShouldUseImm && Pred && IsEqualityPred(*Pred)) {
  4193. // Try commutating the operands.
  4194. const ConstantFP *LHSImm = getConstantFPVRegVal(LHS, MRI);
  4195. if (LHSImm && (LHSImm->isZero() && !LHSImm->isNegative())) {
  4196. ShouldUseImm = true;
  4197. std::swap(LHS, RHS);
  4198. }
  4199. }
  4200. unsigned CmpOpcTbl[2][2] = {{AArch64::FCMPSrr, AArch64::FCMPDrr},
  4201. {AArch64::FCMPSri, AArch64::FCMPDri}};
  4202. unsigned CmpOpc = CmpOpcTbl[ShouldUseImm][OpSize == 64];
  4203. // Partially build the compare. Decide if we need to add a use for the
  4204. // third operand based off whether or not we're comparing against 0.0.
  4205. auto CmpMI = MIRBuilder.buildInstr(CmpOpc).addUse(LHS);
  4206. CmpMI.setMIFlags(MachineInstr::NoFPExcept);
  4207. if (!ShouldUseImm)
  4208. CmpMI.addUse(RHS);
  4209. constrainSelectedInstRegOperands(*CmpMI, TII, TRI, RBI);
  4210. return &*CmpMI;
  4211. }
  4212. MachineInstr *AArch64InstructionSelector::emitVectorConcat(
  4213. std::optional<Register> Dst, Register Op1, Register Op2,
  4214. MachineIRBuilder &MIRBuilder) const {
  4215. // We implement a vector concat by:
  4216. // 1. Use scalar_to_vector to insert the lower vector into the larger dest
  4217. // 2. Insert the upper vector into the destination's upper element
  4218. // TODO: some of this code is common with G_BUILD_VECTOR handling.
  4219. MachineRegisterInfo &MRI = MIRBuilder.getMF().getRegInfo();
  4220. const LLT Op1Ty = MRI.getType(Op1);
  4221. const LLT Op2Ty = MRI.getType(Op2);
  4222. if (Op1Ty != Op2Ty) {
  4223. LLVM_DEBUG(dbgs() << "Could not do vector concat of differing vector tys");
  4224. return nullptr;
  4225. }
  4226. assert(Op1Ty.isVector() && "Expected a vector for vector concat");
  4227. if (Op1Ty.getSizeInBits() >= 128) {
  4228. LLVM_DEBUG(dbgs() << "Vector concat not supported for full size vectors");
  4229. return nullptr;
  4230. }
  4231. // At the moment we just support 64 bit vector concats.
  4232. if (Op1Ty.getSizeInBits() != 64) {
  4233. LLVM_DEBUG(dbgs() << "Vector concat supported for 64b vectors");
  4234. return nullptr;
  4235. }
  4236. const LLT ScalarTy = LLT::scalar(Op1Ty.getSizeInBits());
  4237. const RegisterBank &FPRBank = *RBI.getRegBank(Op1, MRI, TRI);
  4238. const TargetRegisterClass *DstRC =
  4239. getRegClassForTypeOnBank(Op1Ty.multiplyElements(2), FPRBank);
  4240. MachineInstr *WidenedOp1 =
  4241. emitScalarToVector(ScalarTy.getSizeInBits(), DstRC, Op1, MIRBuilder);
  4242. MachineInstr *WidenedOp2 =
  4243. emitScalarToVector(ScalarTy.getSizeInBits(), DstRC, Op2, MIRBuilder);
  4244. if (!WidenedOp1 || !WidenedOp2) {
  4245. LLVM_DEBUG(dbgs() << "Could not emit a vector from scalar value");
  4246. return nullptr;
  4247. }
  4248. // Now do the insert of the upper element.
  4249. unsigned InsertOpc, InsSubRegIdx;
  4250. std::tie(InsertOpc, InsSubRegIdx) =
  4251. getInsertVecEltOpInfo(FPRBank, ScalarTy.getSizeInBits());
  4252. if (!Dst)
  4253. Dst = MRI.createVirtualRegister(DstRC);
  4254. auto InsElt =
  4255. MIRBuilder
  4256. .buildInstr(InsertOpc, {*Dst}, {WidenedOp1->getOperand(0).getReg()})
  4257. .addImm(1) /* Lane index */
  4258. .addUse(WidenedOp2->getOperand(0).getReg())
  4259. .addImm(0);
  4260. constrainSelectedInstRegOperands(*InsElt, TII, TRI, RBI);
  4261. return &*InsElt;
  4262. }
  4263. MachineInstr *
  4264. AArch64InstructionSelector::emitCSINC(Register Dst, Register Src1,
  4265. Register Src2, AArch64CC::CondCode Pred,
  4266. MachineIRBuilder &MIRBuilder) const {
  4267. auto &MRI = *MIRBuilder.getMRI();
  4268. const RegClassOrRegBank &RegClassOrBank = MRI.getRegClassOrRegBank(Dst);
  4269. // If we used a register class, then this won't necessarily have an LLT.
  4270. // Compute the size based off whether or not we have a class or bank.
  4271. unsigned Size;
  4272. if (const auto *RC = RegClassOrBank.dyn_cast<const TargetRegisterClass *>())
  4273. Size = TRI.getRegSizeInBits(*RC);
  4274. else
  4275. Size = MRI.getType(Dst).getSizeInBits();
  4276. // Some opcodes use s1.
  4277. assert(Size <= 64 && "Expected 64 bits or less only!");
  4278. static const unsigned OpcTable[2] = {AArch64::CSINCWr, AArch64::CSINCXr};
  4279. unsigned Opc = OpcTable[Size == 64];
  4280. auto CSINC = MIRBuilder.buildInstr(Opc, {Dst}, {Src1, Src2}).addImm(Pred);
  4281. constrainSelectedInstRegOperands(*CSINC, TII, TRI, RBI);
  4282. return &*CSINC;
  4283. }
  4284. std::pair<MachineInstr *, AArch64CC::CondCode>
  4285. AArch64InstructionSelector::emitOverflowOp(unsigned Opcode, Register Dst,
  4286. MachineOperand &LHS,
  4287. MachineOperand &RHS,
  4288. MachineIRBuilder &MIRBuilder) const {
  4289. switch (Opcode) {
  4290. default:
  4291. llvm_unreachable("Unexpected opcode!");
  4292. case TargetOpcode::G_SADDO:
  4293. return std::make_pair(emitADDS(Dst, LHS, RHS, MIRBuilder), AArch64CC::VS);
  4294. case TargetOpcode::G_UADDO:
  4295. return std::make_pair(emitADDS(Dst, LHS, RHS, MIRBuilder), AArch64CC::HS);
  4296. case TargetOpcode::G_SSUBO:
  4297. return std::make_pair(emitSUBS(Dst, LHS, RHS, MIRBuilder), AArch64CC::VS);
  4298. case TargetOpcode::G_USUBO:
  4299. return std::make_pair(emitSUBS(Dst, LHS, RHS, MIRBuilder), AArch64CC::LO);
  4300. }
  4301. }
  4302. /// Returns true if @p Val is a tree of AND/OR/CMP operations that can be
  4303. /// expressed as a conjunction.
  4304. /// \param CanNegate Set to true if we can negate the whole sub-tree just by
  4305. /// changing the conditions on the CMP tests.
  4306. /// (this means we can call emitConjunctionRec() with
  4307. /// Negate==true on this sub-tree)
  4308. /// \param MustBeFirst Set to true if this subtree needs to be negated and we
  4309. /// cannot do the negation naturally. We are required to
  4310. /// emit the subtree first in this case.
  4311. /// \param WillNegate Is true if are called when the result of this
  4312. /// subexpression must be negated. This happens when the
  4313. /// outer expression is an OR. We can use this fact to know
  4314. /// that we have a double negation (or (or ...) ...) that
  4315. /// can be implemented for free.
  4316. static bool canEmitConjunction(Register Val, bool &CanNegate, bool &MustBeFirst,
  4317. bool WillNegate, MachineRegisterInfo &MRI,
  4318. unsigned Depth = 0) {
  4319. if (!MRI.hasOneNonDBGUse(Val))
  4320. return false;
  4321. MachineInstr *ValDef = MRI.getVRegDef(Val);
  4322. unsigned Opcode = ValDef->getOpcode();
  4323. if (isa<GAnyCmp>(ValDef)) {
  4324. CanNegate = true;
  4325. MustBeFirst = false;
  4326. return true;
  4327. }
  4328. // Protect against exponential runtime and stack overflow.
  4329. if (Depth > 6)
  4330. return false;
  4331. if (Opcode == TargetOpcode::G_AND || Opcode == TargetOpcode::G_OR) {
  4332. bool IsOR = Opcode == TargetOpcode::G_OR;
  4333. Register O0 = ValDef->getOperand(1).getReg();
  4334. Register O1 = ValDef->getOperand(2).getReg();
  4335. bool CanNegateL;
  4336. bool MustBeFirstL;
  4337. if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, MRI, Depth + 1))
  4338. return false;
  4339. bool CanNegateR;
  4340. bool MustBeFirstR;
  4341. if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, MRI, Depth + 1))
  4342. return false;
  4343. if (MustBeFirstL && MustBeFirstR)
  4344. return false;
  4345. if (IsOR) {
  4346. // For an OR expression we need to be able to naturally negate at least
  4347. // one side or we cannot do the transformation at all.
  4348. if (!CanNegateL && !CanNegateR)
  4349. return false;
  4350. // If we the result of the OR will be negated and we can naturally negate
  4351. // the leaves, then this sub-tree as a whole negates naturally.
  4352. CanNegate = WillNegate && CanNegateL && CanNegateR;
  4353. // If we cannot naturally negate the whole sub-tree, then this must be
  4354. // emitted first.
  4355. MustBeFirst = !CanNegate;
  4356. } else {
  4357. assert(Opcode == TargetOpcode::G_AND && "Must be G_AND");
  4358. // We cannot naturally negate an AND operation.
  4359. CanNegate = false;
  4360. MustBeFirst = MustBeFirstL || MustBeFirstR;
  4361. }
  4362. return true;
  4363. }
  4364. return false;
  4365. }
  4366. MachineInstr *AArch64InstructionSelector::emitConditionalComparison(
  4367. Register LHS, Register RHS, CmpInst::Predicate CC,
  4368. AArch64CC::CondCode Predicate, AArch64CC::CondCode OutCC,
  4369. MachineIRBuilder &MIB) const {
  4370. // TODO: emit CMN as an optimization.
  4371. auto &MRI = *MIB.getMRI();
  4372. LLT OpTy = MRI.getType(LHS);
  4373. assert(OpTy.getSizeInBits() == 32 || OpTy.getSizeInBits() == 64);
  4374. unsigned CCmpOpc;
  4375. std::optional<ValueAndVReg> C;
  4376. if (CmpInst::isIntPredicate(CC)) {
  4377. C = getIConstantVRegValWithLookThrough(RHS, MRI);
  4378. if (C && C->Value.ult(32))
  4379. CCmpOpc = OpTy.getSizeInBits() == 32 ? AArch64::CCMPWi : AArch64::CCMPXi;
  4380. else
  4381. CCmpOpc = OpTy.getSizeInBits() == 32 ? AArch64::CCMPWr : AArch64::CCMPXr;
  4382. } else {
  4383. switch (OpTy.getSizeInBits()) {
  4384. case 16:
  4385. CCmpOpc = AArch64::FCCMPHrr;
  4386. break;
  4387. case 32:
  4388. CCmpOpc = AArch64::FCCMPSrr;
  4389. break;
  4390. case 64:
  4391. CCmpOpc = AArch64::FCCMPDrr;
  4392. break;
  4393. default:
  4394. return nullptr;
  4395. }
  4396. }
  4397. AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
  4398. unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
  4399. auto CCmp =
  4400. MIB.buildInstr(CCmpOpc, {}, {LHS});
  4401. if (CCmpOpc == AArch64::CCMPWi || CCmpOpc == AArch64::CCMPXi)
  4402. CCmp.addImm(C->Value.getZExtValue());
  4403. else
  4404. CCmp.addReg(RHS);
  4405. CCmp.addImm(NZCV).addImm(Predicate);
  4406. constrainSelectedInstRegOperands(*CCmp, TII, TRI, RBI);
  4407. return &*CCmp;
  4408. }
  4409. MachineInstr *AArch64InstructionSelector::emitConjunctionRec(
  4410. Register Val, AArch64CC::CondCode &OutCC, bool Negate, Register CCOp,
  4411. AArch64CC::CondCode Predicate, MachineIRBuilder &MIB) const {
  4412. // We're at a tree leaf, produce a conditional comparison operation.
  4413. auto &MRI = *MIB.getMRI();
  4414. MachineInstr *ValDef = MRI.getVRegDef(Val);
  4415. unsigned Opcode = ValDef->getOpcode();
  4416. if (auto *Cmp = dyn_cast<GAnyCmp>(ValDef)) {
  4417. Register LHS = Cmp->getLHSReg();
  4418. Register RHS = Cmp->getRHSReg();
  4419. CmpInst::Predicate CC = Cmp->getCond();
  4420. if (Negate)
  4421. CC = CmpInst::getInversePredicate(CC);
  4422. if (isa<GICmp>(Cmp)) {
  4423. OutCC = changeICMPPredToAArch64CC(CC);
  4424. } else {
  4425. // Handle special FP cases.
  4426. AArch64CC::CondCode ExtraCC;
  4427. changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
  4428. // Some floating point conditions can't be tested with a single condition
  4429. // code. Construct an additional comparison in this case.
  4430. if (ExtraCC != AArch64CC::AL) {
  4431. MachineInstr *ExtraCmp;
  4432. if (!CCOp)
  4433. ExtraCmp = emitFPCompare(LHS, RHS, MIB, CC);
  4434. else
  4435. ExtraCmp =
  4436. emitConditionalComparison(LHS, RHS, CC, Predicate, ExtraCC, MIB);
  4437. CCOp = ExtraCmp->getOperand(0).getReg();
  4438. Predicate = ExtraCC;
  4439. }
  4440. }
  4441. // Produce a normal comparison if we are first in the chain
  4442. if (!CCOp) {
  4443. auto Dst = MRI.cloneVirtualRegister(LHS);
  4444. if (isa<GICmp>(Cmp))
  4445. return emitSUBS(Dst, Cmp->getOperand(2), Cmp->getOperand(3), MIB);
  4446. return emitFPCompare(Cmp->getOperand(2).getReg(),
  4447. Cmp->getOperand(3).getReg(), MIB);
  4448. }
  4449. // Otherwise produce a ccmp.
  4450. return emitConditionalComparison(LHS, RHS, CC, Predicate, OutCC, MIB);
  4451. }
  4452. assert(MRI.hasOneNonDBGUse(Val) && "Valid conjunction/disjunction tree");
  4453. bool IsOR = Opcode == TargetOpcode::G_OR;
  4454. Register LHS = ValDef->getOperand(1).getReg();
  4455. bool CanNegateL;
  4456. bool MustBeFirstL;
  4457. bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR, MRI);
  4458. assert(ValidL && "Valid conjunction/disjunction tree");
  4459. (void)ValidL;
  4460. Register RHS = ValDef->getOperand(2).getReg();
  4461. bool CanNegateR;
  4462. bool MustBeFirstR;
  4463. bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR, MRI);
  4464. assert(ValidR && "Valid conjunction/disjunction tree");
  4465. (void)ValidR;
  4466. // Swap sub-tree that must come first to the right side.
  4467. if (MustBeFirstL) {
  4468. assert(!MustBeFirstR && "Valid conjunction/disjunction tree");
  4469. std::swap(LHS, RHS);
  4470. std::swap(CanNegateL, CanNegateR);
  4471. std::swap(MustBeFirstL, MustBeFirstR);
  4472. }
  4473. bool NegateR;
  4474. bool NegateAfterR;
  4475. bool NegateL;
  4476. bool NegateAfterAll;
  4477. if (Opcode == TargetOpcode::G_OR) {
  4478. // Swap the sub-tree that we can negate naturally to the left.
  4479. if (!CanNegateL) {
  4480. assert(CanNegateR && "at least one side must be negatable");
  4481. assert(!MustBeFirstR && "invalid conjunction/disjunction tree");
  4482. assert(!Negate);
  4483. std::swap(LHS, RHS);
  4484. NegateR = false;
  4485. NegateAfterR = true;
  4486. } else {
  4487. // Negate the left sub-tree if possible, otherwise negate the result.
  4488. NegateR = CanNegateR;
  4489. NegateAfterR = !CanNegateR;
  4490. }
  4491. NegateL = true;
  4492. NegateAfterAll = !Negate;
  4493. } else {
  4494. assert(Opcode == TargetOpcode::G_AND &&
  4495. "Valid conjunction/disjunction tree");
  4496. assert(!Negate && "Valid conjunction/disjunction tree");
  4497. NegateL = false;
  4498. NegateR = false;
  4499. NegateAfterR = false;
  4500. NegateAfterAll = false;
  4501. }
  4502. // Emit sub-trees.
  4503. AArch64CC::CondCode RHSCC;
  4504. MachineInstr *CmpR =
  4505. emitConjunctionRec(RHS, RHSCC, NegateR, CCOp, Predicate, MIB);
  4506. if (NegateAfterR)
  4507. RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
  4508. MachineInstr *CmpL = emitConjunctionRec(
  4509. LHS, OutCC, NegateL, CmpR->getOperand(0).getReg(), RHSCC, MIB);
  4510. if (NegateAfterAll)
  4511. OutCC = AArch64CC::getInvertedCondCode(OutCC);
  4512. return CmpL;
  4513. }
  4514. MachineInstr *AArch64InstructionSelector::emitConjunction(
  4515. Register Val, AArch64CC::CondCode &OutCC, MachineIRBuilder &MIB) const {
  4516. bool DummyCanNegate;
  4517. bool DummyMustBeFirst;
  4518. if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false,
  4519. *MIB.getMRI()))
  4520. return nullptr;
  4521. return emitConjunctionRec(Val, OutCC, false, Register(), AArch64CC::AL, MIB);
  4522. }
  4523. bool AArch64InstructionSelector::tryOptSelectConjunction(GSelect &SelI,
  4524. MachineInstr &CondMI) {
  4525. AArch64CC::CondCode AArch64CC;
  4526. MachineInstr *ConjMI = emitConjunction(SelI.getCondReg(), AArch64CC, MIB);
  4527. if (!ConjMI)
  4528. return false;
  4529. emitSelect(SelI.getReg(0), SelI.getTrueReg(), SelI.getFalseReg(), AArch64CC, MIB);
  4530. SelI.eraseFromParent();
  4531. return true;
  4532. }
  4533. bool AArch64InstructionSelector::tryOptSelect(GSelect &I) {
  4534. MachineRegisterInfo &MRI = *MIB.getMRI();
  4535. // We want to recognize this pattern:
  4536. //
  4537. // $z = G_FCMP pred, $x, $y
  4538. // ...
  4539. // $w = G_SELECT $z, $a, $b
  4540. //
  4541. // Where the value of $z is *only* ever used by the G_SELECT (possibly with
  4542. // some copies/truncs in between.)
  4543. //
  4544. // If we see this, then we can emit something like this:
  4545. //
  4546. // fcmp $x, $y
  4547. // fcsel $w, $a, $b, pred
  4548. //
  4549. // Rather than emitting both of the rather long sequences in the standard
  4550. // G_FCMP/G_SELECT select methods.
  4551. // First, check if the condition is defined by a compare.
  4552. MachineInstr *CondDef = MRI.getVRegDef(I.getOperand(1).getReg());
  4553. // We can only fold if all of the defs have one use.
  4554. Register CondDefReg = CondDef->getOperand(0).getReg();
  4555. if (!MRI.hasOneNonDBGUse(CondDefReg)) {
  4556. // Unless it's another select.
  4557. for (const MachineInstr &UI : MRI.use_nodbg_instructions(CondDefReg)) {
  4558. if (CondDef == &UI)
  4559. continue;
  4560. if (UI.getOpcode() != TargetOpcode::G_SELECT)
  4561. return false;
  4562. }
  4563. }
  4564. // Is the condition defined by a compare?
  4565. unsigned CondOpc = CondDef->getOpcode();
  4566. if (CondOpc != TargetOpcode::G_ICMP && CondOpc != TargetOpcode::G_FCMP) {
  4567. if (tryOptSelectConjunction(I, *CondDef))
  4568. return true;
  4569. return false;
  4570. }
  4571. AArch64CC::CondCode CondCode;
  4572. if (CondOpc == TargetOpcode::G_ICMP) {
  4573. auto Pred =
  4574. static_cast<CmpInst::Predicate>(CondDef->getOperand(1).getPredicate());
  4575. CondCode = changeICMPPredToAArch64CC(Pred);
  4576. emitIntegerCompare(CondDef->getOperand(2), CondDef->getOperand(3),
  4577. CondDef->getOperand(1), MIB);
  4578. } else {
  4579. // Get the condition code for the select.
  4580. auto Pred =
  4581. static_cast<CmpInst::Predicate>(CondDef->getOperand(1).getPredicate());
  4582. AArch64CC::CondCode CondCode2;
  4583. changeFCMPPredToAArch64CC(Pred, CondCode, CondCode2);
  4584. // changeFCMPPredToAArch64CC sets CondCode2 to AL when we require two
  4585. // instructions to emit the comparison.
  4586. // TODO: Handle FCMP_UEQ and FCMP_ONE. After that, this check will be
  4587. // unnecessary.
  4588. if (CondCode2 != AArch64CC::AL)
  4589. return false;
  4590. if (!emitFPCompare(CondDef->getOperand(2).getReg(),
  4591. CondDef->getOperand(3).getReg(), MIB)) {
  4592. LLVM_DEBUG(dbgs() << "Couldn't emit compare for select!\n");
  4593. return false;
  4594. }
  4595. }
  4596. // Emit the select.
  4597. emitSelect(I.getOperand(0).getReg(), I.getOperand(2).getReg(),
  4598. I.getOperand(3).getReg(), CondCode, MIB);
  4599. I.eraseFromParent();
  4600. return true;
  4601. }
  4602. MachineInstr *AArch64InstructionSelector::tryFoldIntegerCompare(
  4603. MachineOperand &LHS, MachineOperand &RHS, MachineOperand &Predicate,
  4604. MachineIRBuilder &MIRBuilder) const {
  4605. assert(LHS.isReg() && RHS.isReg() && Predicate.isPredicate() &&
  4606. "Unexpected MachineOperand");
  4607. MachineRegisterInfo &MRI = *MIRBuilder.getMRI();
  4608. // We want to find this sort of thing:
  4609. // x = G_SUB 0, y
  4610. // G_ICMP z, x
  4611. //
  4612. // In this case, we can fold the G_SUB into the G_ICMP using a CMN instead.
  4613. // e.g:
  4614. //
  4615. // cmn z, y
  4616. // Check if the RHS or LHS of the G_ICMP is defined by a SUB
  4617. MachineInstr *LHSDef = getDefIgnoringCopies(LHS.getReg(), MRI);
  4618. MachineInstr *RHSDef = getDefIgnoringCopies(RHS.getReg(), MRI);
  4619. auto P = static_cast<CmpInst::Predicate>(Predicate.getPredicate());
  4620. // Given this:
  4621. //
  4622. // x = G_SUB 0, y
  4623. // G_ICMP x, z
  4624. //
  4625. // Produce this:
  4626. //
  4627. // cmn y, z
  4628. if (isCMN(LHSDef, P, MRI))
  4629. return emitCMN(LHSDef->getOperand(2), RHS, MIRBuilder);
  4630. // Same idea here, but with the RHS of the compare instead:
  4631. //
  4632. // Given this:
  4633. //
  4634. // x = G_SUB 0, y
  4635. // G_ICMP z, x
  4636. //
  4637. // Produce this:
  4638. //
  4639. // cmn z, y
  4640. if (isCMN(RHSDef, P, MRI))
  4641. return emitCMN(LHS, RHSDef->getOperand(2), MIRBuilder);
  4642. // Given this:
  4643. //
  4644. // z = G_AND x, y
  4645. // G_ICMP z, 0
  4646. //
  4647. // Produce this if the compare is signed:
  4648. //
  4649. // tst x, y
  4650. if (!CmpInst::isUnsigned(P) && LHSDef &&
  4651. LHSDef->getOpcode() == TargetOpcode::G_AND) {
  4652. // Make sure that the RHS is 0.
  4653. auto ValAndVReg = getIConstantVRegValWithLookThrough(RHS.getReg(), MRI);
  4654. if (!ValAndVReg || ValAndVReg->Value != 0)
  4655. return nullptr;
  4656. return emitTST(LHSDef->getOperand(1),
  4657. LHSDef->getOperand(2), MIRBuilder);
  4658. }
  4659. return nullptr;
  4660. }
  4661. bool AArch64InstructionSelector::selectShuffleVector(
  4662. MachineInstr &I, MachineRegisterInfo &MRI) {
  4663. const LLT DstTy = MRI.getType(I.getOperand(0).getReg());
  4664. Register Src1Reg = I.getOperand(1).getReg();
  4665. const LLT Src1Ty = MRI.getType(Src1Reg);
  4666. Register Src2Reg = I.getOperand(2).getReg();
  4667. const LLT Src2Ty = MRI.getType(Src2Reg);
  4668. ArrayRef<int> Mask = I.getOperand(3).getShuffleMask();
  4669. MachineBasicBlock &MBB = *I.getParent();
  4670. MachineFunction &MF = *MBB.getParent();
  4671. LLVMContext &Ctx = MF.getFunction().getContext();
  4672. // G_SHUFFLE_VECTOR is weird in that the source operands can be scalars, if
  4673. // it's originated from a <1 x T> type. Those should have been lowered into
  4674. // G_BUILD_VECTOR earlier.
  4675. if (!Src1Ty.isVector() || !Src2Ty.isVector()) {
  4676. LLVM_DEBUG(dbgs() << "Could not select a \"scalar\" G_SHUFFLE_VECTOR\n");
  4677. return false;
  4678. }
  4679. unsigned BytesPerElt = DstTy.getElementType().getSizeInBits() / 8;
  4680. SmallVector<Constant *, 64> CstIdxs;
  4681. for (int Val : Mask) {
  4682. // For now, any undef indexes we'll just assume to be 0. This should be
  4683. // optimized in future, e.g. to select DUP etc.
  4684. Val = Val < 0 ? 0 : Val;
  4685. for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
  4686. unsigned Offset = Byte + Val * BytesPerElt;
  4687. CstIdxs.emplace_back(ConstantInt::get(Type::getInt8Ty(Ctx), Offset));
  4688. }
  4689. }
  4690. // Use a constant pool to load the index vector for TBL.
  4691. Constant *CPVal = ConstantVector::get(CstIdxs);
  4692. MachineInstr *IndexLoad = emitLoadFromConstantPool(CPVal, MIB);
  4693. if (!IndexLoad) {
  4694. LLVM_DEBUG(dbgs() << "Could not load from a constant pool");
  4695. return false;
  4696. }
  4697. if (DstTy.getSizeInBits() != 128) {
  4698. assert(DstTy.getSizeInBits() == 64 && "Unexpected shuffle result ty");
  4699. // This case can be done with TBL1.
  4700. MachineInstr *Concat =
  4701. emitVectorConcat(std::nullopt, Src1Reg, Src2Reg, MIB);
  4702. if (!Concat) {
  4703. LLVM_DEBUG(dbgs() << "Could not do vector concat for tbl1");
  4704. return false;
  4705. }
  4706. // The constant pool load will be 64 bits, so need to convert to FPR128 reg.
  4707. IndexLoad = emitScalarToVector(64, &AArch64::FPR128RegClass,
  4708. IndexLoad->getOperand(0).getReg(), MIB);
  4709. auto TBL1 = MIB.buildInstr(
  4710. AArch64::TBLv16i8One, {&AArch64::FPR128RegClass},
  4711. {Concat->getOperand(0).getReg(), IndexLoad->getOperand(0).getReg()});
  4712. constrainSelectedInstRegOperands(*TBL1, TII, TRI, RBI);
  4713. auto Copy =
  4714. MIB.buildInstr(TargetOpcode::COPY, {I.getOperand(0).getReg()}, {})
  4715. .addReg(TBL1.getReg(0), 0, AArch64::dsub);
  4716. RBI.constrainGenericRegister(Copy.getReg(0), AArch64::FPR64RegClass, MRI);
  4717. I.eraseFromParent();
  4718. return true;
  4719. }
  4720. // For TBL2 we need to emit a REG_SEQUENCE to tie together two consecutive
  4721. // Q registers for regalloc.
  4722. SmallVector<Register, 2> Regs = {Src1Reg, Src2Reg};
  4723. auto RegSeq = createQTuple(Regs, MIB);
  4724. auto TBL2 = MIB.buildInstr(AArch64::TBLv16i8Two, {I.getOperand(0)},
  4725. {RegSeq, IndexLoad->getOperand(0)});
  4726. constrainSelectedInstRegOperands(*TBL2, TII, TRI, RBI);
  4727. I.eraseFromParent();
  4728. return true;
  4729. }
  4730. MachineInstr *AArch64InstructionSelector::emitLaneInsert(
  4731. std::optional<Register> DstReg, Register SrcReg, Register EltReg,
  4732. unsigned LaneIdx, const RegisterBank &RB,
  4733. MachineIRBuilder &MIRBuilder) const {
  4734. MachineInstr *InsElt = nullptr;
  4735. const TargetRegisterClass *DstRC = &AArch64::FPR128RegClass;
  4736. MachineRegisterInfo &MRI = *MIRBuilder.getMRI();
  4737. // Create a register to define with the insert if one wasn't passed in.
  4738. if (!DstReg)
  4739. DstReg = MRI.createVirtualRegister(DstRC);
  4740. unsigned EltSize = MRI.getType(EltReg).getSizeInBits();
  4741. unsigned Opc = getInsertVecEltOpInfo(RB, EltSize).first;
  4742. if (RB.getID() == AArch64::FPRRegBankID) {
  4743. auto InsSub = emitScalarToVector(EltSize, DstRC, EltReg, MIRBuilder);
  4744. InsElt = MIRBuilder.buildInstr(Opc, {*DstReg}, {SrcReg})
  4745. .addImm(LaneIdx)
  4746. .addUse(InsSub->getOperand(0).getReg())
  4747. .addImm(0);
  4748. } else {
  4749. InsElt = MIRBuilder.buildInstr(Opc, {*DstReg}, {SrcReg})
  4750. .addImm(LaneIdx)
  4751. .addUse(EltReg);
  4752. }
  4753. constrainSelectedInstRegOperands(*InsElt, TII, TRI, RBI);
  4754. return InsElt;
  4755. }
  4756. bool AArch64InstructionSelector::selectUSMovFromExtend(
  4757. MachineInstr &MI, MachineRegisterInfo &MRI) {
  4758. if (MI.getOpcode() != TargetOpcode::G_SEXT &&
  4759. MI.getOpcode() != TargetOpcode::G_ZEXT &&
  4760. MI.getOpcode() != TargetOpcode::G_ANYEXT)
  4761. return false;
  4762. bool IsSigned = MI.getOpcode() == TargetOpcode::G_SEXT;
  4763. const Register DefReg = MI.getOperand(0).getReg();
  4764. const LLT DstTy = MRI.getType(DefReg);
  4765. unsigned DstSize = DstTy.getSizeInBits();
  4766. if (DstSize != 32 && DstSize != 64)
  4767. return false;
  4768. MachineInstr *Extract = getOpcodeDef(TargetOpcode::G_EXTRACT_VECTOR_ELT,
  4769. MI.getOperand(1).getReg(), MRI);
  4770. int64_t Lane;
  4771. if (!Extract || !mi_match(Extract->getOperand(2).getReg(), MRI, m_ICst(Lane)))
  4772. return false;
  4773. Register Src0 = Extract->getOperand(1).getReg();
  4774. const LLT &VecTy = MRI.getType(Src0);
  4775. if (VecTy.getSizeInBits() != 128) {
  4776. const MachineInstr *ScalarToVector = emitScalarToVector(
  4777. VecTy.getSizeInBits(), &AArch64::FPR128RegClass, Src0, MIB);
  4778. assert(ScalarToVector && "Didn't expect emitScalarToVector to fail!");
  4779. Src0 = ScalarToVector->getOperand(0).getReg();
  4780. }
  4781. unsigned Opcode;
  4782. if (DstSize == 64 && VecTy.getScalarSizeInBits() == 32)
  4783. Opcode = IsSigned ? AArch64::SMOVvi32to64 : AArch64::UMOVvi32;
  4784. else if (DstSize == 64 && VecTy.getScalarSizeInBits() == 16)
  4785. Opcode = IsSigned ? AArch64::SMOVvi16to64 : AArch64::UMOVvi16;
  4786. else if (DstSize == 64 && VecTy.getScalarSizeInBits() == 8)
  4787. Opcode = IsSigned ? AArch64::SMOVvi8to64 : AArch64::UMOVvi8;
  4788. else if (DstSize == 32 && VecTy.getScalarSizeInBits() == 16)
  4789. Opcode = IsSigned ? AArch64::SMOVvi16to32 : AArch64::UMOVvi16;
  4790. else if (DstSize == 32 && VecTy.getScalarSizeInBits() == 8)
  4791. Opcode = IsSigned ? AArch64::SMOVvi8to32 : AArch64::UMOVvi8;
  4792. else
  4793. llvm_unreachable("Unexpected type combo for S/UMov!");
  4794. // We may need to generate one of these, depending on the type and sign of the
  4795. // input:
  4796. // DstReg = SMOV Src0, Lane;
  4797. // NewReg = UMOV Src0, Lane; DstReg = SUBREG_TO_REG NewReg, sub_32;
  4798. MachineInstr *ExtI = nullptr;
  4799. if (DstSize == 64 && !IsSigned) {
  4800. Register NewReg = MRI.createVirtualRegister(&AArch64::GPR32RegClass);
  4801. MIB.buildInstr(Opcode, {NewReg}, {Src0}).addImm(Lane);
  4802. ExtI = MIB.buildInstr(AArch64::SUBREG_TO_REG, {DefReg}, {})
  4803. .addImm(0)
  4804. .addUse(NewReg)
  4805. .addImm(AArch64::sub_32);
  4806. RBI.constrainGenericRegister(DefReg, AArch64::GPR64RegClass, MRI);
  4807. } else
  4808. ExtI = MIB.buildInstr(Opcode, {DefReg}, {Src0}).addImm(Lane);
  4809. constrainSelectedInstRegOperands(*ExtI, TII, TRI, RBI);
  4810. MI.eraseFromParent();
  4811. return true;
  4812. }
  4813. bool AArch64InstructionSelector::selectInsertElt(MachineInstr &I,
  4814. MachineRegisterInfo &MRI) {
  4815. assert(I.getOpcode() == TargetOpcode::G_INSERT_VECTOR_ELT);
  4816. // Get information on the destination.
  4817. Register DstReg = I.getOperand(0).getReg();
  4818. const LLT DstTy = MRI.getType(DstReg);
  4819. unsigned VecSize = DstTy.getSizeInBits();
  4820. // Get information on the element we want to insert into the destination.
  4821. Register EltReg = I.getOperand(2).getReg();
  4822. const LLT EltTy = MRI.getType(EltReg);
  4823. unsigned EltSize = EltTy.getSizeInBits();
  4824. if (EltSize < 16 || EltSize > 64)
  4825. return false; // Don't support all element types yet.
  4826. // Find the definition of the index. Bail out if it's not defined by a
  4827. // G_CONSTANT.
  4828. Register IdxReg = I.getOperand(3).getReg();
  4829. auto VRegAndVal = getIConstantVRegValWithLookThrough(IdxReg, MRI);
  4830. if (!VRegAndVal)
  4831. return false;
  4832. unsigned LaneIdx = VRegAndVal->Value.getSExtValue();
  4833. // Perform the lane insert.
  4834. Register SrcReg = I.getOperand(1).getReg();
  4835. const RegisterBank &EltRB = *RBI.getRegBank(EltReg, MRI, TRI);
  4836. if (VecSize < 128) {
  4837. // If the vector we're inserting into is smaller than 128 bits, widen it
  4838. // to 128 to do the insert.
  4839. MachineInstr *ScalarToVec =
  4840. emitScalarToVector(VecSize, &AArch64::FPR128RegClass, SrcReg, MIB);
  4841. if (!ScalarToVec)
  4842. return false;
  4843. SrcReg = ScalarToVec->getOperand(0).getReg();
  4844. }
  4845. // Create an insert into a new FPR128 register.
  4846. // Note that if our vector is already 128 bits, we end up emitting an extra
  4847. // register.
  4848. MachineInstr *InsMI =
  4849. emitLaneInsert(std::nullopt, SrcReg, EltReg, LaneIdx, EltRB, MIB);
  4850. if (VecSize < 128) {
  4851. // If we had to widen to perform the insert, then we have to demote back to
  4852. // the original size to get the result we want.
  4853. Register DemoteVec = InsMI->getOperand(0).getReg();
  4854. const TargetRegisterClass *RC =
  4855. getRegClassForTypeOnBank(DstTy, *RBI.getRegBank(DemoteVec, MRI, TRI));
  4856. if (RC != &AArch64::FPR32RegClass && RC != &AArch64::FPR64RegClass) {
  4857. LLVM_DEBUG(dbgs() << "Unsupported register class!\n");
  4858. return false;
  4859. }
  4860. unsigned SubReg = 0;
  4861. if (!getSubRegForClass(RC, TRI, SubReg))
  4862. return false;
  4863. if (SubReg != AArch64::ssub && SubReg != AArch64::dsub) {
  4864. LLVM_DEBUG(dbgs() << "Unsupported destination size! (" << VecSize
  4865. << "\n");
  4866. return false;
  4867. }
  4868. MIB.buildInstr(TargetOpcode::COPY, {DstReg}, {})
  4869. .addReg(DemoteVec, 0, SubReg);
  4870. RBI.constrainGenericRegister(DstReg, *RC, MRI);
  4871. } else {
  4872. // No widening needed.
  4873. InsMI->getOperand(0).setReg(DstReg);
  4874. constrainSelectedInstRegOperands(*InsMI, TII, TRI, RBI);
  4875. }
  4876. I.eraseFromParent();
  4877. return true;
  4878. }
  4879. MachineInstr *
  4880. AArch64InstructionSelector::emitConstantVector(Register Dst, Constant *CV,
  4881. MachineIRBuilder &MIRBuilder,
  4882. MachineRegisterInfo &MRI) {
  4883. LLT DstTy = MRI.getType(Dst);
  4884. unsigned DstSize = DstTy.getSizeInBits();
  4885. if (CV->isNullValue()) {
  4886. if (DstSize == 128) {
  4887. auto Mov =
  4888. MIRBuilder.buildInstr(AArch64::MOVIv2d_ns, {Dst}, {}).addImm(0);
  4889. constrainSelectedInstRegOperands(*Mov, TII, TRI, RBI);
  4890. return &*Mov;
  4891. }
  4892. if (DstSize == 64) {
  4893. auto Mov =
  4894. MIRBuilder
  4895. .buildInstr(AArch64::MOVIv2d_ns, {&AArch64::FPR128RegClass}, {})
  4896. .addImm(0);
  4897. auto Copy = MIRBuilder.buildInstr(TargetOpcode::COPY, {Dst}, {})
  4898. .addReg(Mov.getReg(0), 0, AArch64::dsub);
  4899. RBI.constrainGenericRegister(Dst, AArch64::FPR64RegClass, MRI);
  4900. return &*Copy;
  4901. }
  4902. }
  4903. auto *CPLoad = emitLoadFromConstantPool(CV, MIRBuilder);
  4904. if (!CPLoad) {
  4905. LLVM_DEBUG(dbgs() << "Could not generate cp load for constant vector!");
  4906. return nullptr;
  4907. }
  4908. auto Copy = MIRBuilder.buildCopy(Dst, CPLoad->getOperand(0));
  4909. RBI.constrainGenericRegister(
  4910. Dst, *MRI.getRegClass(CPLoad->getOperand(0).getReg()), MRI);
  4911. return &*Copy;
  4912. }
  4913. bool AArch64InstructionSelector::tryOptConstantBuildVec(
  4914. MachineInstr &I, LLT DstTy, MachineRegisterInfo &MRI) {
  4915. assert(I.getOpcode() == TargetOpcode::G_BUILD_VECTOR);
  4916. unsigned DstSize = DstTy.getSizeInBits();
  4917. assert(DstSize <= 128 && "Unexpected build_vec type!");
  4918. if (DstSize < 32)
  4919. return false;
  4920. // Check if we're building a constant vector, in which case we want to
  4921. // generate a constant pool load instead of a vector insert sequence.
  4922. SmallVector<Constant *, 16> Csts;
  4923. for (unsigned Idx = 1; Idx < I.getNumOperands(); ++Idx) {
  4924. // Try to find G_CONSTANT or G_FCONSTANT
  4925. auto *OpMI =
  4926. getOpcodeDef(TargetOpcode::G_CONSTANT, I.getOperand(Idx).getReg(), MRI);
  4927. if (OpMI)
  4928. Csts.emplace_back(
  4929. const_cast<ConstantInt *>(OpMI->getOperand(1).getCImm()));
  4930. else if ((OpMI = getOpcodeDef(TargetOpcode::G_FCONSTANT,
  4931. I.getOperand(Idx).getReg(), MRI)))
  4932. Csts.emplace_back(
  4933. const_cast<ConstantFP *>(OpMI->getOperand(1).getFPImm()));
  4934. else
  4935. return false;
  4936. }
  4937. Constant *CV = ConstantVector::get(Csts);
  4938. if (!emitConstantVector(I.getOperand(0).getReg(), CV, MIB, MRI))
  4939. return false;
  4940. I.eraseFromParent();
  4941. return true;
  4942. }
  4943. bool AArch64InstructionSelector::tryOptBuildVecToSubregToReg(
  4944. MachineInstr &I, MachineRegisterInfo &MRI) {
  4945. // Given:
  4946. // %vec = G_BUILD_VECTOR %elt, %undef, %undef, ... %undef
  4947. //
  4948. // Select the G_BUILD_VECTOR as a SUBREG_TO_REG from %elt.
  4949. Register Dst = I.getOperand(0).getReg();
  4950. Register EltReg = I.getOperand(1).getReg();
  4951. LLT EltTy = MRI.getType(EltReg);
  4952. // If the index isn't on the same bank as its elements, then this can't be a
  4953. // SUBREG_TO_REG.
  4954. const RegisterBank &EltRB = *RBI.getRegBank(EltReg, MRI, TRI);
  4955. const RegisterBank &DstRB = *RBI.getRegBank(Dst, MRI, TRI);
  4956. if (EltRB != DstRB)
  4957. return false;
  4958. if (any_of(make_range(I.operands_begin() + 2, I.operands_end()),
  4959. [&MRI](const MachineOperand &Op) {
  4960. return !getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, Op.getReg(),
  4961. MRI);
  4962. }))
  4963. return false;
  4964. unsigned SubReg;
  4965. const TargetRegisterClass *EltRC = getRegClassForTypeOnBank(EltTy, EltRB);
  4966. if (!EltRC)
  4967. return false;
  4968. const TargetRegisterClass *DstRC =
  4969. getRegClassForTypeOnBank(MRI.getType(Dst), DstRB);
  4970. if (!DstRC)
  4971. return false;
  4972. if (!getSubRegForClass(EltRC, TRI, SubReg))
  4973. return false;
  4974. auto SubregToReg = MIB.buildInstr(AArch64::SUBREG_TO_REG, {Dst}, {})
  4975. .addImm(0)
  4976. .addUse(EltReg)
  4977. .addImm(SubReg);
  4978. I.eraseFromParent();
  4979. constrainSelectedInstRegOperands(*SubregToReg, TII, TRI, RBI);
  4980. return RBI.constrainGenericRegister(Dst, *DstRC, MRI);
  4981. }
  4982. bool AArch64InstructionSelector::selectBuildVector(MachineInstr &I,
  4983. MachineRegisterInfo &MRI) {
  4984. assert(I.getOpcode() == TargetOpcode::G_BUILD_VECTOR);
  4985. // Until we port more of the optimized selections, for now just use a vector
  4986. // insert sequence.
  4987. const LLT DstTy = MRI.getType(I.getOperand(0).getReg());
  4988. const LLT EltTy = MRI.getType(I.getOperand(1).getReg());
  4989. unsigned EltSize = EltTy.getSizeInBits();
  4990. if (tryOptConstantBuildVec(I, DstTy, MRI))
  4991. return true;
  4992. if (tryOptBuildVecToSubregToReg(I, MRI))
  4993. return true;
  4994. if (EltSize < 16 || EltSize > 64)
  4995. return false; // Don't support all element types yet.
  4996. const RegisterBank &RB = *RBI.getRegBank(I.getOperand(1).getReg(), MRI, TRI);
  4997. const TargetRegisterClass *DstRC = &AArch64::FPR128RegClass;
  4998. MachineInstr *ScalarToVec =
  4999. emitScalarToVector(DstTy.getElementType().getSizeInBits(), DstRC,
  5000. I.getOperand(1).getReg(), MIB);
  5001. if (!ScalarToVec)
  5002. return false;
  5003. Register DstVec = ScalarToVec->getOperand(0).getReg();
  5004. unsigned DstSize = DstTy.getSizeInBits();
  5005. // Keep track of the last MI we inserted. Later on, we might be able to save
  5006. // a copy using it.
  5007. MachineInstr *PrevMI = nullptr;
  5008. for (unsigned i = 2, e = DstSize / EltSize + 1; i < e; ++i) {
  5009. // Note that if we don't do a subregister copy, we can end up making an
  5010. // extra register.
  5011. PrevMI = &*emitLaneInsert(std::nullopt, DstVec, I.getOperand(i).getReg(),
  5012. i - 1, RB, MIB);
  5013. DstVec = PrevMI->getOperand(0).getReg();
  5014. }
  5015. // If DstTy's size in bits is less than 128, then emit a subregister copy
  5016. // from DstVec to the last register we've defined.
  5017. if (DstSize < 128) {
  5018. // Force this to be FPR using the destination vector.
  5019. const TargetRegisterClass *RC =
  5020. getRegClassForTypeOnBank(DstTy, *RBI.getRegBank(DstVec, MRI, TRI));
  5021. if (!RC)
  5022. return false;
  5023. if (RC != &AArch64::FPR32RegClass && RC != &AArch64::FPR64RegClass) {
  5024. LLVM_DEBUG(dbgs() << "Unsupported register class!\n");
  5025. return false;
  5026. }
  5027. unsigned SubReg = 0;
  5028. if (!getSubRegForClass(RC, TRI, SubReg))
  5029. return false;
  5030. if (SubReg != AArch64::ssub && SubReg != AArch64::dsub) {
  5031. LLVM_DEBUG(dbgs() << "Unsupported destination size! (" << DstSize
  5032. << "\n");
  5033. return false;
  5034. }
  5035. Register Reg = MRI.createVirtualRegister(RC);
  5036. Register DstReg = I.getOperand(0).getReg();
  5037. MIB.buildInstr(TargetOpcode::COPY, {DstReg}, {}).addReg(DstVec, 0, SubReg);
  5038. MachineOperand &RegOp = I.getOperand(1);
  5039. RegOp.setReg(Reg);
  5040. RBI.constrainGenericRegister(DstReg, *RC, MRI);
  5041. } else {
  5042. // We don't need a subregister copy. Save a copy by re-using the
  5043. // destination register on the final insert.
  5044. assert(PrevMI && "PrevMI was null?");
  5045. PrevMI->getOperand(0).setReg(I.getOperand(0).getReg());
  5046. constrainSelectedInstRegOperands(*PrevMI, TII, TRI, RBI);
  5047. }
  5048. I.eraseFromParent();
  5049. return true;
  5050. }
  5051. bool AArch64InstructionSelector::selectVectorLoadIntrinsic(unsigned Opc,
  5052. unsigned NumVecs,
  5053. MachineInstr &I) {
  5054. assert(I.getOpcode() == TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS);
  5055. assert(Opc && "Expected an opcode?");
  5056. assert(NumVecs > 1 && NumVecs < 5 && "Only support 2, 3, or 4 vectors");
  5057. auto &MRI = *MIB.getMRI();
  5058. LLT Ty = MRI.getType(I.getOperand(0).getReg());
  5059. unsigned Size = Ty.getSizeInBits();
  5060. assert((Size == 64 || Size == 128) &&
  5061. "Destination must be 64 bits or 128 bits?");
  5062. unsigned SubReg = Size == 64 ? AArch64::dsub0 : AArch64::qsub0;
  5063. auto Ptr = I.getOperand(I.getNumOperands() - 1).getReg();
  5064. assert(MRI.getType(Ptr).isPointer() && "Expected a pointer type?");
  5065. auto Load = MIB.buildInstr(Opc, {Ty}, {Ptr});
  5066. Load.cloneMemRefs(I);
  5067. constrainSelectedInstRegOperands(*Load, TII, TRI, RBI);
  5068. Register SelectedLoadDst = Load->getOperand(0).getReg();
  5069. for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
  5070. auto Vec = MIB.buildInstr(TargetOpcode::COPY, {I.getOperand(Idx)}, {})
  5071. .addReg(SelectedLoadDst, 0, SubReg + Idx);
  5072. // Emit the subreg copies and immediately select them.
  5073. // FIXME: We should refactor our copy code into an emitCopy helper and
  5074. // clean up uses of this pattern elsewhere in the selector.
  5075. selectCopy(*Vec, TII, MRI, TRI, RBI);
  5076. }
  5077. return true;
  5078. }
  5079. bool AArch64InstructionSelector::selectIntrinsicWithSideEffects(
  5080. MachineInstr &I, MachineRegisterInfo &MRI) {
  5081. // Find the intrinsic ID.
  5082. unsigned IntrinID = I.getIntrinsicID();
  5083. const LLT S8 = LLT::scalar(8);
  5084. const LLT S16 = LLT::scalar(16);
  5085. const LLT S32 = LLT::scalar(32);
  5086. const LLT S64 = LLT::scalar(64);
  5087. const LLT P0 = LLT::pointer(0, 64);
  5088. // Select the instruction.
  5089. switch (IntrinID) {
  5090. default:
  5091. return false;
  5092. case Intrinsic::aarch64_ldxp:
  5093. case Intrinsic::aarch64_ldaxp: {
  5094. auto NewI = MIB.buildInstr(
  5095. IntrinID == Intrinsic::aarch64_ldxp ? AArch64::LDXPX : AArch64::LDAXPX,
  5096. {I.getOperand(0).getReg(), I.getOperand(1).getReg()},
  5097. {I.getOperand(3)});
  5098. NewI.cloneMemRefs(I);
  5099. constrainSelectedInstRegOperands(*NewI, TII, TRI, RBI);
  5100. break;
  5101. }
  5102. case Intrinsic::trap:
  5103. MIB.buildInstr(AArch64::BRK, {}, {}).addImm(1);
  5104. break;
  5105. case Intrinsic::debugtrap:
  5106. MIB.buildInstr(AArch64::BRK, {}, {}).addImm(0xF000);
  5107. break;
  5108. case Intrinsic::ubsantrap:
  5109. MIB.buildInstr(AArch64::BRK, {}, {})
  5110. .addImm(I.getOperand(1).getImm() | ('U' << 8));
  5111. break;
  5112. case Intrinsic::aarch64_neon_ld2: {
  5113. LLT Ty = MRI.getType(I.getOperand(0).getReg());
  5114. unsigned Opc = 0;
  5115. if (Ty == LLT::fixed_vector(8, S8))
  5116. Opc = AArch64::LD2Twov8b;
  5117. else if (Ty == LLT::fixed_vector(16, S8))
  5118. Opc = AArch64::LD2Twov16b;
  5119. else if (Ty == LLT::fixed_vector(4, S16))
  5120. Opc = AArch64::LD2Twov4h;
  5121. else if (Ty == LLT::fixed_vector(8, S16))
  5122. Opc = AArch64::LD2Twov8h;
  5123. else if (Ty == LLT::fixed_vector(2, S32))
  5124. Opc = AArch64::LD2Twov2s;
  5125. else if (Ty == LLT::fixed_vector(4, S32))
  5126. Opc = AArch64::LD2Twov4s;
  5127. else if (Ty == LLT::fixed_vector(2, S64) || Ty == LLT::fixed_vector(2, P0))
  5128. Opc = AArch64::LD2Twov2d;
  5129. else if (Ty == S64 || Ty == P0)
  5130. Opc = AArch64::LD1Twov1d;
  5131. else
  5132. llvm_unreachable("Unexpected type for ld2!");
  5133. selectVectorLoadIntrinsic(Opc, 2, I);
  5134. break;
  5135. }
  5136. case Intrinsic::aarch64_neon_ld4: {
  5137. LLT Ty = MRI.getType(I.getOperand(0).getReg());
  5138. unsigned Opc = 0;
  5139. if (Ty == LLT::fixed_vector(8, S8))
  5140. Opc = AArch64::LD4Fourv8b;
  5141. else if (Ty == LLT::fixed_vector(16, S8))
  5142. Opc = AArch64::LD4Fourv16b;
  5143. else if (Ty == LLT::fixed_vector(4, S16))
  5144. Opc = AArch64::LD4Fourv4h;
  5145. else if (Ty == LLT::fixed_vector(8, S16))
  5146. Opc = AArch64::LD4Fourv8h;
  5147. else if (Ty == LLT::fixed_vector(2, S32))
  5148. Opc = AArch64::LD4Fourv2s;
  5149. else if (Ty == LLT::fixed_vector(4, S32))
  5150. Opc = AArch64::LD4Fourv4s;
  5151. else if (Ty == LLT::fixed_vector(2, S64) || Ty == LLT::fixed_vector(2, P0))
  5152. Opc = AArch64::LD4Fourv2d;
  5153. else if (Ty == S64 || Ty == P0)
  5154. Opc = AArch64::LD1Fourv1d;
  5155. else
  5156. llvm_unreachable("Unexpected type for ld4!");
  5157. selectVectorLoadIntrinsic(Opc, 4, I);
  5158. break;
  5159. }
  5160. case Intrinsic::aarch64_neon_st2: {
  5161. Register Src1 = I.getOperand(1).getReg();
  5162. Register Src2 = I.getOperand(2).getReg();
  5163. Register Ptr = I.getOperand(3).getReg();
  5164. LLT Ty = MRI.getType(Src1);
  5165. unsigned Opc;
  5166. if (Ty == LLT::fixed_vector(8, S8))
  5167. Opc = AArch64::ST2Twov8b;
  5168. else if (Ty == LLT::fixed_vector(16, S8))
  5169. Opc = AArch64::ST2Twov16b;
  5170. else if (Ty == LLT::fixed_vector(4, S16))
  5171. Opc = AArch64::ST2Twov4h;
  5172. else if (Ty == LLT::fixed_vector(8, S16))
  5173. Opc = AArch64::ST2Twov8h;
  5174. else if (Ty == LLT::fixed_vector(2, S32))
  5175. Opc = AArch64::ST2Twov2s;
  5176. else if (Ty == LLT::fixed_vector(4, S32))
  5177. Opc = AArch64::ST2Twov4s;
  5178. else if (Ty == LLT::fixed_vector(2, S64) || Ty == LLT::fixed_vector(2, P0))
  5179. Opc = AArch64::ST2Twov2d;
  5180. else if (Ty == S64 || Ty == P0)
  5181. Opc = AArch64::ST1Twov1d;
  5182. else
  5183. llvm_unreachable("Unexpected type for st2!");
  5184. SmallVector<Register, 2> Regs = {Src1, Src2};
  5185. Register Tuple = Ty.getSizeInBits() == 128 ? createQTuple(Regs, MIB)
  5186. : createDTuple(Regs, MIB);
  5187. auto Store = MIB.buildInstr(Opc, {}, {Tuple, Ptr});
  5188. Store.cloneMemRefs(I);
  5189. constrainSelectedInstRegOperands(*Store, TII, TRI, RBI);
  5190. break;
  5191. }
  5192. case Intrinsic::aarch64_mops_memset_tag: {
  5193. // Transform
  5194. // %dst:gpr(p0) = \
  5195. // G_INTRINSIC_W_SIDE_EFFECTS intrinsic(@llvm.aarch64.mops.memset.tag),
  5196. // \ %dst:gpr(p0), %val:gpr(s64), %n:gpr(s64)
  5197. // where %dst is updated, into
  5198. // %Rd:GPR64common, %Rn:GPR64) = \
  5199. // MOPSMemorySetTaggingPseudo \
  5200. // %Rd:GPR64common, %Rn:GPR64, %Rm:GPR64
  5201. // where Rd and Rn are tied.
  5202. // It is expected that %val has been extended to s64 in legalization.
  5203. // Note that the order of the size/value operands are swapped.
  5204. Register DstDef = I.getOperand(0).getReg();
  5205. // I.getOperand(1) is the intrinsic function
  5206. Register DstUse = I.getOperand(2).getReg();
  5207. Register ValUse = I.getOperand(3).getReg();
  5208. Register SizeUse = I.getOperand(4).getReg();
  5209. // MOPSMemorySetTaggingPseudo has two defs; the intrinsic call has only one.
  5210. // Therefore an additional virtual register is requried for the updated size
  5211. // operand. This value is not accessible via the semantics of the intrinsic.
  5212. Register SizeDef = MRI.createGenericVirtualRegister(LLT::scalar(64));
  5213. auto Memset = MIB.buildInstr(AArch64::MOPSMemorySetTaggingPseudo,
  5214. {DstDef, SizeDef}, {DstUse, SizeUse, ValUse});
  5215. Memset.cloneMemRefs(I);
  5216. constrainSelectedInstRegOperands(*Memset, TII, TRI, RBI);
  5217. break;
  5218. }
  5219. }
  5220. I.eraseFromParent();
  5221. return true;
  5222. }
  5223. bool AArch64InstructionSelector::selectIntrinsic(MachineInstr &I,
  5224. MachineRegisterInfo &MRI) {
  5225. unsigned IntrinID = I.getIntrinsicID();
  5226. switch (IntrinID) {
  5227. default:
  5228. break;
  5229. case Intrinsic::aarch64_crypto_sha1h: {
  5230. Register DstReg = I.getOperand(0).getReg();
  5231. Register SrcReg = I.getOperand(2).getReg();
  5232. // FIXME: Should this be an assert?
  5233. if (MRI.getType(DstReg).getSizeInBits() != 32 ||
  5234. MRI.getType(SrcReg).getSizeInBits() != 32)
  5235. return false;
  5236. // The operation has to happen on FPRs. Set up some new FPR registers for
  5237. // the source and destination if they are on GPRs.
  5238. if (RBI.getRegBank(SrcReg, MRI, TRI)->getID() != AArch64::FPRRegBankID) {
  5239. SrcReg = MRI.createVirtualRegister(&AArch64::FPR32RegClass);
  5240. MIB.buildCopy({SrcReg}, {I.getOperand(2)});
  5241. // Make sure the copy ends up getting constrained properly.
  5242. RBI.constrainGenericRegister(I.getOperand(2).getReg(),
  5243. AArch64::GPR32RegClass, MRI);
  5244. }
  5245. if (RBI.getRegBank(DstReg, MRI, TRI)->getID() != AArch64::FPRRegBankID)
  5246. DstReg = MRI.createVirtualRegister(&AArch64::FPR32RegClass);
  5247. // Actually insert the instruction.
  5248. auto SHA1Inst = MIB.buildInstr(AArch64::SHA1Hrr, {DstReg}, {SrcReg});
  5249. constrainSelectedInstRegOperands(*SHA1Inst, TII, TRI, RBI);
  5250. // Did we create a new register for the destination?
  5251. if (DstReg != I.getOperand(0).getReg()) {
  5252. // Yep. Copy the result of the instruction back into the original
  5253. // destination.
  5254. MIB.buildCopy({I.getOperand(0)}, {DstReg});
  5255. RBI.constrainGenericRegister(I.getOperand(0).getReg(),
  5256. AArch64::GPR32RegClass, MRI);
  5257. }
  5258. I.eraseFromParent();
  5259. return true;
  5260. }
  5261. case Intrinsic::ptrauth_sign: {
  5262. Register DstReg = I.getOperand(0).getReg();
  5263. Register ValReg = I.getOperand(2).getReg();
  5264. uint64_t Key = I.getOperand(3).getImm();
  5265. Register DiscReg = I.getOperand(4).getReg();
  5266. auto DiscVal = getIConstantVRegVal(DiscReg, MRI);
  5267. bool IsDiscZero = DiscVal && DiscVal->isNullValue();
  5268. if (Key > AArch64PACKey::LAST)
  5269. return false;
  5270. unsigned Opcodes[][4] = {
  5271. {AArch64::PACIA, AArch64::PACIB, AArch64::PACDA, AArch64::PACDB},
  5272. {AArch64::PACIZA, AArch64::PACIZB, AArch64::PACDZA, AArch64::PACDZB}};
  5273. unsigned Opcode = Opcodes[IsDiscZero][Key];
  5274. auto PAC = MIB.buildInstr(Opcode, {DstReg}, {ValReg});
  5275. if (!IsDiscZero) {
  5276. PAC.addUse(DiscReg);
  5277. RBI.constrainGenericRegister(DiscReg, AArch64::GPR64spRegClass, MRI);
  5278. }
  5279. RBI.constrainGenericRegister(DstReg, AArch64::GPR64RegClass, MRI);
  5280. I.eraseFromParent();
  5281. return true;
  5282. }
  5283. case Intrinsic::ptrauth_strip: {
  5284. Register DstReg = I.getOperand(0).getReg();
  5285. Register ValReg = I.getOperand(2).getReg();
  5286. uint64_t Key = I.getOperand(3).getImm();
  5287. if (Key > AArch64PACKey::LAST)
  5288. return false;
  5289. unsigned Opcode = getXPACOpcodeForKey((AArch64PACKey::ID)Key);
  5290. MIB.buildInstr(Opcode, {DstReg}, {ValReg});
  5291. RBI.constrainGenericRegister(DstReg, AArch64::GPR64RegClass, MRI);
  5292. RBI.constrainGenericRegister(ValReg, AArch64::GPR64RegClass, MRI);
  5293. I.eraseFromParent();
  5294. return true;
  5295. }
  5296. case Intrinsic::frameaddress:
  5297. case Intrinsic::returnaddress: {
  5298. MachineFunction &MF = *I.getParent()->getParent();
  5299. MachineFrameInfo &MFI = MF.getFrameInfo();
  5300. unsigned Depth = I.getOperand(2).getImm();
  5301. Register DstReg = I.getOperand(0).getReg();
  5302. RBI.constrainGenericRegister(DstReg, AArch64::GPR64RegClass, MRI);
  5303. if (Depth == 0 && IntrinID == Intrinsic::returnaddress) {
  5304. if (!MFReturnAddr) {
  5305. // Insert the copy from LR/X30 into the entry block, before it can be
  5306. // clobbered by anything.
  5307. MFI.setReturnAddressIsTaken(true);
  5308. MFReturnAddr = getFunctionLiveInPhysReg(
  5309. MF, TII, AArch64::LR, AArch64::GPR64RegClass, I.getDebugLoc());
  5310. }
  5311. if (STI.hasPAuth()) {
  5312. MIB.buildInstr(AArch64::XPACI, {DstReg}, {MFReturnAddr});
  5313. } else {
  5314. MIB.buildCopy({Register(AArch64::LR)}, {MFReturnAddr});
  5315. MIB.buildInstr(AArch64::XPACLRI);
  5316. MIB.buildCopy({DstReg}, {Register(AArch64::LR)});
  5317. }
  5318. I.eraseFromParent();
  5319. return true;
  5320. }
  5321. MFI.setFrameAddressIsTaken(true);
  5322. Register FrameAddr(AArch64::FP);
  5323. while (Depth--) {
  5324. Register NextFrame = MRI.createVirtualRegister(&AArch64::GPR64spRegClass);
  5325. auto Ldr =
  5326. MIB.buildInstr(AArch64::LDRXui, {NextFrame}, {FrameAddr}).addImm(0);
  5327. constrainSelectedInstRegOperands(*Ldr, TII, TRI, RBI);
  5328. FrameAddr = NextFrame;
  5329. }
  5330. if (IntrinID == Intrinsic::frameaddress)
  5331. MIB.buildCopy({DstReg}, {FrameAddr});
  5332. else {
  5333. MFI.setReturnAddressIsTaken(true);
  5334. if (STI.hasPAuth()) {
  5335. Register TmpReg = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
  5336. MIB.buildInstr(AArch64::LDRXui, {TmpReg}, {FrameAddr}).addImm(1);
  5337. MIB.buildInstr(AArch64::XPACI, {DstReg}, {TmpReg});
  5338. } else {
  5339. MIB.buildInstr(AArch64::LDRXui, {Register(AArch64::LR)}, {FrameAddr})
  5340. .addImm(1);
  5341. MIB.buildInstr(AArch64::XPACLRI);
  5342. MIB.buildCopy({DstReg}, {Register(AArch64::LR)});
  5343. }
  5344. }
  5345. I.eraseFromParent();
  5346. return true;
  5347. }
  5348. case Intrinsic::swift_async_context_addr:
  5349. auto Sub = MIB.buildInstr(AArch64::SUBXri, {I.getOperand(0).getReg()},
  5350. {Register(AArch64::FP)})
  5351. .addImm(8)
  5352. .addImm(0);
  5353. constrainSelectedInstRegOperands(*Sub, TII, TRI, RBI);
  5354. MF->getFrameInfo().setFrameAddressIsTaken(true);
  5355. MF->getInfo<AArch64FunctionInfo>()->setHasSwiftAsyncContext(true);
  5356. I.eraseFromParent();
  5357. return true;
  5358. }
  5359. return false;
  5360. }
  5361. InstructionSelector::ComplexRendererFns
  5362. AArch64InstructionSelector::selectShiftA_32(const MachineOperand &Root) const {
  5363. auto MaybeImmed = getImmedFromMO(Root);
  5364. if (MaybeImmed == std::nullopt || *MaybeImmed > 31)
  5365. return std::nullopt;
  5366. uint64_t Enc = (32 - *MaybeImmed) & 0x1f;
  5367. return {{[=](MachineInstrBuilder &MIB) { MIB.addImm(Enc); }}};
  5368. }
  5369. InstructionSelector::ComplexRendererFns
  5370. AArch64InstructionSelector::selectShiftB_32(const MachineOperand &Root) const {
  5371. auto MaybeImmed = getImmedFromMO(Root);
  5372. if (MaybeImmed == std::nullopt || *MaybeImmed > 31)
  5373. return std::nullopt;
  5374. uint64_t Enc = 31 - *MaybeImmed;
  5375. return {{[=](MachineInstrBuilder &MIB) { MIB.addImm(Enc); }}};
  5376. }
  5377. InstructionSelector::ComplexRendererFns
  5378. AArch64InstructionSelector::selectShiftA_64(const MachineOperand &Root) const {
  5379. auto MaybeImmed = getImmedFromMO(Root);
  5380. if (MaybeImmed == std::nullopt || *MaybeImmed > 63)
  5381. return std::nullopt;
  5382. uint64_t Enc = (64 - *MaybeImmed) & 0x3f;
  5383. return {{[=](MachineInstrBuilder &MIB) { MIB.addImm(Enc); }}};
  5384. }
  5385. InstructionSelector::ComplexRendererFns
  5386. AArch64InstructionSelector::selectShiftB_64(const MachineOperand &Root) const {
  5387. auto MaybeImmed = getImmedFromMO(Root);
  5388. if (MaybeImmed == std::nullopt || *MaybeImmed > 63)
  5389. return std::nullopt;
  5390. uint64_t Enc = 63 - *MaybeImmed;
  5391. return {{[=](MachineInstrBuilder &MIB) { MIB.addImm(Enc); }}};
  5392. }
  5393. /// Helper to select an immediate value that can be represented as a 12-bit
  5394. /// value shifted left by either 0 or 12. If it is possible to do so, return
  5395. /// the immediate and shift value. If not, return std::nullopt.
  5396. ///
  5397. /// Used by selectArithImmed and selectNegArithImmed.
  5398. InstructionSelector::ComplexRendererFns
  5399. AArch64InstructionSelector::select12BitValueWithLeftShift(
  5400. uint64_t Immed) const {
  5401. unsigned ShiftAmt;
  5402. if (Immed >> 12 == 0) {
  5403. ShiftAmt = 0;
  5404. } else if ((Immed & 0xfff) == 0 && Immed >> 24 == 0) {
  5405. ShiftAmt = 12;
  5406. Immed = Immed >> 12;
  5407. } else
  5408. return std::nullopt;
  5409. unsigned ShVal = AArch64_AM::getShifterImm(AArch64_AM::LSL, ShiftAmt);
  5410. return {{
  5411. [=](MachineInstrBuilder &MIB) { MIB.addImm(Immed); },
  5412. [=](MachineInstrBuilder &MIB) { MIB.addImm(ShVal); },
  5413. }};
  5414. }
  5415. /// SelectArithImmed - Select an immediate value that can be represented as
  5416. /// a 12-bit value shifted left by either 0 or 12. If so, return true with
  5417. /// Val set to the 12-bit value and Shift set to the shifter operand.
  5418. InstructionSelector::ComplexRendererFns
  5419. AArch64InstructionSelector::selectArithImmed(MachineOperand &Root) const {
  5420. // This function is called from the addsub_shifted_imm ComplexPattern,
  5421. // which lists [imm] as the list of opcode it's interested in, however
  5422. // we still need to check whether the operand is actually an immediate
  5423. // here because the ComplexPattern opcode list is only used in
  5424. // root-level opcode matching.
  5425. auto MaybeImmed = getImmedFromMO(Root);
  5426. if (MaybeImmed == std::nullopt)
  5427. return std::nullopt;
  5428. return select12BitValueWithLeftShift(*MaybeImmed);
  5429. }
  5430. /// SelectNegArithImmed - As above, but negates the value before trying to
  5431. /// select it.
  5432. InstructionSelector::ComplexRendererFns
  5433. AArch64InstructionSelector::selectNegArithImmed(MachineOperand &Root) const {
  5434. // We need a register here, because we need to know if we have a 64 or 32
  5435. // bit immediate.
  5436. if (!Root.isReg())
  5437. return std::nullopt;
  5438. auto MaybeImmed = getImmedFromMO(Root);
  5439. if (MaybeImmed == std::nullopt)
  5440. return std::nullopt;
  5441. uint64_t Immed = *MaybeImmed;
  5442. // This negation is almost always valid, but "cmp wN, #0" and "cmn wN, #0"
  5443. // have the opposite effect on the C flag, so this pattern mustn't match under
  5444. // those circumstances.
  5445. if (Immed == 0)
  5446. return std::nullopt;
  5447. // Check if we're dealing with a 32-bit type on the root or a 64-bit type on
  5448. // the root.
  5449. MachineRegisterInfo &MRI = Root.getParent()->getMF()->getRegInfo();
  5450. if (MRI.getType(Root.getReg()).getSizeInBits() == 32)
  5451. Immed = ~((uint32_t)Immed) + 1;
  5452. else
  5453. Immed = ~Immed + 1ULL;
  5454. if (Immed & 0xFFFFFFFFFF000000ULL)
  5455. return std::nullopt;
  5456. Immed &= 0xFFFFFFULL;
  5457. return select12BitValueWithLeftShift(Immed);
  5458. }
  5459. /// Return true if it is worth folding MI into an extended register. That is,
  5460. /// if it's safe to pull it into the addressing mode of a load or store as a
  5461. /// shift.
  5462. bool AArch64InstructionSelector::isWorthFoldingIntoExtendedReg(
  5463. MachineInstr &MI, const MachineRegisterInfo &MRI) const {
  5464. // Always fold if there is one use, or if we're optimizing for size.
  5465. Register DefReg = MI.getOperand(0).getReg();
  5466. if (MRI.hasOneNonDBGUse(DefReg) ||
  5467. MI.getParent()->getParent()->getFunction().hasOptSize())
  5468. return true;
  5469. // It's better to avoid folding and recomputing shifts when we don't have a
  5470. // fastpath.
  5471. if (!STI.hasLSLFast())
  5472. return false;
  5473. // We have a fastpath, so folding a shift in and potentially computing it
  5474. // many times may be beneficial. Check if this is only used in memory ops.
  5475. // If it is, then we should fold.
  5476. return all_of(MRI.use_nodbg_instructions(DefReg),
  5477. [](MachineInstr &Use) { return Use.mayLoadOrStore(); });
  5478. }
  5479. static bool isSignExtendShiftType(AArch64_AM::ShiftExtendType Type) {
  5480. switch (Type) {
  5481. case AArch64_AM::SXTB:
  5482. case AArch64_AM::SXTH:
  5483. case AArch64_AM::SXTW:
  5484. return true;
  5485. default:
  5486. return false;
  5487. }
  5488. }
  5489. InstructionSelector::ComplexRendererFns
  5490. AArch64InstructionSelector::selectExtendedSHL(
  5491. MachineOperand &Root, MachineOperand &Base, MachineOperand &Offset,
  5492. unsigned SizeInBytes, bool WantsExt) const {
  5493. assert(Base.isReg() && "Expected base to be a register operand");
  5494. assert(Offset.isReg() && "Expected offset to be a register operand");
  5495. MachineRegisterInfo &MRI = Root.getParent()->getMF()->getRegInfo();
  5496. MachineInstr *OffsetInst = MRI.getVRegDef(Offset.getReg());
  5497. unsigned OffsetOpc = OffsetInst->getOpcode();
  5498. bool LookedThroughZExt = false;
  5499. if (OffsetOpc != TargetOpcode::G_SHL && OffsetOpc != TargetOpcode::G_MUL) {
  5500. // Try to look through a ZEXT.
  5501. if (OffsetOpc != TargetOpcode::G_ZEXT || !WantsExt)
  5502. return std::nullopt;
  5503. OffsetInst = MRI.getVRegDef(OffsetInst->getOperand(1).getReg());
  5504. OffsetOpc = OffsetInst->getOpcode();
  5505. LookedThroughZExt = true;
  5506. if (OffsetOpc != TargetOpcode::G_SHL && OffsetOpc != TargetOpcode::G_MUL)
  5507. return std::nullopt;
  5508. }
  5509. // Make sure that the memory op is a valid size.
  5510. int64_t LegalShiftVal = Log2_32(SizeInBytes);
  5511. if (LegalShiftVal == 0)
  5512. return std::nullopt;
  5513. if (!isWorthFoldingIntoExtendedReg(*OffsetInst, MRI))
  5514. return std::nullopt;
  5515. // Now, try to find the specific G_CONSTANT. Start by assuming that the
  5516. // register we will offset is the LHS, and the register containing the
  5517. // constant is the RHS.
  5518. Register OffsetReg = OffsetInst->getOperand(1).getReg();
  5519. Register ConstantReg = OffsetInst->getOperand(2).getReg();
  5520. auto ValAndVReg = getIConstantVRegValWithLookThrough(ConstantReg, MRI);
  5521. if (!ValAndVReg) {
  5522. // We didn't get a constant on the RHS. If the opcode is a shift, then
  5523. // we're done.
  5524. if (OffsetOpc == TargetOpcode::G_SHL)
  5525. return std::nullopt;
  5526. // If we have a G_MUL, we can use either register. Try looking at the RHS.
  5527. std::swap(OffsetReg, ConstantReg);
  5528. ValAndVReg = getIConstantVRegValWithLookThrough(ConstantReg, MRI);
  5529. if (!ValAndVReg)
  5530. return std::nullopt;
  5531. }
  5532. // The value must fit into 3 bits, and must be positive. Make sure that is
  5533. // true.
  5534. int64_t ImmVal = ValAndVReg->Value.getSExtValue();
  5535. // Since we're going to pull this into a shift, the constant value must be
  5536. // a power of 2. If we got a multiply, then we need to check this.
  5537. if (OffsetOpc == TargetOpcode::G_MUL) {
  5538. if (!isPowerOf2_32(ImmVal))
  5539. return std::nullopt;
  5540. // Got a power of 2. So, the amount we'll shift is the log base-2 of that.
  5541. ImmVal = Log2_32(ImmVal);
  5542. }
  5543. if ((ImmVal & 0x7) != ImmVal)
  5544. return std::nullopt;
  5545. // We are only allowed to shift by LegalShiftVal. This shift value is built
  5546. // into the instruction, so we can't just use whatever we want.
  5547. if (ImmVal != LegalShiftVal)
  5548. return std::nullopt;
  5549. unsigned SignExtend = 0;
  5550. if (WantsExt) {
  5551. // Check if the offset is defined by an extend, unless we looked through a
  5552. // G_ZEXT earlier.
  5553. if (!LookedThroughZExt) {
  5554. MachineInstr *ExtInst = getDefIgnoringCopies(OffsetReg, MRI);
  5555. auto Ext = getExtendTypeForInst(*ExtInst, MRI, true);
  5556. if (Ext == AArch64_AM::InvalidShiftExtend)
  5557. return std::nullopt;
  5558. SignExtend = isSignExtendShiftType(Ext) ? 1 : 0;
  5559. // We only support SXTW for signed extension here.
  5560. if (SignExtend && Ext != AArch64_AM::SXTW)
  5561. return std::nullopt;
  5562. OffsetReg = ExtInst->getOperand(1).getReg();
  5563. }
  5564. // Need a 32-bit wide register here.
  5565. MachineIRBuilder MIB(*MRI.getVRegDef(Root.getReg()));
  5566. OffsetReg = moveScalarRegClass(OffsetReg, AArch64::GPR32RegClass, MIB);
  5567. }
  5568. // We can use the LHS of the GEP as the base, and the LHS of the shift as an
  5569. // offset. Signify that we are shifting by setting the shift flag to 1.
  5570. return {{[=](MachineInstrBuilder &MIB) { MIB.addUse(Base.getReg()); },
  5571. [=](MachineInstrBuilder &MIB) { MIB.addUse(OffsetReg); },
  5572. [=](MachineInstrBuilder &MIB) {
  5573. // Need to add both immediates here to make sure that they are both
  5574. // added to the instruction.
  5575. MIB.addImm(SignExtend);
  5576. MIB.addImm(1);
  5577. }}};
  5578. }
  5579. /// This is used for computing addresses like this:
  5580. ///
  5581. /// ldr x1, [x2, x3, lsl #3]
  5582. ///
  5583. /// Where x2 is the base register, and x3 is an offset register. The shift-left
  5584. /// is a constant value specific to this load instruction. That is, we'll never
  5585. /// see anything other than a 3 here (which corresponds to the size of the
  5586. /// element being loaded.)
  5587. InstructionSelector::ComplexRendererFns
  5588. AArch64InstructionSelector::selectAddrModeShiftedExtendXReg(
  5589. MachineOperand &Root, unsigned SizeInBytes) const {
  5590. if (!Root.isReg())
  5591. return std::nullopt;
  5592. MachineRegisterInfo &MRI = Root.getParent()->getMF()->getRegInfo();
  5593. // We want to find something like this:
  5594. //
  5595. // val = G_CONSTANT LegalShiftVal
  5596. // shift = G_SHL off_reg val
  5597. // ptr = G_PTR_ADD base_reg shift
  5598. // x = G_LOAD ptr
  5599. //
  5600. // And fold it into this addressing mode:
  5601. //
  5602. // ldr x, [base_reg, off_reg, lsl #LegalShiftVal]
  5603. // Check if we can find the G_PTR_ADD.
  5604. MachineInstr *PtrAdd =
  5605. getOpcodeDef(TargetOpcode::G_PTR_ADD, Root.getReg(), MRI);
  5606. if (!PtrAdd || !isWorthFoldingIntoExtendedReg(*PtrAdd, MRI))
  5607. return std::nullopt;
  5608. // Now, try to match an opcode which will match our specific offset.
  5609. // We want a G_SHL or a G_MUL.
  5610. MachineInstr *OffsetInst =
  5611. getDefIgnoringCopies(PtrAdd->getOperand(2).getReg(), MRI);
  5612. return selectExtendedSHL(Root, PtrAdd->getOperand(1),
  5613. OffsetInst->getOperand(0), SizeInBytes,
  5614. /*WantsExt=*/false);
  5615. }
  5616. /// This is used for computing addresses like this:
  5617. ///
  5618. /// ldr x1, [x2, x3]
  5619. ///
  5620. /// Where x2 is the base register, and x3 is an offset register.
  5621. ///
  5622. /// When possible (or profitable) to fold a G_PTR_ADD into the address
  5623. /// calculation, this will do so. Otherwise, it will return std::nullopt.
  5624. InstructionSelector::ComplexRendererFns
  5625. AArch64InstructionSelector::selectAddrModeRegisterOffset(
  5626. MachineOperand &Root) const {
  5627. MachineRegisterInfo &MRI = Root.getParent()->getMF()->getRegInfo();
  5628. // We need a GEP.
  5629. MachineInstr *Gep = MRI.getVRegDef(Root.getReg());
  5630. if (Gep->getOpcode() != TargetOpcode::G_PTR_ADD)
  5631. return std::nullopt;
  5632. // If this is used more than once, let's not bother folding.
  5633. // TODO: Check if they are memory ops. If they are, then we can still fold
  5634. // without having to recompute anything.
  5635. if (!MRI.hasOneNonDBGUse(Gep->getOperand(0).getReg()))
  5636. return std::nullopt;
  5637. // Base is the GEP's LHS, offset is its RHS.
  5638. return {{[=](MachineInstrBuilder &MIB) {
  5639. MIB.addUse(Gep->getOperand(1).getReg());
  5640. },
  5641. [=](MachineInstrBuilder &MIB) {
  5642. MIB.addUse(Gep->getOperand(2).getReg());
  5643. },
  5644. [=](MachineInstrBuilder &MIB) {
  5645. // Need to add both immediates here to make sure that they are both
  5646. // added to the instruction.
  5647. MIB.addImm(0);
  5648. MIB.addImm(0);
  5649. }}};
  5650. }
  5651. /// This is intended to be equivalent to selectAddrModeXRO in
  5652. /// AArch64ISelDAGtoDAG. It's used for selecting X register offset loads.
  5653. InstructionSelector::ComplexRendererFns
  5654. AArch64InstructionSelector::selectAddrModeXRO(MachineOperand &Root,
  5655. unsigned SizeInBytes) const {
  5656. MachineRegisterInfo &MRI = Root.getParent()->getMF()->getRegInfo();
  5657. if (!Root.isReg())
  5658. return std::nullopt;
  5659. MachineInstr *PtrAdd =
  5660. getOpcodeDef(TargetOpcode::G_PTR_ADD, Root.getReg(), MRI);
  5661. if (!PtrAdd)
  5662. return std::nullopt;
  5663. // Check for an immediates which cannot be encoded in the [base + imm]
  5664. // addressing mode, and can't be encoded in an add/sub. If this happens, we'll
  5665. // end up with code like:
  5666. //
  5667. // mov x0, wide
  5668. // add x1 base, x0
  5669. // ldr x2, [x1, x0]
  5670. //
  5671. // In this situation, we can use the [base, xreg] addressing mode to save an
  5672. // add/sub:
  5673. //
  5674. // mov x0, wide
  5675. // ldr x2, [base, x0]
  5676. auto ValAndVReg =
  5677. getIConstantVRegValWithLookThrough(PtrAdd->getOperand(2).getReg(), MRI);
  5678. if (ValAndVReg) {
  5679. unsigned Scale = Log2_32(SizeInBytes);
  5680. int64_t ImmOff = ValAndVReg->Value.getSExtValue();
  5681. // Skip immediates that can be selected in the load/store addresing
  5682. // mode.
  5683. if (ImmOff % SizeInBytes == 0 && ImmOff >= 0 &&
  5684. ImmOff < (0x1000 << Scale))
  5685. return std::nullopt;
  5686. // Helper lambda to decide whether or not it is preferable to emit an add.
  5687. auto isPreferredADD = [](int64_t ImmOff) {
  5688. // Constants in [0x0, 0xfff] can be encoded in an add.
  5689. if ((ImmOff & 0xfffffffffffff000LL) == 0x0LL)
  5690. return true;
  5691. // Can it be encoded in an add lsl #12?
  5692. if ((ImmOff & 0xffffffffff000fffLL) != 0x0LL)
  5693. return false;
  5694. // It can be encoded in an add lsl #12, but we may not want to. If it is
  5695. // possible to select this as a single movz, then prefer that. A single
  5696. // movz is faster than an add with a shift.
  5697. return (ImmOff & 0xffffffffff00ffffLL) != 0x0LL &&
  5698. (ImmOff & 0xffffffffffff0fffLL) != 0x0LL;
  5699. };
  5700. // If the immediate can be encoded in a single add/sub, then bail out.
  5701. if (isPreferredADD(ImmOff) || isPreferredADD(-ImmOff))
  5702. return std::nullopt;
  5703. }
  5704. // Try to fold shifts into the addressing mode.
  5705. auto AddrModeFns = selectAddrModeShiftedExtendXReg(Root, SizeInBytes);
  5706. if (AddrModeFns)
  5707. return AddrModeFns;
  5708. // If that doesn't work, see if it's possible to fold in registers from
  5709. // a GEP.
  5710. return selectAddrModeRegisterOffset(Root);
  5711. }
  5712. /// This is used for computing addresses like this:
  5713. ///
  5714. /// ldr x0, [xBase, wOffset, sxtw #LegalShiftVal]
  5715. ///
  5716. /// Where we have a 64-bit base register, a 32-bit offset register, and an
  5717. /// extend (which may or may not be signed).
  5718. InstructionSelector::ComplexRendererFns
  5719. AArch64InstructionSelector::selectAddrModeWRO(MachineOperand &Root,
  5720. unsigned SizeInBytes) const {
  5721. MachineRegisterInfo &MRI = Root.getParent()->getMF()->getRegInfo();
  5722. MachineInstr *PtrAdd =
  5723. getOpcodeDef(TargetOpcode::G_PTR_ADD, Root.getReg(), MRI);
  5724. if (!PtrAdd || !isWorthFoldingIntoExtendedReg(*PtrAdd, MRI))
  5725. return std::nullopt;
  5726. MachineOperand &LHS = PtrAdd->getOperand(1);
  5727. MachineOperand &RHS = PtrAdd->getOperand(2);
  5728. MachineInstr *OffsetInst = getDefIgnoringCopies(RHS.getReg(), MRI);
  5729. // The first case is the same as selectAddrModeXRO, except we need an extend.
  5730. // In this case, we try to find a shift and extend, and fold them into the
  5731. // addressing mode.
  5732. //
  5733. // E.g.
  5734. //
  5735. // off_reg = G_Z/S/ANYEXT ext_reg
  5736. // val = G_CONSTANT LegalShiftVal
  5737. // shift = G_SHL off_reg val
  5738. // ptr = G_PTR_ADD base_reg shift
  5739. // x = G_LOAD ptr
  5740. //
  5741. // In this case we can get a load like this:
  5742. //
  5743. // ldr x0, [base_reg, ext_reg, sxtw #LegalShiftVal]
  5744. auto ExtendedShl = selectExtendedSHL(Root, LHS, OffsetInst->getOperand(0),
  5745. SizeInBytes, /*WantsExt=*/true);
  5746. if (ExtendedShl)
  5747. return ExtendedShl;
  5748. // There was no shift. We can try and fold a G_Z/S/ANYEXT in alone though.
  5749. //
  5750. // e.g.
  5751. // ldr something, [base_reg, ext_reg, sxtw]
  5752. if (!isWorthFoldingIntoExtendedReg(*OffsetInst, MRI))
  5753. return std::nullopt;
  5754. // Check if this is an extend. We'll get an extend type if it is.
  5755. AArch64_AM::ShiftExtendType Ext =
  5756. getExtendTypeForInst(*OffsetInst, MRI, /*IsLoadStore=*/true);
  5757. if (Ext == AArch64_AM::InvalidShiftExtend)
  5758. return std::nullopt;
  5759. // Need a 32-bit wide register.
  5760. MachineIRBuilder MIB(*PtrAdd);
  5761. Register ExtReg = moveScalarRegClass(OffsetInst->getOperand(1).getReg(),
  5762. AArch64::GPR32RegClass, MIB);
  5763. unsigned SignExtend = Ext == AArch64_AM::SXTW;
  5764. // Base is LHS, offset is ExtReg.
  5765. return {{[=](MachineInstrBuilder &MIB) { MIB.addUse(LHS.getReg()); },
  5766. [=](MachineInstrBuilder &MIB) { MIB.addUse(ExtReg); },
  5767. [=](MachineInstrBuilder &MIB) {
  5768. MIB.addImm(SignExtend);
  5769. MIB.addImm(0);
  5770. }}};
  5771. }
  5772. /// Select a "register plus unscaled signed 9-bit immediate" address. This
  5773. /// should only match when there is an offset that is not valid for a scaled
  5774. /// immediate addressing mode. The "Size" argument is the size in bytes of the
  5775. /// memory reference, which is needed here to know what is valid for a scaled
  5776. /// immediate.
  5777. InstructionSelector::ComplexRendererFns
  5778. AArch64InstructionSelector::selectAddrModeUnscaled(MachineOperand &Root,
  5779. unsigned Size) const {
  5780. MachineRegisterInfo &MRI =
  5781. Root.getParent()->getParent()->getParent()->getRegInfo();
  5782. if (!Root.isReg())
  5783. return std::nullopt;
  5784. if (!isBaseWithConstantOffset(Root, MRI))
  5785. return std::nullopt;
  5786. MachineInstr *RootDef = MRI.getVRegDef(Root.getReg());
  5787. MachineOperand &OffImm = RootDef->getOperand(2);
  5788. if (!OffImm.isReg())
  5789. return std::nullopt;
  5790. MachineInstr *RHS = MRI.getVRegDef(OffImm.getReg());
  5791. if (RHS->getOpcode() != TargetOpcode::G_CONSTANT)
  5792. return std::nullopt;
  5793. int64_t RHSC;
  5794. MachineOperand &RHSOp1 = RHS->getOperand(1);
  5795. if (!RHSOp1.isCImm() || RHSOp1.getCImm()->getBitWidth() > 64)
  5796. return std::nullopt;
  5797. RHSC = RHSOp1.getCImm()->getSExtValue();
  5798. // If the offset is valid as a scaled immediate, don't match here.
  5799. if ((RHSC & (Size - 1)) == 0 && RHSC >= 0 && RHSC < (0x1000 << Log2_32(Size)))
  5800. return std::nullopt;
  5801. if (RHSC >= -256 && RHSC < 256) {
  5802. MachineOperand &Base = RootDef->getOperand(1);
  5803. return {{
  5804. [=](MachineInstrBuilder &MIB) { MIB.add(Base); },
  5805. [=](MachineInstrBuilder &MIB) { MIB.addImm(RHSC); },
  5806. }};
  5807. }
  5808. return std::nullopt;
  5809. }
  5810. InstructionSelector::ComplexRendererFns
  5811. AArch64InstructionSelector::tryFoldAddLowIntoImm(MachineInstr &RootDef,
  5812. unsigned Size,
  5813. MachineRegisterInfo &MRI) const {
  5814. if (RootDef.getOpcode() != AArch64::G_ADD_LOW)
  5815. return std::nullopt;
  5816. MachineInstr &Adrp = *MRI.getVRegDef(RootDef.getOperand(1).getReg());
  5817. if (Adrp.getOpcode() != AArch64::ADRP)
  5818. return std::nullopt;
  5819. // TODO: add heuristics like isWorthFoldingADDlow() from SelectionDAG.
  5820. auto Offset = Adrp.getOperand(1).getOffset();
  5821. if (Offset % Size != 0)
  5822. return std::nullopt;
  5823. auto GV = Adrp.getOperand(1).getGlobal();
  5824. if (GV->isThreadLocal())
  5825. return std::nullopt;
  5826. auto &MF = *RootDef.getParent()->getParent();
  5827. if (GV->getPointerAlignment(MF.getDataLayout()) < Size)
  5828. return std::nullopt;
  5829. unsigned OpFlags = STI.ClassifyGlobalReference(GV, MF.getTarget());
  5830. MachineIRBuilder MIRBuilder(RootDef);
  5831. Register AdrpReg = Adrp.getOperand(0).getReg();
  5832. return {{[=](MachineInstrBuilder &MIB) { MIB.addUse(AdrpReg); },
  5833. [=](MachineInstrBuilder &MIB) {
  5834. MIB.addGlobalAddress(GV, Offset,
  5835. OpFlags | AArch64II::MO_PAGEOFF |
  5836. AArch64II::MO_NC);
  5837. }}};
  5838. }
  5839. /// Select a "register plus scaled unsigned 12-bit immediate" address. The
  5840. /// "Size" argument is the size in bytes of the memory reference, which
  5841. /// determines the scale.
  5842. InstructionSelector::ComplexRendererFns
  5843. AArch64InstructionSelector::selectAddrModeIndexed(MachineOperand &Root,
  5844. unsigned Size) const {
  5845. MachineFunction &MF = *Root.getParent()->getParent()->getParent();
  5846. MachineRegisterInfo &MRI = MF.getRegInfo();
  5847. if (!Root.isReg())
  5848. return std::nullopt;
  5849. MachineInstr *RootDef = MRI.getVRegDef(Root.getReg());
  5850. if (RootDef->getOpcode() == TargetOpcode::G_FRAME_INDEX) {
  5851. return {{
  5852. [=](MachineInstrBuilder &MIB) { MIB.add(RootDef->getOperand(1)); },
  5853. [=](MachineInstrBuilder &MIB) { MIB.addImm(0); },
  5854. }};
  5855. }
  5856. CodeModel::Model CM = MF.getTarget().getCodeModel();
  5857. // Check if we can fold in the ADD of small code model ADRP + ADD address.
  5858. if (CM == CodeModel::Small) {
  5859. auto OpFns = tryFoldAddLowIntoImm(*RootDef, Size, MRI);
  5860. if (OpFns)
  5861. return OpFns;
  5862. }
  5863. if (isBaseWithConstantOffset(Root, MRI)) {
  5864. MachineOperand &LHS = RootDef->getOperand(1);
  5865. MachineOperand &RHS = RootDef->getOperand(2);
  5866. MachineInstr *LHSDef = MRI.getVRegDef(LHS.getReg());
  5867. MachineInstr *RHSDef = MRI.getVRegDef(RHS.getReg());
  5868. int64_t RHSC = (int64_t)RHSDef->getOperand(1).getCImm()->getZExtValue();
  5869. unsigned Scale = Log2_32(Size);
  5870. if ((RHSC & (Size - 1)) == 0 && RHSC >= 0 && RHSC < (0x1000 << Scale)) {
  5871. if (LHSDef->getOpcode() == TargetOpcode::G_FRAME_INDEX)
  5872. return {{
  5873. [=](MachineInstrBuilder &MIB) { MIB.add(LHSDef->getOperand(1)); },
  5874. [=](MachineInstrBuilder &MIB) { MIB.addImm(RHSC >> Scale); },
  5875. }};
  5876. return {{
  5877. [=](MachineInstrBuilder &MIB) { MIB.add(LHS); },
  5878. [=](MachineInstrBuilder &MIB) { MIB.addImm(RHSC >> Scale); },
  5879. }};
  5880. }
  5881. }
  5882. // Before falling back to our general case, check if the unscaled
  5883. // instructions can handle this. If so, that's preferable.
  5884. if (selectAddrModeUnscaled(Root, Size))
  5885. return std::nullopt;
  5886. return {{
  5887. [=](MachineInstrBuilder &MIB) { MIB.add(Root); },
  5888. [=](MachineInstrBuilder &MIB) { MIB.addImm(0); },
  5889. }};
  5890. }
  5891. /// Given a shift instruction, return the correct shift type for that
  5892. /// instruction.
  5893. static AArch64_AM::ShiftExtendType getShiftTypeForInst(MachineInstr &MI) {
  5894. switch (MI.getOpcode()) {
  5895. default:
  5896. return AArch64_AM::InvalidShiftExtend;
  5897. case TargetOpcode::G_SHL:
  5898. return AArch64_AM::LSL;
  5899. case TargetOpcode::G_LSHR:
  5900. return AArch64_AM::LSR;
  5901. case TargetOpcode::G_ASHR:
  5902. return AArch64_AM::ASR;
  5903. case TargetOpcode::G_ROTR:
  5904. return AArch64_AM::ROR;
  5905. }
  5906. }
  5907. /// Select a "shifted register" operand. If the value is not shifted, set the
  5908. /// shift operand to a default value of "lsl 0".
  5909. InstructionSelector::ComplexRendererFns
  5910. AArch64InstructionSelector::selectShiftedRegister(MachineOperand &Root,
  5911. bool AllowROR) const {
  5912. if (!Root.isReg())
  5913. return std::nullopt;
  5914. MachineRegisterInfo &MRI =
  5915. Root.getParent()->getParent()->getParent()->getRegInfo();
  5916. // Check if the operand is defined by an instruction which corresponds to
  5917. // a ShiftExtendType. E.g. a G_SHL, G_LSHR, etc.
  5918. MachineInstr *ShiftInst = MRI.getVRegDef(Root.getReg());
  5919. AArch64_AM::ShiftExtendType ShType = getShiftTypeForInst(*ShiftInst);
  5920. if (ShType == AArch64_AM::InvalidShiftExtend)
  5921. return std::nullopt;
  5922. if (ShType == AArch64_AM::ROR && !AllowROR)
  5923. return std::nullopt;
  5924. if (!isWorthFoldingIntoExtendedReg(*ShiftInst, MRI))
  5925. return std::nullopt;
  5926. // Need an immediate on the RHS.
  5927. MachineOperand &ShiftRHS = ShiftInst->getOperand(2);
  5928. auto Immed = getImmedFromMO(ShiftRHS);
  5929. if (!Immed)
  5930. return std::nullopt;
  5931. // We have something that we can fold. Fold in the shift's LHS and RHS into
  5932. // the instruction.
  5933. MachineOperand &ShiftLHS = ShiftInst->getOperand(1);
  5934. Register ShiftReg = ShiftLHS.getReg();
  5935. unsigned NumBits = MRI.getType(ShiftReg).getSizeInBits();
  5936. unsigned Val = *Immed & (NumBits - 1);
  5937. unsigned ShiftVal = AArch64_AM::getShifterImm(ShType, Val);
  5938. return {{[=](MachineInstrBuilder &MIB) { MIB.addUse(ShiftReg); },
  5939. [=](MachineInstrBuilder &MIB) { MIB.addImm(ShiftVal); }}};
  5940. }
  5941. AArch64_AM::ShiftExtendType AArch64InstructionSelector::getExtendTypeForInst(
  5942. MachineInstr &MI, MachineRegisterInfo &MRI, bool IsLoadStore) const {
  5943. unsigned Opc = MI.getOpcode();
  5944. // Handle explicit extend instructions first.
  5945. if (Opc == TargetOpcode::G_SEXT || Opc == TargetOpcode::G_SEXT_INREG) {
  5946. unsigned Size;
  5947. if (Opc == TargetOpcode::G_SEXT)
  5948. Size = MRI.getType(MI.getOperand(1).getReg()).getSizeInBits();
  5949. else
  5950. Size = MI.getOperand(2).getImm();
  5951. assert(Size != 64 && "Extend from 64 bits?");
  5952. switch (Size) {
  5953. case 8:
  5954. return IsLoadStore ? AArch64_AM::InvalidShiftExtend : AArch64_AM::SXTB;
  5955. case 16:
  5956. return IsLoadStore ? AArch64_AM::InvalidShiftExtend : AArch64_AM::SXTH;
  5957. case 32:
  5958. return AArch64_AM::SXTW;
  5959. default:
  5960. return AArch64_AM::InvalidShiftExtend;
  5961. }
  5962. }
  5963. if (Opc == TargetOpcode::G_ZEXT || Opc == TargetOpcode::G_ANYEXT) {
  5964. unsigned Size = MRI.getType(MI.getOperand(1).getReg()).getSizeInBits();
  5965. assert(Size != 64 && "Extend from 64 bits?");
  5966. switch (Size) {
  5967. case 8:
  5968. return IsLoadStore ? AArch64_AM::InvalidShiftExtend : AArch64_AM::UXTB;
  5969. case 16:
  5970. return IsLoadStore ? AArch64_AM::InvalidShiftExtend : AArch64_AM::UXTH;
  5971. case 32:
  5972. return AArch64_AM::UXTW;
  5973. default:
  5974. return AArch64_AM::InvalidShiftExtend;
  5975. }
  5976. }
  5977. // Don't have an explicit extend. Try to handle a G_AND with a constant mask
  5978. // on the RHS.
  5979. if (Opc != TargetOpcode::G_AND)
  5980. return AArch64_AM::InvalidShiftExtend;
  5981. std::optional<uint64_t> MaybeAndMask = getImmedFromMO(MI.getOperand(2));
  5982. if (!MaybeAndMask)
  5983. return AArch64_AM::InvalidShiftExtend;
  5984. uint64_t AndMask = *MaybeAndMask;
  5985. switch (AndMask) {
  5986. default:
  5987. return AArch64_AM::InvalidShiftExtend;
  5988. case 0xFF:
  5989. return !IsLoadStore ? AArch64_AM::UXTB : AArch64_AM::InvalidShiftExtend;
  5990. case 0xFFFF:
  5991. return !IsLoadStore ? AArch64_AM::UXTH : AArch64_AM::InvalidShiftExtend;
  5992. case 0xFFFFFFFF:
  5993. return AArch64_AM::UXTW;
  5994. }
  5995. }
  5996. Register AArch64InstructionSelector::moveScalarRegClass(
  5997. Register Reg, const TargetRegisterClass &RC, MachineIRBuilder &MIB) const {
  5998. MachineRegisterInfo &MRI = *MIB.getMRI();
  5999. auto Ty = MRI.getType(Reg);
  6000. assert(!Ty.isVector() && "Expected scalars only!");
  6001. if (Ty.getSizeInBits() == TRI.getRegSizeInBits(RC))
  6002. return Reg;
  6003. // Create a copy and immediately select it.
  6004. // FIXME: We should have an emitCopy function?
  6005. auto Copy = MIB.buildCopy({&RC}, {Reg});
  6006. selectCopy(*Copy, TII, MRI, TRI, RBI);
  6007. return Copy.getReg(0);
  6008. }
  6009. /// Select an "extended register" operand. This operand folds in an extend
  6010. /// followed by an optional left shift.
  6011. InstructionSelector::ComplexRendererFns
  6012. AArch64InstructionSelector::selectArithExtendedRegister(
  6013. MachineOperand &Root) const {
  6014. if (!Root.isReg())
  6015. return std::nullopt;
  6016. MachineRegisterInfo &MRI =
  6017. Root.getParent()->getParent()->getParent()->getRegInfo();
  6018. uint64_t ShiftVal = 0;
  6019. Register ExtReg;
  6020. AArch64_AM::ShiftExtendType Ext;
  6021. MachineInstr *RootDef = getDefIgnoringCopies(Root.getReg(), MRI);
  6022. if (!RootDef)
  6023. return std::nullopt;
  6024. if (!isWorthFoldingIntoExtendedReg(*RootDef, MRI))
  6025. return std::nullopt;
  6026. // Check if we can fold a shift and an extend.
  6027. if (RootDef->getOpcode() == TargetOpcode::G_SHL) {
  6028. // Look for a constant on the RHS of the shift.
  6029. MachineOperand &RHS = RootDef->getOperand(2);
  6030. std::optional<uint64_t> MaybeShiftVal = getImmedFromMO(RHS);
  6031. if (!MaybeShiftVal)
  6032. return std::nullopt;
  6033. ShiftVal = *MaybeShiftVal;
  6034. if (ShiftVal > 4)
  6035. return std::nullopt;
  6036. // Look for a valid extend instruction on the LHS of the shift.
  6037. MachineOperand &LHS = RootDef->getOperand(1);
  6038. MachineInstr *ExtDef = getDefIgnoringCopies(LHS.getReg(), MRI);
  6039. if (!ExtDef)
  6040. return std::nullopt;
  6041. Ext = getExtendTypeForInst(*ExtDef, MRI);
  6042. if (Ext == AArch64_AM::InvalidShiftExtend)
  6043. return std::nullopt;
  6044. ExtReg = ExtDef->getOperand(1).getReg();
  6045. } else {
  6046. // Didn't get a shift. Try just folding an extend.
  6047. Ext = getExtendTypeForInst(*RootDef, MRI);
  6048. if (Ext == AArch64_AM::InvalidShiftExtend)
  6049. return std::nullopt;
  6050. ExtReg = RootDef->getOperand(1).getReg();
  6051. // If we have a 32 bit instruction which zeroes out the high half of a
  6052. // register, we get an implicit zero extend for free. Check if we have one.
  6053. // FIXME: We actually emit the extend right now even though we don't have
  6054. // to.
  6055. if (Ext == AArch64_AM::UXTW && MRI.getType(ExtReg).getSizeInBits() == 32) {
  6056. MachineInstr *ExtInst = MRI.getVRegDef(ExtReg);
  6057. if (isDef32(*ExtInst))
  6058. return std::nullopt;
  6059. }
  6060. }
  6061. // We require a GPR32 here. Narrow the ExtReg if needed using a subregister
  6062. // copy.
  6063. MachineIRBuilder MIB(*RootDef);
  6064. ExtReg = moveScalarRegClass(ExtReg, AArch64::GPR32RegClass, MIB);
  6065. return {{[=](MachineInstrBuilder &MIB) { MIB.addUse(ExtReg); },
  6066. [=](MachineInstrBuilder &MIB) {
  6067. MIB.addImm(getArithExtendImm(Ext, ShiftVal));
  6068. }}};
  6069. }
  6070. void AArch64InstructionSelector::renderTruncImm(MachineInstrBuilder &MIB,
  6071. const MachineInstr &MI,
  6072. int OpIdx) const {
  6073. const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
  6074. assert(MI.getOpcode() == TargetOpcode::G_CONSTANT && OpIdx == -1 &&
  6075. "Expected G_CONSTANT");
  6076. std::optional<int64_t> CstVal =
  6077. getIConstantVRegSExtVal(MI.getOperand(0).getReg(), MRI);
  6078. assert(CstVal && "Expected constant value");
  6079. MIB.addImm(*CstVal);
  6080. }
  6081. void AArch64InstructionSelector::renderLogicalImm32(
  6082. MachineInstrBuilder &MIB, const MachineInstr &I, int OpIdx) const {
  6083. assert(I.getOpcode() == TargetOpcode::G_CONSTANT && OpIdx == -1 &&
  6084. "Expected G_CONSTANT");
  6085. uint64_t CstVal = I.getOperand(1).getCImm()->getZExtValue();
  6086. uint64_t Enc = AArch64_AM::encodeLogicalImmediate(CstVal, 32);
  6087. MIB.addImm(Enc);
  6088. }
  6089. void AArch64InstructionSelector::renderLogicalImm64(
  6090. MachineInstrBuilder &MIB, const MachineInstr &I, int OpIdx) const {
  6091. assert(I.getOpcode() == TargetOpcode::G_CONSTANT && OpIdx == -1 &&
  6092. "Expected G_CONSTANT");
  6093. uint64_t CstVal = I.getOperand(1).getCImm()->getZExtValue();
  6094. uint64_t Enc = AArch64_AM::encodeLogicalImmediate(CstVal, 64);
  6095. MIB.addImm(Enc);
  6096. }
  6097. void AArch64InstructionSelector::renderFPImm16(MachineInstrBuilder &MIB,
  6098. const MachineInstr &MI,
  6099. int OpIdx) const {
  6100. assert(MI.getOpcode() == TargetOpcode::G_FCONSTANT && OpIdx == -1 &&
  6101. "Expected G_FCONSTANT");
  6102. MIB.addImm(
  6103. AArch64_AM::getFP16Imm(MI.getOperand(1).getFPImm()->getValueAPF()));
  6104. }
  6105. void AArch64InstructionSelector::renderFPImm32(MachineInstrBuilder &MIB,
  6106. const MachineInstr &MI,
  6107. int OpIdx) const {
  6108. assert(MI.getOpcode() == TargetOpcode::G_FCONSTANT && OpIdx == -1 &&
  6109. "Expected G_FCONSTANT");
  6110. MIB.addImm(
  6111. AArch64_AM::getFP32Imm(MI.getOperand(1).getFPImm()->getValueAPF()));
  6112. }
  6113. void AArch64InstructionSelector::renderFPImm64(MachineInstrBuilder &MIB,
  6114. const MachineInstr &MI,
  6115. int OpIdx) const {
  6116. assert(MI.getOpcode() == TargetOpcode::G_FCONSTANT && OpIdx == -1 &&
  6117. "Expected G_FCONSTANT");
  6118. MIB.addImm(
  6119. AArch64_AM::getFP64Imm(MI.getOperand(1).getFPImm()->getValueAPF()));
  6120. }
  6121. void AArch64InstructionSelector::renderFPImm32SIMDModImmType4(
  6122. MachineInstrBuilder &MIB, const MachineInstr &MI, int OpIdx) const {
  6123. assert(MI.getOpcode() == TargetOpcode::G_FCONSTANT && OpIdx == -1 &&
  6124. "Expected G_FCONSTANT");
  6125. MIB.addImm(AArch64_AM::encodeAdvSIMDModImmType4(MI.getOperand(1)
  6126. .getFPImm()
  6127. ->getValueAPF()
  6128. .bitcastToAPInt()
  6129. .getZExtValue()));
  6130. }
  6131. bool AArch64InstructionSelector::isLoadStoreOfNumBytes(
  6132. const MachineInstr &MI, unsigned NumBytes) const {
  6133. if (!MI.mayLoadOrStore())
  6134. return false;
  6135. assert(MI.hasOneMemOperand() &&
  6136. "Expected load/store to have only one mem op!");
  6137. return (*MI.memoperands_begin())->getSize() == NumBytes;
  6138. }
  6139. bool AArch64InstructionSelector::isDef32(const MachineInstr &MI) const {
  6140. const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
  6141. if (MRI.getType(MI.getOperand(0).getReg()).getSizeInBits() != 32)
  6142. return false;
  6143. // Only return true if we know the operation will zero-out the high half of
  6144. // the 64-bit register. Truncates can be subregister copies, which don't
  6145. // zero out the high bits. Copies and other copy-like instructions can be
  6146. // fed by truncates, or could be lowered as subregister copies.
  6147. switch (MI.getOpcode()) {
  6148. default:
  6149. return true;
  6150. case TargetOpcode::COPY:
  6151. case TargetOpcode::G_BITCAST:
  6152. case TargetOpcode::G_TRUNC:
  6153. case TargetOpcode::G_PHI:
  6154. return false;
  6155. }
  6156. }
  6157. // Perform fixups on the given PHI instruction's operands to force them all
  6158. // to be the same as the destination regbank.
  6159. static void fixupPHIOpBanks(MachineInstr &MI, MachineRegisterInfo &MRI,
  6160. const AArch64RegisterBankInfo &RBI) {
  6161. assert(MI.getOpcode() == TargetOpcode::G_PHI && "Expected a G_PHI");
  6162. Register DstReg = MI.getOperand(0).getReg();
  6163. const RegisterBank *DstRB = MRI.getRegBankOrNull(DstReg);
  6164. assert(DstRB && "Expected PHI dst to have regbank assigned");
  6165. MachineIRBuilder MIB(MI);
  6166. // Go through each operand and ensure it has the same regbank.
  6167. for (MachineOperand &MO : llvm::drop_begin(MI.operands())) {
  6168. if (!MO.isReg())
  6169. continue;
  6170. Register OpReg = MO.getReg();
  6171. const RegisterBank *RB = MRI.getRegBankOrNull(OpReg);
  6172. if (RB != DstRB) {
  6173. // Insert a cross-bank copy.
  6174. auto *OpDef = MRI.getVRegDef(OpReg);
  6175. const LLT &Ty = MRI.getType(OpReg);
  6176. MachineBasicBlock &OpDefBB = *OpDef->getParent();
  6177. // Any instruction we insert must appear after all PHIs in the block
  6178. // for the block to be valid MIR.
  6179. MachineBasicBlock::iterator InsertPt = std::next(OpDef->getIterator());
  6180. if (InsertPt != OpDefBB.end() && InsertPt->isPHI())
  6181. InsertPt = OpDefBB.getFirstNonPHI();
  6182. MIB.setInsertPt(*OpDef->getParent(), InsertPt);
  6183. auto Copy = MIB.buildCopy(Ty, OpReg);
  6184. MRI.setRegBank(Copy.getReg(0), *DstRB);
  6185. MO.setReg(Copy.getReg(0));
  6186. }
  6187. }
  6188. }
  6189. void AArch64InstructionSelector::processPHIs(MachineFunction &MF) {
  6190. // We're looking for PHIs, build a list so we don't invalidate iterators.
  6191. MachineRegisterInfo &MRI = MF.getRegInfo();
  6192. SmallVector<MachineInstr *, 32> Phis;
  6193. for (auto &BB : MF) {
  6194. for (auto &MI : BB) {
  6195. if (MI.getOpcode() == TargetOpcode::G_PHI)
  6196. Phis.emplace_back(&MI);
  6197. }
  6198. }
  6199. for (auto *MI : Phis) {
  6200. // We need to do some work here if the operand types are < 16 bit and they
  6201. // are split across fpr/gpr banks. Since all types <32b on gpr
  6202. // end up being assigned gpr32 regclasses, we can end up with PHIs here
  6203. // which try to select between a gpr32 and an fpr16. Ideally RBS shouldn't
  6204. // be selecting heterogenous regbanks for operands if possible, but we
  6205. // still need to be able to deal with it here.
  6206. //
  6207. // To fix this, if we have a gpr-bank operand < 32b in size and at least
  6208. // one other operand is on the fpr bank, then we add cross-bank copies
  6209. // to homogenize the operand banks. For simplicity the bank that we choose
  6210. // to settle on is whatever bank the def operand has. For example:
  6211. //
  6212. // %endbb:
  6213. // %dst:gpr(s16) = G_PHI %in1:gpr(s16), %bb1, %in2:fpr(s16), %bb2
  6214. // =>
  6215. // %bb2:
  6216. // ...
  6217. // %in2_copy:gpr(s16) = COPY %in2:fpr(s16)
  6218. // ...
  6219. // %endbb:
  6220. // %dst:gpr(s16) = G_PHI %in1:gpr(s16), %bb1, %in2_copy:gpr(s16), %bb2
  6221. bool HasGPROp = false, HasFPROp = false;
  6222. for (const MachineOperand &MO : llvm::drop_begin(MI->operands())) {
  6223. if (!MO.isReg())
  6224. continue;
  6225. const LLT &Ty = MRI.getType(MO.getReg());
  6226. if (!Ty.isValid() || !Ty.isScalar())
  6227. break;
  6228. if (Ty.getSizeInBits() >= 32)
  6229. break;
  6230. const RegisterBank *RB = MRI.getRegBankOrNull(MO.getReg());
  6231. // If for some reason we don't have a regbank yet. Don't try anything.
  6232. if (!RB)
  6233. break;
  6234. if (RB->getID() == AArch64::GPRRegBankID)
  6235. HasGPROp = true;
  6236. else
  6237. HasFPROp = true;
  6238. }
  6239. // We have heterogenous regbanks, need to fixup.
  6240. if (HasGPROp && HasFPROp)
  6241. fixupPHIOpBanks(*MI, MRI, RBI);
  6242. }
  6243. }
  6244. namespace llvm {
  6245. InstructionSelector *
  6246. createAArch64InstructionSelector(const AArch64TargetMachine &TM,
  6247. AArch64Subtarget &Subtarget,
  6248. AArch64RegisterBankInfo &RBI) {
  6249. return new AArch64InstructionSelector(TM, Subtarget, RBI);
  6250. }
  6251. }