GlobalISelEmitter.cpp 231 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243
  1. //===- GlobalISelEmitter.cpp - Generate an instruction selector -----------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. /// \file
  10. /// This tablegen backend emits code for use by the GlobalISel instruction
  11. /// selector. See include/llvm/CodeGen/TargetGlobalISel.td.
  12. ///
  13. /// This file analyzes the patterns recognized by the SelectionDAGISel tablegen
  14. /// backend, filters out the ones that are unsupported, maps
  15. /// SelectionDAG-specific constructs to their GlobalISel counterpart
  16. /// (when applicable: MVT to LLT; SDNode to generic Instruction).
  17. ///
  18. /// Not all patterns are supported: pass the tablegen invocation
  19. /// "-warn-on-skipped-patterns" to emit a warning when a pattern is skipped,
  20. /// as well as why.
  21. ///
  22. /// The generated file defines a single method:
  23. /// bool <Target>InstructionSelector::selectImpl(MachineInstr &I) const;
  24. /// intended to be used in InstructionSelector::select as the first-step
  25. /// selector for the patterns that don't require complex C++.
  26. ///
  27. /// FIXME: We'll probably want to eventually define a base
  28. /// "TargetGenInstructionSelector" class.
  29. ///
  30. //===----------------------------------------------------------------------===//
  31. #include "CodeGenDAGPatterns.h"
  32. #include "SubtargetFeatureInfo.h"
  33. #include "llvm/ADT/Optional.h"
  34. #include "llvm/ADT/Statistic.h"
  35. #include "llvm/Support/CodeGenCoverage.h"
  36. #include "llvm/Support/CommandLine.h"
  37. #include "llvm/Support/Error.h"
  38. #include "llvm/Support/LowLevelTypeImpl.h"
  39. #include "llvm/Support/MachineValueType.h"
  40. #include "llvm/Support/ScopedPrinter.h"
  41. #include "llvm/TableGen/Error.h"
  42. #include "llvm/TableGen/Record.h"
  43. #include "llvm/TableGen/TableGenBackend.h"
  44. #include <numeric>
  45. #include <string>
  46. using namespace llvm;
  47. #define DEBUG_TYPE "gisel-emitter"
  48. STATISTIC(NumPatternTotal, "Total number of patterns");
  49. STATISTIC(NumPatternImported, "Number of patterns imported from SelectionDAG");
  50. STATISTIC(NumPatternImportsSkipped, "Number of SelectionDAG imports skipped");
  51. STATISTIC(NumPatternsTested, "Number of patterns executed according to coverage information");
  52. STATISTIC(NumPatternEmitted, "Number of patterns emitted");
  53. cl::OptionCategory GlobalISelEmitterCat("Options for -gen-global-isel");
  54. static cl::opt<bool> WarnOnSkippedPatterns(
  55. "warn-on-skipped-patterns",
  56. cl::desc("Explain why a pattern was skipped for inclusion "
  57. "in the GlobalISel selector"),
  58. cl::init(false), cl::cat(GlobalISelEmitterCat));
  59. static cl::opt<bool> GenerateCoverage(
  60. "instrument-gisel-coverage",
  61. cl::desc("Generate coverage instrumentation for GlobalISel"),
  62. cl::init(false), cl::cat(GlobalISelEmitterCat));
  63. static cl::opt<std::string> UseCoverageFile(
  64. "gisel-coverage-file", cl::init(""),
  65. cl::desc("Specify file to retrieve coverage information from"),
  66. cl::cat(GlobalISelEmitterCat));
  67. static cl::opt<bool> OptimizeMatchTable(
  68. "optimize-match-table",
  69. cl::desc("Generate an optimized version of the match table"),
  70. cl::init(true), cl::cat(GlobalISelEmitterCat));
  71. namespace {
  72. //===- Helper functions ---------------------------------------------------===//
  73. /// Get the name of the enum value used to number the predicate function.
  74. std::string getEnumNameForPredicate(const TreePredicateFn &Predicate) {
  75. if (Predicate.hasGISelPredicateCode())
  76. return "GIPFP_MI_" + Predicate.getFnName();
  77. return "GIPFP_" + Predicate.getImmTypeIdentifier().str() + "_" +
  78. Predicate.getFnName();
  79. }
  80. /// Get the opcode used to check this predicate.
  81. std::string getMatchOpcodeForImmPredicate(const TreePredicateFn &Predicate) {
  82. return "GIM_Check" + Predicate.getImmTypeIdentifier().str() + "ImmPredicate";
  83. }
  84. /// This class stands in for LLT wherever we want to tablegen-erate an
  85. /// equivalent at compiler run-time.
  86. class LLTCodeGen {
  87. private:
  88. LLT Ty;
  89. public:
  90. LLTCodeGen() = default;
  91. LLTCodeGen(const LLT &Ty) : Ty(Ty) {}
  92. std::string getCxxEnumValue() const {
  93. std::string Str;
  94. raw_string_ostream OS(Str);
  95. emitCxxEnumValue(OS);
  96. return Str;
  97. }
  98. void emitCxxEnumValue(raw_ostream &OS) const {
  99. if (Ty.isScalar()) {
  100. OS << "GILLT_s" << Ty.getSizeInBits();
  101. return;
  102. }
  103. if (Ty.isVector()) {
  104. OS << (Ty.isScalable() ? "GILLT_nxv" : "GILLT_v")
  105. << Ty.getElementCount().getKnownMinValue() << "s"
  106. << Ty.getScalarSizeInBits();
  107. return;
  108. }
  109. if (Ty.isPointer()) {
  110. OS << "GILLT_p" << Ty.getAddressSpace();
  111. if (Ty.getSizeInBits() > 0)
  112. OS << "s" << Ty.getSizeInBits();
  113. return;
  114. }
  115. llvm_unreachable("Unhandled LLT");
  116. }
  117. void emitCxxConstructorCall(raw_ostream &OS) const {
  118. if (Ty.isScalar()) {
  119. OS << "LLT::scalar(" << Ty.getSizeInBits() << ")";
  120. return;
  121. }
  122. if (Ty.isVector()) {
  123. OS << "LLT::vector("
  124. << (Ty.isScalable() ? "ElementCount::getScalable("
  125. : "ElementCount::getFixed(")
  126. << Ty.getElementCount().getKnownMinValue() << "), "
  127. << Ty.getScalarSizeInBits() << ")";
  128. return;
  129. }
  130. if (Ty.isPointer() && Ty.getSizeInBits() > 0) {
  131. OS << "LLT::pointer(" << Ty.getAddressSpace() << ", "
  132. << Ty.getSizeInBits() << ")";
  133. return;
  134. }
  135. llvm_unreachable("Unhandled LLT");
  136. }
  137. const LLT &get() const { return Ty; }
  138. /// This ordering is used for std::unique() and llvm::sort(). There's no
  139. /// particular logic behind the order but either A < B or B < A must be
  140. /// true if A != B.
  141. bool operator<(const LLTCodeGen &Other) const {
  142. if (Ty.isValid() != Other.Ty.isValid())
  143. return Ty.isValid() < Other.Ty.isValid();
  144. if (!Ty.isValid())
  145. return false;
  146. if (Ty.isVector() != Other.Ty.isVector())
  147. return Ty.isVector() < Other.Ty.isVector();
  148. if (Ty.isScalar() != Other.Ty.isScalar())
  149. return Ty.isScalar() < Other.Ty.isScalar();
  150. if (Ty.isPointer() != Other.Ty.isPointer())
  151. return Ty.isPointer() < Other.Ty.isPointer();
  152. if (Ty.isPointer() && Ty.getAddressSpace() != Other.Ty.getAddressSpace())
  153. return Ty.getAddressSpace() < Other.Ty.getAddressSpace();
  154. if (Ty.isVector() && Ty.getElementCount() != Other.Ty.getElementCount())
  155. return std::make_tuple(Ty.isScalable(),
  156. Ty.getElementCount().getKnownMinValue()) <
  157. std::make_tuple(Other.Ty.isScalable(),
  158. Other.Ty.getElementCount().getKnownMinValue());
  159. assert((!Ty.isVector() || Ty.isScalable() == Other.Ty.isScalable()) &&
  160. "Unexpected mismatch of scalable property");
  161. return Ty.isVector()
  162. ? std::make_tuple(Ty.isScalable(),
  163. Ty.getSizeInBits().getKnownMinSize()) <
  164. std::make_tuple(Other.Ty.isScalable(),
  165. Other.Ty.getSizeInBits().getKnownMinSize())
  166. : Ty.getSizeInBits().getFixedSize() <
  167. Other.Ty.getSizeInBits().getFixedSize();
  168. }
  169. bool operator==(const LLTCodeGen &B) const { return Ty == B.Ty; }
  170. };
  171. // Track all types that are used so we can emit the corresponding enum.
  172. std::set<LLTCodeGen> KnownTypes;
  173. class InstructionMatcher;
  174. /// Convert an MVT to an equivalent LLT if possible, or the invalid LLT() for
  175. /// MVTs that don't map cleanly to an LLT (e.g., iPTR, *any, ...).
  176. static Optional<LLTCodeGen> MVTToLLT(MVT::SimpleValueType SVT) {
  177. MVT VT(SVT);
  178. if (VT.isVector() && !VT.getVectorElementCount().isScalar())
  179. return LLTCodeGen(
  180. LLT::vector(VT.getVectorElementCount(), VT.getScalarSizeInBits()));
  181. if (VT.isInteger() || VT.isFloatingPoint())
  182. return LLTCodeGen(LLT::scalar(VT.getSizeInBits()));
  183. return None;
  184. }
  185. static std::string explainPredicates(const TreePatternNode *N) {
  186. std::string Explanation;
  187. StringRef Separator = "";
  188. for (const TreePredicateCall &Call : N->getPredicateCalls()) {
  189. const TreePredicateFn &P = Call.Fn;
  190. Explanation +=
  191. (Separator + P.getOrigPatFragRecord()->getRecord()->getName()).str();
  192. Separator = ", ";
  193. if (P.isAlwaysTrue())
  194. Explanation += " always-true";
  195. if (P.isImmediatePattern())
  196. Explanation += " immediate";
  197. if (P.isUnindexed())
  198. Explanation += " unindexed";
  199. if (P.isNonExtLoad())
  200. Explanation += " non-extload";
  201. if (P.isAnyExtLoad())
  202. Explanation += " extload";
  203. if (P.isSignExtLoad())
  204. Explanation += " sextload";
  205. if (P.isZeroExtLoad())
  206. Explanation += " zextload";
  207. if (P.isNonTruncStore())
  208. Explanation += " non-truncstore";
  209. if (P.isTruncStore())
  210. Explanation += " truncstore";
  211. if (Record *VT = P.getMemoryVT())
  212. Explanation += (" MemVT=" + VT->getName()).str();
  213. if (Record *VT = P.getScalarMemoryVT())
  214. Explanation += (" ScalarVT(MemVT)=" + VT->getName()).str();
  215. if (ListInit *AddrSpaces = P.getAddressSpaces()) {
  216. raw_string_ostream OS(Explanation);
  217. OS << " AddressSpaces=[";
  218. StringRef AddrSpaceSeparator;
  219. for (Init *Val : AddrSpaces->getValues()) {
  220. IntInit *IntVal = dyn_cast<IntInit>(Val);
  221. if (!IntVal)
  222. continue;
  223. OS << AddrSpaceSeparator << IntVal->getValue();
  224. AddrSpaceSeparator = ", ";
  225. }
  226. OS << ']';
  227. }
  228. int64_t MinAlign = P.getMinAlignment();
  229. if (MinAlign > 0)
  230. Explanation += " MinAlign=" + utostr(MinAlign);
  231. if (P.isAtomicOrderingMonotonic())
  232. Explanation += " monotonic";
  233. if (P.isAtomicOrderingAcquire())
  234. Explanation += " acquire";
  235. if (P.isAtomicOrderingRelease())
  236. Explanation += " release";
  237. if (P.isAtomicOrderingAcquireRelease())
  238. Explanation += " acq_rel";
  239. if (P.isAtomicOrderingSequentiallyConsistent())
  240. Explanation += " seq_cst";
  241. if (P.isAtomicOrderingAcquireOrStronger())
  242. Explanation += " >=acquire";
  243. if (P.isAtomicOrderingWeakerThanAcquire())
  244. Explanation += " <acquire";
  245. if (P.isAtomicOrderingReleaseOrStronger())
  246. Explanation += " >=release";
  247. if (P.isAtomicOrderingWeakerThanRelease())
  248. Explanation += " <release";
  249. }
  250. return Explanation;
  251. }
  252. std::string explainOperator(Record *Operator) {
  253. if (Operator->isSubClassOf("SDNode"))
  254. return (" (" + Operator->getValueAsString("Opcode") + ")").str();
  255. if (Operator->isSubClassOf("Intrinsic"))
  256. return (" (Operator is an Intrinsic, " + Operator->getName() + ")").str();
  257. if (Operator->isSubClassOf("ComplexPattern"))
  258. return (" (Operator is an unmapped ComplexPattern, " + Operator->getName() +
  259. ")")
  260. .str();
  261. if (Operator->isSubClassOf("SDNodeXForm"))
  262. return (" (Operator is an unmapped SDNodeXForm, " + Operator->getName() +
  263. ")")
  264. .str();
  265. return (" (Operator " + Operator->getName() + " not understood)").str();
  266. }
  267. /// Helper function to let the emitter report skip reason error messages.
  268. static Error failedImport(const Twine &Reason) {
  269. return make_error<StringError>(Reason, inconvertibleErrorCode());
  270. }
  271. static Error isTrivialOperatorNode(const TreePatternNode *N) {
  272. std::string Explanation;
  273. std::string Separator;
  274. bool HasUnsupportedPredicate = false;
  275. for (const TreePredicateCall &Call : N->getPredicateCalls()) {
  276. const TreePredicateFn &Predicate = Call.Fn;
  277. if (Predicate.isAlwaysTrue())
  278. continue;
  279. if (Predicate.isImmediatePattern())
  280. continue;
  281. if (Predicate.isNonExtLoad() || Predicate.isAnyExtLoad() ||
  282. Predicate.isSignExtLoad() || Predicate.isZeroExtLoad())
  283. continue;
  284. if (Predicate.isNonTruncStore() || Predicate.isTruncStore())
  285. continue;
  286. if (Predicate.isLoad() && Predicate.getMemoryVT())
  287. continue;
  288. if (Predicate.isLoad() || Predicate.isStore()) {
  289. if (Predicate.isUnindexed())
  290. continue;
  291. }
  292. if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
  293. const ListInit *AddrSpaces = Predicate.getAddressSpaces();
  294. if (AddrSpaces && !AddrSpaces->empty())
  295. continue;
  296. if (Predicate.getMinAlignment() > 0)
  297. continue;
  298. }
  299. if (Predicate.isAtomic() && Predicate.getMemoryVT())
  300. continue;
  301. if (Predicate.isAtomic() &&
  302. (Predicate.isAtomicOrderingMonotonic() ||
  303. Predicate.isAtomicOrderingAcquire() ||
  304. Predicate.isAtomicOrderingRelease() ||
  305. Predicate.isAtomicOrderingAcquireRelease() ||
  306. Predicate.isAtomicOrderingSequentiallyConsistent() ||
  307. Predicate.isAtomicOrderingAcquireOrStronger() ||
  308. Predicate.isAtomicOrderingWeakerThanAcquire() ||
  309. Predicate.isAtomicOrderingReleaseOrStronger() ||
  310. Predicate.isAtomicOrderingWeakerThanRelease()))
  311. continue;
  312. if (Predicate.hasGISelPredicateCode())
  313. continue;
  314. HasUnsupportedPredicate = true;
  315. Explanation = Separator + "Has a predicate (" + explainPredicates(N) + ")";
  316. Separator = ", ";
  317. Explanation += (Separator + "first-failing:" +
  318. Predicate.getOrigPatFragRecord()->getRecord()->getName())
  319. .str();
  320. break;
  321. }
  322. if (!HasUnsupportedPredicate)
  323. return Error::success();
  324. return failedImport(Explanation);
  325. }
  326. static Record *getInitValueAsRegClass(Init *V) {
  327. if (DefInit *VDefInit = dyn_cast<DefInit>(V)) {
  328. if (VDefInit->getDef()->isSubClassOf("RegisterOperand"))
  329. return VDefInit->getDef()->getValueAsDef("RegClass");
  330. if (VDefInit->getDef()->isSubClassOf("RegisterClass"))
  331. return VDefInit->getDef();
  332. }
  333. return nullptr;
  334. }
  335. std::string
  336. getNameForFeatureBitset(const std::vector<Record *> &FeatureBitset) {
  337. std::string Name = "GIFBS";
  338. for (const auto &Feature : FeatureBitset)
  339. Name += ("_" + Feature->getName()).str();
  340. return Name;
  341. }
  342. static std::string getScopedName(unsigned Scope, const std::string &Name) {
  343. return ("pred:" + Twine(Scope) + ":" + Name).str();
  344. }
  345. //===- MatchTable Helpers -------------------------------------------------===//
  346. class MatchTable;
  347. /// A record to be stored in a MatchTable.
  348. ///
  349. /// This class represents any and all output that may be required to emit the
  350. /// MatchTable. Instances are most often configured to represent an opcode or
  351. /// value that will be emitted to the table with some formatting but it can also
  352. /// represent commas, comments, and other formatting instructions.
  353. struct MatchTableRecord {
  354. enum RecordFlagsBits {
  355. MTRF_None = 0x0,
  356. /// Causes EmitStr to be formatted as comment when emitted.
  357. MTRF_Comment = 0x1,
  358. /// Causes the record value to be followed by a comma when emitted.
  359. MTRF_CommaFollows = 0x2,
  360. /// Causes the record value to be followed by a line break when emitted.
  361. MTRF_LineBreakFollows = 0x4,
  362. /// Indicates that the record defines a label and causes an additional
  363. /// comment to be emitted containing the index of the label.
  364. MTRF_Label = 0x8,
  365. /// Causes the record to be emitted as the index of the label specified by
  366. /// LabelID along with a comment indicating where that label is.
  367. MTRF_JumpTarget = 0x10,
  368. /// Causes the formatter to add a level of indentation before emitting the
  369. /// record.
  370. MTRF_Indent = 0x20,
  371. /// Causes the formatter to remove a level of indentation after emitting the
  372. /// record.
  373. MTRF_Outdent = 0x40,
  374. };
  375. /// When MTRF_Label or MTRF_JumpTarget is used, indicates a label id to
  376. /// reference or define.
  377. unsigned LabelID;
  378. /// The string to emit. Depending on the MTRF_* flags it may be a comment, a
  379. /// value, a label name.
  380. std::string EmitStr;
  381. private:
  382. /// The number of MatchTable elements described by this record. Comments are 0
  383. /// while values are typically 1. Values >1 may occur when we need to emit
  384. /// values that exceed the size of a MatchTable element.
  385. unsigned NumElements;
  386. public:
  387. /// A bitfield of RecordFlagsBits flags.
  388. unsigned Flags;
  389. /// The actual run-time value, if known
  390. int64_t RawValue;
  391. MatchTableRecord(Optional<unsigned> LabelID_, StringRef EmitStr,
  392. unsigned NumElements, unsigned Flags,
  393. int64_t RawValue = std::numeric_limits<int64_t>::min())
  394. : LabelID(LabelID_.getValueOr(~0u)), EmitStr(EmitStr),
  395. NumElements(NumElements), Flags(Flags), RawValue(RawValue) {
  396. assert((!LabelID_.hasValue() || LabelID != ~0u) &&
  397. "This value is reserved for non-labels");
  398. }
  399. MatchTableRecord(const MatchTableRecord &Other) = default;
  400. MatchTableRecord(MatchTableRecord &&Other) = default;
  401. /// Useful if a Match Table Record gets optimized out
  402. void turnIntoComment() {
  403. Flags |= MTRF_Comment;
  404. Flags &= ~MTRF_CommaFollows;
  405. NumElements = 0;
  406. }
  407. /// For Jump Table generation purposes
  408. bool operator<(const MatchTableRecord &Other) const {
  409. return RawValue < Other.RawValue;
  410. }
  411. int64_t getRawValue() const { return RawValue; }
  412. void emit(raw_ostream &OS, bool LineBreakNextAfterThis,
  413. const MatchTable &Table) const;
  414. unsigned size() const { return NumElements; }
  415. };
  416. class Matcher;
  417. /// Holds the contents of a generated MatchTable to enable formatting and the
  418. /// necessary index tracking needed to support GIM_Try.
  419. class MatchTable {
  420. /// An unique identifier for the table. The generated table will be named
  421. /// MatchTable${ID}.
  422. unsigned ID;
  423. /// The records that make up the table. Also includes comments describing the
  424. /// values being emitted and line breaks to format it.
  425. std::vector<MatchTableRecord> Contents;
  426. /// The currently defined labels.
  427. DenseMap<unsigned, unsigned> LabelMap;
  428. /// Tracks the sum of MatchTableRecord::NumElements as the table is built.
  429. unsigned CurrentSize = 0;
  430. /// A unique identifier for a MatchTable label.
  431. unsigned CurrentLabelID = 0;
  432. /// Determines if the table should be instrumented for rule coverage tracking.
  433. bool IsWithCoverage;
  434. public:
  435. static MatchTableRecord LineBreak;
  436. static MatchTableRecord Comment(StringRef Comment) {
  437. return MatchTableRecord(None, Comment, 0, MatchTableRecord::MTRF_Comment);
  438. }
  439. static MatchTableRecord Opcode(StringRef Opcode, int IndentAdjust = 0) {
  440. unsigned ExtraFlags = 0;
  441. if (IndentAdjust > 0)
  442. ExtraFlags |= MatchTableRecord::MTRF_Indent;
  443. if (IndentAdjust < 0)
  444. ExtraFlags |= MatchTableRecord::MTRF_Outdent;
  445. return MatchTableRecord(None, Opcode, 1,
  446. MatchTableRecord::MTRF_CommaFollows | ExtraFlags);
  447. }
  448. static MatchTableRecord NamedValue(StringRef NamedValue) {
  449. return MatchTableRecord(None, NamedValue, 1,
  450. MatchTableRecord::MTRF_CommaFollows);
  451. }
  452. static MatchTableRecord NamedValue(StringRef NamedValue, int64_t RawValue) {
  453. return MatchTableRecord(None, NamedValue, 1,
  454. MatchTableRecord::MTRF_CommaFollows, RawValue);
  455. }
  456. static MatchTableRecord NamedValue(StringRef Namespace,
  457. StringRef NamedValue) {
  458. return MatchTableRecord(None, (Namespace + "::" + NamedValue).str(), 1,
  459. MatchTableRecord::MTRF_CommaFollows);
  460. }
  461. static MatchTableRecord NamedValue(StringRef Namespace, StringRef NamedValue,
  462. int64_t RawValue) {
  463. return MatchTableRecord(None, (Namespace + "::" + NamedValue).str(), 1,
  464. MatchTableRecord::MTRF_CommaFollows, RawValue);
  465. }
  466. static MatchTableRecord IntValue(int64_t IntValue) {
  467. return MatchTableRecord(None, llvm::to_string(IntValue), 1,
  468. MatchTableRecord::MTRF_CommaFollows);
  469. }
  470. static MatchTableRecord Label(unsigned LabelID) {
  471. return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 0,
  472. MatchTableRecord::MTRF_Label |
  473. MatchTableRecord::MTRF_Comment |
  474. MatchTableRecord::MTRF_LineBreakFollows);
  475. }
  476. static MatchTableRecord JumpTarget(unsigned LabelID) {
  477. return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 1,
  478. MatchTableRecord::MTRF_JumpTarget |
  479. MatchTableRecord::MTRF_Comment |
  480. MatchTableRecord::MTRF_CommaFollows);
  481. }
  482. static MatchTable buildTable(ArrayRef<Matcher *> Rules, bool WithCoverage);
  483. MatchTable(bool WithCoverage, unsigned ID = 0)
  484. : ID(ID), IsWithCoverage(WithCoverage) {}
  485. bool isWithCoverage() const { return IsWithCoverage; }
  486. void push_back(const MatchTableRecord &Value) {
  487. if (Value.Flags & MatchTableRecord::MTRF_Label)
  488. defineLabel(Value.LabelID);
  489. Contents.push_back(Value);
  490. CurrentSize += Value.size();
  491. }
  492. unsigned allocateLabelID() { return CurrentLabelID++; }
  493. void defineLabel(unsigned LabelID) {
  494. LabelMap.insert(std::make_pair(LabelID, CurrentSize));
  495. }
  496. unsigned getLabelIndex(unsigned LabelID) const {
  497. const auto I = LabelMap.find(LabelID);
  498. assert(I != LabelMap.end() && "Use of undeclared label");
  499. return I->second;
  500. }
  501. void emitUse(raw_ostream &OS) const { OS << "MatchTable" << ID; }
  502. void emitDeclaration(raw_ostream &OS) const {
  503. unsigned Indentation = 4;
  504. OS << " constexpr static int64_t MatchTable" << ID << "[] = {";
  505. LineBreak.emit(OS, true, *this);
  506. OS << std::string(Indentation, ' ');
  507. for (auto I = Contents.begin(), E = Contents.end(); I != E;
  508. ++I) {
  509. bool LineBreakIsNext = false;
  510. const auto &NextI = std::next(I);
  511. if (NextI != E) {
  512. if (NextI->EmitStr == "" &&
  513. NextI->Flags == MatchTableRecord::MTRF_LineBreakFollows)
  514. LineBreakIsNext = true;
  515. }
  516. if (I->Flags & MatchTableRecord::MTRF_Indent)
  517. Indentation += 2;
  518. I->emit(OS, LineBreakIsNext, *this);
  519. if (I->Flags & MatchTableRecord::MTRF_LineBreakFollows)
  520. OS << std::string(Indentation, ' ');
  521. if (I->Flags & MatchTableRecord::MTRF_Outdent)
  522. Indentation -= 2;
  523. }
  524. OS << "};\n";
  525. }
  526. };
  527. MatchTableRecord MatchTable::LineBreak = {
  528. None, "" /* Emit String */, 0 /* Elements */,
  529. MatchTableRecord::MTRF_LineBreakFollows};
  530. void MatchTableRecord::emit(raw_ostream &OS, bool LineBreakIsNextAfterThis,
  531. const MatchTable &Table) const {
  532. bool UseLineComment =
  533. LineBreakIsNextAfterThis || (Flags & MTRF_LineBreakFollows);
  534. if (Flags & (MTRF_JumpTarget | MTRF_CommaFollows))
  535. UseLineComment = false;
  536. if (Flags & MTRF_Comment)
  537. OS << (UseLineComment ? "// " : "/*");
  538. OS << EmitStr;
  539. if (Flags & MTRF_Label)
  540. OS << ": @" << Table.getLabelIndex(LabelID);
  541. if ((Flags & MTRF_Comment) && !UseLineComment)
  542. OS << "*/";
  543. if (Flags & MTRF_JumpTarget) {
  544. if (Flags & MTRF_Comment)
  545. OS << " ";
  546. OS << Table.getLabelIndex(LabelID);
  547. }
  548. if (Flags & MTRF_CommaFollows) {
  549. OS << ",";
  550. if (!LineBreakIsNextAfterThis && !(Flags & MTRF_LineBreakFollows))
  551. OS << " ";
  552. }
  553. if (Flags & MTRF_LineBreakFollows)
  554. OS << "\n";
  555. }
  556. MatchTable &operator<<(MatchTable &Table, const MatchTableRecord &Value) {
  557. Table.push_back(Value);
  558. return Table;
  559. }
  560. //===- Matchers -----------------------------------------------------------===//
  561. class OperandMatcher;
  562. class MatchAction;
  563. class PredicateMatcher;
  564. class Matcher {
  565. public:
  566. virtual ~Matcher() = default;
  567. virtual void optimize() {}
  568. virtual void emit(MatchTable &Table) = 0;
  569. virtual bool hasFirstCondition() const = 0;
  570. virtual const PredicateMatcher &getFirstCondition() const = 0;
  571. virtual std::unique_ptr<PredicateMatcher> popFirstCondition() = 0;
  572. };
  573. MatchTable MatchTable::buildTable(ArrayRef<Matcher *> Rules,
  574. bool WithCoverage) {
  575. MatchTable Table(WithCoverage);
  576. for (Matcher *Rule : Rules)
  577. Rule->emit(Table);
  578. return Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
  579. }
  580. class GroupMatcher final : public Matcher {
  581. /// Conditions that form a common prefix of all the matchers contained.
  582. SmallVector<std::unique_ptr<PredicateMatcher>, 1> Conditions;
  583. /// All the nested matchers, sharing a common prefix.
  584. std::vector<Matcher *> Matchers;
  585. /// An owning collection for any auxiliary matchers created while optimizing
  586. /// nested matchers contained.
  587. std::vector<std::unique_ptr<Matcher>> MatcherStorage;
  588. public:
  589. /// Add a matcher to the collection of nested matchers if it meets the
  590. /// requirements, and return true. If it doesn't, do nothing and return false.
  591. ///
  592. /// Expected to preserve its argument, so it could be moved out later on.
  593. bool addMatcher(Matcher &Candidate);
  594. /// Mark the matcher as fully-built and ensure any invariants expected by both
  595. /// optimize() and emit(...) methods. Generally, both sequences of calls
  596. /// are expected to lead to a sensible result:
  597. ///
  598. /// addMatcher(...)*; finalize(); optimize(); emit(...); and
  599. /// addMatcher(...)*; finalize(); emit(...);
  600. ///
  601. /// or generally
  602. ///
  603. /// addMatcher(...)*; finalize(); { optimize()*; emit(...); }*
  604. ///
  605. /// Multiple calls to optimize() are expected to be handled gracefully, though
  606. /// optimize() is not expected to be idempotent. Multiple calls to finalize()
  607. /// aren't generally supported. emit(...) is expected to be non-mutating and
  608. /// producing the exact same results upon repeated calls.
  609. ///
  610. /// addMatcher() calls after the finalize() call are not supported.
  611. ///
  612. /// finalize() and optimize() are both allowed to mutate the contained
  613. /// matchers, so moving them out after finalize() is not supported.
  614. void finalize();
  615. void optimize() override;
  616. void emit(MatchTable &Table) override;
  617. /// Could be used to move out the matchers added previously, unless finalize()
  618. /// has been already called. If any of the matchers are moved out, the group
  619. /// becomes safe to destroy, but not safe to re-use for anything else.
  620. iterator_range<std::vector<Matcher *>::iterator> matchers() {
  621. return make_range(Matchers.begin(), Matchers.end());
  622. }
  623. size_t size() const { return Matchers.size(); }
  624. bool empty() const { return Matchers.empty(); }
  625. std::unique_ptr<PredicateMatcher> popFirstCondition() override {
  626. assert(!Conditions.empty() &&
  627. "Trying to pop a condition from a condition-less group");
  628. std::unique_ptr<PredicateMatcher> P = std::move(Conditions.front());
  629. Conditions.erase(Conditions.begin());
  630. return P;
  631. }
  632. const PredicateMatcher &getFirstCondition() const override {
  633. assert(!Conditions.empty() &&
  634. "Trying to get a condition from a condition-less group");
  635. return *Conditions.front();
  636. }
  637. bool hasFirstCondition() const override { return !Conditions.empty(); }
  638. private:
  639. /// See if a candidate matcher could be added to this group solely by
  640. /// analyzing its first condition.
  641. bool candidateConditionMatches(const PredicateMatcher &Predicate) const;
  642. };
  643. class SwitchMatcher : public Matcher {
  644. /// All the nested matchers, representing distinct switch-cases. The first
  645. /// conditions (as Matcher::getFirstCondition() reports) of all the nested
  646. /// matchers must share the same type and path to a value they check, in other
  647. /// words, be isIdenticalDownToValue, but have different values they check
  648. /// against.
  649. std::vector<Matcher *> Matchers;
  650. /// The representative condition, with a type and a path (InsnVarID and OpIdx
  651. /// in most cases) shared by all the matchers contained.
  652. std::unique_ptr<PredicateMatcher> Condition = nullptr;
  653. /// Temporary set used to check that the case values don't repeat within the
  654. /// same switch.
  655. std::set<MatchTableRecord> Values;
  656. /// An owning collection for any auxiliary matchers created while optimizing
  657. /// nested matchers contained.
  658. std::vector<std::unique_ptr<Matcher>> MatcherStorage;
  659. public:
  660. bool addMatcher(Matcher &Candidate);
  661. void finalize();
  662. void emit(MatchTable &Table) override;
  663. iterator_range<std::vector<Matcher *>::iterator> matchers() {
  664. return make_range(Matchers.begin(), Matchers.end());
  665. }
  666. size_t size() const { return Matchers.size(); }
  667. bool empty() const { return Matchers.empty(); }
  668. std::unique_ptr<PredicateMatcher> popFirstCondition() override {
  669. // SwitchMatcher doesn't have a common first condition for its cases, as all
  670. // the cases only share a kind of a value (a type and a path to it) they
  671. // match, but deliberately differ in the actual value they match.
  672. llvm_unreachable("Trying to pop a condition from a condition-less group");
  673. }
  674. const PredicateMatcher &getFirstCondition() const override {
  675. llvm_unreachable("Trying to pop a condition from a condition-less group");
  676. }
  677. bool hasFirstCondition() const override { return false; }
  678. private:
  679. /// See if the predicate type has a Switch-implementation for it.
  680. static bool isSupportedPredicateType(const PredicateMatcher &Predicate);
  681. bool candidateConditionMatches(const PredicateMatcher &Predicate) const;
  682. /// emit()-helper
  683. static void emitPredicateSpecificOpcodes(const PredicateMatcher &P,
  684. MatchTable &Table);
  685. };
  686. /// Generates code to check that a match rule matches.
  687. class RuleMatcher : public Matcher {
  688. public:
  689. using ActionList = std::list<std::unique_ptr<MatchAction>>;
  690. using action_iterator = ActionList::iterator;
  691. protected:
  692. /// A list of matchers that all need to succeed for the current rule to match.
  693. /// FIXME: This currently supports a single match position but could be
  694. /// extended to support multiple positions to support div/rem fusion or
  695. /// load-multiple instructions.
  696. using MatchersTy = std::vector<std::unique_ptr<InstructionMatcher>> ;
  697. MatchersTy Matchers;
  698. /// A list of actions that need to be taken when all predicates in this rule
  699. /// have succeeded.
  700. ActionList Actions;
  701. using DefinedInsnVariablesMap = std::map<InstructionMatcher *, unsigned>;
  702. /// A map of instruction matchers to the local variables
  703. DefinedInsnVariablesMap InsnVariableIDs;
  704. using MutatableInsnSet = SmallPtrSet<InstructionMatcher *, 4>;
  705. // The set of instruction matchers that have not yet been claimed for mutation
  706. // by a BuildMI.
  707. MutatableInsnSet MutatableInsns;
  708. /// A map of named operands defined by the matchers that may be referenced by
  709. /// the renderers.
  710. StringMap<OperandMatcher *> DefinedOperands;
  711. /// A map of anonymous physical register operands defined by the matchers that
  712. /// may be referenced by the renderers.
  713. DenseMap<Record *, OperandMatcher *> PhysRegOperands;
  714. /// ID for the next instruction variable defined with implicitlyDefineInsnVar()
  715. unsigned NextInsnVarID;
  716. /// ID for the next output instruction allocated with allocateOutputInsnID()
  717. unsigned NextOutputInsnID;
  718. /// ID for the next temporary register ID allocated with allocateTempRegID()
  719. unsigned NextTempRegID;
  720. std::vector<Record *> RequiredFeatures;
  721. std::vector<std::unique_ptr<PredicateMatcher>> EpilogueMatchers;
  722. ArrayRef<SMLoc> SrcLoc;
  723. typedef std::tuple<Record *, unsigned, unsigned>
  724. DefinedComplexPatternSubOperand;
  725. typedef StringMap<DefinedComplexPatternSubOperand>
  726. DefinedComplexPatternSubOperandMap;
  727. /// A map of Symbolic Names to ComplexPattern sub-operands.
  728. DefinedComplexPatternSubOperandMap ComplexSubOperands;
  729. /// A map used to for multiple referenced error check of ComplexSubOperand.
  730. /// ComplexSubOperand can't be referenced multiple from different operands,
  731. /// however multiple references from same operand are allowed since that is
  732. /// how 'same operand checks' are generated.
  733. StringMap<std::string> ComplexSubOperandsParentName;
  734. uint64_t RuleID;
  735. static uint64_t NextRuleID;
  736. public:
  737. RuleMatcher(ArrayRef<SMLoc> SrcLoc)
  738. : NextInsnVarID(0), NextOutputInsnID(0), NextTempRegID(0), SrcLoc(SrcLoc),
  739. RuleID(NextRuleID++) {}
  740. RuleMatcher(RuleMatcher &&Other) = default;
  741. RuleMatcher &operator=(RuleMatcher &&Other) = default;
  742. uint64_t getRuleID() const { return RuleID; }
  743. InstructionMatcher &addInstructionMatcher(StringRef SymbolicName);
  744. void addRequiredFeature(Record *Feature);
  745. const std::vector<Record *> &getRequiredFeatures() const;
  746. template <class Kind, class... Args> Kind &addAction(Args &&... args);
  747. template <class Kind, class... Args>
  748. action_iterator insertAction(action_iterator InsertPt, Args &&... args);
  749. /// Define an instruction without emitting any code to do so.
  750. unsigned implicitlyDefineInsnVar(InstructionMatcher &Matcher);
  751. unsigned getInsnVarID(InstructionMatcher &InsnMatcher) const;
  752. DefinedInsnVariablesMap::const_iterator defined_insn_vars_begin() const {
  753. return InsnVariableIDs.begin();
  754. }
  755. DefinedInsnVariablesMap::const_iterator defined_insn_vars_end() const {
  756. return InsnVariableIDs.end();
  757. }
  758. iterator_range<typename DefinedInsnVariablesMap::const_iterator>
  759. defined_insn_vars() const {
  760. return make_range(defined_insn_vars_begin(), defined_insn_vars_end());
  761. }
  762. MutatableInsnSet::const_iterator mutatable_insns_begin() const {
  763. return MutatableInsns.begin();
  764. }
  765. MutatableInsnSet::const_iterator mutatable_insns_end() const {
  766. return MutatableInsns.end();
  767. }
  768. iterator_range<typename MutatableInsnSet::const_iterator>
  769. mutatable_insns() const {
  770. return make_range(mutatable_insns_begin(), mutatable_insns_end());
  771. }
  772. void reserveInsnMatcherForMutation(InstructionMatcher *InsnMatcher) {
  773. bool R = MutatableInsns.erase(InsnMatcher);
  774. assert(R && "Reserving a mutatable insn that isn't available");
  775. (void)R;
  776. }
  777. action_iterator actions_begin() { return Actions.begin(); }
  778. action_iterator actions_end() { return Actions.end(); }
  779. iterator_range<action_iterator> actions() {
  780. return make_range(actions_begin(), actions_end());
  781. }
  782. void defineOperand(StringRef SymbolicName, OperandMatcher &OM);
  783. void definePhysRegOperand(Record *Reg, OperandMatcher &OM);
  784. Error defineComplexSubOperand(StringRef SymbolicName, Record *ComplexPattern,
  785. unsigned RendererID, unsigned SubOperandID,
  786. StringRef ParentSymbolicName) {
  787. std::string ParentName(ParentSymbolicName);
  788. if (ComplexSubOperands.count(SymbolicName)) {
  789. const std::string &RecordedParentName =
  790. ComplexSubOperandsParentName[SymbolicName];
  791. if (RecordedParentName != ParentName)
  792. return failedImport("Error: Complex suboperand " + SymbolicName +
  793. " referenced by different operands: " +
  794. RecordedParentName + " and " + ParentName + ".");
  795. // Complex suboperand referenced more than once from same the operand is
  796. // used to generate 'same operand check'. Emitting of
  797. // GIR_ComplexSubOperandRenderer for them is already handled.
  798. return Error::success();
  799. }
  800. ComplexSubOperands[SymbolicName] =
  801. std::make_tuple(ComplexPattern, RendererID, SubOperandID);
  802. ComplexSubOperandsParentName[SymbolicName] = ParentName;
  803. return Error::success();
  804. }
  805. Optional<DefinedComplexPatternSubOperand>
  806. getComplexSubOperand(StringRef SymbolicName) const {
  807. const auto &I = ComplexSubOperands.find(SymbolicName);
  808. if (I == ComplexSubOperands.end())
  809. return None;
  810. return I->second;
  811. }
  812. InstructionMatcher &getInstructionMatcher(StringRef SymbolicName) const;
  813. const OperandMatcher &getOperandMatcher(StringRef Name) const;
  814. const OperandMatcher &getPhysRegOperandMatcher(Record *) const;
  815. void optimize() override;
  816. void emit(MatchTable &Table) override;
  817. /// Compare the priority of this object and B.
  818. ///
  819. /// Returns true if this object is more important than B.
  820. bool isHigherPriorityThan(const RuleMatcher &B) const;
  821. /// Report the maximum number of temporary operands needed by the rule
  822. /// matcher.
  823. unsigned countRendererFns() const;
  824. std::unique_ptr<PredicateMatcher> popFirstCondition() override;
  825. const PredicateMatcher &getFirstCondition() const override;
  826. LLTCodeGen getFirstConditionAsRootType();
  827. bool hasFirstCondition() const override;
  828. unsigned getNumOperands() const;
  829. StringRef getOpcode() const;
  830. // FIXME: Remove this as soon as possible
  831. InstructionMatcher &insnmatchers_front() const { return *Matchers.front(); }
  832. unsigned allocateOutputInsnID() { return NextOutputInsnID++; }
  833. unsigned allocateTempRegID() { return NextTempRegID++; }
  834. iterator_range<MatchersTy::iterator> insnmatchers() {
  835. return make_range(Matchers.begin(), Matchers.end());
  836. }
  837. bool insnmatchers_empty() const { return Matchers.empty(); }
  838. void insnmatchers_pop_front() { Matchers.erase(Matchers.begin()); }
  839. };
  840. uint64_t RuleMatcher::NextRuleID = 0;
  841. using action_iterator = RuleMatcher::action_iterator;
  842. template <class PredicateTy> class PredicateListMatcher {
  843. private:
  844. /// Template instantiations should specialize this to return a string to use
  845. /// for the comment emitted when there are no predicates.
  846. std::string getNoPredicateComment() const;
  847. protected:
  848. using PredicatesTy = std::deque<std::unique_ptr<PredicateTy>>;
  849. PredicatesTy Predicates;
  850. /// Track if the list of predicates was manipulated by one of the optimization
  851. /// methods.
  852. bool Optimized = false;
  853. public:
  854. typename PredicatesTy::iterator predicates_begin() {
  855. return Predicates.begin();
  856. }
  857. typename PredicatesTy::iterator predicates_end() {
  858. return Predicates.end();
  859. }
  860. iterator_range<typename PredicatesTy::iterator> predicates() {
  861. return make_range(predicates_begin(), predicates_end());
  862. }
  863. typename PredicatesTy::size_type predicates_size() const {
  864. return Predicates.size();
  865. }
  866. bool predicates_empty() const { return Predicates.empty(); }
  867. std::unique_ptr<PredicateTy> predicates_pop_front() {
  868. std::unique_ptr<PredicateTy> Front = std::move(Predicates.front());
  869. Predicates.pop_front();
  870. Optimized = true;
  871. return Front;
  872. }
  873. void prependPredicate(std::unique_ptr<PredicateTy> &&Predicate) {
  874. Predicates.push_front(std::move(Predicate));
  875. }
  876. void eraseNullPredicates() {
  877. const auto NewEnd =
  878. std::stable_partition(Predicates.begin(), Predicates.end(),
  879. std::logical_not<std::unique_ptr<PredicateTy>>());
  880. if (NewEnd != Predicates.begin()) {
  881. Predicates.erase(Predicates.begin(), NewEnd);
  882. Optimized = true;
  883. }
  884. }
  885. /// Emit MatchTable opcodes that tests whether all the predicates are met.
  886. template <class... Args>
  887. void emitPredicateListOpcodes(MatchTable &Table, Args &&... args) {
  888. if (Predicates.empty() && !Optimized) {
  889. Table << MatchTable::Comment(getNoPredicateComment())
  890. << MatchTable::LineBreak;
  891. return;
  892. }
  893. for (const auto &Predicate : predicates())
  894. Predicate->emitPredicateOpcodes(Table, std::forward<Args>(args)...);
  895. }
  896. /// Provide a function to avoid emitting certain predicates. This is used to
  897. /// defer some predicate checks until after others
  898. using PredicateFilterFunc = std::function<bool(const PredicateTy&)>;
  899. /// Emit MatchTable opcodes for predicates which satisfy \p
  900. /// ShouldEmitPredicate. This should be called multiple times to ensure all
  901. /// predicates are eventually added to the match table.
  902. template <class... Args>
  903. void emitFilteredPredicateListOpcodes(PredicateFilterFunc ShouldEmitPredicate,
  904. MatchTable &Table, Args &&... args) {
  905. if (Predicates.empty() && !Optimized) {
  906. Table << MatchTable::Comment(getNoPredicateComment())
  907. << MatchTable::LineBreak;
  908. return;
  909. }
  910. for (const auto &Predicate : predicates()) {
  911. if (ShouldEmitPredicate(*Predicate))
  912. Predicate->emitPredicateOpcodes(Table, std::forward<Args>(args)...);
  913. }
  914. }
  915. };
  916. class PredicateMatcher {
  917. public:
  918. /// This enum is used for RTTI and also defines the priority that is given to
  919. /// the predicate when generating the matcher code. Kinds with higher priority
  920. /// must be tested first.
  921. ///
  922. /// The relative priority of OPM_LLT, OPM_RegBank, and OPM_MBB do not matter
  923. /// but OPM_Int must have priority over OPM_RegBank since constant integers
  924. /// are represented by a virtual register defined by a G_CONSTANT instruction.
  925. ///
  926. /// Note: The relative priority between IPM_ and OPM_ does not matter, they
  927. /// are currently not compared between each other.
  928. enum PredicateKind {
  929. IPM_Opcode,
  930. IPM_NumOperands,
  931. IPM_ImmPredicate,
  932. IPM_Imm,
  933. IPM_AtomicOrderingMMO,
  934. IPM_MemoryLLTSize,
  935. IPM_MemoryVsLLTSize,
  936. IPM_MemoryAddressSpace,
  937. IPM_MemoryAlignment,
  938. IPM_VectorSplatImm,
  939. IPM_GenericPredicate,
  940. OPM_SameOperand,
  941. OPM_ComplexPattern,
  942. OPM_IntrinsicID,
  943. OPM_CmpPredicate,
  944. OPM_Instruction,
  945. OPM_Int,
  946. OPM_LiteralInt,
  947. OPM_LLT,
  948. OPM_PointerToAny,
  949. OPM_RegBank,
  950. OPM_MBB,
  951. OPM_RecordNamedOperand,
  952. };
  953. protected:
  954. PredicateKind Kind;
  955. unsigned InsnVarID;
  956. unsigned OpIdx;
  957. public:
  958. PredicateMatcher(PredicateKind Kind, unsigned InsnVarID, unsigned OpIdx = ~0)
  959. : Kind(Kind), InsnVarID(InsnVarID), OpIdx(OpIdx) {}
  960. unsigned getInsnVarID() const { return InsnVarID; }
  961. unsigned getOpIdx() const { return OpIdx; }
  962. virtual ~PredicateMatcher() = default;
  963. /// Emit MatchTable opcodes that check the predicate for the given operand.
  964. virtual void emitPredicateOpcodes(MatchTable &Table,
  965. RuleMatcher &Rule) const = 0;
  966. PredicateKind getKind() const { return Kind; }
  967. bool dependsOnOperands() const {
  968. // Custom predicates really depend on the context pattern of the
  969. // instruction, not just the individual instruction. This therefore
  970. // implicitly depends on all other pattern constraints.
  971. return Kind == IPM_GenericPredicate;
  972. }
  973. virtual bool isIdentical(const PredicateMatcher &B) const {
  974. return B.getKind() == getKind() && InsnVarID == B.InsnVarID &&
  975. OpIdx == B.OpIdx;
  976. }
  977. virtual bool isIdenticalDownToValue(const PredicateMatcher &B) const {
  978. return hasValue() && PredicateMatcher::isIdentical(B);
  979. }
  980. virtual MatchTableRecord getValue() const {
  981. assert(hasValue() && "Can not get a value of a value-less predicate!");
  982. llvm_unreachable("Not implemented yet");
  983. }
  984. virtual bool hasValue() const { return false; }
  985. /// Report the maximum number of temporary operands needed by the predicate
  986. /// matcher.
  987. virtual unsigned countRendererFns() const { return 0; }
  988. };
  989. /// Generates code to check a predicate of an operand.
  990. ///
  991. /// Typical predicates include:
  992. /// * Operand is a particular register.
  993. /// * Operand is assigned a particular register bank.
  994. /// * Operand is an MBB.
  995. class OperandPredicateMatcher : public PredicateMatcher {
  996. public:
  997. OperandPredicateMatcher(PredicateKind Kind, unsigned InsnVarID,
  998. unsigned OpIdx)
  999. : PredicateMatcher(Kind, InsnVarID, OpIdx) {}
  1000. virtual ~OperandPredicateMatcher() {}
  1001. /// Compare the priority of this object and B.
  1002. ///
  1003. /// Returns true if this object is more important than B.
  1004. virtual bool isHigherPriorityThan(const OperandPredicateMatcher &B) const;
  1005. };
  1006. template <>
  1007. std::string
  1008. PredicateListMatcher<OperandPredicateMatcher>::getNoPredicateComment() const {
  1009. return "No operand predicates";
  1010. }
  1011. /// Generates code to check that a register operand is defined by the same exact
  1012. /// one as another.
  1013. class SameOperandMatcher : public OperandPredicateMatcher {
  1014. std::string MatchingName;
  1015. unsigned OrigOpIdx;
  1016. public:
  1017. SameOperandMatcher(unsigned InsnVarID, unsigned OpIdx, StringRef MatchingName,
  1018. unsigned OrigOpIdx)
  1019. : OperandPredicateMatcher(OPM_SameOperand, InsnVarID, OpIdx),
  1020. MatchingName(MatchingName), OrigOpIdx(OrigOpIdx) {}
  1021. static bool classof(const PredicateMatcher *P) {
  1022. return P->getKind() == OPM_SameOperand;
  1023. }
  1024. void emitPredicateOpcodes(MatchTable &Table,
  1025. RuleMatcher &Rule) const override;
  1026. bool isIdentical(const PredicateMatcher &B) const override {
  1027. return OperandPredicateMatcher::isIdentical(B) &&
  1028. OrigOpIdx == cast<SameOperandMatcher>(&B)->OrigOpIdx &&
  1029. MatchingName == cast<SameOperandMatcher>(&B)->MatchingName;
  1030. }
  1031. };
  1032. /// Generates code to check that an operand is a particular LLT.
  1033. class LLTOperandMatcher : public OperandPredicateMatcher {
  1034. protected:
  1035. LLTCodeGen Ty;
  1036. public:
  1037. static std::map<LLTCodeGen, unsigned> TypeIDValues;
  1038. static void initTypeIDValuesMap() {
  1039. TypeIDValues.clear();
  1040. unsigned ID = 0;
  1041. for (const LLTCodeGen &LLTy : KnownTypes)
  1042. TypeIDValues[LLTy] = ID++;
  1043. }
  1044. LLTOperandMatcher(unsigned InsnVarID, unsigned OpIdx, const LLTCodeGen &Ty)
  1045. : OperandPredicateMatcher(OPM_LLT, InsnVarID, OpIdx), Ty(Ty) {
  1046. KnownTypes.insert(Ty);
  1047. }
  1048. static bool classof(const PredicateMatcher *P) {
  1049. return P->getKind() == OPM_LLT;
  1050. }
  1051. bool isIdentical(const PredicateMatcher &B) const override {
  1052. return OperandPredicateMatcher::isIdentical(B) &&
  1053. Ty == cast<LLTOperandMatcher>(&B)->Ty;
  1054. }
  1055. MatchTableRecord getValue() const override {
  1056. const auto VI = TypeIDValues.find(Ty);
  1057. if (VI == TypeIDValues.end())
  1058. return MatchTable::NamedValue(getTy().getCxxEnumValue());
  1059. return MatchTable::NamedValue(getTy().getCxxEnumValue(), VI->second);
  1060. }
  1061. bool hasValue() const override {
  1062. if (TypeIDValues.size() != KnownTypes.size())
  1063. initTypeIDValuesMap();
  1064. return TypeIDValues.count(Ty);
  1065. }
  1066. LLTCodeGen getTy() const { return Ty; }
  1067. void emitPredicateOpcodes(MatchTable &Table,
  1068. RuleMatcher &Rule) const override {
  1069. Table << MatchTable::Opcode("GIM_CheckType") << MatchTable::Comment("MI")
  1070. << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
  1071. << MatchTable::IntValue(OpIdx) << MatchTable::Comment("Type")
  1072. << getValue() << MatchTable::LineBreak;
  1073. }
  1074. };
  1075. std::map<LLTCodeGen, unsigned> LLTOperandMatcher::TypeIDValues;
  1076. /// Generates code to check that an operand is a pointer to any address space.
  1077. ///
  1078. /// In SelectionDAG, the types did not describe pointers or address spaces. As a
  1079. /// result, iN is used to describe a pointer of N bits to any address space and
  1080. /// PatFrag predicates are typically used to constrain the address space. There's
  1081. /// no reliable means to derive the missing type information from the pattern so
  1082. /// imported rules must test the components of a pointer separately.
  1083. ///
  1084. /// If SizeInBits is zero, then the pointer size will be obtained from the
  1085. /// subtarget.
  1086. class PointerToAnyOperandMatcher : public OperandPredicateMatcher {
  1087. protected:
  1088. unsigned SizeInBits;
  1089. public:
  1090. PointerToAnyOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
  1091. unsigned SizeInBits)
  1092. : OperandPredicateMatcher(OPM_PointerToAny, InsnVarID, OpIdx),
  1093. SizeInBits(SizeInBits) {}
  1094. static bool classof(const PredicateMatcher *P) {
  1095. return P->getKind() == OPM_PointerToAny;
  1096. }
  1097. bool isIdentical(const PredicateMatcher &B) const override {
  1098. return OperandPredicateMatcher::isIdentical(B) &&
  1099. SizeInBits == cast<PointerToAnyOperandMatcher>(&B)->SizeInBits;
  1100. }
  1101. void emitPredicateOpcodes(MatchTable &Table,
  1102. RuleMatcher &Rule) const override {
  1103. Table << MatchTable::Opcode("GIM_CheckPointerToAny")
  1104. << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
  1105. << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
  1106. << MatchTable::Comment("SizeInBits")
  1107. << MatchTable::IntValue(SizeInBits) << MatchTable::LineBreak;
  1108. }
  1109. };
  1110. /// Generates code to record named operand in RecordedOperands list at StoreIdx.
  1111. /// Predicates with 'let PredicateCodeUsesOperands = 1' get RecordedOperands as
  1112. /// an argument to predicate's c++ code once all operands have been matched.
  1113. class RecordNamedOperandMatcher : public OperandPredicateMatcher {
  1114. protected:
  1115. unsigned StoreIdx;
  1116. std::string Name;
  1117. public:
  1118. RecordNamedOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
  1119. unsigned StoreIdx, StringRef Name)
  1120. : OperandPredicateMatcher(OPM_RecordNamedOperand, InsnVarID, OpIdx),
  1121. StoreIdx(StoreIdx), Name(Name) {}
  1122. static bool classof(const PredicateMatcher *P) {
  1123. return P->getKind() == OPM_RecordNamedOperand;
  1124. }
  1125. bool isIdentical(const PredicateMatcher &B) const override {
  1126. return OperandPredicateMatcher::isIdentical(B) &&
  1127. StoreIdx == cast<RecordNamedOperandMatcher>(&B)->StoreIdx &&
  1128. Name == cast<RecordNamedOperandMatcher>(&B)->Name;
  1129. }
  1130. void emitPredicateOpcodes(MatchTable &Table,
  1131. RuleMatcher &Rule) const override {
  1132. Table << MatchTable::Opcode("GIM_RecordNamedOperand")
  1133. << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
  1134. << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
  1135. << MatchTable::Comment("StoreIdx") << MatchTable::IntValue(StoreIdx)
  1136. << MatchTable::Comment("Name : " + Name) << MatchTable::LineBreak;
  1137. }
  1138. };
  1139. /// Generates code to check that an operand is a particular target constant.
  1140. class ComplexPatternOperandMatcher : public OperandPredicateMatcher {
  1141. protected:
  1142. const OperandMatcher &Operand;
  1143. const Record &TheDef;
  1144. unsigned getAllocatedTemporariesBaseID() const;
  1145. public:
  1146. bool isIdentical(const PredicateMatcher &B) const override { return false; }
  1147. ComplexPatternOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
  1148. const OperandMatcher &Operand,
  1149. const Record &TheDef)
  1150. : OperandPredicateMatcher(OPM_ComplexPattern, InsnVarID, OpIdx),
  1151. Operand(Operand), TheDef(TheDef) {}
  1152. static bool classof(const PredicateMatcher *P) {
  1153. return P->getKind() == OPM_ComplexPattern;
  1154. }
  1155. void emitPredicateOpcodes(MatchTable &Table,
  1156. RuleMatcher &Rule) const override {
  1157. unsigned ID = getAllocatedTemporariesBaseID();
  1158. Table << MatchTable::Opcode("GIM_CheckComplexPattern")
  1159. << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
  1160. << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
  1161. << MatchTable::Comment("Renderer") << MatchTable::IntValue(ID)
  1162. << MatchTable::NamedValue(("GICP_" + TheDef.getName()).str())
  1163. << MatchTable::LineBreak;
  1164. }
  1165. unsigned countRendererFns() const override {
  1166. return 1;
  1167. }
  1168. };
  1169. /// Generates code to check that an operand is in a particular register bank.
  1170. class RegisterBankOperandMatcher : public OperandPredicateMatcher {
  1171. protected:
  1172. const CodeGenRegisterClass &RC;
  1173. public:
  1174. RegisterBankOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
  1175. const CodeGenRegisterClass &RC)
  1176. : OperandPredicateMatcher(OPM_RegBank, InsnVarID, OpIdx), RC(RC) {}
  1177. bool isIdentical(const PredicateMatcher &B) const override {
  1178. return OperandPredicateMatcher::isIdentical(B) &&
  1179. RC.getDef() == cast<RegisterBankOperandMatcher>(&B)->RC.getDef();
  1180. }
  1181. static bool classof(const PredicateMatcher *P) {
  1182. return P->getKind() == OPM_RegBank;
  1183. }
  1184. void emitPredicateOpcodes(MatchTable &Table,
  1185. RuleMatcher &Rule) const override {
  1186. Table << MatchTable::Opcode("GIM_CheckRegBankForClass")
  1187. << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
  1188. << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
  1189. << MatchTable::Comment("RC")
  1190. << MatchTable::NamedValue(RC.getQualifiedName() + "RegClassID")
  1191. << MatchTable::LineBreak;
  1192. }
  1193. };
  1194. /// Generates code to check that an operand is a basic block.
  1195. class MBBOperandMatcher : public OperandPredicateMatcher {
  1196. public:
  1197. MBBOperandMatcher(unsigned InsnVarID, unsigned OpIdx)
  1198. : OperandPredicateMatcher(OPM_MBB, InsnVarID, OpIdx) {}
  1199. static bool classof(const PredicateMatcher *P) {
  1200. return P->getKind() == OPM_MBB;
  1201. }
  1202. void emitPredicateOpcodes(MatchTable &Table,
  1203. RuleMatcher &Rule) const override {
  1204. Table << MatchTable::Opcode("GIM_CheckIsMBB") << MatchTable::Comment("MI")
  1205. << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
  1206. << MatchTable::IntValue(OpIdx) << MatchTable::LineBreak;
  1207. }
  1208. };
  1209. class ImmOperandMatcher : public OperandPredicateMatcher {
  1210. public:
  1211. ImmOperandMatcher(unsigned InsnVarID, unsigned OpIdx)
  1212. : OperandPredicateMatcher(IPM_Imm, InsnVarID, OpIdx) {}
  1213. static bool classof(const PredicateMatcher *P) {
  1214. return P->getKind() == IPM_Imm;
  1215. }
  1216. void emitPredicateOpcodes(MatchTable &Table,
  1217. RuleMatcher &Rule) const override {
  1218. Table << MatchTable::Opcode("GIM_CheckIsImm") << MatchTable::Comment("MI")
  1219. << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
  1220. << MatchTable::IntValue(OpIdx) << MatchTable::LineBreak;
  1221. }
  1222. };
  1223. /// Generates code to check that an operand is a G_CONSTANT with a particular
  1224. /// int.
  1225. class ConstantIntOperandMatcher : public OperandPredicateMatcher {
  1226. protected:
  1227. int64_t Value;
  1228. public:
  1229. ConstantIntOperandMatcher(unsigned InsnVarID, unsigned OpIdx, int64_t Value)
  1230. : OperandPredicateMatcher(OPM_Int, InsnVarID, OpIdx), Value(Value) {}
  1231. bool isIdentical(const PredicateMatcher &B) const override {
  1232. return OperandPredicateMatcher::isIdentical(B) &&
  1233. Value == cast<ConstantIntOperandMatcher>(&B)->Value;
  1234. }
  1235. static bool classof(const PredicateMatcher *P) {
  1236. return P->getKind() == OPM_Int;
  1237. }
  1238. void emitPredicateOpcodes(MatchTable &Table,
  1239. RuleMatcher &Rule) const override {
  1240. Table << MatchTable::Opcode("GIM_CheckConstantInt")
  1241. << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
  1242. << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
  1243. << MatchTable::IntValue(Value) << MatchTable::LineBreak;
  1244. }
  1245. };
  1246. /// Generates code to check that an operand is a raw int (where MO.isImm() or
  1247. /// MO.isCImm() is true).
  1248. class LiteralIntOperandMatcher : public OperandPredicateMatcher {
  1249. protected:
  1250. int64_t Value;
  1251. public:
  1252. LiteralIntOperandMatcher(unsigned InsnVarID, unsigned OpIdx, int64_t Value)
  1253. : OperandPredicateMatcher(OPM_LiteralInt, InsnVarID, OpIdx),
  1254. Value(Value) {}
  1255. bool isIdentical(const PredicateMatcher &B) const override {
  1256. return OperandPredicateMatcher::isIdentical(B) &&
  1257. Value == cast<LiteralIntOperandMatcher>(&B)->Value;
  1258. }
  1259. static bool classof(const PredicateMatcher *P) {
  1260. return P->getKind() == OPM_LiteralInt;
  1261. }
  1262. void emitPredicateOpcodes(MatchTable &Table,
  1263. RuleMatcher &Rule) const override {
  1264. Table << MatchTable::Opcode("GIM_CheckLiteralInt")
  1265. << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
  1266. << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
  1267. << MatchTable::IntValue(Value) << MatchTable::LineBreak;
  1268. }
  1269. };
  1270. /// Generates code to check that an operand is an CmpInst predicate
  1271. class CmpPredicateOperandMatcher : public OperandPredicateMatcher {
  1272. protected:
  1273. std::string PredName;
  1274. public:
  1275. CmpPredicateOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
  1276. std::string P)
  1277. : OperandPredicateMatcher(OPM_CmpPredicate, InsnVarID, OpIdx), PredName(P) {}
  1278. bool isIdentical(const PredicateMatcher &B) const override {
  1279. return OperandPredicateMatcher::isIdentical(B) &&
  1280. PredName == cast<CmpPredicateOperandMatcher>(&B)->PredName;
  1281. }
  1282. static bool classof(const PredicateMatcher *P) {
  1283. return P->getKind() == OPM_CmpPredicate;
  1284. }
  1285. void emitPredicateOpcodes(MatchTable &Table,
  1286. RuleMatcher &Rule) const override {
  1287. Table << MatchTable::Opcode("GIM_CheckCmpPredicate")
  1288. << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
  1289. << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
  1290. << MatchTable::Comment("Predicate")
  1291. << MatchTable::NamedValue("CmpInst", PredName)
  1292. << MatchTable::LineBreak;
  1293. }
  1294. };
  1295. /// Generates code to check that an operand is an intrinsic ID.
  1296. class IntrinsicIDOperandMatcher : public OperandPredicateMatcher {
  1297. protected:
  1298. const CodeGenIntrinsic *II;
  1299. public:
  1300. IntrinsicIDOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
  1301. const CodeGenIntrinsic *II)
  1302. : OperandPredicateMatcher(OPM_IntrinsicID, InsnVarID, OpIdx), II(II) {}
  1303. bool isIdentical(const PredicateMatcher &B) const override {
  1304. return OperandPredicateMatcher::isIdentical(B) &&
  1305. II == cast<IntrinsicIDOperandMatcher>(&B)->II;
  1306. }
  1307. static bool classof(const PredicateMatcher *P) {
  1308. return P->getKind() == OPM_IntrinsicID;
  1309. }
  1310. void emitPredicateOpcodes(MatchTable &Table,
  1311. RuleMatcher &Rule) const override {
  1312. Table << MatchTable::Opcode("GIM_CheckIntrinsicID")
  1313. << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
  1314. << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
  1315. << MatchTable::NamedValue("Intrinsic::" + II->EnumName)
  1316. << MatchTable::LineBreak;
  1317. }
  1318. };
  1319. /// Generates code to check that this operand is an immediate whose value meets
  1320. /// an immediate predicate.
  1321. class OperandImmPredicateMatcher : public OperandPredicateMatcher {
  1322. protected:
  1323. TreePredicateFn Predicate;
  1324. public:
  1325. OperandImmPredicateMatcher(unsigned InsnVarID, unsigned OpIdx,
  1326. const TreePredicateFn &Predicate)
  1327. : OperandPredicateMatcher(IPM_ImmPredicate, InsnVarID, OpIdx),
  1328. Predicate(Predicate) {}
  1329. bool isIdentical(const PredicateMatcher &B) const override {
  1330. return OperandPredicateMatcher::isIdentical(B) &&
  1331. Predicate.getOrigPatFragRecord() ==
  1332. cast<OperandImmPredicateMatcher>(&B)
  1333. ->Predicate.getOrigPatFragRecord();
  1334. }
  1335. static bool classof(const PredicateMatcher *P) {
  1336. return P->getKind() == IPM_ImmPredicate;
  1337. }
  1338. void emitPredicateOpcodes(MatchTable &Table,
  1339. RuleMatcher &Rule) const override {
  1340. Table << MatchTable::Opcode("GIM_CheckImmOperandPredicate")
  1341. << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
  1342. << MatchTable::Comment("MO") << MatchTable::IntValue(OpIdx)
  1343. << MatchTable::Comment("Predicate")
  1344. << MatchTable::NamedValue(getEnumNameForPredicate(Predicate))
  1345. << MatchTable::LineBreak;
  1346. }
  1347. };
  1348. /// Generates code to check that a set of predicates match for a particular
  1349. /// operand.
  1350. class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> {
  1351. protected:
  1352. InstructionMatcher &Insn;
  1353. unsigned OpIdx;
  1354. std::string SymbolicName;
  1355. /// The index of the first temporary variable allocated to this operand. The
  1356. /// number of allocated temporaries can be found with
  1357. /// countRendererFns().
  1358. unsigned AllocatedTemporariesBaseID;
  1359. public:
  1360. OperandMatcher(InstructionMatcher &Insn, unsigned OpIdx,
  1361. const std::string &SymbolicName,
  1362. unsigned AllocatedTemporariesBaseID)
  1363. : Insn(Insn), OpIdx(OpIdx), SymbolicName(SymbolicName),
  1364. AllocatedTemporariesBaseID(AllocatedTemporariesBaseID) {}
  1365. bool hasSymbolicName() const { return !SymbolicName.empty(); }
  1366. StringRef getSymbolicName() const { return SymbolicName; }
  1367. void setSymbolicName(StringRef Name) {
  1368. assert(SymbolicName.empty() && "Operand already has a symbolic name");
  1369. SymbolicName = std::string(Name);
  1370. }
  1371. /// Construct a new operand predicate and add it to the matcher.
  1372. template <class Kind, class... Args>
  1373. Optional<Kind *> addPredicate(Args &&... args) {
  1374. if (isSameAsAnotherOperand())
  1375. return None;
  1376. Predicates.emplace_back(std::make_unique<Kind>(
  1377. getInsnVarID(), getOpIdx(), std::forward<Args>(args)...));
  1378. return static_cast<Kind *>(Predicates.back().get());
  1379. }
  1380. unsigned getOpIdx() const { return OpIdx; }
  1381. unsigned getInsnVarID() const;
  1382. std::string getOperandExpr(unsigned InsnVarID) const {
  1383. return "State.MIs[" + llvm::to_string(InsnVarID) + "]->getOperand(" +
  1384. llvm::to_string(OpIdx) + ")";
  1385. }
  1386. InstructionMatcher &getInstructionMatcher() const { return Insn; }
  1387. Error addTypeCheckPredicate(const TypeSetByHwMode &VTy,
  1388. bool OperandIsAPointer);
  1389. /// Emit MatchTable opcodes that test whether the instruction named in
  1390. /// InsnVarID matches all the predicates and all the operands.
  1391. void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule) {
  1392. if (!Optimized) {
  1393. std::string Comment;
  1394. raw_string_ostream CommentOS(Comment);
  1395. CommentOS << "MIs[" << getInsnVarID() << "] ";
  1396. if (SymbolicName.empty())
  1397. CommentOS << "Operand " << OpIdx;
  1398. else
  1399. CommentOS << SymbolicName;
  1400. Table << MatchTable::Comment(Comment) << MatchTable::LineBreak;
  1401. }
  1402. emitPredicateListOpcodes(Table, Rule);
  1403. }
  1404. /// Compare the priority of this object and B.
  1405. ///
  1406. /// Returns true if this object is more important than B.
  1407. bool isHigherPriorityThan(OperandMatcher &B) {
  1408. // Operand matchers involving more predicates have higher priority.
  1409. if (predicates_size() > B.predicates_size())
  1410. return true;
  1411. if (predicates_size() < B.predicates_size())
  1412. return false;
  1413. // This assumes that predicates are added in a consistent order.
  1414. for (auto &&Predicate : zip(predicates(), B.predicates())) {
  1415. if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
  1416. return true;
  1417. if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
  1418. return false;
  1419. }
  1420. return false;
  1421. };
  1422. /// Report the maximum number of temporary operands needed by the operand
  1423. /// matcher.
  1424. unsigned countRendererFns() {
  1425. return std::accumulate(
  1426. predicates().begin(), predicates().end(), 0,
  1427. [](unsigned A,
  1428. const std::unique_ptr<OperandPredicateMatcher> &Predicate) {
  1429. return A + Predicate->countRendererFns();
  1430. });
  1431. }
  1432. unsigned getAllocatedTemporariesBaseID() const {
  1433. return AllocatedTemporariesBaseID;
  1434. }
  1435. bool isSameAsAnotherOperand() {
  1436. for (const auto &Predicate : predicates())
  1437. if (isa<SameOperandMatcher>(Predicate))
  1438. return true;
  1439. return false;
  1440. }
  1441. };
  1442. Error OperandMatcher::addTypeCheckPredicate(const TypeSetByHwMode &VTy,
  1443. bool OperandIsAPointer) {
  1444. if (!VTy.isMachineValueType())
  1445. return failedImport("unsupported typeset");
  1446. if (VTy.getMachineValueType() == MVT::iPTR && OperandIsAPointer) {
  1447. addPredicate<PointerToAnyOperandMatcher>(0);
  1448. return Error::success();
  1449. }
  1450. auto OpTyOrNone = MVTToLLT(VTy.getMachineValueType().SimpleTy);
  1451. if (!OpTyOrNone)
  1452. return failedImport("unsupported type");
  1453. if (OperandIsAPointer)
  1454. addPredicate<PointerToAnyOperandMatcher>(OpTyOrNone->get().getSizeInBits());
  1455. else if (VTy.isPointer())
  1456. addPredicate<LLTOperandMatcher>(LLT::pointer(VTy.getPtrAddrSpace(),
  1457. OpTyOrNone->get().getSizeInBits()));
  1458. else
  1459. addPredicate<LLTOperandMatcher>(*OpTyOrNone);
  1460. return Error::success();
  1461. }
  1462. unsigned ComplexPatternOperandMatcher::getAllocatedTemporariesBaseID() const {
  1463. return Operand.getAllocatedTemporariesBaseID();
  1464. }
  1465. /// Generates code to check a predicate on an instruction.
  1466. ///
  1467. /// Typical predicates include:
  1468. /// * The opcode of the instruction is a particular value.
  1469. /// * The nsw/nuw flag is/isn't set.
  1470. class InstructionPredicateMatcher : public PredicateMatcher {
  1471. public:
  1472. InstructionPredicateMatcher(PredicateKind Kind, unsigned InsnVarID)
  1473. : PredicateMatcher(Kind, InsnVarID) {}
  1474. virtual ~InstructionPredicateMatcher() {}
  1475. /// Compare the priority of this object and B.
  1476. ///
  1477. /// Returns true if this object is more important than B.
  1478. virtual bool
  1479. isHigherPriorityThan(const InstructionPredicateMatcher &B) const {
  1480. return Kind < B.Kind;
  1481. };
  1482. };
  1483. template <>
  1484. std::string
  1485. PredicateListMatcher<PredicateMatcher>::getNoPredicateComment() const {
  1486. return "No instruction predicates";
  1487. }
  1488. /// Generates code to check the opcode of an instruction.
  1489. class InstructionOpcodeMatcher : public InstructionPredicateMatcher {
  1490. protected:
  1491. // Allow matching one to several, similar opcodes that share properties. This
  1492. // is to handle patterns where one SelectionDAG operation maps to multiple
  1493. // GlobalISel ones (e.g. G_BUILD_VECTOR and G_BUILD_VECTOR_TRUNC). The first
  1494. // is treated as the canonical opcode.
  1495. SmallVector<const CodeGenInstruction *, 2> Insts;
  1496. static DenseMap<const CodeGenInstruction *, unsigned> OpcodeValues;
  1497. MatchTableRecord getInstValue(const CodeGenInstruction *I) const {
  1498. const auto VI = OpcodeValues.find(I);
  1499. if (VI != OpcodeValues.end())
  1500. return MatchTable::NamedValue(I->Namespace, I->TheDef->getName(),
  1501. VI->second);
  1502. return MatchTable::NamedValue(I->Namespace, I->TheDef->getName());
  1503. }
  1504. public:
  1505. static void initOpcodeValuesMap(const CodeGenTarget &Target) {
  1506. OpcodeValues.clear();
  1507. unsigned OpcodeValue = 0;
  1508. for (const CodeGenInstruction *I : Target.getInstructionsByEnumValue())
  1509. OpcodeValues[I] = OpcodeValue++;
  1510. }
  1511. InstructionOpcodeMatcher(unsigned InsnVarID,
  1512. ArrayRef<const CodeGenInstruction *> I)
  1513. : InstructionPredicateMatcher(IPM_Opcode, InsnVarID),
  1514. Insts(I.begin(), I.end()) {
  1515. assert((Insts.size() == 1 || Insts.size() == 2) &&
  1516. "unexpected number of opcode alternatives");
  1517. }
  1518. static bool classof(const PredicateMatcher *P) {
  1519. return P->getKind() == IPM_Opcode;
  1520. }
  1521. bool isIdentical(const PredicateMatcher &B) const override {
  1522. return InstructionPredicateMatcher::isIdentical(B) &&
  1523. Insts == cast<InstructionOpcodeMatcher>(&B)->Insts;
  1524. }
  1525. bool hasValue() const override {
  1526. return Insts.size() == 1 && OpcodeValues.count(Insts[0]);
  1527. }
  1528. // TODO: This is used for the SwitchMatcher optimization. We should be able to
  1529. // return a list of the opcodes to match.
  1530. MatchTableRecord getValue() const override {
  1531. assert(Insts.size() == 1);
  1532. const CodeGenInstruction *I = Insts[0];
  1533. const auto VI = OpcodeValues.find(I);
  1534. if (VI != OpcodeValues.end())
  1535. return MatchTable::NamedValue(I->Namespace, I->TheDef->getName(),
  1536. VI->second);
  1537. return MatchTable::NamedValue(I->Namespace, I->TheDef->getName());
  1538. }
  1539. void emitPredicateOpcodes(MatchTable &Table,
  1540. RuleMatcher &Rule) const override {
  1541. StringRef CheckType = Insts.size() == 1 ?
  1542. "GIM_CheckOpcode" : "GIM_CheckOpcodeIsEither";
  1543. Table << MatchTable::Opcode(CheckType) << MatchTable::Comment("MI")
  1544. << MatchTable::IntValue(InsnVarID);
  1545. for (const CodeGenInstruction *I : Insts)
  1546. Table << getInstValue(I);
  1547. Table << MatchTable::LineBreak;
  1548. }
  1549. /// Compare the priority of this object and B.
  1550. ///
  1551. /// Returns true if this object is more important than B.
  1552. bool
  1553. isHigherPriorityThan(const InstructionPredicateMatcher &B) const override {
  1554. if (InstructionPredicateMatcher::isHigherPriorityThan(B))
  1555. return true;
  1556. if (B.InstructionPredicateMatcher::isHigherPriorityThan(*this))
  1557. return false;
  1558. // Prioritize opcodes for cosmetic reasons in the generated source. Although
  1559. // this is cosmetic at the moment, we may want to drive a similar ordering
  1560. // using instruction frequency information to improve compile time.
  1561. if (const InstructionOpcodeMatcher *BO =
  1562. dyn_cast<InstructionOpcodeMatcher>(&B))
  1563. return Insts[0]->TheDef->getName() < BO->Insts[0]->TheDef->getName();
  1564. return false;
  1565. };
  1566. bool isConstantInstruction() const {
  1567. return Insts.size() == 1 && Insts[0]->TheDef->getName() == "G_CONSTANT";
  1568. }
  1569. // The first opcode is the canonical opcode, and later are alternatives.
  1570. StringRef getOpcode() const {
  1571. return Insts[0]->TheDef->getName();
  1572. }
  1573. ArrayRef<const CodeGenInstruction *> getAlternativeOpcodes() {
  1574. return Insts;
  1575. }
  1576. bool isVariadicNumOperands() const {
  1577. // If one is variadic, they all should be.
  1578. return Insts[0]->Operands.isVariadic;
  1579. }
  1580. StringRef getOperandType(unsigned OpIdx) const {
  1581. // Types expected to be uniform for all alternatives.
  1582. return Insts[0]->Operands[OpIdx].OperandType;
  1583. }
  1584. };
  1585. DenseMap<const CodeGenInstruction *, unsigned>
  1586. InstructionOpcodeMatcher::OpcodeValues;
  1587. class InstructionNumOperandsMatcher final : public InstructionPredicateMatcher {
  1588. unsigned NumOperands = 0;
  1589. public:
  1590. InstructionNumOperandsMatcher(unsigned InsnVarID, unsigned NumOperands)
  1591. : InstructionPredicateMatcher(IPM_NumOperands, InsnVarID),
  1592. NumOperands(NumOperands) {}
  1593. static bool classof(const PredicateMatcher *P) {
  1594. return P->getKind() == IPM_NumOperands;
  1595. }
  1596. bool isIdentical(const PredicateMatcher &B) const override {
  1597. return InstructionPredicateMatcher::isIdentical(B) &&
  1598. NumOperands == cast<InstructionNumOperandsMatcher>(&B)->NumOperands;
  1599. }
  1600. void emitPredicateOpcodes(MatchTable &Table,
  1601. RuleMatcher &Rule) const override {
  1602. Table << MatchTable::Opcode("GIM_CheckNumOperands")
  1603. << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
  1604. << MatchTable::Comment("Expected")
  1605. << MatchTable::IntValue(NumOperands) << MatchTable::LineBreak;
  1606. }
  1607. };
  1608. /// Generates code to check that this instruction is a constant whose value
  1609. /// meets an immediate predicate.
  1610. ///
  1611. /// Immediates are slightly odd since they are typically used like an operand
  1612. /// but are represented as an operator internally. We typically write simm8:$src
  1613. /// in a tablegen pattern, but this is just syntactic sugar for
  1614. /// (imm:i32)<<P:Predicate_simm8>>:$imm which more directly describes the nodes
  1615. /// that will be matched and the predicate (which is attached to the imm
  1616. /// operator) that will be tested. In SelectionDAG this describes a
  1617. /// ConstantSDNode whose internal value will be tested using the simm8 predicate.
  1618. ///
  1619. /// The corresponding GlobalISel representation is %1 = G_CONSTANT iN Value. In
  1620. /// this representation, the immediate could be tested with an
  1621. /// InstructionMatcher, InstructionOpcodeMatcher, OperandMatcher, and a
  1622. /// OperandPredicateMatcher-subclass to check the Value meets the predicate but
  1623. /// there are two implementation issues with producing that matcher
  1624. /// configuration from the SelectionDAG pattern:
  1625. /// * ImmLeaf is a PatFrag whose root is an InstructionMatcher. This means that
  1626. /// were we to sink the immediate predicate to the operand we would have to
  1627. /// have two partial implementations of PatFrag support, one for immediates
  1628. /// and one for non-immediates.
  1629. /// * At the point we handle the predicate, the OperandMatcher hasn't been
  1630. /// created yet. If we were to sink the predicate to the OperandMatcher we
  1631. /// would also have to complicate (or duplicate) the code that descends and
  1632. /// creates matchers for the subtree.
  1633. /// Overall, it's simpler to handle it in the place it was found.
  1634. class InstructionImmPredicateMatcher : public InstructionPredicateMatcher {
  1635. protected:
  1636. TreePredicateFn Predicate;
  1637. public:
  1638. InstructionImmPredicateMatcher(unsigned InsnVarID,
  1639. const TreePredicateFn &Predicate)
  1640. : InstructionPredicateMatcher(IPM_ImmPredicate, InsnVarID),
  1641. Predicate(Predicate) {}
  1642. bool isIdentical(const PredicateMatcher &B) const override {
  1643. return InstructionPredicateMatcher::isIdentical(B) &&
  1644. Predicate.getOrigPatFragRecord() ==
  1645. cast<InstructionImmPredicateMatcher>(&B)
  1646. ->Predicate.getOrigPatFragRecord();
  1647. }
  1648. static bool classof(const PredicateMatcher *P) {
  1649. return P->getKind() == IPM_ImmPredicate;
  1650. }
  1651. void emitPredicateOpcodes(MatchTable &Table,
  1652. RuleMatcher &Rule) const override {
  1653. Table << MatchTable::Opcode(getMatchOpcodeForImmPredicate(Predicate))
  1654. << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
  1655. << MatchTable::Comment("Predicate")
  1656. << MatchTable::NamedValue(getEnumNameForPredicate(Predicate))
  1657. << MatchTable::LineBreak;
  1658. }
  1659. };
  1660. /// Generates code to check that a memory instruction has a atomic ordering
  1661. /// MachineMemoryOperand.
  1662. class AtomicOrderingMMOPredicateMatcher : public InstructionPredicateMatcher {
  1663. public:
  1664. enum AOComparator {
  1665. AO_Exactly,
  1666. AO_OrStronger,
  1667. AO_WeakerThan,
  1668. };
  1669. protected:
  1670. StringRef Order;
  1671. AOComparator Comparator;
  1672. public:
  1673. AtomicOrderingMMOPredicateMatcher(unsigned InsnVarID, StringRef Order,
  1674. AOComparator Comparator = AO_Exactly)
  1675. : InstructionPredicateMatcher(IPM_AtomicOrderingMMO, InsnVarID),
  1676. Order(Order), Comparator(Comparator) {}
  1677. static bool classof(const PredicateMatcher *P) {
  1678. return P->getKind() == IPM_AtomicOrderingMMO;
  1679. }
  1680. bool isIdentical(const PredicateMatcher &B) const override {
  1681. if (!InstructionPredicateMatcher::isIdentical(B))
  1682. return false;
  1683. const auto &R = *cast<AtomicOrderingMMOPredicateMatcher>(&B);
  1684. return Order == R.Order && Comparator == R.Comparator;
  1685. }
  1686. void emitPredicateOpcodes(MatchTable &Table,
  1687. RuleMatcher &Rule) const override {
  1688. StringRef Opcode = "GIM_CheckAtomicOrdering";
  1689. if (Comparator == AO_OrStronger)
  1690. Opcode = "GIM_CheckAtomicOrderingOrStrongerThan";
  1691. if (Comparator == AO_WeakerThan)
  1692. Opcode = "GIM_CheckAtomicOrderingWeakerThan";
  1693. Table << MatchTable::Opcode(Opcode) << MatchTable::Comment("MI")
  1694. << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Order")
  1695. << MatchTable::NamedValue(("(int64_t)AtomicOrdering::" + Order).str())
  1696. << MatchTable::LineBreak;
  1697. }
  1698. };
  1699. /// Generates code to check that the size of an MMO is exactly N bytes.
  1700. class MemorySizePredicateMatcher : public InstructionPredicateMatcher {
  1701. protected:
  1702. unsigned MMOIdx;
  1703. uint64_t Size;
  1704. public:
  1705. MemorySizePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx, unsigned Size)
  1706. : InstructionPredicateMatcher(IPM_MemoryLLTSize, InsnVarID),
  1707. MMOIdx(MMOIdx), Size(Size) {}
  1708. static bool classof(const PredicateMatcher *P) {
  1709. return P->getKind() == IPM_MemoryLLTSize;
  1710. }
  1711. bool isIdentical(const PredicateMatcher &B) const override {
  1712. return InstructionPredicateMatcher::isIdentical(B) &&
  1713. MMOIdx == cast<MemorySizePredicateMatcher>(&B)->MMOIdx &&
  1714. Size == cast<MemorySizePredicateMatcher>(&B)->Size;
  1715. }
  1716. void emitPredicateOpcodes(MatchTable &Table,
  1717. RuleMatcher &Rule) const override {
  1718. Table << MatchTable::Opcode("GIM_CheckMemorySizeEqualTo")
  1719. << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
  1720. << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
  1721. << MatchTable::Comment("Size") << MatchTable::IntValue(Size)
  1722. << MatchTable::LineBreak;
  1723. }
  1724. };
  1725. class MemoryAddressSpacePredicateMatcher : public InstructionPredicateMatcher {
  1726. protected:
  1727. unsigned MMOIdx;
  1728. SmallVector<unsigned, 4> AddrSpaces;
  1729. public:
  1730. MemoryAddressSpacePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
  1731. ArrayRef<unsigned> AddrSpaces)
  1732. : InstructionPredicateMatcher(IPM_MemoryAddressSpace, InsnVarID),
  1733. MMOIdx(MMOIdx), AddrSpaces(AddrSpaces.begin(), AddrSpaces.end()) {}
  1734. static bool classof(const PredicateMatcher *P) {
  1735. return P->getKind() == IPM_MemoryAddressSpace;
  1736. }
  1737. bool isIdentical(const PredicateMatcher &B) const override {
  1738. if (!InstructionPredicateMatcher::isIdentical(B))
  1739. return false;
  1740. auto *Other = cast<MemoryAddressSpacePredicateMatcher>(&B);
  1741. return MMOIdx == Other->MMOIdx && AddrSpaces == Other->AddrSpaces;
  1742. }
  1743. void emitPredicateOpcodes(MatchTable &Table,
  1744. RuleMatcher &Rule) const override {
  1745. Table << MatchTable::Opcode("GIM_CheckMemoryAddressSpace")
  1746. << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
  1747. << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
  1748. // Encode number of address spaces to expect.
  1749. << MatchTable::Comment("NumAddrSpace")
  1750. << MatchTable::IntValue(AddrSpaces.size());
  1751. for (unsigned AS : AddrSpaces)
  1752. Table << MatchTable::Comment("AddrSpace") << MatchTable::IntValue(AS);
  1753. Table << MatchTable::LineBreak;
  1754. }
  1755. };
  1756. class MemoryAlignmentPredicateMatcher : public InstructionPredicateMatcher {
  1757. protected:
  1758. unsigned MMOIdx;
  1759. int MinAlign;
  1760. public:
  1761. MemoryAlignmentPredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
  1762. int MinAlign)
  1763. : InstructionPredicateMatcher(IPM_MemoryAlignment, InsnVarID),
  1764. MMOIdx(MMOIdx), MinAlign(MinAlign) {
  1765. assert(MinAlign > 0);
  1766. }
  1767. static bool classof(const PredicateMatcher *P) {
  1768. return P->getKind() == IPM_MemoryAlignment;
  1769. }
  1770. bool isIdentical(const PredicateMatcher &B) const override {
  1771. if (!InstructionPredicateMatcher::isIdentical(B))
  1772. return false;
  1773. auto *Other = cast<MemoryAlignmentPredicateMatcher>(&B);
  1774. return MMOIdx == Other->MMOIdx && MinAlign == Other->MinAlign;
  1775. }
  1776. void emitPredicateOpcodes(MatchTable &Table,
  1777. RuleMatcher &Rule) const override {
  1778. Table << MatchTable::Opcode("GIM_CheckMemoryAlignment")
  1779. << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
  1780. << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
  1781. << MatchTable::Comment("MinAlign") << MatchTable::IntValue(MinAlign)
  1782. << MatchTable::LineBreak;
  1783. }
  1784. };
  1785. /// Generates code to check that the size of an MMO is less-than, equal-to, or
  1786. /// greater than a given LLT.
  1787. class MemoryVsLLTSizePredicateMatcher : public InstructionPredicateMatcher {
  1788. public:
  1789. enum RelationKind {
  1790. GreaterThan,
  1791. EqualTo,
  1792. LessThan,
  1793. };
  1794. protected:
  1795. unsigned MMOIdx;
  1796. RelationKind Relation;
  1797. unsigned OpIdx;
  1798. public:
  1799. MemoryVsLLTSizePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
  1800. enum RelationKind Relation,
  1801. unsigned OpIdx)
  1802. : InstructionPredicateMatcher(IPM_MemoryVsLLTSize, InsnVarID),
  1803. MMOIdx(MMOIdx), Relation(Relation), OpIdx(OpIdx) {}
  1804. static bool classof(const PredicateMatcher *P) {
  1805. return P->getKind() == IPM_MemoryVsLLTSize;
  1806. }
  1807. bool isIdentical(const PredicateMatcher &B) const override {
  1808. return InstructionPredicateMatcher::isIdentical(B) &&
  1809. MMOIdx == cast<MemoryVsLLTSizePredicateMatcher>(&B)->MMOIdx &&
  1810. Relation == cast<MemoryVsLLTSizePredicateMatcher>(&B)->Relation &&
  1811. OpIdx == cast<MemoryVsLLTSizePredicateMatcher>(&B)->OpIdx;
  1812. }
  1813. void emitPredicateOpcodes(MatchTable &Table,
  1814. RuleMatcher &Rule) const override {
  1815. Table << MatchTable::Opcode(Relation == EqualTo
  1816. ? "GIM_CheckMemorySizeEqualToLLT"
  1817. : Relation == GreaterThan
  1818. ? "GIM_CheckMemorySizeGreaterThanLLT"
  1819. : "GIM_CheckMemorySizeLessThanLLT")
  1820. << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
  1821. << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
  1822. << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
  1823. << MatchTable::LineBreak;
  1824. }
  1825. };
  1826. // Matcher for immAllOnesV/immAllZerosV
  1827. class VectorSplatImmPredicateMatcher : public InstructionPredicateMatcher {
  1828. public:
  1829. enum SplatKind {
  1830. AllZeros,
  1831. AllOnes
  1832. };
  1833. private:
  1834. SplatKind Kind;
  1835. public:
  1836. VectorSplatImmPredicateMatcher(unsigned InsnVarID, SplatKind K)
  1837. : InstructionPredicateMatcher(IPM_VectorSplatImm, InsnVarID), Kind(K) {}
  1838. static bool classof(const PredicateMatcher *P) {
  1839. return P->getKind() == IPM_VectorSplatImm;
  1840. }
  1841. bool isIdentical(const PredicateMatcher &B) const override {
  1842. return InstructionPredicateMatcher::isIdentical(B) &&
  1843. Kind == static_cast<const VectorSplatImmPredicateMatcher &>(B).Kind;
  1844. }
  1845. void emitPredicateOpcodes(MatchTable &Table,
  1846. RuleMatcher &Rule) const override {
  1847. if (Kind == AllOnes)
  1848. Table << MatchTable::Opcode("GIM_CheckIsBuildVectorAllOnes");
  1849. else
  1850. Table << MatchTable::Opcode("GIM_CheckIsBuildVectorAllZeros");
  1851. Table << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID);
  1852. Table << MatchTable::LineBreak;
  1853. }
  1854. };
  1855. /// Generates code to check an arbitrary C++ instruction predicate.
  1856. class GenericInstructionPredicateMatcher : public InstructionPredicateMatcher {
  1857. protected:
  1858. TreePredicateFn Predicate;
  1859. public:
  1860. GenericInstructionPredicateMatcher(unsigned InsnVarID,
  1861. TreePredicateFn Predicate)
  1862. : InstructionPredicateMatcher(IPM_GenericPredicate, InsnVarID),
  1863. Predicate(Predicate) {}
  1864. static bool classof(const InstructionPredicateMatcher *P) {
  1865. return P->getKind() == IPM_GenericPredicate;
  1866. }
  1867. bool isIdentical(const PredicateMatcher &B) const override {
  1868. return InstructionPredicateMatcher::isIdentical(B) &&
  1869. Predicate ==
  1870. static_cast<const GenericInstructionPredicateMatcher &>(B)
  1871. .Predicate;
  1872. }
  1873. void emitPredicateOpcodes(MatchTable &Table,
  1874. RuleMatcher &Rule) const override {
  1875. Table << MatchTable::Opcode("GIM_CheckCxxInsnPredicate")
  1876. << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
  1877. << MatchTable::Comment("FnId")
  1878. << MatchTable::NamedValue(getEnumNameForPredicate(Predicate))
  1879. << MatchTable::LineBreak;
  1880. }
  1881. };
  1882. /// Generates code to check that a set of predicates and operands match for a
  1883. /// particular instruction.
  1884. ///
  1885. /// Typical predicates include:
  1886. /// * Has a specific opcode.
  1887. /// * Has an nsw/nuw flag or doesn't.
  1888. class InstructionMatcher final : public PredicateListMatcher<PredicateMatcher> {
  1889. protected:
  1890. typedef std::vector<std::unique_ptr<OperandMatcher>> OperandVec;
  1891. RuleMatcher &Rule;
  1892. /// The operands to match. All rendered operands must be present even if the
  1893. /// condition is always true.
  1894. OperandVec Operands;
  1895. bool NumOperandsCheck = true;
  1896. std::string SymbolicName;
  1897. unsigned InsnVarID;
  1898. /// PhysRegInputs - List list has an entry for each explicitly specified
  1899. /// physreg input to the pattern. The first elt is the Register node, the
  1900. /// second is the recorded slot number the input pattern match saved it in.
  1901. SmallVector<std::pair<Record *, unsigned>, 2> PhysRegInputs;
  1902. public:
  1903. InstructionMatcher(RuleMatcher &Rule, StringRef SymbolicName,
  1904. bool NumOpsCheck = true)
  1905. : Rule(Rule), NumOperandsCheck(NumOpsCheck), SymbolicName(SymbolicName) {
  1906. // We create a new instruction matcher.
  1907. // Get a new ID for that instruction.
  1908. InsnVarID = Rule.implicitlyDefineInsnVar(*this);
  1909. }
  1910. /// Construct a new instruction predicate and add it to the matcher.
  1911. template <class Kind, class... Args>
  1912. Optional<Kind *> addPredicate(Args &&... args) {
  1913. Predicates.emplace_back(
  1914. std::make_unique<Kind>(getInsnVarID(), std::forward<Args>(args)...));
  1915. return static_cast<Kind *>(Predicates.back().get());
  1916. }
  1917. RuleMatcher &getRuleMatcher() const { return Rule; }
  1918. unsigned getInsnVarID() const { return InsnVarID; }
  1919. /// Add an operand to the matcher.
  1920. OperandMatcher &addOperand(unsigned OpIdx, const std::string &SymbolicName,
  1921. unsigned AllocatedTemporariesBaseID) {
  1922. Operands.emplace_back(new OperandMatcher(*this, OpIdx, SymbolicName,
  1923. AllocatedTemporariesBaseID));
  1924. if (!SymbolicName.empty())
  1925. Rule.defineOperand(SymbolicName, *Operands.back());
  1926. return *Operands.back();
  1927. }
  1928. OperandMatcher &getOperand(unsigned OpIdx) {
  1929. auto I = llvm::find_if(Operands,
  1930. [&OpIdx](const std::unique_ptr<OperandMatcher> &X) {
  1931. return X->getOpIdx() == OpIdx;
  1932. });
  1933. if (I != Operands.end())
  1934. return **I;
  1935. llvm_unreachable("Failed to lookup operand");
  1936. }
  1937. OperandMatcher &addPhysRegInput(Record *Reg, unsigned OpIdx,
  1938. unsigned TempOpIdx) {
  1939. assert(SymbolicName.empty());
  1940. OperandMatcher *OM = new OperandMatcher(*this, OpIdx, "", TempOpIdx);
  1941. Operands.emplace_back(OM);
  1942. Rule.definePhysRegOperand(Reg, *OM);
  1943. PhysRegInputs.emplace_back(Reg, OpIdx);
  1944. return *OM;
  1945. }
  1946. ArrayRef<std::pair<Record *, unsigned>> getPhysRegInputs() const {
  1947. return PhysRegInputs;
  1948. }
  1949. StringRef getSymbolicName() const { return SymbolicName; }
  1950. unsigned getNumOperands() const { return Operands.size(); }
  1951. OperandVec::iterator operands_begin() { return Operands.begin(); }
  1952. OperandVec::iterator operands_end() { return Operands.end(); }
  1953. iterator_range<OperandVec::iterator> operands() {
  1954. return make_range(operands_begin(), operands_end());
  1955. }
  1956. OperandVec::const_iterator operands_begin() const { return Operands.begin(); }
  1957. OperandVec::const_iterator operands_end() const { return Operands.end(); }
  1958. iterator_range<OperandVec::const_iterator> operands() const {
  1959. return make_range(operands_begin(), operands_end());
  1960. }
  1961. bool operands_empty() const { return Operands.empty(); }
  1962. void pop_front() { Operands.erase(Operands.begin()); }
  1963. void optimize();
  1964. /// Emit MatchTable opcodes that test whether the instruction named in
  1965. /// InsnVarName matches all the predicates and all the operands.
  1966. void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule) {
  1967. if (NumOperandsCheck)
  1968. InstructionNumOperandsMatcher(InsnVarID, getNumOperands())
  1969. .emitPredicateOpcodes(Table, Rule);
  1970. // First emit all instruction level predicates need to be verified before we
  1971. // can verify operands.
  1972. emitFilteredPredicateListOpcodes(
  1973. [](const PredicateMatcher &P) {
  1974. return !P.dependsOnOperands();
  1975. }, Table, Rule);
  1976. // Emit all operand constraints.
  1977. for (const auto &Operand : Operands)
  1978. Operand->emitPredicateOpcodes(Table, Rule);
  1979. // All of the tablegen defined predicates should now be matched. Now emit
  1980. // any custom predicates that rely on all generated checks.
  1981. emitFilteredPredicateListOpcodes(
  1982. [](const PredicateMatcher &P) {
  1983. return P.dependsOnOperands();
  1984. }, Table, Rule);
  1985. }
  1986. /// Compare the priority of this object and B.
  1987. ///
  1988. /// Returns true if this object is more important than B.
  1989. bool isHigherPriorityThan(InstructionMatcher &B) {
  1990. // Instruction matchers involving more operands have higher priority.
  1991. if (Operands.size() > B.Operands.size())
  1992. return true;
  1993. if (Operands.size() < B.Operands.size())
  1994. return false;
  1995. for (auto &&P : zip(predicates(), B.predicates())) {
  1996. auto L = static_cast<InstructionPredicateMatcher *>(std::get<0>(P).get());
  1997. auto R = static_cast<InstructionPredicateMatcher *>(std::get<1>(P).get());
  1998. if (L->isHigherPriorityThan(*R))
  1999. return true;
  2000. if (R->isHigherPriorityThan(*L))
  2001. return false;
  2002. }
  2003. for (auto Operand : zip(Operands, B.Operands)) {
  2004. if (std::get<0>(Operand)->isHigherPriorityThan(*std::get<1>(Operand)))
  2005. return true;
  2006. if (std::get<1>(Operand)->isHigherPriorityThan(*std::get<0>(Operand)))
  2007. return false;
  2008. }
  2009. return false;
  2010. };
  2011. /// Report the maximum number of temporary operands needed by the instruction
  2012. /// matcher.
  2013. unsigned countRendererFns() {
  2014. return std::accumulate(
  2015. predicates().begin(), predicates().end(), 0,
  2016. [](unsigned A,
  2017. const std::unique_ptr<PredicateMatcher> &Predicate) {
  2018. return A + Predicate->countRendererFns();
  2019. }) +
  2020. std::accumulate(
  2021. Operands.begin(), Operands.end(), 0,
  2022. [](unsigned A, const std::unique_ptr<OperandMatcher> &Operand) {
  2023. return A + Operand->countRendererFns();
  2024. });
  2025. }
  2026. InstructionOpcodeMatcher &getOpcodeMatcher() {
  2027. for (auto &P : predicates())
  2028. if (auto *OpMatcher = dyn_cast<InstructionOpcodeMatcher>(P.get()))
  2029. return *OpMatcher;
  2030. llvm_unreachable("Didn't find an opcode matcher");
  2031. }
  2032. bool isConstantInstruction() {
  2033. return getOpcodeMatcher().isConstantInstruction();
  2034. }
  2035. StringRef getOpcode() { return getOpcodeMatcher().getOpcode(); }
  2036. };
  2037. StringRef RuleMatcher::getOpcode() const {
  2038. return Matchers.front()->getOpcode();
  2039. }
  2040. unsigned RuleMatcher::getNumOperands() const {
  2041. return Matchers.front()->getNumOperands();
  2042. }
  2043. LLTCodeGen RuleMatcher::getFirstConditionAsRootType() {
  2044. InstructionMatcher &InsnMatcher = *Matchers.front();
  2045. if (!InsnMatcher.predicates_empty())
  2046. if (const auto *TM =
  2047. dyn_cast<LLTOperandMatcher>(&**InsnMatcher.predicates_begin()))
  2048. if (TM->getInsnVarID() == 0 && TM->getOpIdx() == 0)
  2049. return TM->getTy();
  2050. return {};
  2051. }
  2052. /// Generates code to check that the operand is a register defined by an
  2053. /// instruction that matches the given instruction matcher.
  2054. ///
  2055. /// For example, the pattern:
  2056. /// (set $dst, (G_MUL (G_ADD $src1, $src2), $src3))
  2057. /// would use an InstructionOperandMatcher for operand 1 of the G_MUL to match
  2058. /// the:
  2059. /// (G_ADD $src1, $src2)
  2060. /// subpattern.
  2061. class InstructionOperandMatcher : public OperandPredicateMatcher {
  2062. protected:
  2063. std::unique_ptr<InstructionMatcher> InsnMatcher;
  2064. public:
  2065. InstructionOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
  2066. RuleMatcher &Rule, StringRef SymbolicName,
  2067. bool NumOpsCheck = true)
  2068. : OperandPredicateMatcher(OPM_Instruction, InsnVarID, OpIdx),
  2069. InsnMatcher(new InstructionMatcher(Rule, SymbolicName, NumOpsCheck)) {}
  2070. static bool classof(const PredicateMatcher *P) {
  2071. return P->getKind() == OPM_Instruction;
  2072. }
  2073. InstructionMatcher &getInsnMatcher() const { return *InsnMatcher; }
  2074. void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule) const {
  2075. const unsigned NewInsnVarID = InsnMatcher->getInsnVarID();
  2076. Table << MatchTable::Opcode("GIM_RecordInsn")
  2077. << MatchTable::Comment("DefineMI")
  2078. << MatchTable::IntValue(NewInsnVarID) << MatchTable::Comment("MI")
  2079. << MatchTable::IntValue(getInsnVarID())
  2080. << MatchTable::Comment("OpIdx") << MatchTable::IntValue(getOpIdx())
  2081. << MatchTable::Comment("MIs[" + llvm::to_string(NewInsnVarID) + "]")
  2082. << MatchTable::LineBreak;
  2083. }
  2084. void emitPredicateOpcodes(MatchTable &Table,
  2085. RuleMatcher &Rule) const override {
  2086. emitCaptureOpcodes(Table, Rule);
  2087. InsnMatcher->emitPredicateOpcodes(Table, Rule);
  2088. }
  2089. bool isHigherPriorityThan(const OperandPredicateMatcher &B) const override {
  2090. if (OperandPredicateMatcher::isHigherPriorityThan(B))
  2091. return true;
  2092. if (B.OperandPredicateMatcher::isHigherPriorityThan(*this))
  2093. return false;
  2094. if (const InstructionOperandMatcher *BP =
  2095. dyn_cast<InstructionOperandMatcher>(&B))
  2096. if (InsnMatcher->isHigherPriorityThan(*BP->InsnMatcher))
  2097. return true;
  2098. return false;
  2099. }
  2100. };
  2101. void InstructionMatcher::optimize() {
  2102. SmallVector<std::unique_ptr<PredicateMatcher>, 8> Stash;
  2103. const auto &OpcMatcher = getOpcodeMatcher();
  2104. Stash.push_back(predicates_pop_front());
  2105. if (Stash.back().get() == &OpcMatcher) {
  2106. if (NumOperandsCheck && OpcMatcher.isVariadicNumOperands())
  2107. Stash.emplace_back(
  2108. new InstructionNumOperandsMatcher(InsnVarID, getNumOperands()));
  2109. NumOperandsCheck = false;
  2110. for (auto &OM : Operands)
  2111. for (auto &OP : OM->predicates())
  2112. if (isa<IntrinsicIDOperandMatcher>(OP)) {
  2113. Stash.push_back(std::move(OP));
  2114. OM->eraseNullPredicates();
  2115. break;
  2116. }
  2117. }
  2118. if (InsnVarID > 0) {
  2119. assert(!Operands.empty() && "Nested instruction is expected to def a vreg");
  2120. for (auto &OP : Operands[0]->predicates())
  2121. OP.reset();
  2122. Operands[0]->eraseNullPredicates();
  2123. }
  2124. for (auto &OM : Operands) {
  2125. for (auto &OP : OM->predicates())
  2126. if (isa<LLTOperandMatcher>(OP))
  2127. Stash.push_back(std::move(OP));
  2128. OM->eraseNullPredicates();
  2129. }
  2130. while (!Stash.empty())
  2131. prependPredicate(Stash.pop_back_val());
  2132. }
  2133. //===- Actions ------------------------------------------------------------===//
  2134. class OperandRenderer {
  2135. public:
  2136. enum RendererKind {
  2137. OR_Copy,
  2138. OR_CopyOrAddZeroReg,
  2139. OR_CopySubReg,
  2140. OR_CopyPhysReg,
  2141. OR_CopyConstantAsImm,
  2142. OR_CopyFConstantAsFPImm,
  2143. OR_Imm,
  2144. OR_SubRegIndex,
  2145. OR_Register,
  2146. OR_TempRegister,
  2147. OR_ComplexPattern,
  2148. OR_Custom,
  2149. OR_CustomOperand
  2150. };
  2151. protected:
  2152. RendererKind Kind;
  2153. public:
  2154. OperandRenderer(RendererKind Kind) : Kind(Kind) {}
  2155. virtual ~OperandRenderer() {}
  2156. RendererKind getKind() const { return Kind; }
  2157. virtual void emitRenderOpcodes(MatchTable &Table,
  2158. RuleMatcher &Rule) const = 0;
  2159. };
  2160. /// A CopyRenderer emits code to copy a single operand from an existing
  2161. /// instruction to the one being built.
  2162. class CopyRenderer : public OperandRenderer {
  2163. protected:
  2164. unsigned NewInsnID;
  2165. /// The name of the operand.
  2166. const StringRef SymbolicName;
  2167. public:
  2168. CopyRenderer(unsigned NewInsnID, StringRef SymbolicName)
  2169. : OperandRenderer(OR_Copy), NewInsnID(NewInsnID),
  2170. SymbolicName(SymbolicName) {
  2171. assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
  2172. }
  2173. static bool classof(const OperandRenderer *R) {
  2174. return R->getKind() == OR_Copy;
  2175. }
  2176. StringRef getSymbolicName() const { return SymbolicName; }
  2177. void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
  2178. const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
  2179. unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
  2180. Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID")
  2181. << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID")
  2182. << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
  2183. << MatchTable::IntValue(Operand.getOpIdx())
  2184. << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
  2185. }
  2186. };
  2187. /// A CopyRenderer emits code to copy a virtual register to a specific physical
  2188. /// register.
  2189. class CopyPhysRegRenderer : public OperandRenderer {
  2190. protected:
  2191. unsigned NewInsnID;
  2192. Record *PhysReg;
  2193. public:
  2194. CopyPhysRegRenderer(unsigned NewInsnID, Record *Reg)
  2195. : OperandRenderer(OR_CopyPhysReg), NewInsnID(NewInsnID),
  2196. PhysReg(Reg) {
  2197. assert(PhysReg);
  2198. }
  2199. static bool classof(const OperandRenderer *R) {
  2200. return R->getKind() == OR_CopyPhysReg;
  2201. }
  2202. Record *getPhysReg() const { return PhysReg; }
  2203. void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
  2204. const OperandMatcher &Operand = Rule.getPhysRegOperandMatcher(PhysReg);
  2205. unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
  2206. Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID")
  2207. << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID")
  2208. << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
  2209. << MatchTable::IntValue(Operand.getOpIdx())
  2210. << MatchTable::Comment(PhysReg->getName())
  2211. << MatchTable::LineBreak;
  2212. }
  2213. };
  2214. /// A CopyOrAddZeroRegRenderer emits code to copy a single operand from an
  2215. /// existing instruction to the one being built. If the operand turns out to be
  2216. /// a 'G_CONSTANT 0' then it replaces the operand with a zero register.
  2217. class CopyOrAddZeroRegRenderer : public OperandRenderer {
  2218. protected:
  2219. unsigned NewInsnID;
  2220. /// The name of the operand.
  2221. const StringRef SymbolicName;
  2222. const Record *ZeroRegisterDef;
  2223. public:
  2224. CopyOrAddZeroRegRenderer(unsigned NewInsnID,
  2225. StringRef SymbolicName, Record *ZeroRegisterDef)
  2226. : OperandRenderer(OR_CopyOrAddZeroReg), NewInsnID(NewInsnID),
  2227. SymbolicName(SymbolicName), ZeroRegisterDef(ZeroRegisterDef) {
  2228. assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
  2229. }
  2230. static bool classof(const OperandRenderer *R) {
  2231. return R->getKind() == OR_CopyOrAddZeroReg;
  2232. }
  2233. StringRef getSymbolicName() const { return SymbolicName; }
  2234. void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
  2235. const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
  2236. unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
  2237. Table << MatchTable::Opcode("GIR_CopyOrAddZeroReg")
  2238. << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
  2239. << MatchTable::Comment("OldInsnID")
  2240. << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
  2241. << MatchTable::IntValue(Operand.getOpIdx())
  2242. << MatchTable::NamedValue(
  2243. (ZeroRegisterDef->getValue("Namespace")
  2244. ? ZeroRegisterDef->getValueAsString("Namespace")
  2245. : ""),
  2246. ZeroRegisterDef->getName())
  2247. << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
  2248. }
  2249. };
  2250. /// A CopyConstantAsImmRenderer emits code to render a G_CONSTANT instruction to
  2251. /// an extended immediate operand.
  2252. class CopyConstantAsImmRenderer : public OperandRenderer {
  2253. protected:
  2254. unsigned NewInsnID;
  2255. /// The name of the operand.
  2256. const std::string SymbolicName;
  2257. bool Signed;
  2258. public:
  2259. CopyConstantAsImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
  2260. : OperandRenderer(OR_CopyConstantAsImm), NewInsnID(NewInsnID),
  2261. SymbolicName(SymbolicName), Signed(true) {}
  2262. static bool classof(const OperandRenderer *R) {
  2263. return R->getKind() == OR_CopyConstantAsImm;
  2264. }
  2265. StringRef getSymbolicName() const { return SymbolicName; }
  2266. void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
  2267. InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
  2268. unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
  2269. Table << MatchTable::Opcode(Signed ? "GIR_CopyConstantAsSImm"
  2270. : "GIR_CopyConstantAsUImm")
  2271. << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
  2272. << MatchTable::Comment("OldInsnID")
  2273. << MatchTable::IntValue(OldInsnVarID)
  2274. << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
  2275. }
  2276. };
  2277. /// A CopyFConstantAsFPImmRenderer emits code to render a G_FCONSTANT
  2278. /// instruction to an extended immediate operand.
  2279. class CopyFConstantAsFPImmRenderer : public OperandRenderer {
  2280. protected:
  2281. unsigned NewInsnID;
  2282. /// The name of the operand.
  2283. const std::string SymbolicName;
  2284. public:
  2285. CopyFConstantAsFPImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
  2286. : OperandRenderer(OR_CopyFConstantAsFPImm), NewInsnID(NewInsnID),
  2287. SymbolicName(SymbolicName) {}
  2288. static bool classof(const OperandRenderer *R) {
  2289. return R->getKind() == OR_CopyFConstantAsFPImm;
  2290. }
  2291. StringRef getSymbolicName() const { return SymbolicName; }
  2292. void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
  2293. InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
  2294. unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
  2295. Table << MatchTable::Opcode("GIR_CopyFConstantAsFPImm")
  2296. << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
  2297. << MatchTable::Comment("OldInsnID")
  2298. << MatchTable::IntValue(OldInsnVarID)
  2299. << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
  2300. }
  2301. };
  2302. /// A CopySubRegRenderer emits code to copy a single register operand from an
  2303. /// existing instruction to the one being built and indicate that only a
  2304. /// subregister should be copied.
  2305. class CopySubRegRenderer : public OperandRenderer {
  2306. protected:
  2307. unsigned NewInsnID;
  2308. /// The name of the operand.
  2309. const StringRef SymbolicName;
  2310. /// The subregister to extract.
  2311. const CodeGenSubRegIndex *SubReg;
  2312. public:
  2313. CopySubRegRenderer(unsigned NewInsnID, StringRef SymbolicName,
  2314. const CodeGenSubRegIndex *SubReg)
  2315. : OperandRenderer(OR_CopySubReg), NewInsnID(NewInsnID),
  2316. SymbolicName(SymbolicName), SubReg(SubReg) {}
  2317. static bool classof(const OperandRenderer *R) {
  2318. return R->getKind() == OR_CopySubReg;
  2319. }
  2320. StringRef getSymbolicName() const { return SymbolicName; }
  2321. void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
  2322. const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
  2323. unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
  2324. Table << MatchTable::Opcode("GIR_CopySubReg")
  2325. << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
  2326. << MatchTable::Comment("OldInsnID")
  2327. << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
  2328. << MatchTable::IntValue(Operand.getOpIdx())
  2329. << MatchTable::Comment("SubRegIdx")
  2330. << MatchTable::IntValue(SubReg->EnumValue)
  2331. << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
  2332. }
  2333. };
  2334. /// Adds a specific physical register to the instruction being built.
  2335. /// This is typically useful for WZR/XZR on AArch64.
  2336. class AddRegisterRenderer : public OperandRenderer {
  2337. protected:
  2338. unsigned InsnID;
  2339. const Record *RegisterDef;
  2340. bool IsDef;
  2341. const CodeGenTarget &Target;
  2342. public:
  2343. AddRegisterRenderer(unsigned InsnID, const CodeGenTarget &Target,
  2344. const Record *RegisterDef, bool IsDef = false)
  2345. : OperandRenderer(OR_Register), InsnID(InsnID), RegisterDef(RegisterDef),
  2346. IsDef(IsDef), Target(Target) {}
  2347. static bool classof(const OperandRenderer *R) {
  2348. return R->getKind() == OR_Register;
  2349. }
  2350. void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
  2351. Table << MatchTable::Opcode("GIR_AddRegister")
  2352. << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID);
  2353. if (RegisterDef->getName() != "zero_reg") {
  2354. Table << MatchTable::NamedValue(
  2355. (RegisterDef->getValue("Namespace")
  2356. ? RegisterDef->getValueAsString("Namespace")
  2357. : ""),
  2358. RegisterDef->getName());
  2359. } else {
  2360. Table << MatchTable::NamedValue(Target.getRegNamespace(), "NoRegister");
  2361. }
  2362. Table << MatchTable::Comment("AddRegisterRegFlags");
  2363. // TODO: This is encoded as a 64-bit element, but only 16 or 32-bits are
  2364. // really needed for a physical register reference. We can pack the
  2365. // register and flags in a single field.
  2366. if (IsDef)
  2367. Table << MatchTable::NamedValue("RegState::Define");
  2368. else
  2369. Table << MatchTable::IntValue(0);
  2370. Table << MatchTable::LineBreak;
  2371. }
  2372. };
  2373. /// Adds a specific temporary virtual register to the instruction being built.
  2374. /// This is used to chain instructions together when emitting multiple
  2375. /// instructions.
  2376. class TempRegRenderer : public OperandRenderer {
  2377. protected:
  2378. unsigned InsnID;
  2379. unsigned TempRegID;
  2380. const CodeGenSubRegIndex *SubRegIdx;
  2381. bool IsDef;
  2382. bool IsDead;
  2383. public:
  2384. TempRegRenderer(unsigned InsnID, unsigned TempRegID, bool IsDef = false,
  2385. const CodeGenSubRegIndex *SubReg = nullptr,
  2386. bool IsDead = false)
  2387. : OperandRenderer(OR_Register), InsnID(InsnID), TempRegID(TempRegID),
  2388. SubRegIdx(SubReg), IsDef(IsDef), IsDead(IsDead) {}
  2389. static bool classof(const OperandRenderer *R) {
  2390. return R->getKind() == OR_TempRegister;
  2391. }
  2392. void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
  2393. if (SubRegIdx) {
  2394. assert(!IsDef);
  2395. Table << MatchTable::Opcode("GIR_AddTempSubRegister");
  2396. } else
  2397. Table << MatchTable::Opcode("GIR_AddTempRegister");
  2398. Table << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
  2399. << MatchTable::Comment("TempRegID") << MatchTable::IntValue(TempRegID)
  2400. << MatchTable::Comment("TempRegFlags");
  2401. if (IsDef) {
  2402. SmallString<32> RegFlags;
  2403. RegFlags += "RegState::Define";
  2404. if (IsDead)
  2405. RegFlags += "|RegState::Dead";
  2406. Table << MatchTable::NamedValue(RegFlags);
  2407. } else
  2408. Table << MatchTable::IntValue(0);
  2409. if (SubRegIdx)
  2410. Table << MatchTable::NamedValue(SubRegIdx->getQualifiedName());
  2411. Table << MatchTable::LineBreak;
  2412. }
  2413. };
  2414. /// Adds a specific immediate to the instruction being built.
  2415. class ImmRenderer : public OperandRenderer {
  2416. protected:
  2417. unsigned InsnID;
  2418. int64_t Imm;
  2419. public:
  2420. ImmRenderer(unsigned InsnID, int64_t Imm)
  2421. : OperandRenderer(OR_Imm), InsnID(InsnID), Imm(Imm) {}
  2422. static bool classof(const OperandRenderer *R) {
  2423. return R->getKind() == OR_Imm;
  2424. }
  2425. void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
  2426. Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID")
  2427. << MatchTable::IntValue(InsnID) << MatchTable::Comment("Imm")
  2428. << MatchTable::IntValue(Imm) << MatchTable::LineBreak;
  2429. }
  2430. };
  2431. /// Adds an enum value for a subreg index to the instruction being built.
  2432. class SubRegIndexRenderer : public OperandRenderer {
  2433. protected:
  2434. unsigned InsnID;
  2435. const CodeGenSubRegIndex *SubRegIdx;
  2436. public:
  2437. SubRegIndexRenderer(unsigned InsnID, const CodeGenSubRegIndex *SRI)
  2438. : OperandRenderer(OR_SubRegIndex), InsnID(InsnID), SubRegIdx(SRI) {}
  2439. static bool classof(const OperandRenderer *R) {
  2440. return R->getKind() == OR_SubRegIndex;
  2441. }
  2442. void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
  2443. Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID")
  2444. << MatchTable::IntValue(InsnID) << MatchTable::Comment("SubRegIndex")
  2445. << MatchTable::IntValue(SubRegIdx->EnumValue)
  2446. << MatchTable::LineBreak;
  2447. }
  2448. };
  2449. /// Adds operands by calling a renderer function supplied by the ComplexPattern
  2450. /// matcher function.
  2451. class RenderComplexPatternOperand : public OperandRenderer {
  2452. private:
  2453. unsigned InsnID;
  2454. const Record &TheDef;
  2455. /// The name of the operand.
  2456. const StringRef SymbolicName;
  2457. /// The renderer number. This must be unique within a rule since it's used to
  2458. /// identify a temporary variable to hold the renderer function.
  2459. unsigned RendererID;
  2460. /// When provided, this is the suboperand of the ComplexPattern operand to
  2461. /// render. Otherwise all the suboperands will be rendered.
  2462. Optional<unsigned> SubOperand;
  2463. unsigned getNumOperands() const {
  2464. return TheDef.getValueAsDag("Operands")->getNumArgs();
  2465. }
  2466. public:
  2467. RenderComplexPatternOperand(unsigned InsnID, const Record &TheDef,
  2468. StringRef SymbolicName, unsigned RendererID,
  2469. Optional<unsigned> SubOperand = None)
  2470. : OperandRenderer(OR_ComplexPattern), InsnID(InsnID), TheDef(TheDef),
  2471. SymbolicName(SymbolicName), RendererID(RendererID),
  2472. SubOperand(SubOperand) {}
  2473. static bool classof(const OperandRenderer *R) {
  2474. return R->getKind() == OR_ComplexPattern;
  2475. }
  2476. void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
  2477. Table << MatchTable::Opcode(SubOperand.hasValue() ? "GIR_ComplexSubOperandRenderer"
  2478. : "GIR_ComplexRenderer")
  2479. << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
  2480. << MatchTable::Comment("RendererID")
  2481. << MatchTable::IntValue(RendererID);
  2482. if (SubOperand.hasValue())
  2483. Table << MatchTable::Comment("SubOperand")
  2484. << MatchTable::IntValue(SubOperand.getValue());
  2485. Table << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
  2486. }
  2487. };
  2488. class CustomRenderer : public OperandRenderer {
  2489. protected:
  2490. unsigned InsnID;
  2491. const Record &Renderer;
  2492. /// The name of the operand.
  2493. const std::string SymbolicName;
  2494. public:
  2495. CustomRenderer(unsigned InsnID, const Record &Renderer,
  2496. StringRef SymbolicName)
  2497. : OperandRenderer(OR_Custom), InsnID(InsnID), Renderer(Renderer),
  2498. SymbolicName(SymbolicName) {}
  2499. static bool classof(const OperandRenderer *R) {
  2500. return R->getKind() == OR_Custom;
  2501. }
  2502. void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
  2503. InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
  2504. unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
  2505. Table << MatchTable::Opcode("GIR_CustomRenderer")
  2506. << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
  2507. << MatchTable::Comment("OldInsnID")
  2508. << MatchTable::IntValue(OldInsnVarID)
  2509. << MatchTable::Comment("Renderer")
  2510. << MatchTable::NamedValue(
  2511. "GICR_" + Renderer.getValueAsString("RendererFn").str())
  2512. << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
  2513. }
  2514. };
  2515. class CustomOperandRenderer : public OperandRenderer {
  2516. protected:
  2517. unsigned InsnID;
  2518. const Record &Renderer;
  2519. /// The name of the operand.
  2520. const std::string SymbolicName;
  2521. public:
  2522. CustomOperandRenderer(unsigned InsnID, const Record &Renderer,
  2523. StringRef SymbolicName)
  2524. : OperandRenderer(OR_CustomOperand), InsnID(InsnID), Renderer(Renderer),
  2525. SymbolicName(SymbolicName) {}
  2526. static bool classof(const OperandRenderer *R) {
  2527. return R->getKind() == OR_CustomOperand;
  2528. }
  2529. void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
  2530. const OperandMatcher &OpdMatcher = Rule.getOperandMatcher(SymbolicName);
  2531. Table << MatchTable::Opcode("GIR_CustomOperandRenderer")
  2532. << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
  2533. << MatchTable::Comment("OldInsnID")
  2534. << MatchTable::IntValue(OpdMatcher.getInsnVarID())
  2535. << MatchTable::Comment("OpIdx")
  2536. << MatchTable::IntValue(OpdMatcher.getOpIdx())
  2537. << MatchTable::Comment("OperandRenderer")
  2538. << MatchTable::NamedValue(
  2539. "GICR_" + Renderer.getValueAsString("RendererFn").str())
  2540. << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
  2541. }
  2542. };
  2543. /// An action taken when all Matcher predicates succeeded for a parent rule.
  2544. ///
  2545. /// Typical actions include:
  2546. /// * Changing the opcode of an instruction.
  2547. /// * Adding an operand to an instruction.
  2548. class MatchAction {
  2549. public:
  2550. virtual ~MatchAction() {}
  2551. /// Emit the MatchTable opcodes to implement the action.
  2552. virtual void emitActionOpcodes(MatchTable &Table,
  2553. RuleMatcher &Rule) const = 0;
  2554. };
  2555. /// Generates a comment describing the matched rule being acted upon.
  2556. class DebugCommentAction : public MatchAction {
  2557. private:
  2558. std::string S;
  2559. public:
  2560. DebugCommentAction(StringRef S) : S(std::string(S)) {}
  2561. void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
  2562. Table << MatchTable::Comment(S) << MatchTable::LineBreak;
  2563. }
  2564. };
  2565. /// Generates code to build an instruction or mutate an existing instruction
  2566. /// into the desired instruction when this is possible.
  2567. class BuildMIAction : public MatchAction {
  2568. private:
  2569. unsigned InsnID;
  2570. const CodeGenInstruction *I;
  2571. InstructionMatcher *Matched;
  2572. std::vector<std::unique_ptr<OperandRenderer>> OperandRenderers;
  2573. /// True if the instruction can be built solely by mutating the opcode.
  2574. bool canMutate(RuleMatcher &Rule, const InstructionMatcher *Insn) const {
  2575. if (!Insn)
  2576. return false;
  2577. if (OperandRenderers.size() != Insn->getNumOperands())
  2578. return false;
  2579. for (const auto &Renderer : enumerate(OperandRenderers)) {
  2580. if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.value())) {
  2581. const OperandMatcher &OM = Rule.getOperandMatcher(Copy->getSymbolicName());
  2582. if (Insn != &OM.getInstructionMatcher() ||
  2583. OM.getOpIdx() != Renderer.index())
  2584. return false;
  2585. } else
  2586. return false;
  2587. }
  2588. return true;
  2589. }
  2590. public:
  2591. BuildMIAction(unsigned InsnID, const CodeGenInstruction *I)
  2592. : InsnID(InsnID), I(I), Matched(nullptr) {}
  2593. unsigned getInsnID() const { return InsnID; }
  2594. const CodeGenInstruction *getCGI() const { return I; }
  2595. void chooseInsnToMutate(RuleMatcher &Rule) {
  2596. for (auto *MutateCandidate : Rule.mutatable_insns()) {
  2597. if (canMutate(Rule, MutateCandidate)) {
  2598. // Take the first one we're offered that we're able to mutate.
  2599. Rule.reserveInsnMatcherForMutation(MutateCandidate);
  2600. Matched = MutateCandidate;
  2601. return;
  2602. }
  2603. }
  2604. }
  2605. template <class Kind, class... Args>
  2606. Kind &addRenderer(Args&&... args) {
  2607. OperandRenderers.emplace_back(
  2608. std::make_unique<Kind>(InsnID, std::forward<Args>(args)...));
  2609. return *static_cast<Kind *>(OperandRenderers.back().get());
  2610. }
  2611. void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
  2612. if (Matched) {
  2613. assert(canMutate(Rule, Matched) &&
  2614. "Arranged to mutate an insn that isn't mutatable");
  2615. unsigned RecycleInsnID = Rule.getInsnVarID(*Matched);
  2616. Table << MatchTable::Opcode("GIR_MutateOpcode")
  2617. << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
  2618. << MatchTable::Comment("RecycleInsnID")
  2619. << MatchTable::IntValue(RecycleInsnID)
  2620. << MatchTable::Comment("Opcode")
  2621. << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
  2622. << MatchTable::LineBreak;
  2623. if (!I->ImplicitDefs.empty() || !I->ImplicitUses.empty()) {
  2624. for (auto Def : I->ImplicitDefs) {
  2625. auto Namespace = Def->getValue("Namespace")
  2626. ? Def->getValueAsString("Namespace")
  2627. : "";
  2628. Table << MatchTable::Opcode("GIR_AddImplicitDef")
  2629. << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
  2630. << MatchTable::NamedValue(Namespace, Def->getName())
  2631. << MatchTable::LineBreak;
  2632. }
  2633. for (auto Use : I->ImplicitUses) {
  2634. auto Namespace = Use->getValue("Namespace")
  2635. ? Use->getValueAsString("Namespace")
  2636. : "";
  2637. Table << MatchTable::Opcode("GIR_AddImplicitUse")
  2638. << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
  2639. << MatchTable::NamedValue(Namespace, Use->getName())
  2640. << MatchTable::LineBreak;
  2641. }
  2642. }
  2643. return;
  2644. }
  2645. // TODO: Simple permutation looks like it could be almost as common as
  2646. // mutation due to commutative operations.
  2647. Table << MatchTable::Opcode("GIR_BuildMI") << MatchTable::Comment("InsnID")
  2648. << MatchTable::IntValue(InsnID) << MatchTable::Comment("Opcode")
  2649. << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
  2650. << MatchTable::LineBreak;
  2651. for (const auto &Renderer : OperandRenderers)
  2652. Renderer->emitRenderOpcodes(Table, Rule);
  2653. if (I->mayLoad || I->mayStore) {
  2654. Table << MatchTable::Opcode("GIR_MergeMemOperands")
  2655. << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
  2656. << MatchTable::Comment("MergeInsnID's");
  2657. // Emit the ID's for all the instructions that are matched by this rule.
  2658. // TODO: Limit this to matched instructions that mayLoad/mayStore or have
  2659. // some other means of having a memoperand. Also limit this to
  2660. // emitted instructions that expect to have a memoperand too. For
  2661. // example, (G_SEXT (G_LOAD x)) that results in separate load and
  2662. // sign-extend instructions shouldn't put the memoperand on the
  2663. // sign-extend since it has no effect there.
  2664. std::vector<unsigned> MergeInsnIDs;
  2665. for (const auto &IDMatcherPair : Rule.defined_insn_vars())
  2666. MergeInsnIDs.push_back(IDMatcherPair.second);
  2667. llvm::sort(MergeInsnIDs);
  2668. for (const auto &MergeInsnID : MergeInsnIDs)
  2669. Table << MatchTable::IntValue(MergeInsnID);
  2670. Table << MatchTable::NamedValue("GIU_MergeMemOperands_EndOfList")
  2671. << MatchTable::LineBreak;
  2672. }
  2673. // FIXME: This is a hack but it's sufficient for ISel. We'll need to do
  2674. // better for combines. Particularly when there are multiple match
  2675. // roots.
  2676. if (InsnID == 0)
  2677. Table << MatchTable::Opcode("GIR_EraseFromParent")
  2678. << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
  2679. << MatchTable::LineBreak;
  2680. }
  2681. };
  2682. /// Generates code to constrain the operands of an output instruction to the
  2683. /// register classes specified by the definition of that instruction.
  2684. class ConstrainOperandsToDefinitionAction : public MatchAction {
  2685. unsigned InsnID;
  2686. public:
  2687. ConstrainOperandsToDefinitionAction(unsigned InsnID) : InsnID(InsnID) {}
  2688. void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
  2689. Table << MatchTable::Opcode("GIR_ConstrainSelectedInstOperands")
  2690. << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
  2691. << MatchTable::LineBreak;
  2692. }
  2693. };
  2694. /// Generates code to constrain the specified operand of an output instruction
  2695. /// to the specified register class.
  2696. class ConstrainOperandToRegClassAction : public MatchAction {
  2697. unsigned InsnID;
  2698. unsigned OpIdx;
  2699. const CodeGenRegisterClass &RC;
  2700. public:
  2701. ConstrainOperandToRegClassAction(unsigned InsnID, unsigned OpIdx,
  2702. const CodeGenRegisterClass &RC)
  2703. : InsnID(InsnID), OpIdx(OpIdx), RC(RC) {}
  2704. void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
  2705. Table << MatchTable::Opcode("GIR_ConstrainOperandRC")
  2706. << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
  2707. << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
  2708. << MatchTable::NamedValue(RC.getQualifiedName() + "RegClassID")
  2709. << MatchTable::LineBreak;
  2710. }
  2711. };
  2712. /// Generates code to create a temporary register which can be used to chain
  2713. /// instructions together.
  2714. class MakeTempRegisterAction : public MatchAction {
  2715. private:
  2716. LLTCodeGen Ty;
  2717. unsigned TempRegID;
  2718. public:
  2719. MakeTempRegisterAction(const LLTCodeGen &Ty, unsigned TempRegID)
  2720. : Ty(Ty), TempRegID(TempRegID) {
  2721. KnownTypes.insert(Ty);
  2722. }
  2723. void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
  2724. Table << MatchTable::Opcode("GIR_MakeTempReg")
  2725. << MatchTable::Comment("TempRegID") << MatchTable::IntValue(TempRegID)
  2726. << MatchTable::Comment("TypeID")
  2727. << MatchTable::NamedValue(Ty.getCxxEnumValue())
  2728. << MatchTable::LineBreak;
  2729. }
  2730. };
  2731. InstructionMatcher &RuleMatcher::addInstructionMatcher(StringRef SymbolicName) {
  2732. Matchers.emplace_back(new InstructionMatcher(*this, SymbolicName));
  2733. MutatableInsns.insert(Matchers.back().get());
  2734. return *Matchers.back();
  2735. }
  2736. void RuleMatcher::addRequiredFeature(Record *Feature) {
  2737. RequiredFeatures.push_back(Feature);
  2738. }
  2739. const std::vector<Record *> &RuleMatcher::getRequiredFeatures() const {
  2740. return RequiredFeatures;
  2741. }
  2742. // Emplaces an action of the specified Kind at the end of the action list.
  2743. //
  2744. // Returns a reference to the newly created action.
  2745. //
  2746. // Like std::vector::emplace_back(), may invalidate all iterators if the new
  2747. // size exceeds the capacity. Otherwise, only invalidates the past-the-end
  2748. // iterator.
  2749. template <class Kind, class... Args>
  2750. Kind &RuleMatcher::addAction(Args &&... args) {
  2751. Actions.emplace_back(std::make_unique<Kind>(std::forward<Args>(args)...));
  2752. return *static_cast<Kind *>(Actions.back().get());
  2753. }
  2754. // Emplaces an action of the specified Kind before the given insertion point.
  2755. //
  2756. // Returns an iterator pointing at the newly created instruction.
  2757. //
  2758. // Like std::vector::insert(), may invalidate all iterators if the new size
  2759. // exceeds the capacity. Otherwise, only invalidates the iterators from the
  2760. // insertion point onwards.
  2761. template <class Kind, class... Args>
  2762. action_iterator RuleMatcher::insertAction(action_iterator InsertPt,
  2763. Args &&... args) {
  2764. return Actions.emplace(InsertPt,
  2765. std::make_unique<Kind>(std::forward<Args>(args)...));
  2766. }
  2767. unsigned RuleMatcher::implicitlyDefineInsnVar(InstructionMatcher &Matcher) {
  2768. unsigned NewInsnVarID = NextInsnVarID++;
  2769. InsnVariableIDs[&Matcher] = NewInsnVarID;
  2770. return NewInsnVarID;
  2771. }
  2772. unsigned RuleMatcher::getInsnVarID(InstructionMatcher &InsnMatcher) const {
  2773. const auto &I = InsnVariableIDs.find(&InsnMatcher);
  2774. if (I != InsnVariableIDs.end())
  2775. return I->second;
  2776. llvm_unreachable("Matched Insn was not captured in a local variable");
  2777. }
  2778. void RuleMatcher::defineOperand(StringRef SymbolicName, OperandMatcher &OM) {
  2779. if (DefinedOperands.find(SymbolicName) == DefinedOperands.end()) {
  2780. DefinedOperands[SymbolicName] = &OM;
  2781. return;
  2782. }
  2783. // If the operand is already defined, then we must ensure both references in
  2784. // the matcher have the exact same node.
  2785. OM.addPredicate<SameOperandMatcher>(
  2786. OM.getSymbolicName(), getOperandMatcher(OM.getSymbolicName()).getOpIdx());
  2787. }
  2788. void RuleMatcher::definePhysRegOperand(Record *Reg, OperandMatcher &OM) {
  2789. if (PhysRegOperands.find(Reg) == PhysRegOperands.end()) {
  2790. PhysRegOperands[Reg] = &OM;
  2791. return;
  2792. }
  2793. }
  2794. InstructionMatcher &
  2795. RuleMatcher::getInstructionMatcher(StringRef SymbolicName) const {
  2796. for (const auto &I : InsnVariableIDs)
  2797. if (I.first->getSymbolicName() == SymbolicName)
  2798. return *I.first;
  2799. llvm_unreachable(
  2800. ("Failed to lookup instruction " + SymbolicName).str().c_str());
  2801. }
  2802. const OperandMatcher &
  2803. RuleMatcher::getPhysRegOperandMatcher(Record *Reg) const {
  2804. const auto &I = PhysRegOperands.find(Reg);
  2805. if (I == PhysRegOperands.end()) {
  2806. PrintFatalError(SrcLoc, "Register " + Reg->getName() +
  2807. " was not declared in matcher");
  2808. }
  2809. return *I->second;
  2810. }
  2811. const OperandMatcher &
  2812. RuleMatcher::getOperandMatcher(StringRef Name) const {
  2813. const auto &I = DefinedOperands.find(Name);
  2814. if (I == DefinedOperands.end())
  2815. PrintFatalError(SrcLoc, "Operand " + Name + " was not declared in matcher");
  2816. return *I->second;
  2817. }
  2818. void RuleMatcher::emit(MatchTable &Table) {
  2819. if (Matchers.empty())
  2820. llvm_unreachable("Unexpected empty matcher!");
  2821. // The representation supports rules that require multiple roots such as:
  2822. // %ptr(p0) = ...
  2823. // %elt0(s32) = G_LOAD %ptr
  2824. // %1(p0) = G_ADD %ptr, 4
  2825. // %elt1(s32) = G_LOAD p0 %1
  2826. // which could be usefully folded into:
  2827. // %ptr(p0) = ...
  2828. // %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr
  2829. // on some targets but we don't need to make use of that yet.
  2830. assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
  2831. unsigned LabelID = Table.allocateLabelID();
  2832. Table << MatchTable::Opcode("GIM_Try", +1)
  2833. << MatchTable::Comment("On fail goto")
  2834. << MatchTable::JumpTarget(LabelID)
  2835. << MatchTable::Comment(("Rule ID " + Twine(RuleID) + " //").str())
  2836. << MatchTable::LineBreak;
  2837. if (!RequiredFeatures.empty()) {
  2838. Table << MatchTable::Opcode("GIM_CheckFeatures")
  2839. << MatchTable::NamedValue(getNameForFeatureBitset(RequiredFeatures))
  2840. << MatchTable::LineBreak;
  2841. }
  2842. Matchers.front()->emitPredicateOpcodes(Table, *this);
  2843. // We must also check if it's safe to fold the matched instructions.
  2844. if (InsnVariableIDs.size() >= 2) {
  2845. // Invert the map to create stable ordering (by var names)
  2846. SmallVector<unsigned, 2> InsnIDs;
  2847. for (const auto &Pair : InsnVariableIDs) {
  2848. // Skip the root node since it isn't moving anywhere. Everything else is
  2849. // sinking to meet it.
  2850. if (Pair.first == Matchers.front().get())
  2851. continue;
  2852. InsnIDs.push_back(Pair.second);
  2853. }
  2854. llvm::sort(InsnIDs);
  2855. for (const auto &InsnID : InsnIDs) {
  2856. // Reject the difficult cases until we have a more accurate check.
  2857. Table << MatchTable::Opcode("GIM_CheckIsSafeToFold")
  2858. << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
  2859. << MatchTable::LineBreak;
  2860. // FIXME: Emit checks to determine it's _actually_ safe to fold and/or
  2861. // account for unsafe cases.
  2862. //
  2863. // Example:
  2864. // MI1--> %0 = ...
  2865. // %1 = ... %0
  2866. // MI0--> %2 = ... %0
  2867. // It's not safe to erase MI1. We currently handle this by not
  2868. // erasing %0 (even when it's dead).
  2869. //
  2870. // Example:
  2871. // MI1--> %0 = load volatile @a
  2872. // %1 = load volatile @a
  2873. // MI0--> %2 = ... %0
  2874. // It's not safe to sink %0's def past %1. We currently handle
  2875. // this by rejecting all loads.
  2876. //
  2877. // Example:
  2878. // MI1--> %0 = load @a
  2879. // %1 = store @a
  2880. // MI0--> %2 = ... %0
  2881. // It's not safe to sink %0's def past %1. We currently handle
  2882. // this by rejecting all loads.
  2883. //
  2884. // Example:
  2885. // G_CONDBR %cond, @BB1
  2886. // BB0:
  2887. // MI1--> %0 = load @a
  2888. // G_BR @BB1
  2889. // BB1:
  2890. // MI0--> %2 = ... %0
  2891. // It's not always safe to sink %0 across control flow. In this
  2892. // case it may introduce a memory fault. We currentl handle this
  2893. // by rejecting all loads.
  2894. }
  2895. }
  2896. for (const auto &PM : EpilogueMatchers)
  2897. PM->emitPredicateOpcodes(Table, *this);
  2898. for (const auto &MA : Actions)
  2899. MA->emitActionOpcodes(Table, *this);
  2900. if (Table.isWithCoverage())
  2901. Table << MatchTable::Opcode("GIR_Coverage") << MatchTable::IntValue(RuleID)
  2902. << MatchTable::LineBreak;
  2903. else
  2904. Table << MatchTable::Comment(("GIR_Coverage, " + Twine(RuleID) + ",").str())
  2905. << MatchTable::LineBreak;
  2906. Table << MatchTable::Opcode("GIR_Done", -1) << MatchTable::LineBreak
  2907. << MatchTable::Label(LabelID);
  2908. ++NumPatternEmitted;
  2909. }
  2910. bool RuleMatcher::isHigherPriorityThan(const RuleMatcher &B) const {
  2911. // Rules involving more match roots have higher priority.
  2912. if (Matchers.size() > B.Matchers.size())
  2913. return true;
  2914. if (Matchers.size() < B.Matchers.size())
  2915. return false;
  2916. for (auto Matcher : zip(Matchers, B.Matchers)) {
  2917. if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher)))
  2918. return true;
  2919. if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher)))
  2920. return false;
  2921. }
  2922. return false;
  2923. }
  2924. unsigned RuleMatcher::countRendererFns() const {
  2925. return std::accumulate(
  2926. Matchers.begin(), Matchers.end(), 0,
  2927. [](unsigned A, const std::unique_ptr<InstructionMatcher> &Matcher) {
  2928. return A + Matcher->countRendererFns();
  2929. });
  2930. }
  2931. bool OperandPredicateMatcher::isHigherPriorityThan(
  2932. const OperandPredicateMatcher &B) const {
  2933. // Generally speaking, an instruction is more important than an Int or a
  2934. // LiteralInt because it can cover more nodes but theres an exception to
  2935. // this. G_CONSTANT's are less important than either of those two because they
  2936. // are more permissive.
  2937. const InstructionOperandMatcher *AOM =
  2938. dyn_cast<InstructionOperandMatcher>(this);
  2939. const InstructionOperandMatcher *BOM =
  2940. dyn_cast<InstructionOperandMatcher>(&B);
  2941. bool AIsConstantInsn = AOM && AOM->getInsnMatcher().isConstantInstruction();
  2942. bool BIsConstantInsn = BOM && BOM->getInsnMatcher().isConstantInstruction();
  2943. if (AOM && BOM) {
  2944. // The relative priorities between a G_CONSTANT and any other instruction
  2945. // don't actually matter but this code is needed to ensure a strict weak
  2946. // ordering. This is particularly important on Windows where the rules will
  2947. // be incorrectly sorted without it.
  2948. if (AIsConstantInsn != BIsConstantInsn)
  2949. return AIsConstantInsn < BIsConstantInsn;
  2950. return false;
  2951. }
  2952. if (AOM && AIsConstantInsn && (B.Kind == OPM_Int || B.Kind == OPM_LiteralInt))
  2953. return false;
  2954. if (BOM && BIsConstantInsn && (Kind == OPM_Int || Kind == OPM_LiteralInt))
  2955. return true;
  2956. return Kind < B.Kind;
  2957. }
  2958. void SameOperandMatcher::emitPredicateOpcodes(MatchTable &Table,
  2959. RuleMatcher &Rule) const {
  2960. const OperandMatcher &OtherOM = Rule.getOperandMatcher(MatchingName);
  2961. unsigned OtherInsnVarID = Rule.getInsnVarID(OtherOM.getInstructionMatcher());
  2962. assert(OtherInsnVarID == OtherOM.getInstructionMatcher().getInsnVarID());
  2963. Table << MatchTable::Opcode("GIM_CheckIsSameOperand")
  2964. << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
  2965. << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
  2966. << MatchTable::Comment("OtherMI")
  2967. << MatchTable::IntValue(OtherInsnVarID)
  2968. << MatchTable::Comment("OtherOpIdx")
  2969. << MatchTable::IntValue(OtherOM.getOpIdx())
  2970. << MatchTable::LineBreak;
  2971. }
  2972. //===- GlobalISelEmitter class --------------------------------------------===//
  2973. static Expected<LLTCodeGen> getInstResultType(const TreePatternNode *Dst) {
  2974. ArrayRef<TypeSetByHwMode> ChildTypes = Dst->getExtTypes();
  2975. if (ChildTypes.size() != 1)
  2976. return failedImport("Dst pattern child has multiple results");
  2977. Optional<LLTCodeGen> MaybeOpTy;
  2978. if (ChildTypes.front().isMachineValueType()) {
  2979. MaybeOpTy =
  2980. MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
  2981. }
  2982. if (!MaybeOpTy)
  2983. return failedImport("Dst operand has an unsupported type");
  2984. return *MaybeOpTy;
  2985. }
  2986. class GlobalISelEmitter {
  2987. public:
  2988. explicit GlobalISelEmitter(RecordKeeper &RK);
  2989. void run(raw_ostream &OS);
  2990. private:
  2991. const RecordKeeper &RK;
  2992. const CodeGenDAGPatterns CGP;
  2993. const CodeGenTarget &Target;
  2994. CodeGenRegBank &CGRegs;
  2995. /// Keep track of the equivalence between SDNodes and Instruction by mapping
  2996. /// SDNodes to the GINodeEquiv mapping. We need to map to the GINodeEquiv to
  2997. /// check for attributes on the relation such as CheckMMOIsNonAtomic.
  2998. /// This is defined using 'GINodeEquiv' in the target description.
  2999. DenseMap<Record *, Record *> NodeEquivs;
  3000. /// Keep track of the equivalence between ComplexPattern's and
  3001. /// GIComplexOperandMatcher. Map entries are specified by subclassing
  3002. /// GIComplexPatternEquiv.
  3003. DenseMap<const Record *, const Record *> ComplexPatternEquivs;
  3004. /// Keep track of the equivalence between SDNodeXForm's and
  3005. /// GICustomOperandRenderer. Map entries are specified by subclassing
  3006. /// GISDNodeXFormEquiv.
  3007. DenseMap<const Record *, const Record *> SDNodeXFormEquivs;
  3008. /// Keep track of Scores of PatternsToMatch similar to how the DAG does.
  3009. /// This adds compatibility for RuleMatchers to use this for ordering rules.
  3010. DenseMap<uint64_t, int> RuleMatcherScores;
  3011. // Map of predicates to their subtarget features.
  3012. SubtargetFeatureInfoMap SubtargetFeatures;
  3013. // Rule coverage information.
  3014. Optional<CodeGenCoverage> RuleCoverage;
  3015. /// Variables used to help with collecting of named operands for predicates
  3016. /// with 'let PredicateCodeUsesOperands = 1'. WaitingForNamedOperands is set
  3017. /// to the number of named operands that predicate expects. Store locations in
  3018. /// StoreIdxForName correspond to the order in which operand names appear in
  3019. /// predicate's argument list.
  3020. /// When we visit named leaf operand and WaitingForNamedOperands is not zero,
  3021. /// add matcher that will record operand and decrease counter.
  3022. unsigned WaitingForNamedOperands = 0;
  3023. StringMap<unsigned> StoreIdxForName;
  3024. void gatherOpcodeValues();
  3025. void gatherTypeIDValues();
  3026. void gatherNodeEquivs();
  3027. Record *findNodeEquiv(Record *N) const;
  3028. const CodeGenInstruction *getEquivNode(Record &Equiv,
  3029. const TreePatternNode *N) const;
  3030. Error importRulePredicates(RuleMatcher &M, ArrayRef<Record *> Predicates);
  3031. Expected<InstructionMatcher &>
  3032. createAndImportSelDAGMatcher(RuleMatcher &Rule,
  3033. InstructionMatcher &InsnMatcher,
  3034. const TreePatternNode *Src, unsigned &TempOpIdx);
  3035. Error importComplexPatternOperandMatcher(OperandMatcher &OM, Record *R,
  3036. unsigned &TempOpIdx) const;
  3037. Error importChildMatcher(RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
  3038. const TreePatternNode *SrcChild,
  3039. bool OperandIsAPointer, bool OperandIsImmArg,
  3040. unsigned OpIdx, unsigned &TempOpIdx);
  3041. Expected<BuildMIAction &> createAndImportInstructionRenderer(
  3042. RuleMatcher &M, InstructionMatcher &InsnMatcher,
  3043. const TreePatternNode *Src, const TreePatternNode *Dst);
  3044. Expected<action_iterator> createAndImportSubInstructionRenderer(
  3045. action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst,
  3046. unsigned TempReg);
  3047. Expected<action_iterator>
  3048. createInstructionRenderer(action_iterator InsertPt, RuleMatcher &M,
  3049. const TreePatternNode *Dst);
  3050. Expected<action_iterator>
  3051. importExplicitDefRenderers(action_iterator InsertPt, RuleMatcher &M,
  3052. BuildMIAction &DstMIBuilder,
  3053. const TreePatternNode *Dst);
  3054. Expected<action_iterator>
  3055. importExplicitUseRenderers(action_iterator InsertPt, RuleMatcher &M,
  3056. BuildMIAction &DstMIBuilder,
  3057. const llvm::TreePatternNode *Dst);
  3058. Expected<action_iterator>
  3059. importExplicitUseRenderer(action_iterator InsertPt, RuleMatcher &Rule,
  3060. BuildMIAction &DstMIBuilder,
  3061. TreePatternNode *DstChild);
  3062. Error importDefaultOperandRenderers(action_iterator InsertPt, RuleMatcher &M,
  3063. BuildMIAction &DstMIBuilder,
  3064. DagInit *DefaultOps) const;
  3065. Error
  3066. importImplicitDefRenderers(BuildMIAction &DstMIBuilder,
  3067. const std::vector<Record *> &ImplicitDefs) const;
  3068. void emitCxxPredicateFns(raw_ostream &OS, StringRef CodeFieldName,
  3069. StringRef TypeIdentifier, StringRef ArgType,
  3070. StringRef ArgName, StringRef AdditionalArgs,
  3071. StringRef AdditionalDeclarations,
  3072. std::function<bool(const Record *R)> Filter);
  3073. void emitImmPredicateFns(raw_ostream &OS, StringRef TypeIdentifier,
  3074. StringRef ArgType,
  3075. std::function<bool(const Record *R)> Filter);
  3076. void emitMIPredicateFns(raw_ostream &OS);
  3077. /// Analyze pattern \p P, returning a matcher for it if possible.
  3078. /// Otherwise, return an Error explaining why we don't support it.
  3079. Expected<RuleMatcher> runOnPattern(const PatternToMatch &P);
  3080. void declareSubtargetFeature(Record *Predicate);
  3081. MatchTable buildMatchTable(MutableArrayRef<RuleMatcher> Rules, bool Optimize,
  3082. bool WithCoverage);
  3083. /// Infer a CodeGenRegisterClass for the type of \p SuperRegNode. The returned
  3084. /// CodeGenRegisterClass will support the CodeGenRegisterClass of
  3085. /// \p SubRegNode, and the subregister index defined by \p SubRegIdxNode.
  3086. /// If no register class is found, return None.
  3087. Optional<const CodeGenRegisterClass *>
  3088. inferSuperRegisterClassForNode(const TypeSetByHwMode &Ty,
  3089. TreePatternNode *SuperRegNode,
  3090. TreePatternNode *SubRegIdxNode);
  3091. Optional<CodeGenSubRegIndex *>
  3092. inferSubRegIndexForNode(TreePatternNode *SubRegIdxNode);
  3093. /// Infer a CodeGenRegisterClass which suppoorts \p Ty and \p SubRegIdxNode.
  3094. /// Return None if no such class exists.
  3095. Optional<const CodeGenRegisterClass *>
  3096. inferSuperRegisterClass(const TypeSetByHwMode &Ty,
  3097. TreePatternNode *SubRegIdxNode);
  3098. /// Return the CodeGenRegisterClass associated with \p Leaf if it has one.
  3099. Optional<const CodeGenRegisterClass *>
  3100. getRegClassFromLeaf(TreePatternNode *Leaf);
  3101. /// Return a CodeGenRegisterClass for \p N if one can be found. Return None
  3102. /// otherwise.
  3103. Optional<const CodeGenRegisterClass *>
  3104. inferRegClassFromPattern(TreePatternNode *N);
  3105. /// Return the size of the MemoryVT in this predicate, if possible.
  3106. Optional<unsigned>
  3107. getMemSizeBitsFromPredicate(const TreePredicateFn &Predicate);
  3108. // Add builtin predicates.
  3109. Expected<InstructionMatcher &>
  3110. addBuiltinPredicates(const Record *SrcGIEquivOrNull,
  3111. const TreePredicateFn &Predicate,
  3112. InstructionMatcher &InsnMatcher, bool &HasAddedMatcher);
  3113. public:
  3114. /// Takes a sequence of \p Rules and group them based on the predicates
  3115. /// they share. \p MatcherStorage is used as a memory container
  3116. /// for the group that are created as part of this process.
  3117. ///
  3118. /// What this optimization does looks like if GroupT = GroupMatcher:
  3119. /// Output without optimization:
  3120. /// \verbatim
  3121. /// # R1
  3122. /// # predicate A
  3123. /// # predicate B
  3124. /// ...
  3125. /// # R2
  3126. /// # predicate A // <-- effectively this is going to be checked twice.
  3127. /// // Once in R1 and once in R2.
  3128. /// # predicate C
  3129. /// \endverbatim
  3130. /// Output with optimization:
  3131. /// \verbatim
  3132. /// # Group1_2
  3133. /// # predicate A // <-- Check is now shared.
  3134. /// # R1
  3135. /// # predicate B
  3136. /// # R2
  3137. /// # predicate C
  3138. /// \endverbatim
  3139. template <class GroupT>
  3140. static std::vector<Matcher *> optimizeRules(
  3141. ArrayRef<Matcher *> Rules,
  3142. std::vector<std::unique_ptr<Matcher>> &MatcherStorage);
  3143. };
  3144. void GlobalISelEmitter::gatherOpcodeValues() {
  3145. InstructionOpcodeMatcher::initOpcodeValuesMap(Target);
  3146. }
  3147. void GlobalISelEmitter::gatherTypeIDValues() {
  3148. LLTOperandMatcher::initTypeIDValuesMap();
  3149. }
  3150. void GlobalISelEmitter::gatherNodeEquivs() {
  3151. assert(NodeEquivs.empty());
  3152. for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
  3153. NodeEquivs[Equiv->getValueAsDef("Node")] = Equiv;
  3154. assert(ComplexPatternEquivs.empty());
  3155. for (Record *Equiv : RK.getAllDerivedDefinitions("GIComplexPatternEquiv")) {
  3156. Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
  3157. if (!SelDAGEquiv)
  3158. continue;
  3159. ComplexPatternEquivs[SelDAGEquiv] = Equiv;
  3160. }
  3161. assert(SDNodeXFormEquivs.empty());
  3162. for (Record *Equiv : RK.getAllDerivedDefinitions("GISDNodeXFormEquiv")) {
  3163. Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
  3164. if (!SelDAGEquiv)
  3165. continue;
  3166. SDNodeXFormEquivs[SelDAGEquiv] = Equiv;
  3167. }
  3168. }
  3169. Record *GlobalISelEmitter::findNodeEquiv(Record *N) const {
  3170. return NodeEquivs.lookup(N);
  3171. }
  3172. const CodeGenInstruction *
  3173. GlobalISelEmitter::getEquivNode(Record &Equiv, const TreePatternNode *N) const {
  3174. if (N->getNumChildren() >= 1) {
  3175. // setcc operation maps to two different G_* instructions based on the type.
  3176. if (!Equiv.isValueUnset("IfFloatingPoint") &&
  3177. MVT(N->getChild(0)->getSimpleType(0)).isFloatingPoint())
  3178. return &Target.getInstruction(Equiv.getValueAsDef("IfFloatingPoint"));
  3179. }
  3180. for (const TreePredicateCall &Call : N->getPredicateCalls()) {
  3181. const TreePredicateFn &Predicate = Call.Fn;
  3182. if (!Equiv.isValueUnset("IfSignExtend") && Predicate.isLoad() &&
  3183. Predicate.isSignExtLoad())
  3184. return &Target.getInstruction(Equiv.getValueAsDef("IfSignExtend"));
  3185. if (!Equiv.isValueUnset("IfZeroExtend") && Predicate.isLoad() &&
  3186. Predicate.isZeroExtLoad())
  3187. return &Target.getInstruction(Equiv.getValueAsDef("IfZeroExtend"));
  3188. }
  3189. return &Target.getInstruction(Equiv.getValueAsDef("I"));
  3190. }
  3191. GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK)
  3192. : RK(RK), CGP(RK), Target(CGP.getTargetInfo()),
  3193. CGRegs(Target.getRegBank()) {}
  3194. //===- Emitter ------------------------------------------------------------===//
  3195. Error GlobalISelEmitter::importRulePredicates(RuleMatcher &M,
  3196. ArrayRef<Record *> Predicates) {
  3197. for (Record *Pred : Predicates) {
  3198. if (Pred->getValueAsString("CondString").empty())
  3199. continue;
  3200. declareSubtargetFeature(Pred);
  3201. M.addRequiredFeature(Pred);
  3202. }
  3203. return Error::success();
  3204. }
  3205. Optional<unsigned> GlobalISelEmitter::getMemSizeBitsFromPredicate(const TreePredicateFn &Predicate) {
  3206. Optional<LLTCodeGen> MemTyOrNone =
  3207. MVTToLLT(getValueType(Predicate.getMemoryVT()));
  3208. if (!MemTyOrNone)
  3209. return None;
  3210. // Align so unusual types like i1 don't get rounded down.
  3211. return llvm::alignTo(
  3212. static_cast<unsigned>(MemTyOrNone->get().getSizeInBits()), 8);
  3213. }
  3214. Expected<InstructionMatcher &> GlobalISelEmitter::addBuiltinPredicates(
  3215. const Record *SrcGIEquivOrNull, const TreePredicateFn &Predicate,
  3216. InstructionMatcher &InsnMatcher, bool &HasAddedMatcher) {
  3217. if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
  3218. if (const ListInit *AddrSpaces = Predicate.getAddressSpaces()) {
  3219. SmallVector<unsigned, 4> ParsedAddrSpaces;
  3220. for (Init *Val : AddrSpaces->getValues()) {
  3221. IntInit *IntVal = dyn_cast<IntInit>(Val);
  3222. if (!IntVal)
  3223. return failedImport("Address space is not an integer");
  3224. ParsedAddrSpaces.push_back(IntVal->getValue());
  3225. }
  3226. if (!ParsedAddrSpaces.empty()) {
  3227. InsnMatcher.addPredicate<MemoryAddressSpacePredicateMatcher>(
  3228. 0, ParsedAddrSpaces);
  3229. }
  3230. }
  3231. int64_t MinAlign = Predicate.getMinAlignment();
  3232. if (MinAlign > 0)
  3233. InsnMatcher.addPredicate<MemoryAlignmentPredicateMatcher>(0, MinAlign);
  3234. }
  3235. // G_LOAD is used for both non-extending and any-extending loads.
  3236. if (Predicate.isLoad() && Predicate.isNonExtLoad()) {
  3237. InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
  3238. 0, MemoryVsLLTSizePredicateMatcher::EqualTo, 0);
  3239. return InsnMatcher;
  3240. }
  3241. if (Predicate.isLoad() && Predicate.isAnyExtLoad()) {
  3242. InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
  3243. 0, MemoryVsLLTSizePredicateMatcher::LessThan, 0);
  3244. return InsnMatcher;
  3245. }
  3246. if (Predicate.isStore()) {
  3247. if (Predicate.isTruncStore()) {
  3248. if (Predicate.getMemoryVT() != nullptr) {
  3249. // FIXME: If MemoryVT is set, we end up with 2 checks for the MMO size.
  3250. auto MemSizeInBits = getMemSizeBitsFromPredicate(Predicate);
  3251. if (!MemSizeInBits)
  3252. return failedImport("MemVT could not be converted to LLT");
  3253. InsnMatcher.addPredicate<MemorySizePredicateMatcher>(0, *MemSizeInBits /
  3254. 8);
  3255. } else {
  3256. InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
  3257. 0, MemoryVsLLTSizePredicateMatcher::LessThan, 0);
  3258. }
  3259. return InsnMatcher;
  3260. }
  3261. if (Predicate.isNonTruncStore()) {
  3262. // We need to check the sizes match here otherwise we could incorrectly
  3263. // match truncating stores with non-truncating ones.
  3264. InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
  3265. 0, MemoryVsLLTSizePredicateMatcher::EqualTo, 0);
  3266. }
  3267. }
  3268. // No check required. We already did it by swapping the opcode.
  3269. if (!SrcGIEquivOrNull->isValueUnset("IfSignExtend") &&
  3270. Predicate.isSignExtLoad())
  3271. return InsnMatcher;
  3272. // No check required. We already did it by swapping the opcode.
  3273. if (!SrcGIEquivOrNull->isValueUnset("IfZeroExtend") &&
  3274. Predicate.isZeroExtLoad())
  3275. return InsnMatcher;
  3276. // No check required. G_STORE by itself is a non-extending store.
  3277. if (Predicate.isNonTruncStore())
  3278. return InsnMatcher;
  3279. if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
  3280. if (Predicate.getMemoryVT() != nullptr) {
  3281. auto MemSizeInBits = getMemSizeBitsFromPredicate(Predicate);
  3282. if (!MemSizeInBits)
  3283. return failedImport("MemVT could not be converted to LLT");
  3284. InsnMatcher.addPredicate<MemorySizePredicateMatcher>(0,
  3285. *MemSizeInBits / 8);
  3286. return InsnMatcher;
  3287. }
  3288. }
  3289. if (Predicate.isLoad() || Predicate.isStore()) {
  3290. // No check required. A G_LOAD/G_STORE is an unindexed load.
  3291. if (Predicate.isUnindexed())
  3292. return InsnMatcher;
  3293. }
  3294. if (Predicate.isAtomic()) {
  3295. if (Predicate.isAtomicOrderingMonotonic()) {
  3296. InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Monotonic");
  3297. return InsnMatcher;
  3298. }
  3299. if (Predicate.isAtomicOrderingAcquire()) {
  3300. InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Acquire");
  3301. return InsnMatcher;
  3302. }
  3303. if (Predicate.isAtomicOrderingRelease()) {
  3304. InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Release");
  3305. return InsnMatcher;
  3306. }
  3307. if (Predicate.isAtomicOrderingAcquireRelease()) {
  3308. InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
  3309. "AcquireRelease");
  3310. return InsnMatcher;
  3311. }
  3312. if (Predicate.isAtomicOrderingSequentiallyConsistent()) {
  3313. InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
  3314. "SequentiallyConsistent");
  3315. return InsnMatcher;
  3316. }
  3317. }
  3318. if (Predicate.isAtomicOrderingAcquireOrStronger()) {
  3319. InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
  3320. "Acquire", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
  3321. return InsnMatcher;
  3322. }
  3323. if (Predicate.isAtomicOrderingWeakerThanAcquire()) {
  3324. InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
  3325. "Acquire", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan);
  3326. return InsnMatcher;
  3327. }
  3328. if (Predicate.isAtomicOrderingReleaseOrStronger()) {
  3329. InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
  3330. "Release", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
  3331. return InsnMatcher;
  3332. }
  3333. if (Predicate.isAtomicOrderingWeakerThanRelease()) {
  3334. InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
  3335. "Release", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan);
  3336. return InsnMatcher;
  3337. }
  3338. HasAddedMatcher = false;
  3339. return InsnMatcher;
  3340. }
  3341. Expected<InstructionMatcher &> GlobalISelEmitter::createAndImportSelDAGMatcher(
  3342. RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
  3343. const TreePatternNode *Src, unsigned &TempOpIdx) {
  3344. Record *SrcGIEquivOrNull = nullptr;
  3345. const CodeGenInstruction *SrcGIOrNull = nullptr;
  3346. // Start with the defined operands (i.e., the results of the root operator).
  3347. if (Src->getExtTypes().size() > 1)
  3348. return failedImport("Src pattern has multiple results");
  3349. if (Src->isLeaf()) {
  3350. Init *SrcInit = Src->getLeafValue();
  3351. if (isa<IntInit>(SrcInit)) {
  3352. InsnMatcher.addPredicate<InstructionOpcodeMatcher>(
  3353. &Target.getInstruction(RK.getDef("G_CONSTANT")));
  3354. } else
  3355. return failedImport(
  3356. "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
  3357. } else {
  3358. SrcGIEquivOrNull = findNodeEquiv(Src->getOperator());
  3359. if (!SrcGIEquivOrNull)
  3360. return failedImport("Pattern operator lacks an equivalent Instruction" +
  3361. explainOperator(Src->getOperator()));
  3362. SrcGIOrNull = getEquivNode(*SrcGIEquivOrNull, Src);
  3363. // The operators look good: match the opcode
  3364. InsnMatcher.addPredicate<InstructionOpcodeMatcher>(SrcGIOrNull);
  3365. }
  3366. unsigned OpIdx = 0;
  3367. for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
  3368. // Results don't have a name unless they are the root node. The caller will
  3369. // set the name if appropriate.
  3370. OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
  3371. if (auto Error = OM.addTypeCheckPredicate(VTy, false /* OperandIsAPointer */))
  3372. return failedImport(toString(std::move(Error)) +
  3373. " for result of Src pattern operator");
  3374. }
  3375. for (const TreePredicateCall &Call : Src->getPredicateCalls()) {
  3376. const TreePredicateFn &Predicate = Call.Fn;
  3377. bool HasAddedBuiltinMatcher = true;
  3378. if (Predicate.isAlwaysTrue())
  3379. continue;
  3380. if (Predicate.isImmediatePattern()) {
  3381. InsnMatcher.addPredicate<InstructionImmPredicateMatcher>(Predicate);
  3382. continue;
  3383. }
  3384. auto InsnMatcherOrError = addBuiltinPredicates(
  3385. SrcGIEquivOrNull, Predicate, InsnMatcher, HasAddedBuiltinMatcher);
  3386. if (auto Error = InsnMatcherOrError.takeError())
  3387. return std::move(Error);
  3388. if (Predicate.hasGISelPredicateCode()) {
  3389. if (Predicate.usesOperands()) {
  3390. assert(WaitingForNamedOperands == 0 &&
  3391. "previous predicate didn't find all operands or "
  3392. "nested predicate that uses operands");
  3393. TreePattern *TP = Predicate.getOrigPatFragRecord();
  3394. WaitingForNamedOperands = TP->getNumArgs();
  3395. for (unsigned i = 0; i < WaitingForNamedOperands; ++i)
  3396. StoreIdxForName[getScopedName(Call.Scope, TP->getArgName(i))] = i;
  3397. }
  3398. InsnMatcher.addPredicate<GenericInstructionPredicateMatcher>(Predicate);
  3399. continue;
  3400. }
  3401. if (!HasAddedBuiltinMatcher) {
  3402. return failedImport("Src pattern child has predicate (" +
  3403. explainPredicates(Src) + ")");
  3404. }
  3405. }
  3406. bool IsAtomic = false;
  3407. if (SrcGIEquivOrNull && SrcGIEquivOrNull->getValueAsBit("CheckMMOIsNonAtomic"))
  3408. InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("NotAtomic");
  3409. else if (SrcGIEquivOrNull && SrcGIEquivOrNull->getValueAsBit("CheckMMOIsAtomic")) {
  3410. IsAtomic = true;
  3411. InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
  3412. "Unordered", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
  3413. }
  3414. if (Src->isLeaf()) {
  3415. Init *SrcInit = Src->getLeafValue();
  3416. if (IntInit *SrcIntInit = dyn_cast<IntInit>(SrcInit)) {
  3417. OperandMatcher &OM =
  3418. InsnMatcher.addOperand(OpIdx++, Src->getName(), TempOpIdx);
  3419. OM.addPredicate<LiteralIntOperandMatcher>(SrcIntInit->getValue());
  3420. } else
  3421. return failedImport(
  3422. "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
  3423. } else {
  3424. assert(SrcGIOrNull &&
  3425. "Expected to have already found an equivalent Instruction");
  3426. if (SrcGIOrNull->TheDef->getName() == "G_CONSTANT" ||
  3427. SrcGIOrNull->TheDef->getName() == "G_FCONSTANT") {
  3428. // imm/fpimm still have operands but we don't need to do anything with it
  3429. // here since we don't support ImmLeaf predicates yet. However, we still
  3430. // need to note the hidden operand to get GIM_CheckNumOperands correct.
  3431. InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
  3432. return InsnMatcher;
  3433. }
  3434. // Special case because the operand order is changed from setcc. The
  3435. // predicate operand needs to be swapped from the last operand to the first
  3436. // source.
  3437. unsigned NumChildren = Src->getNumChildren();
  3438. bool IsFCmp = SrcGIOrNull->TheDef->getName() == "G_FCMP";
  3439. if (IsFCmp || SrcGIOrNull->TheDef->getName() == "G_ICMP") {
  3440. TreePatternNode *SrcChild = Src->getChild(NumChildren - 1);
  3441. if (SrcChild->isLeaf()) {
  3442. DefInit *DI = dyn_cast<DefInit>(SrcChild->getLeafValue());
  3443. Record *CCDef = DI ? DI->getDef() : nullptr;
  3444. if (!CCDef || !CCDef->isSubClassOf("CondCode"))
  3445. return failedImport("Unable to handle CondCode");
  3446. OperandMatcher &OM =
  3447. InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx);
  3448. StringRef PredType = IsFCmp ? CCDef->getValueAsString("FCmpPredicate") :
  3449. CCDef->getValueAsString("ICmpPredicate");
  3450. if (!PredType.empty()) {
  3451. OM.addPredicate<CmpPredicateOperandMatcher>(std::string(PredType));
  3452. // Process the other 2 operands normally.
  3453. --NumChildren;
  3454. }
  3455. }
  3456. }
  3457. // Hack around an unfortunate mistake in how atomic store (and really
  3458. // atomicrmw in general) operands were ordered. A ISD::STORE used the order
  3459. // <stored value>, <pointer> order. ISD::ATOMIC_STORE used the opposite,
  3460. // <pointer>, <stored value>. In GlobalISel there's just the one store
  3461. // opcode, so we need to swap the operands here to get the right type check.
  3462. if (IsAtomic && SrcGIOrNull->TheDef->getName() == "G_STORE") {
  3463. assert(NumChildren == 2 && "wrong operands for atomic store");
  3464. TreePatternNode *PtrChild = Src->getChild(0);
  3465. TreePatternNode *ValueChild = Src->getChild(1);
  3466. if (auto Error = importChildMatcher(Rule, InsnMatcher, PtrChild, true,
  3467. false, 1, TempOpIdx))
  3468. return std::move(Error);
  3469. if (auto Error = importChildMatcher(Rule, InsnMatcher, ValueChild, false,
  3470. false, 0, TempOpIdx))
  3471. return std::move(Error);
  3472. return InsnMatcher;
  3473. }
  3474. // Match the used operands (i.e. the children of the operator).
  3475. bool IsIntrinsic =
  3476. SrcGIOrNull->TheDef->getName() == "G_INTRINSIC" ||
  3477. SrcGIOrNull->TheDef->getName() == "G_INTRINSIC_W_SIDE_EFFECTS";
  3478. const CodeGenIntrinsic *II = Src->getIntrinsicInfo(CGP);
  3479. if (IsIntrinsic && !II)
  3480. return failedImport("Expected IntInit containing intrinsic ID)");
  3481. for (unsigned i = 0; i != NumChildren; ++i) {
  3482. TreePatternNode *SrcChild = Src->getChild(i);
  3483. // We need to determine the meaning of a literal integer based on the
  3484. // context. If this is a field required to be an immediate (such as an
  3485. // immarg intrinsic argument), the required predicates are different than
  3486. // a constant which may be materialized in a register. If we have an
  3487. // argument that is required to be an immediate, we should not emit an LLT
  3488. // type check, and should not be looking for a G_CONSTANT defined
  3489. // register.
  3490. bool OperandIsImmArg = SrcGIOrNull->isOperandImmArg(i);
  3491. // SelectionDAG allows pointers to be represented with iN since it doesn't
  3492. // distinguish between pointers and integers but they are different types in GlobalISel.
  3493. // Coerce integers to pointers to address space 0 if the context indicates a pointer.
  3494. //
  3495. bool OperandIsAPointer = SrcGIOrNull->isOperandAPointer(i);
  3496. if (IsIntrinsic) {
  3497. // For G_INTRINSIC/G_INTRINSIC_W_SIDE_EFFECTS, the operand immediately
  3498. // following the defs is an intrinsic ID.
  3499. if (i == 0) {
  3500. OperandMatcher &OM =
  3501. InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx);
  3502. OM.addPredicate<IntrinsicIDOperandMatcher>(II);
  3503. continue;
  3504. }
  3505. // We have to check intrinsics for llvm_anyptr_ty and immarg parameters.
  3506. //
  3507. // Note that we have to look at the i-1th parameter, because we don't
  3508. // have the intrinsic ID in the intrinsic's parameter list.
  3509. OperandIsAPointer |= II->isParamAPointer(i - 1);
  3510. OperandIsImmArg |= II->isParamImmArg(i - 1);
  3511. }
  3512. if (auto Error =
  3513. importChildMatcher(Rule, InsnMatcher, SrcChild, OperandIsAPointer,
  3514. OperandIsImmArg, OpIdx++, TempOpIdx))
  3515. return std::move(Error);
  3516. }
  3517. }
  3518. return InsnMatcher;
  3519. }
  3520. Error GlobalISelEmitter::importComplexPatternOperandMatcher(
  3521. OperandMatcher &OM, Record *R, unsigned &TempOpIdx) const {
  3522. const auto &ComplexPattern = ComplexPatternEquivs.find(R);
  3523. if (ComplexPattern == ComplexPatternEquivs.end())
  3524. return failedImport("SelectionDAG ComplexPattern (" + R->getName() +
  3525. ") not mapped to GlobalISel");
  3526. OM.addPredicate<ComplexPatternOperandMatcher>(OM, *ComplexPattern->second);
  3527. TempOpIdx++;
  3528. return Error::success();
  3529. }
  3530. // Get the name to use for a pattern operand. For an anonymous physical register
  3531. // input, this should use the register name.
  3532. static StringRef getSrcChildName(const TreePatternNode *SrcChild,
  3533. Record *&PhysReg) {
  3534. StringRef SrcChildName = SrcChild->getName();
  3535. if (SrcChildName.empty() && SrcChild->isLeaf()) {
  3536. if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
  3537. auto *ChildRec = ChildDefInit->getDef();
  3538. if (ChildRec->isSubClassOf("Register")) {
  3539. SrcChildName = ChildRec->getName();
  3540. PhysReg = ChildRec;
  3541. }
  3542. }
  3543. }
  3544. return SrcChildName;
  3545. }
  3546. Error GlobalISelEmitter::importChildMatcher(
  3547. RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
  3548. const TreePatternNode *SrcChild, bool OperandIsAPointer,
  3549. bool OperandIsImmArg, unsigned OpIdx, unsigned &TempOpIdx) {
  3550. Record *PhysReg = nullptr;
  3551. std::string SrcChildName = std::string(getSrcChildName(SrcChild, PhysReg));
  3552. if (!SrcChild->isLeaf() &&
  3553. SrcChild->getOperator()->isSubClassOf("ComplexPattern")) {
  3554. // The "name" of a non-leaf complex pattern (MY_PAT $op1, $op2) is
  3555. // "MY_PAT:op1:op2" and the ones with same "name" represent same operand.
  3556. std::string PatternName = std::string(SrcChild->getOperator()->getName());
  3557. for (unsigned i = 0; i < SrcChild->getNumChildren(); ++i) {
  3558. PatternName += ":";
  3559. PatternName += SrcChild->getChild(i)->getName();
  3560. }
  3561. SrcChildName = PatternName;
  3562. }
  3563. OperandMatcher &OM =
  3564. PhysReg ? InsnMatcher.addPhysRegInput(PhysReg, OpIdx, TempOpIdx)
  3565. : InsnMatcher.addOperand(OpIdx, SrcChildName, TempOpIdx);
  3566. if (OM.isSameAsAnotherOperand())
  3567. return Error::success();
  3568. ArrayRef<TypeSetByHwMode> ChildTypes = SrcChild->getExtTypes();
  3569. if (ChildTypes.size() != 1)
  3570. return failedImport("Src pattern child has multiple results");
  3571. // Check MBB's before the type check since they are not a known type.
  3572. if (!SrcChild->isLeaf()) {
  3573. if (SrcChild->getOperator()->isSubClassOf("SDNode")) {
  3574. auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator());
  3575. if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
  3576. OM.addPredicate<MBBOperandMatcher>();
  3577. return Error::success();
  3578. }
  3579. if (SrcChild->getOperator()->getName() == "timm") {
  3580. OM.addPredicate<ImmOperandMatcher>();
  3581. // Add predicates, if any
  3582. for (const TreePredicateCall &Call : SrcChild->getPredicateCalls()) {
  3583. const TreePredicateFn &Predicate = Call.Fn;
  3584. // Only handle immediate patterns for now
  3585. if (Predicate.isImmediatePattern()) {
  3586. OM.addPredicate<OperandImmPredicateMatcher>(Predicate);
  3587. }
  3588. }
  3589. return Error::success();
  3590. }
  3591. }
  3592. }
  3593. // Immediate arguments have no meaningful type to check as they don't have
  3594. // registers.
  3595. if (!OperandIsImmArg) {
  3596. if (auto Error =
  3597. OM.addTypeCheckPredicate(ChildTypes.front(), OperandIsAPointer))
  3598. return failedImport(toString(std::move(Error)) + " for Src operand (" +
  3599. to_string(*SrcChild) + ")");
  3600. }
  3601. // Check for nested instructions.
  3602. if (!SrcChild->isLeaf()) {
  3603. if (SrcChild->getOperator()->isSubClassOf("ComplexPattern")) {
  3604. // When a ComplexPattern is used as an operator, it should do the same
  3605. // thing as when used as a leaf. However, the children of the operator
  3606. // name the sub-operands that make up the complex operand and we must
  3607. // prepare to reference them in the renderer too.
  3608. unsigned RendererID = TempOpIdx;
  3609. if (auto Error = importComplexPatternOperandMatcher(
  3610. OM, SrcChild->getOperator(), TempOpIdx))
  3611. return Error;
  3612. for (unsigned i = 0, e = SrcChild->getNumChildren(); i != e; ++i) {
  3613. auto *SubOperand = SrcChild->getChild(i);
  3614. if (!SubOperand->getName().empty()) {
  3615. if (auto Error = Rule.defineComplexSubOperand(
  3616. SubOperand->getName(), SrcChild->getOperator(), RendererID, i,
  3617. SrcChildName))
  3618. return Error;
  3619. }
  3620. }
  3621. return Error::success();
  3622. }
  3623. auto MaybeInsnOperand = OM.addPredicate<InstructionOperandMatcher>(
  3624. InsnMatcher.getRuleMatcher(), SrcChild->getName());
  3625. if (!MaybeInsnOperand.hasValue()) {
  3626. // This isn't strictly true. If the user were to provide exactly the same
  3627. // matchers as the original operand then we could allow it. However, it's
  3628. // simpler to not permit the redundant specification.
  3629. return failedImport("Nested instruction cannot be the same as another operand");
  3630. }
  3631. // Map the node to a gMIR instruction.
  3632. InstructionOperandMatcher &InsnOperand = **MaybeInsnOperand;
  3633. auto InsnMatcherOrError = createAndImportSelDAGMatcher(
  3634. Rule, InsnOperand.getInsnMatcher(), SrcChild, TempOpIdx);
  3635. if (auto Error = InsnMatcherOrError.takeError())
  3636. return Error;
  3637. return Error::success();
  3638. }
  3639. if (SrcChild->hasAnyPredicate())
  3640. return failedImport("Src pattern child has unsupported predicate");
  3641. // Check for constant immediates.
  3642. if (auto *ChildInt = dyn_cast<IntInit>(SrcChild->getLeafValue())) {
  3643. if (OperandIsImmArg) {
  3644. // Checks for argument directly in operand list
  3645. OM.addPredicate<LiteralIntOperandMatcher>(ChildInt->getValue());
  3646. } else {
  3647. // Checks for materialized constant
  3648. OM.addPredicate<ConstantIntOperandMatcher>(ChildInt->getValue());
  3649. }
  3650. return Error::success();
  3651. }
  3652. // Check for def's like register classes or ComplexPattern's.
  3653. if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
  3654. auto *ChildRec = ChildDefInit->getDef();
  3655. if (WaitingForNamedOperands) {
  3656. auto PA = SrcChild->getNamesAsPredicateArg().begin();
  3657. std::string Name = getScopedName(PA->getScope(), PA->getIdentifier());
  3658. OM.addPredicate<RecordNamedOperandMatcher>(StoreIdxForName[Name], Name);
  3659. --WaitingForNamedOperands;
  3660. }
  3661. // Check for register classes.
  3662. if (ChildRec->isSubClassOf("RegisterClass") ||
  3663. ChildRec->isSubClassOf("RegisterOperand")) {
  3664. OM.addPredicate<RegisterBankOperandMatcher>(
  3665. Target.getRegisterClass(getInitValueAsRegClass(ChildDefInit)));
  3666. return Error::success();
  3667. }
  3668. if (ChildRec->isSubClassOf("Register")) {
  3669. // This just be emitted as a copy to the specific register.
  3670. ValueTypeByHwMode VT = ChildTypes.front().getValueTypeByHwMode();
  3671. const CodeGenRegisterClass *RC
  3672. = CGRegs.getMinimalPhysRegClass(ChildRec, &VT);
  3673. if (!RC) {
  3674. return failedImport(
  3675. "Could not determine physical register class of pattern source");
  3676. }
  3677. OM.addPredicate<RegisterBankOperandMatcher>(*RC);
  3678. return Error::success();
  3679. }
  3680. // Check for ValueType.
  3681. if (ChildRec->isSubClassOf("ValueType")) {
  3682. // We already added a type check as standard practice so this doesn't need
  3683. // to do anything.
  3684. return Error::success();
  3685. }
  3686. // Check for ComplexPattern's.
  3687. if (ChildRec->isSubClassOf("ComplexPattern"))
  3688. return importComplexPatternOperandMatcher(OM, ChildRec, TempOpIdx);
  3689. if (ChildRec->isSubClassOf("ImmLeaf")) {
  3690. return failedImport(
  3691. "Src pattern child def is an unsupported tablegen class (ImmLeaf)");
  3692. }
  3693. // Place holder for SRCVALUE nodes. Nothing to do here.
  3694. if (ChildRec->getName() == "srcvalue")
  3695. return Error::success();
  3696. const bool ImmAllOnesV = ChildRec->getName() == "immAllOnesV";
  3697. if (ImmAllOnesV || ChildRec->getName() == "immAllZerosV") {
  3698. auto MaybeInsnOperand = OM.addPredicate<InstructionOperandMatcher>(
  3699. InsnMatcher.getRuleMatcher(), SrcChild->getName(), false);
  3700. InstructionOperandMatcher &InsnOperand = **MaybeInsnOperand;
  3701. ValueTypeByHwMode VTy = ChildTypes.front().getValueTypeByHwMode();
  3702. const CodeGenInstruction &BuildVector
  3703. = Target.getInstruction(RK.getDef("G_BUILD_VECTOR"));
  3704. const CodeGenInstruction &BuildVectorTrunc
  3705. = Target.getInstruction(RK.getDef("G_BUILD_VECTOR_TRUNC"));
  3706. // Treat G_BUILD_VECTOR as the canonical opcode, and G_BUILD_VECTOR_TRUNC
  3707. // as an alternative.
  3708. InsnOperand.getInsnMatcher().addPredicate<InstructionOpcodeMatcher>(
  3709. makeArrayRef({&BuildVector, &BuildVectorTrunc}));
  3710. // TODO: Handle both G_BUILD_VECTOR and G_BUILD_VECTOR_TRUNC We could
  3711. // theoretically not emit any opcode check, but getOpcodeMatcher currently
  3712. // has to succeed.
  3713. OperandMatcher &OM =
  3714. InsnOperand.getInsnMatcher().addOperand(0, "", TempOpIdx);
  3715. if (auto Error =
  3716. OM.addTypeCheckPredicate(VTy, false /* OperandIsAPointer */))
  3717. return failedImport(toString(std::move(Error)) +
  3718. " for result of Src pattern operator");
  3719. InsnOperand.getInsnMatcher().addPredicate<VectorSplatImmPredicateMatcher>(
  3720. ImmAllOnesV ? VectorSplatImmPredicateMatcher::AllOnes
  3721. : VectorSplatImmPredicateMatcher::AllZeros);
  3722. return Error::success();
  3723. }
  3724. return failedImport(
  3725. "Src pattern child def is an unsupported tablegen class");
  3726. }
  3727. return failedImport("Src pattern child is an unsupported kind");
  3728. }
  3729. Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderer(
  3730. action_iterator InsertPt, RuleMatcher &Rule, BuildMIAction &DstMIBuilder,
  3731. TreePatternNode *DstChild) {
  3732. const auto &SubOperand = Rule.getComplexSubOperand(DstChild->getName());
  3733. if (SubOperand.hasValue()) {
  3734. DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
  3735. *std::get<0>(*SubOperand), DstChild->getName(),
  3736. std::get<1>(*SubOperand), std::get<2>(*SubOperand));
  3737. return InsertPt;
  3738. }
  3739. if (!DstChild->isLeaf()) {
  3740. if (DstChild->getOperator()->isSubClassOf("SDNodeXForm")) {
  3741. auto Child = DstChild->getChild(0);
  3742. auto I = SDNodeXFormEquivs.find(DstChild->getOperator());
  3743. if (I != SDNodeXFormEquivs.end()) {
  3744. Record *XFormOpc = DstChild->getOperator()->getValueAsDef("Opcode");
  3745. if (XFormOpc->getName() == "timm") {
  3746. // If this is a TargetConstant, there won't be a corresponding
  3747. // instruction to transform. Instead, this will refer directly to an
  3748. // operand in an instruction's operand list.
  3749. DstMIBuilder.addRenderer<CustomOperandRenderer>(*I->second,
  3750. Child->getName());
  3751. } else {
  3752. DstMIBuilder.addRenderer<CustomRenderer>(*I->second,
  3753. Child->getName());
  3754. }
  3755. return InsertPt;
  3756. }
  3757. return failedImport("SDNodeXForm " + Child->getName() +
  3758. " has no custom renderer");
  3759. }
  3760. // We accept 'bb' here. It's an operator because BasicBlockSDNode isn't
  3761. // inline, but in MI it's just another operand.
  3762. if (DstChild->getOperator()->isSubClassOf("SDNode")) {
  3763. auto &ChildSDNI = CGP.getSDNodeInfo(DstChild->getOperator());
  3764. if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
  3765. DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
  3766. return InsertPt;
  3767. }
  3768. }
  3769. // Similarly, imm is an operator in TreePatternNode's view but must be
  3770. // rendered as operands.
  3771. // FIXME: The target should be able to choose sign-extended when appropriate
  3772. // (e.g. on Mips).
  3773. if (DstChild->getOperator()->getName() == "timm") {
  3774. DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
  3775. return InsertPt;
  3776. } else if (DstChild->getOperator()->getName() == "imm") {
  3777. DstMIBuilder.addRenderer<CopyConstantAsImmRenderer>(DstChild->getName());
  3778. return InsertPt;
  3779. } else if (DstChild->getOperator()->getName() == "fpimm") {
  3780. DstMIBuilder.addRenderer<CopyFConstantAsFPImmRenderer>(
  3781. DstChild->getName());
  3782. return InsertPt;
  3783. }
  3784. if (DstChild->getOperator()->isSubClassOf("Instruction")) {
  3785. auto OpTy = getInstResultType(DstChild);
  3786. if (!OpTy)
  3787. return OpTy.takeError();
  3788. unsigned TempRegID = Rule.allocateTempRegID();
  3789. InsertPt = Rule.insertAction<MakeTempRegisterAction>(
  3790. InsertPt, *OpTy, TempRegID);
  3791. DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
  3792. auto InsertPtOrError = createAndImportSubInstructionRenderer(
  3793. ++InsertPt, Rule, DstChild, TempRegID);
  3794. if (auto Error = InsertPtOrError.takeError())
  3795. return std::move(Error);
  3796. return InsertPtOrError.get();
  3797. }
  3798. return failedImport("Dst pattern child isn't a leaf node or an MBB" + llvm::to_string(*DstChild));
  3799. }
  3800. // It could be a specific immediate in which case we should just check for
  3801. // that immediate.
  3802. if (const IntInit *ChildIntInit =
  3803. dyn_cast<IntInit>(DstChild->getLeafValue())) {
  3804. DstMIBuilder.addRenderer<ImmRenderer>(ChildIntInit->getValue());
  3805. return InsertPt;
  3806. }
  3807. // Otherwise, we're looking for a bog-standard RegisterClass operand.
  3808. if (auto *ChildDefInit = dyn_cast<DefInit>(DstChild->getLeafValue())) {
  3809. auto *ChildRec = ChildDefInit->getDef();
  3810. ArrayRef<TypeSetByHwMode> ChildTypes = DstChild->getExtTypes();
  3811. if (ChildTypes.size() != 1)
  3812. return failedImport("Dst pattern child has multiple results");
  3813. Optional<LLTCodeGen> OpTyOrNone = None;
  3814. if (ChildTypes.front().isMachineValueType())
  3815. OpTyOrNone = MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
  3816. if (!OpTyOrNone)
  3817. return failedImport("Dst operand has an unsupported type");
  3818. if (ChildRec->isSubClassOf("Register")) {
  3819. DstMIBuilder.addRenderer<AddRegisterRenderer>(Target, ChildRec);
  3820. return InsertPt;
  3821. }
  3822. if (ChildRec->isSubClassOf("RegisterClass") ||
  3823. ChildRec->isSubClassOf("RegisterOperand") ||
  3824. ChildRec->isSubClassOf("ValueType")) {
  3825. if (ChildRec->isSubClassOf("RegisterOperand") &&
  3826. !ChildRec->isValueUnset("GIZeroRegister")) {
  3827. DstMIBuilder.addRenderer<CopyOrAddZeroRegRenderer>(
  3828. DstChild->getName(), ChildRec->getValueAsDef("GIZeroRegister"));
  3829. return InsertPt;
  3830. }
  3831. DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
  3832. return InsertPt;
  3833. }
  3834. if (ChildRec->isSubClassOf("SubRegIndex")) {
  3835. CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(ChildRec);
  3836. DstMIBuilder.addRenderer<ImmRenderer>(SubIdx->EnumValue);
  3837. return InsertPt;
  3838. }
  3839. if (ChildRec->isSubClassOf("ComplexPattern")) {
  3840. const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
  3841. if (ComplexPattern == ComplexPatternEquivs.end())
  3842. return failedImport(
  3843. "SelectionDAG ComplexPattern not mapped to GlobalISel");
  3844. const OperandMatcher &OM = Rule.getOperandMatcher(DstChild->getName());
  3845. DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
  3846. *ComplexPattern->second, DstChild->getName(),
  3847. OM.getAllocatedTemporariesBaseID());
  3848. return InsertPt;
  3849. }
  3850. return failedImport(
  3851. "Dst pattern child def is an unsupported tablegen class");
  3852. }
  3853. return failedImport("Dst pattern child is an unsupported kind");
  3854. }
  3855. Expected<BuildMIAction &> GlobalISelEmitter::createAndImportInstructionRenderer(
  3856. RuleMatcher &M, InstructionMatcher &InsnMatcher, const TreePatternNode *Src,
  3857. const TreePatternNode *Dst) {
  3858. auto InsertPtOrError = createInstructionRenderer(M.actions_end(), M, Dst);
  3859. if (auto Error = InsertPtOrError.takeError())
  3860. return std::move(Error);
  3861. action_iterator InsertPt = InsertPtOrError.get();
  3862. BuildMIAction &DstMIBuilder = *static_cast<BuildMIAction *>(InsertPt->get());
  3863. for (auto PhysInput : InsnMatcher.getPhysRegInputs()) {
  3864. InsertPt = M.insertAction<BuildMIAction>(
  3865. InsertPt, M.allocateOutputInsnID(),
  3866. &Target.getInstruction(RK.getDef("COPY")));
  3867. BuildMIAction &CopyToPhysRegMIBuilder =
  3868. *static_cast<BuildMIAction *>(InsertPt->get());
  3869. CopyToPhysRegMIBuilder.addRenderer<AddRegisterRenderer>(Target,
  3870. PhysInput.first,
  3871. true);
  3872. CopyToPhysRegMIBuilder.addRenderer<CopyPhysRegRenderer>(PhysInput.first);
  3873. }
  3874. if (auto Error = importExplicitDefRenderers(InsertPt, M, DstMIBuilder, Dst)
  3875. .takeError())
  3876. return std::move(Error);
  3877. if (auto Error = importExplicitUseRenderers(InsertPt, M, DstMIBuilder, Dst)
  3878. .takeError())
  3879. return std::move(Error);
  3880. return DstMIBuilder;
  3881. }
  3882. Expected<action_iterator>
  3883. GlobalISelEmitter::createAndImportSubInstructionRenderer(
  3884. const action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst,
  3885. unsigned TempRegID) {
  3886. auto InsertPtOrError = createInstructionRenderer(InsertPt, M, Dst);
  3887. // TODO: Assert there's exactly one result.
  3888. if (auto Error = InsertPtOrError.takeError())
  3889. return std::move(Error);
  3890. BuildMIAction &DstMIBuilder =
  3891. *static_cast<BuildMIAction *>(InsertPtOrError.get()->get());
  3892. // Assign the result to TempReg.
  3893. DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID, true);
  3894. InsertPtOrError =
  3895. importExplicitUseRenderers(InsertPtOrError.get(), M, DstMIBuilder, Dst);
  3896. if (auto Error = InsertPtOrError.takeError())
  3897. return std::move(Error);
  3898. // We need to make sure that when we import an INSERT_SUBREG as a
  3899. // subinstruction that it ends up being constrained to the correct super
  3900. // register and subregister classes.
  3901. auto OpName = Target.getInstruction(Dst->getOperator()).TheDef->getName();
  3902. if (OpName == "INSERT_SUBREG") {
  3903. auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
  3904. if (!SubClass)
  3905. return failedImport(
  3906. "Cannot infer register class from INSERT_SUBREG operand #1");
  3907. Optional<const CodeGenRegisterClass *> SuperClass =
  3908. inferSuperRegisterClassForNode(Dst->getExtType(0), Dst->getChild(0),
  3909. Dst->getChild(2));
  3910. if (!SuperClass)
  3911. return failedImport(
  3912. "Cannot infer register class for INSERT_SUBREG operand #0");
  3913. // The destination and the super register source of an INSERT_SUBREG must
  3914. // be the same register class.
  3915. M.insertAction<ConstrainOperandToRegClassAction>(
  3916. InsertPt, DstMIBuilder.getInsnID(), 0, **SuperClass);
  3917. M.insertAction<ConstrainOperandToRegClassAction>(
  3918. InsertPt, DstMIBuilder.getInsnID(), 1, **SuperClass);
  3919. M.insertAction<ConstrainOperandToRegClassAction>(
  3920. InsertPt, DstMIBuilder.getInsnID(), 2, **SubClass);
  3921. return InsertPtOrError.get();
  3922. }
  3923. if (OpName == "EXTRACT_SUBREG") {
  3924. // EXTRACT_SUBREG selects into a subregister COPY but unlike most
  3925. // instructions, the result register class is controlled by the
  3926. // subregisters of the operand. As a result, we must constrain the result
  3927. // class rather than check that it's already the right one.
  3928. auto SuperClass = inferRegClassFromPattern(Dst->getChild(0));
  3929. if (!SuperClass)
  3930. return failedImport(
  3931. "Cannot infer register class from EXTRACT_SUBREG operand #0");
  3932. auto SubIdx = inferSubRegIndexForNode(Dst->getChild(1));
  3933. if (!SubIdx)
  3934. return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
  3935. const auto SrcRCDstRCPair =
  3936. (*SuperClass)->getMatchingSubClassWithSubRegs(CGRegs, *SubIdx);
  3937. assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
  3938. M.insertAction<ConstrainOperandToRegClassAction>(
  3939. InsertPt, DstMIBuilder.getInsnID(), 0, *SrcRCDstRCPair->second);
  3940. M.insertAction<ConstrainOperandToRegClassAction>(
  3941. InsertPt, DstMIBuilder.getInsnID(), 1, *SrcRCDstRCPair->first);
  3942. // We're done with this pattern! It's eligible for GISel emission; return
  3943. // it.
  3944. return InsertPtOrError.get();
  3945. }
  3946. // Similar to INSERT_SUBREG, we also have to handle SUBREG_TO_REG as a
  3947. // subinstruction.
  3948. if (OpName == "SUBREG_TO_REG") {
  3949. auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
  3950. if (!SubClass)
  3951. return failedImport(
  3952. "Cannot infer register class from SUBREG_TO_REG child #1");
  3953. auto SuperClass = inferSuperRegisterClass(Dst->getExtType(0),
  3954. Dst->getChild(2));
  3955. if (!SuperClass)
  3956. return failedImport(
  3957. "Cannot infer register class for SUBREG_TO_REG operand #0");
  3958. M.insertAction<ConstrainOperandToRegClassAction>(
  3959. InsertPt, DstMIBuilder.getInsnID(), 0, **SuperClass);
  3960. M.insertAction<ConstrainOperandToRegClassAction>(
  3961. InsertPt, DstMIBuilder.getInsnID(), 2, **SubClass);
  3962. return InsertPtOrError.get();
  3963. }
  3964. if (OpName == "REG_SEQUENCE") {
  3965. auto SuperClass = inferRegClassFromPattern(Dst->getChild(0));
  3966. M.insertAction<ConstrainOperandToRegClassAction>(
  3967. InsertPt, DstMIBuilder.getInsnID(), 0, **SuperClass);
  3968. unsigned Num = Dst->getNumChildren();
  3969. for (unsigned I = 1; I != Num; I += 2) {
  3970. TreePatternNode *SubRegChild = Dst->getChild(I + 1);
  3971. auto SubIdx = inferSubRegIndexForNode(SubRegChild);
  3972. if (!SubIdx)
  3973. return failedImport("REG_SEQUENCE child is not a subreg index");
  3974. const auto SrcRCDstRCPair =
  3975. (*SuperClass)->getMatchingSubClassWithSubRegs(CGRegs, *SubIdx);
  3976. assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
  3977. M.insertAction<ConstrainOperandToRegClassAction>(
  3978. InsertPt, DstMIBuilder.getInsnID(), I, *SrcRCDstRCPair->second);
  3979. }
  3980. return InsertPtOrError.get();
  3981. }
  3982. M.insertAction<ConstrainOperandsToDefinitionAction>(InsertPt,
  3983. DstMIBuilder.getInsnID());
  3984. return InsertPtOrError.get();
  3985. }
  3986. Expected<action_iterator> GlobalISelEmitter::createInstructionRenderer(
  3987. action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst) {
  3988. Record *DstOp = Dst->getOperator();
  3989. if (!DstOp->isSubClassOf("Instruction")) {
  3990. if (DstOp->isSubClassOf("ValueType"))
  3991. return failedImport(
  3992. "Pattern operator isn't an instruction (it's a ValueType)");
  3993. return failedImport("Pattern operator isn't an instruction");
  3994. }
  3995. CodeGenInstruction *DstI = &Target.getInstruction(DstOp);
  3996. // COPY_TO_REGCLASS is just a copy with a ConstrainOperandToRegClassAction
  3997. // attached. Similarly for EXTRACT_SUBREG except that's a subregister copy.
  3998. StringRef Name = DstI->TheDef->getName();
  3999. if (Name == "COPY_TO_REGCLASS" || Name == "EXTRACT_SUBREG")
  4000. DstI = &Target.getInstruction(RK.getDef("COPY"));
  4001. return M.insertAction<BuildMIAction>(InsertPt, M.allocateOutputInsnID(),
  4002. DstI);
  4003. }
  4004. Expected<action_iterator> GlobalISelEmitter::importExplicitDefRenderers(
  4005. action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder,
  4006. const TreePatternNode *Dst) {
  4007. const CodeGenInstruction *DstI = DstMIBuilder.getCGI();
  4008. const unsigned NumDefs = DstI->Operands.NumDefs;
  4009. if (NumDefs == 0)
  4010. return InsertPt;
  4011. DstMIBuilder.addRenderer<CopyRenderer>(DstI->Operands[0].Name);
  4012. // Some instructions have multiple defs, but are missing a type entry
  4013. // (e.g. s_cc_out operands).
  4014. if (Dst->getExtTypes().size() < NumDefs)
  4015. return failedImport("unhandled discarded def");
  4016. // Patterns only handle a single result, so any result after the first is an
  4017. // implicitly dead def.
  4018. for (unsigned I = 1; I < NumDefs; ++I) {
  4019. const TypeSetByHwMode &ExtTy = Dst->getExtType(I);
  4020. if (!ExtTy.isMachineValueType())
  4021. return failedImport("unsupported typeset");
  4022. auto OpTy = MVTToLLT(ExtTy.getMachineValueType().SimpleTy);
  4023. if (!OpTy)
  4024. return failedImport("unsupported type");
  4025. unsigned TempRegID = M.allocateTempRegID();
  4026. InsertPt =
  4027. M.insertAction<MakeTempRegisterAction>(InsertPt, *OpTy, TempRegID);
  4028. DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID, true, nullptr, true);
  4029. }
  4030. return InsertPt;
  4031. }
  4032. Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderers(
  4033. action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder,
  4034. const llvm::TreePatternNode *Dst) {
  4035. const CodeGenInstruction *DstI = DstMIBuilder.getCGI();
  4036. CodeGenInstruction *OrigDstI = &Target.getInstruction(Dst->getOperator());
  4037. StringRef Name = OrigDstI->TheDef->getName();
  4038. unsigned ExpectedDstINumUses = Dst->getNumChildren();
  4039. // EXTRACT_SUBREG needs to use a subregister COPY.
  4040. if (Name == "EXTRACT_SUBREG") {
  4041. if (!Dst->getChild(1)->isLeaf())
  4042. return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
  4043. DefInit *SubRegInit = dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue());
  4044. if (!SubRegInit)
  4045. return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
  4046. CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
  4047. TreePatternNode *ValChild = Dst->getChild(0);
  4048. if (!ValChild->isLeaf()) {
  4049. // We really have to handle the source instruction, and then insert a
  4050. // copy from the subregister.
  4051. auto ExtractSrcTy = getInstResultType(ValChild);
  4052. if (!ExtractSrcTy)
  4053. return ExtractSrcTy.takeError();
  4054. unsigned TempRegID = M.allocateTempRegID();
  4055. InsertPt = M.insertAction<MakeTempRegisterAction>(
  4056. InsertPt, *ExtractSrcTy, TempRegID);
  4057. auto InsertPtOrError = createAndImportSubInstructionRenderer(
  4058. ++InsertPt, M, ValChild, TempRegID);
  4059. if (auto Error = InsertPtOrError.takeError())
  4060. return std::move(Error);
  4061. DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID, false, SubIdx);
  4062. return InsertPt;
  4063. }
  4064. // If this is a source operand, this is just a subregister copy.
  4065. Record *RCDef = getInitValueAsRegClass(ValChild->getLeafValue());
  4066. if (!RCDef)
  4067. return failedImport("EXTRACT_SUBREG child #0 could not "
  4068. "be coerced to a register class");
  4069. CodeGenRegisterClass *RC = CGRegs.getRegClass(RCDef);
  4070. const auto SrcRCDstRCPair =
  4071. RC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
  4072. if (SrcRCDstRCPair.hasValue()) {
  4073. assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
  4074. if (SrcRCDstRCPair->first != RC)
  4075. return failedImport("EXTRACT_SUBREG requires an additional COPY");
  4076. }
  4077. DstMIBuilder.addRenderer<CopySubRegRenderer>(Dst->getChild(0)->getName(),
  4078. SubIdx);
  4079. return InsertPt;
  4080. }
  4081. if (Name == "REG_SEQUENCE") {
  4082. if (!Dst->getChild(0)->isLeaf())
  4083. return failedImport("REG_SEQUENCE child #0 is not a leaf");
  4084. Record *RCDef = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
  4085. if (!RCDef)
  4086. return failedImport("REG_SEQUENCE child #0 could not "
  4087. "be coerced to a register class");
  4088. if ((ExpectedDstINumUses - 1) % 2 != 0)
  4089. return failedImport("Malformed REG_SEQUENCE");
  4090. for (unsigned I = 1; I != ExpectedDstINumUses; I += 2) {
  4091. TreePatternNode *ValChild = Dst->getChild(I);
  4092. TreePatternNode *SubRegChild = Dst->getChild(I + 1);
  4093. if (DefInit *SubRegInit =
  4094. dyn_cast<DefInit>(SubRegChild->getLeafValue())) {
  4095. CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
  4096. auto InsertPtOrError =
  4097. importExplicitUseRenderer(InsertPt, M, DstMIBuilder, ValChild);
  4098. if (auto Error = InsertPtOrError.takeError())
  4099. return std::move(Error);
  4100. InsertPt = InsertPtOrError.get();
  4101. DstMIBuilder.addRenderer<SubRegIndexRenderer>(SubIdx);
  4102. }
  4103. }
  4104. return InsertPt;
  4105. }
  4106. // Render the explicit uses.
  4107. unsigned DstINumUses = OrigDstI->Operands.size() - OrigDstI->Operands.NumDefs;
  4108. if (Name == "COPY_TO_REGCLASS") {
  4109. DstINumUses--; // Ignore the class constraint.
  4110. ExpectedDstINumUses--;
  4111. }
  4112. // NumResults - This is the number of results produced by the instruction in
  4113. // the "outs" list.
  4114. unsigned NumResults = OrigDstI->Operands.NumDefs;
  4115. // Number of operands we know the output instruction must have. If it is
  4116. // variadic, we could have more operands.
  4117. unsigned NumFixedOperands = DstI->Operands.size();
  4118. // Loop over all of the fixed operands of the instruction pattern, emitting
  4119. // code to fill them all in. The node 'N' usually has number children equal to
  4120. // the number of input operands of the instruction. However, in cases where
  4121. // there are predicate operands for an instruction, we need to fill in the
  4122. // 'execute always' values. Match up the node operands to the instruction
  4123. // operands to do this.
  4124. unsigned Child = 0;
  4125. // Similarly to the code in TreePatternNode::ApplyTypeConstraints, count the
  4126. // number of operands at the end of the list which have default values.
  4127. // Those can come from the pattern if it provides enough arguments, or be
  4128. // filled in with the default if the pattern hasn't provided them. But any
  4129. // operand with a default value _before_ the last mandatory one will be
  4130. // filled in with their defaults unconditionally.
  4131. unsigned NonOverridableOperands = NumFixedOperands;
  4132. while (NonOverridableOperands > NumResults &&
  4133. CGP.operandHasDefault(DstI->Operands[NonOverridableOperands - 1].Rec))
  4134. --NonOverridableOperands;
  4135. unsigned NumDefaultOps = 0;
  4136. for (unsigned I = 0; I != DstINumUses; ++I) {
  4137. unsigned InstOpNo = DstI->Operands.NumDefs + I;
  4138. // Determine what to emit for this operand.
  4139. Record *OperandNode = DstI->Operands[InstOpNo].Rec;
  4140. // If the operand has default values, introduce them now.
  4141. if (CGP.operandHasDefault(OperandNode) &&
  4142. (InstOpNo < NonOverridableOperands || Child >= Dst->getNumChildren())) {
  4143. // This is a predicate or optional def operand which the pattern has not
  4144. // overridden, or which we aren't letting it override; emit the 'default
  4145. // ops' operands.
  4146. const CGIOperandList::OperandInfo &DstIOperand = DstI->Operands[InstOpNo];
  4147. DagInit *DefaultOps = DstIOperand.Rec->getValueAsDag("DefaultOps");
  4148. if (auto Error = importDefaultOperandRenderers(
  4149. InsertPt, M, DstMIBuilder, DefaultOps))
  4150. return std::move(Error);
  4151. ++NumDefaultOps;
  4152. continue;
  4153. }
  4154. auto InsertPtOrError = importExplicitUseRenderer(InsertPt, M, DstMIBuilder,
  4155. Dst->getChild(Child));
  4156. if (auto Error = InsertPtOrError.takeError())
  4157. return std::move(Error);
  4158. InsertPt = InsertPtOrError.get();
  4159. ++Child;
  4160. }
  4161. if (NumDefaultOps + ExpectedDstINumUses != DstINumUses)
  4162. return failedImport("Expected " + llvm::to_string(DstINumUses) +
  4163. " used operands but found " +
  4164. llvm::to_string(ExpectedDstINumUses) +
  4165. " explicit ones and " + llvm::to_string(NumDefaultOps) +
  4166. " default ones");
  4167. return InsertPt;
  4168. }
  4169. Error GlobalISelEmitter::importDefaultOperandRenderers(
  4170. action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder,
  4171. DagInit *DefaultOps) const {
  4172. for (const auto *DefaultOp : DefaultOps->getArgs()) {
  4173. Optional<LLTCodeGen> OpTyOrNone = None;
  4174. // Look through ValueType operators.
  4175. if (const DagInit *DefaultDagOp = dyn_cast<DagInit>(DefaultOp)) {
  4176. if (const DefInit *DefaultDagOperator =
  4177. dyn_cast<DefInit>(DefaultDagOp->getOperator())) {
  4178. if (DefaultDagOperator->getDef()->isSubClassOf("ValueType")) {
  4179. OpTyOrNone = MVTToLLT(getValueType(
  4180. DefaultDagOperator->getDef()));
  4181. DefaultOp = DefaultDagOp->getArg(0);
  4182. }
  4183. }
  4184. }
  4185. if (const DefInit *DefaultDefOp = dyn_cast<DefInit>(DefaultOp)) {
  4186. auto Def = DefaultDefOp->getDef();
  4187. if (Def->getName() == "undef_tied_input") {
  4188. unsigned TempRegID = M.allocateTempRegID();
  4189. M.insertAction<MakeTempRegisterAction>(
  4190. InsertPt, OpTyOrNone.getValue(), TempRegID);
  4191. InsertPt = M.insertAction<BuildMIAction>(
  4192. InsertPt, M.allocateOutputInsnID(),
  4193. &Target.getInstruction(RK.getDef("IMPLICIT_DEF")));
  4194. BuildMIAction &IDMIBuilder = *static_cast<BuildMIAction *>(
  4195. InsertPt->get());
  4196. IDMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
  4197. DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
  4198. } else {
  4199. DstMIBuilder.addRenderer<AddRegisterRenderer>(Target, Def);
  4200. }
  4201. continue;
  4202. }
  4203. if (const IntInit *DefaultIntOp = dyn_cast<IntInit>(DefaultOp)) {
  4204. DstMIBuilder.addRenderer<ImmRenderer>(DefaultIntOp->getValue());
  4205. continue;
  4206. }
  4207. return failedImport("Could not add default op");
  4208. }
  4209. return Error::success();
  4210. }
  4211. Error GlobalISelEmitter::importImplicitDefRenderers(
  4212. BuildMIAction &DstMIBuilder,
  4213. const std::vector<Record *> &ImplicitDefs) const {
  4214. if (!ImplicitDefs.empty())
  4215. return failedImport("Pattern defines a physical register");
  4216. return Error::success();
  4217. }
  4218. Optional<const CodeGenRegisterClass *>
  4219. GlobalISelEmitter::getRegClassFromLeaf(TreePatternNode *Leaf) {
  4220. assert(Leaf && "Expected node?");
  4221. assert(Leaf->isLeaf() && "Expected leaf?");
  4222. Record *RCRec = getInitValueAsRegClass(Leaf->getLeafValue());
  4223. if (!RCRec)
  4224. return None;
  4225. CodeGenRegisterClass *RC = CGRegs.getRegClass(RCRec);
  4226. if (!RC)
  4227. return None;
  4228. return RC;
  4229. }
  4230. Optional<const CodeGenRegisterClass *>
  4231. GlobalISelEmitter::inferRegClassFromPattern(TreePatternNode *N) {
  4232. if (!N)
  4233. return None;
  4234. if (N->isLeaf())
  4235. return getRegClassFromLeaf(N);
  4236. // We don't have a leaf node, so we have to try and infer something. Check
  4237. // that we have an instruction that we an infer something from.
  4238. // Only handle things that produce a single type.
  4239. if (N->getNumTypes() != 1)
  4240. return None;
  4241. Record *OpRec = N->getOperator();
  4242. // We only want instructions.
  4243. if (!OpRec->isSubClassOf("Instruction"))
  4244. return None;
  4245. // Don't want to try and infer things when there could potentially be more
  4246. // than one candidate register class.
  4247. auto &Inst = Target.getInstruction(OpRec);
  4248. if (Inst.Operands.NumDefs > 1)
  4249. return None;
  4250. // Handle any special-case instructions which we can safely infer register
  4251. // classes from.
  4252. StringRef InstName = Inst.TheDef->getName();
  4253. bool IsRegSequence = InstName == "REG_SEQUENCE";
  4254. if (IsRegSequence || InstName == "COPY_TO_REGCLASS") {
  4255. // If we have a COPY_TO_REGCLASS, then we need to handle it specially. It
  4256. // has the desired register class as the first child.
  4257. TreePatternNode *RCChild = N->getChild(IsRegSequence ? 0 : 1);
  4258. if (!RCChild->isLeaf())
  4259. return None;
  4260. return getRegClassFromLeaf(RCChild);
  4261. }
  4262. if (InstName == "INSERT_SUBREG") {
  4263. TreePatternNode *Child0 = N->getChild(0);
  4264. assert(Child0->getNumTypes() == 1 && "Unexpected number of types!");
  4265. const TypeSetByHwMode &VTy = Child0->getExtType(0);
  4266. return inferSuperRegisterClassForNode(VTy, Child0, N->getChild(2));
  4267. }
  4268. if (InstName == "EXTRACT_SUBREG") {
  4269. assert(N->getNumTypes() == 1 && "Unexpected number of types!");
  4270. const TypeSetByHwMode &VTy = N->getExtType(0);
  4271. return inferSuperRegisterClass(VTy, N->getChild(1));
  4272. }
  4273. // Handle destination record types that we can safely infer a register class
  4274. // from.
  4275. const auto &DstIOperand = Inst.Operands[0];
  4276. Record *DstIOpRec = DstIOperand.Rec;
  4277. if (DstIOpRec->isSubClassOf("RegisterOperand")) {
  4278. DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
  4279. const CodeGenRegisterClass &RC = Target.getRegisterClass(DstIOpRec);
  4280. return &RC;
  4281. }
  4282. if (DstIOpRec->isSubClassOf("RegisterClass")) {
  4283. const CodeGenRegisterClass &RC = Target.getRegisterClass(DstIOpRec);
  4284. return &RC;
  4285. }
  4286. return None;
  4287. }
  4288. Optional<const CodeGenRegisterClass *>
  4289. GlobalISelEmitter::inferSuperRegisterClass(const TypeSetByHwMode &Ty,
  4290. TreePatternNode *SubRegIdxNode) {
  4291. assert(SubRegIdxNode && "Expected subregister index node!");
  4292. // We need a ValueTypeByHwMode for getSuperRegForSubReg.
  4293. if (!Ty.isValueTypeByHwMode(false))
  4294. return None;
  4295. if (!SubRegIdxNode->isLeaf())
  4296. return None;
  4297. DefInit *SubRegInit = dyn_cast<DefInit>(SubRegIdxNode->getLeafValue());
  4298. if (!SubRegInit)
  4299. return None;
  4300. CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
  4301. // Use the information we found above to find a minimal register class which
  4302. // supports the subregister and type we want.
  4303. auto RC =
  4304. Target.getSuperRegForSubReg(Ty.getValueTypeByHwMode(), CGRegs, SubIdx,
  4305. /* MustBeAllocatable */ true);
  4306. if (!RC)
  4307. return None;
  4308. return *RC;
  4309. }
  4310. Optional<const CodeGenRegisterClass *>
  4311. GlobalISelEmitter::inferSuperRegisterClassForNode(
  4312. const TypeSetByHwMode &Ty, TreePatternNode *SuperRegNode,
  4313. TreePatternNode *SubRegIdxNode) {
  4314. assert(SuperRegNode && "Expected super register node!");
  4315. // Check if we already have a defined register class for the super register
  4316. // node. If we do, then we should preserve that rather than inferring anything
  4317. // from the subregister index node. We can assume that whoever wrote the
  4318. // pattern in the first place made sure that the super register and
  4319. // subregister are compatible.
  4320. if (Optional<const CodeGenRegisterClass *> SuperRegisterClass =
  4321. inferRegClassFromPattern(SuperRegNode))
  4322. return *SuperRegisterClass;
  4323. return inferSuperRegisterClass(Ty, SubRegIdxNode);
  4324. }
  4325. Optional<CodeGenSubRegIndex *>
  4326. GlobalISelEmitter::inferSubRegIndexForNode(TreePatternNode *SubRegIdxNode) {
  4327. if (!SubRegIdxNode->isLeaf())
  4328. return None;
  4329. DefInit *SubRegInit = dyn_cast<DefInit>(SubRegIdxNode->getLeafValue());
  4330. if (!SubRegInit)
  4331. return None;
  4332. return CGRegs.getSubRegIdx(SubRegInit->getDef());
  4333. }
  4334. Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) {
  4335. // Keep track of the matchers and actions to emit.
  4336. int Score = P.getPatternComplexity(CGP);
  4337. RuleMatcher M(P.getSrcRecord()->getLoc());
  4338. RuleMatcherScores[M.getRuleID()] = Score;
  4339. M.addAction<DebugCommentAction>(llvm::to_string(*P.getSrcPattern()) +
  4340. " => " +
  4341. llvm::to_string(*P.getDstPattern()));
  4342. SmallVector<Record *, 4> Predicates;
  4343. P.getPredicateRecords(Predicates);
  4344. if (auto Error = importRulePredicates(M, Predicates))
  4345. return std::move(Error);
  4346. // Next, analyze the pattern operators.
  4347. TreePatternNode *Src = P.getSrcPattern();
  4348. TreePatternNode *Dst = P.getDstPattern();
  4349. // If the root of either pattern isn't a simple operator, ignore it.
  4350. if (auto Err = isTrivialOperatorNode(Dst))
  4351. return failedImport("Dst pattern root isn't a trivial operator (" +
  4352. toString(std::move(Err)) + ")");
  4353. if (auto Err = isTrivialOperatorNode(Src))
  4354. return failedImport("Src pattern root isn't a trivial operator (" +
  4355. toString(std::move(Err)) + ")");
  4356. // The different predicates and matchers created during
  4357. // addInstructionMatcher use the RuleMatcher M to set up their
  4358. // instruction ID (InsnVarID) that are going to be used when
  4359. // M is going to be emitted.
  4360. // However, the code doing the emission still relies on the IDs
  4361. // returned during that process by the RuleMatcher when issuing
  4362. // the recordInsn opcodes.
  4363. // Because of that:
  4364. // 1. The order in which we created the predicates
  4365. // and such must be the same as the order in which we emit them,
  4366. // and
  4367. // 2. We need to reset the generation of the IDs in M somewhere between
  4368. // addInstructionMatcher and emit
  4369. //
  4370. // FIXME: Long term, we don't want to have to rely on this implicit
  4371. // naming being the same. One possible solution would be to have
  4372. // explicit operator for operation capture and reference those.
  4373. // The plus side is that it would expose opportunities to share
  4374. // the capture accross rules. The downside is that it would
  4375. // introduce a dependency between predicates (captures must happen
  4376. // before their first use.)
  4377. InstructionMatcher &InsnMatcherTemp = M.addInstructionMatcher(Src->getName());
  4378. unsigned TempOpIdx = 0;
  4379. auto InsnMatcherOrError =
  4380. createAndImportSelDAGMatcher(M, InsnMatcherTemp, Src, TempOpIdx);
  4381. if (auto Error = InsnMatcherOrError.takeError())
  4382. return std::move(Error);
  4383. InstructionMatcher &InsnMatcher = InsnMatcherOrError.get();
  4384. if (Dst->isLeaf()) {
  4385. Record *RCDef = getInitValueAsRegClass(Dst->getLeafValue());
  4386. if (RCDef) {
  4387. const CodeGenRegisterClass &RC = Target.getRegisterClass(RCDef);
  4388. // We need to replace the def and all its uses with the specified
  4389. // operand. However, we must also insert COPY's wherever needed.
  4390. // For now, emit a copy and let the register allocator clean up.
  4391. auto &DstI = Target.getInstruction(RK.getDef("COPY"));
  4392. const auto &DstIOperand = DstI.Operands[0];
  4393. OperandMatcher &OM0 = InsnMatcher.getOperand(0);
  4394. OM0.setSymbolicName(DstIOperand.Name);
  4395. M.defineOperand(OM0.getSymbolicName(), OM0);
  4396. OM0.addPredicate<RegisterBankOperandMatcher>(RC);
  4397. auto &DstMIBuilder =
  4398. M.addAction<BuildMIAction>(M.allocateOutputInsnID(), &DstI);
  4399. DstMIBuilder.addRenderer<CopyRenderer>(DstIOperand.Name);
  4400. DstMIBuilder.addRenderer<CopyRenderer>(Dst->getName());
  4401. M.addAction<ConstrainOperandToRegClassAction>(0, 0, RC);
  4402. // We're done with this pattern! It's eligible for GISel emission; return
  4403. // it.
  4404. ++NumPatternImported;
  4405. return std::move(M);
  4406. }
  4407. return failedImport("Dst pattern root isn't a known leaf");
  4408. }
  4409. // Start with the defined operands (i.e., the results of the root operator).
  4410. Record *DstOp = Dst->getOperator();
  4411. if (!DstOp->isSubClassOf("Instruction"))
  4412. return failedImport("Pattern operator isn't an instruction");
  4413. auto &DstI = Target.getInstruction(DstOp);
  4414. StringRef DstIName = DstI.TheDef->getName();
  4415. if (DstI.Operands.NumDefs < Src->getExtTypes().size())
  4416. return failedImport("Src pattern result has more defs than dst MI (" +
  4417. to_string(Src->getExtTypes().size()) + " def(s) vs " +
  4418. to_string(DstI.Operands.NumDefs) + " def(s))");
  4419. // The root of the match also has constraints on the register bank so that it
  4420. // matches the result instruction.
  4421. unsigned OpIdx = 0;
  4422. for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
  4423. (void)VTy;
  4424. const auto &DstIOperand = DstI.Operands[OpIdx];
  4425. Record *DstIOpRec = DstIOperand.Rec;
  4426. if (DstIName == "COPY_TO_REGCLASS") {
  4427. DstIOpRec = getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
  4428. if (DstIOpRec == nullptr)
  4429. return failedImport(
  4430. "COPY_TO_REGCLASS operand #1 isn't a register class");
  4431. } else if (DstIName == "REG_SEQUENCE") {
  4432. DstIOpRec = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
  4433. if (DstIOpRec == nullptr)
  4434. return failedImport("REG_SEQUENCE operand #0 isn't a register class");
  4435. } else if (DstIName == "EXTRACT_SUBREG") {
  4436. auto InferredClass = inferRegClassFromPattern(Dst->getChild(0));
  4437. if (!InferredClass)
  4438. return failedImport("Could not infer class for EXTRACT_SUBREG operand #0");
  4439. // We can assume that a subregister is in the same bank as it's super
  4440. // register.
  4441. DstIOpRec = (*InferredClass)->getDef();
  4442. } else if (DstIName == "INSERT_SUBREG") {
  4443. auto MaybeSuperClass = inferSuperRegisterClassForNode(
  4444. VTy, Dst->getChild(0), Dst->getChild(2));
  4445. if (!MaybeSuperClass)
  4446. return failedImport(
  4447. "Cannot infer register class for INSERT_SUBREG operand #0");
  4448. // Move to the next pattern here, because the register class we found
  4449. // doesn't necessarily have a record associated with it. So, we can't
  4450. // set DstIOpRec using this.
  4451. OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
  4452. OM.setSymbolicName(DstIOperand.Name);
  4453. M.defineOperand(OM.getSymbolicName(), OM);
  4454. OM.addPredicate<RegisterBankOperandMatcher>(**MaybeSuperClass);
  4455. ++OpIdx;
  4456. continue;
  4457. } else if (DstIName == "SUBREG_TO_REG") {
  4458. auto MaybeRegClass = inferSuperRegisterClass(VTy, Dst->getChild(2));
  4459. if (!MaybeRegClass)
  4460. return failedImport(
  4461. "Cannot infer register class for SUBREG_TO_REG operand #0");
  4462. OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
  4463. OM.setSymbolicName(DstIOperand.Name);
  4464. M.defineOperand(OM.getSymbolicName(), OM);
  4465. OM.addPredicate<RegisterBankOperandMatcher>(**MaybeRegClass);
  4466. ++OpIdx;
  4467. continue;
  4468. } else if (DstIOpRec->isSubClassOf("RegisterOperand"))
  4469. DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
  4470. else if (!DstIOpRec->isSubClassOf("RegisterClass"))
  4471. return failedImport("Dst MI def isn't a register class" +
  4472. to_string(*Dst));
  4473. OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
  4474. OM.setSymbolicName(DstIOperand.Name);
  4475. M.defineOperand(OM.getSymbolicName(), OM);
  4476. OM.addPredicate<RegisterBankOperandMatcher>(
  4477. Target.getRegisterClass(DstIOpRec));
  4478. ++OpIdx;
  4479. }
  4480. auto DstMIBuilderOrError =
  4481. createAndImportInstructionRenderer(M, InsnMatcher, Src, Dst);
  4482. if (auto Error = DstMIBuilderOrError.takeError())
  4483. return std::move(Error);
  4484. BuildMIAction &DstMIBuilder = DstMIBuilderOrError.get();
  4485. // Render the implicit defs.
  4486. // These are only added to the root of the result.
  4487. if (auto Error = importImplicitDefRenderers(DstMIBuilder, P.getDstRegs()))
  4488. return std::move(Error);
  4489. DstMIBuilder.chooseInsnToMutate(M);
  4490. // Constrain the registers to classes. This is normally derived from the
  4491. // emitted instruction but a few instructions require special handling.
  4492. if (DstIName == "COPY_TO_REGCLASS") {
  4493. // COPY_TO_REGCLASS does not provide operand constraints itself but the
  4494. // result is constrained to the class given by the second child.
  4495. Record *DstIOpRec =
  4496. getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
  4497. if (DstIOpRec == nullptr)
  4498. return failedImport("COPY_TO_REGCLASS operand #1 isn't a register class");
  4499. M.addAction<ConstrainOperandToRegClassAction>(
  4500. 0, 0, Target.getRegisterClass(DstIOpRec));
  4501. // We're done with this pattern! It's eligible for GISel emission; return
  4502. // it.
  4503. ++NumPatternImported;
  4504. return std::move(M);
  4505. }
  4506. if (DstIName == "EXTRACT_SUBREG") {
  4507. auto SuperClass = inferRegClassFromPattern(Dst->getChild(0));
  4508. if (!SuperClass)
  4509. return failedImport(
  4510. "Cannot infer register class from EXTRACT_SUBREG operand #0");
  4511. auto SubIdx = inferSubRegIndexForNode(Dst->getChild(1));
  4512. if (!SubIdx)
  4513. return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
  4514. // It would be nice to leave this constraint implicit but we're required
  4515. // to pick a register class so constrain the result to a register class
  4516. // that can hold the correct MVT.
  4517. //
  4518. // FIXME: This may introduce an extra copy if the chosen class doesn't
  4519. // actually contain the subregisters.
  4520. assert(Src->getExtTypes().size() == 1 &&
  4521. "Expected Src of EXTRACT_SUBREG to have one result type");
  4522. const auto SrcRCDstRCPair =
  4523. (*SuperClass)->getMatchingSubClassWithSubRegs(CGRegs, *SubIdx);
  4524. if (!SrcRCDstRCPair) {
  4525. return failedImport("subreg index is incompatible "
  4526. "with inferred reg class");
  4527. }
  4528. assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
  4529. M.addAction<ConstrainOperandToRegClassAction>(0, 0, *SrcRCDstRCPair->second);
  4530. M.addAction<ConstrainOperandToRegClassAction>(0, 1, *SrcRCDstRCPair->first);
  4531. // We're done with this pattern! It's eligible for GISel emission; return
  4532. // it.
  4533. ++NumPatternImported;
  4534. return std::move(M);
  4535. }
  4536. if (DstIName == "INSERT_SUBREG") {
  4537. assert(Src->getExtTypes().size() == 1 &&
  4538. "Expected Src of INSERT_SUBREG to have one result type");
  4539. // We need to constrain the destination, a super regsister source, and a
  4540. // subregister source.
  4541. auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
  4542. if (!SubClass)
  4543. return failedImport(
  4544. "Cannot infer register class from INSERT_SUBREG operand #1");
  4545. auto SuperClass = inferSuperRegisterClassForNode(
  4546. Src->getExtType(0), Dst->getChild(0), Dst->getChild(2));
  4547. if (!SuperClass)
  4548. return failedImport(
  4549. "Cannot infer register class for INSERT_SUBREG operand #0");
  4550. M.addAction<ConstrainOperandToRegClassAction>(0, 0, **SuperClass);
  4551. M.addAction<ConstrainOperandToRegClassAction>(0, 1, **SuperClass);
  4552. M.addAction<ConstrainOperandToRegClassAction>(0, 2, **SubClass);
  4553. ++NumPatternImported;
  4554. return std::move(M);
  4555. }
  4556. if (DstIName == "SUBREG_TO_REG") {
  4557. // We need to constrain the destination and subregister source.
  4558. assert(Src->getExtTypes().size() == 1 &&
  4559. "Expected Src of SUBREG_TO_REG to have one result type");
  4560. // Attempt to infer the subregister source from the first child. If it has
  4561. // an explicitly given register class, we'll use that. Otherwise, we will
  4562. // fail.
  4563. auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
  4564. if (!SubClass)
  4565. return failedImport(
  4566. "Cannot infer register class from SUBREG_TO_REG child #1");
  4567. // We don't have a child to look at that might have a super register node.
  4568. auto SuperClass =
  4569. inferSuperRegisterClass(Src->getExtType(0), Dst->getChild(2));
  4570. if (!SuperClass)
  4571. return failedImport(
  4572. "Cannot infer register class for SUBREG_TO_REG operand #0");
  4573. M.addAction<ConstrainOperandToRegClassAction>(0, 0, **SuperClass);
  4574. M.addAction<ConstrainOperandToRegClassAction>(0, 2, **SubClass);
  4575. ++NumPatternImported;
  4576. return std::move(M);
  4577. }
  4578. if (DstIName == "REG_SEQUENCE") {
  4579. auto SuperClass = inferRegClassFromPattern(Dst->getChild(0));
  4580. M.addAction<ConstrainOperandToRegClassAction>(0, 0, **SuperClass);
  4581. unsigned Num = Dst->getNumChildren();
  4582. for (unsigned I = 1; I != Num; I += 2) {
  4583. TreePatternNode *SubRegChild = Dst->getChild(I + 1);
  4584. auto SubIdx = inferSubRegIndexForNode(SubRegChild);
  4585. if (!SubIdx)
  4586. return failedImport("REG_SEQUENCE child is not a subreg index");
  4587. const auto SrcRCDstRCPair =
  4588. (*SuperClass)->getMatchingSubClassWithSubRegs(CGRegs, *SubIdx);
  4589. M.addAction<ConstrainOperandToRegClassAction>(0, I,
  4590. *SrcRCDstRCPair->second);
  4591. }
  4592. ++NumPatternImported;
  4593. return std::move(M);
  4594. }
  4595. M.addAction<ConstrainOperandsToDefinitionAction>(0);
  4596. // We're done with this pattern! It's eligible for GISel emission; return it.
  4597. ++NumPatternImported;
  4598. return std::move(M);
  4599. }
  4600. // Emit imm predicate table and an enum to reference them with.
  4601. // The 'Predicate_' part of the name is redundant but eliminating it is more
  4602. // trouble than it's worth.
  4603. void GlobalISelEmitter::emitCxxPredicateFns(
  4604. raw_ostream &OS, StringRef CodeFieldName, StringRef TypeIdentifier,
  4605. StringRef ArgType, StringRef ArgName, StringRef AdditionalArgs,
  4606. StringRef AdditionalDeclarations,
  4607. std::function<bool(const Record *R)> Filter) {
  4608. std::vector<const Record *> MatchedRecords;
  4609. const auto &Defs = RK.getAllDerivedDefinitions("PatFrags");
  4610. std::copy_if(Defs.begin(), Defs.end(), std::back_inserter(MatchedRecords),
  4611. [&](Record *Record) {
  4612. return !Record->getValueAsString(CodeFieldName).empty() &&
  4613. Filter(Record);
  4614. });
  4615. if (!MatchedRecords.empty()) {
  4616. OS << "// PatFrag predicates.\n"
  4617. << "enum {\n";
  4618. std::string EnumeratorSeparator =
  4619. (" = GIPFP_" + TypeIdentifier + "_Invalid + 1,\n").str();
  4620. for (const auto *Record : MatchedRecords) {
  4621. OS << " GIPFP_" << TypeIdentifier << "_Predicate_" << Record->getName()
  4622. << EnumeratorSeparator;
  4623. EnumeratorSeparator = ",\n";
  4624. }
  4625. OS << "};\n";
  4626. }
  4627. OS << "bool " << Target.getName() << "InstructionSelector::test" << ArgName
  4628. << "Predicate_" << TypeIdentifier << "(unsigned PredicateID, " << ArgType << " "
  4629. << ArgName << AdditionalArgs <<") const {\n"
  4630. << AdditionalDeclarations;
  4631. if (!AdditionalDeclarations.empty())
  4632. OS << "\n";
  4633. if (!MatchedRecords.empty())
  4634. OS << " switch (PredicateID) {\n";
  4635. for (const auto *Record : MatchedRecords) {
  4636. OS << " case GIPFP_" << TypeIdentifier << "_Predicate_"
  4637. << Record->getName() << ": {\n"
  4638. << " " << Record->getValueAsString(CodeFieldName) << "\n"
  4639. << " llvm_unreachable(\"" << CodeFieldName
  4640. << " should have returned\");\n"
  4641. << " return false;\n"
  4642. << " }\n";
  4643. }
  4644. if (!MatchedRecords.empty())
  4645. OS << " }\n";
  4646. OS << " llvm_unreachable(\"Unknown predicate\");\n"
  4647. << " return false;\n"
  4648. << "}\n";
  4649. }
  4650. void GlobalISelEmitter::emitImmPredicateFns(
  4651. raw_ostream &OS, StringRef TypeIdentifier, StringRef ArgType,
  4652. std::function<bool(const Record *R)> Filter) {
  4653. return emitCxxPredicateFns(OS, "ImmediateCode", TypeIdentifier, ArgType,
  4654. "Imm", "", "", Filter);
  4655. }
  4656. void GlobalISelEmitter::emitMIPredicateFns(raw_ostream &OS) {
  4657. return emitCxxPredicateFns(
  4658. OS, "GISelPredicateCode", "MI", "const MachineInstr &", "MI",
  4659. ", const std::array<const MachineOperand *, 3> &Operands",
  4660. " const MachineFunction &MF = *MI.getParent()->getParent();\n"
  4661. " const MachineRegisterInfo &MRI = MF.getRegInfo();\n"
  4662. " (void)MRI;",
  4663. [](const Record *R) { return true; });
  4664. }
  4665. template <class GroupT>
  4666. std::vector<Matcher *> GlobalISelEmitter::optimizeRules(
  4667. ArrayRef<Matcher *> Rules,
  4668. std::vector<std::unique_ptr<Matcher>> &MatcherStorage) {
  4669. std::vector<Matcher *> OptRules;
  4670. std::unique_ptr<GroupT> CurrentGroup = std::make_unique<GroupT>();
  4671. assert(CurrentGroup->empty() && "Newly created group isn't empty!");
  4672. unsigned NumGroups = 0;
  4673. auto ProcessCurrentGroup = [&]() {
  4674. if (CurrentGroup->empty())
  4675. // An empty group is good to be reused:
  4676. return;
  4677. // If the group isn't large enough to provide any benefit, move all the
  4678. // added rules out of it and make sure to re-create the group to properly
  4679. // re-initialize it:
  4680. if (CurrentGroup->size() < 2)
  4681. append_range(OptRules, CurrentGroup->matchers());
  4682. else {
  4683. CurrentGroup->finalize();
  4684. OptRules.push_back(CurrentGroup.get());
  4685. MatcherStorage.emplace_back(std::move(CurrentGroup));
  4686. ++NumGroups;
  4687. }
  4688. CurrentGroup = std::make_unique<GroupT>();
  4689. };
  4690. for (Matcher *Rule : Rules) {
  4691. // Greedily add as many matchers as possible to the current group:
  4692. if (CurrentGroup->addMatcher(*Rule))
  4693. continue;
  4694. ProcessCurrentGroup();
  4695. assert(CurrentGroup->empty() && "A group wasn't properly re-initialized");
  4696. // Try to add the pending matcher to a newly created empty group:
  4697. if (!CurrentGroup->addMatcher(*Rule))
  4698. // If we couldn't add the matcher to an empty group, that group type
  4699. // doesn't support that kind of matchers at all, so just skip it:
  4700. OptRules.push_back(Rule);
  4701. }
  4702. ProcessCurrentGroup();
  4703. LLVM_DEBUG(dbgs() << "NumGroups: " << NumGroups << "\n");
  4704. assert(CurrentGroup->empty() && "The last group wasn't properly processed");
  4705. return OptRules;
  4706. }
  4707. MatchTable
  4708. GlobalISelEmitter::buildMatchTable(MutableArrayRef<RuleMatcher> Rules,
  4709. bool Optimize, bool WithCoverage) {
  4710. std::vector<Matcher *> InputRules;
  4711. for (Matcher &Rule : Rules)
  4712. InputRules.push_back(&Rule);
  4713. if (!Optimize)
  4714. return MatchTable::buildTable(InputRules, WithCoverage);
  4715. unsigned CurrentOrdering = 0;
  4716. StringMap<unsigned> OpcodeOrder;
  4717. for (RuleMatcher &Rule : Rules) {
  4718. const StringRef Opcode = Rule.getOpcode();
  4719. assert(!Opcode.empty() && "Didn't expect an undefined opcode");
  4720. if (OpcodeOrder.count(Opcode) == 0)
  4721. OpcodeOrder[Opcode] = CurrentOrdering++;
  4722. }
  4723. llvm::stable_sort(InputRules, [&OpcodeOrder](const Matcher *A,
  4724. const Matcher *B) {
  4725. auto *L = static_cast<const RuleMatcher *>(A);
  4726. auto *R = static_cast<const RuleMatcher *>(B);
  4727. return std::make_tuple(OpcodeOrder[L->getOpcode()], L->getNumOperands()) <
  4728. std::make_tuple(OpcodeOrder[R->getOpcode()], R->getNumOperands());
  4729. });
  4730. for (Matcher *Rule : InputRules)
  4731. Rule->optimize();
  4732. std::vector<std::unique_ptr<Matcher>> MatcherStorage;
  4733. std::vector<Matcher *> OptRules =
  4734. optimizeRules<GroupMatcher>(InputRules, MatcherStorage);
  4735. for (Matcher *Rule : OptRules)
  4736. Rule->optimize();
  4737. OptRules = optimizeRules<SwitchMatcher>(OptRules, MatcherStorage);
  4738. return MatchTable::buildTable(OptRules, WithCoverage);
  4739. }
  4740. void GroupMatcher::optimize() {
  4741. // Make sure we only sort by a specific predicate within a range of rules that
  4742. // all have that predicate checked against a specific value (not a wildcard):
  4743. auto F = Matchers.begin();
  4744. auto T = F;
  4745. auto E = Matchers.end();
  4746. while (T != E) {
  4747. while (T != E) {
  4748. auto *R = static_cast<RuleMatcher *>(*T);
  4749. if (!R->getFirstConditionAsRootType().get().isValid())
  4750. break;
  4751. ++T;
  4752. }
  4753. std::stable_sort(F, T, [](Matcher *A, Matcher *B) {
  4754. auto *L = static_cast<RuleMatcher *>(A);
  4755. auto *R = static_cast<RuleMatcher *>(B);
  4756. return L->getFirstConditionAsRootType() <
  4757. R->getFirstConditionAsRootType();
  4758. });
  4759. if (T != E)
  4760. F = ++T;
  4761. }
  4762. GlobalISelEmitter::optimizeRules<GroupMatcher>(Matchers, MatcherStorage)
  4763. .swap(Matchers);
  4764. GlobalISelEmitter::optimizeRules<SwitchMatcher>(Matchers, MatcherStorage)
  4765. .swap(Matchers);
  4766. }
  4767. void GlobalISelEmitter::run(raw_ostream &OS) {
  4768. if (!UseCoverageFile.empty()) {
  4769. RuleCoverage = CodeGenCoverage();
  4770. auto RuleCoverageBufOrErr = MemoryBuffer::getFile(UseCoverageFile);
  4771. if (!RuleCoverageBufOrErr) {
  4772. PrintWarning(SMLoc(), "Missing rule coverage data");
  4773. RuleCoverage = None;
  4774. } else {
  4775. if (!RuleCoverage->parse(*RuleCoverageBufOrErr.get(), Target.getName())) {
  4776. PrintWarning(SMLoc(), "Ignoring invalid or missing rule coverage data");
  4777. RuleCoverage = None;
  4778. }
  4779. }
  4780. }
  4781. // Track the run-time opcode values
  4782. gatherOpcodeValues();
  4783. // Track the run-time LLT ID values
  4784. gatherTypeIDValues();
  4785. // Track the GINodeEquiv definitions.
  4786. gatherNodeEquivs();
  4787. emitSourceFileHeader(("Global Instruction Selector for the " +
  4788. Target.getName() + " target").str(), OS);
  4789. std::vector<RuleMatcher> Rules;
  4790. // Look through the SelectionDAG patterns we found, possibly emitting some.
  4791. for (const PatternToMatch &Pat : CGP.ptms()) {
  4792. ++NumPatternTotal;
  4793. auto MatcherOrErr = runOnPattern(Pat);
  4794. // The pattern analysis can fail, indicating an unsupported pattern.
  4795. // Report that if we've been asked to do so.
  4796. if (auto Err = MatcherOrErr.takeError()) {
  4797. if (WarnOnSkippedPatterns) {
  4798. PrintWarning(Pat.getSrcRecord()->getLoc(),
  4799. "Skipped pattern: " + toString(std::move(Err)));
  4800. } else {
  4801. consumeError(std::move(Err));
  4802. }
  4803. ++NumPatternImportsSkipped;
  4804. continue;
  4805. }
  4806. if (RuleCoverage) {
  4807. if (RuleCoverage->isCovered(MatcherOrErr->getRuleID()))
  4808. ++NumPatternsTested;
  4809. else
  4810. PrintWarning(Pat.getSrcRecord()->getLoc(),
  4811. "Pattern is not covered by a test");
  4812. }
  4813. Rules.push_back(std::move(MatcherOrErr.get()));
  4814. }
  4815. // Comparison function to order records by name.
  4816. auto orderByName = [](const Record *A, const Record *B) {
  4817. return A->getName() < B->getName();
  4818. };
  4819. std::vector<Record *> ComplexPredicates =
  4820. RK.getAllDerivedDefinitions("GIComplexOperandMatcher");
  4821. llvm::sort(ComplexPredicates, orderByName);
  4822. std::vector<StringRef> CustomRendererFns;
  4823. transform(RK.getAllDerivedDefinitions("GICustomOperandRenderer"),
  4824. std::back_inserter(CustomRendererFns), [](const auto &Record) {
  4825. return Record->getValueAsString("RendererFn");
  4826. });
  4827. // Sort and remove duplicates to get a list of unique renderer functions, in
  4828. // case some were mentioned more than once.
  4829. llvm::sort(CustomRendererFns);
  4830. CustomRendererFns.erase(
  4831. std::unique(CustomRendererFns.begin(), CustomRendererFns.end()),
  4832. CustomRendererFns.end());
  4833. unsigned MaxTemporaries = 0;
  4834. for (const auto &Rule : Rules)
  4835. MaxTemporaries = std::max(MaxTemporaries, Rule.countRendererFns());
  4836. OS << "#ifdef GET_GLOBALISEL_PREDICATE_BITSET\n"
  4837. << "const unsigned MAX_SUBTARGET_PREDICATES = " << SubtargetFeatures.size()
  4838. << ";\n"
  4839. << "using PredicateBitset = "
  4840. "llvm::PredicateBitsetImpl<MAX_SUBTARGET_PREDICATES>;\n"
  4841. << "#endif // ifdef GET_GLOBALISEL_PREDICATE_BITSET\n\n";
  4842. OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n"
  4843. << " mutable MatcherState State;\n"
  4844. << " typedef "
  4845. "ComplexRendererFns("
  4846. << Target.getName()
  4847. << "InstructionSelector::*ComplexMatcherMemFn)(MachineOperand &) const;\n"
  4848. << " typedef void(" << Target.getName()
  4849. << "InstructionSelector::*CustomRendererFn)(MachineInstrBuilder &, const "
  4850. "MachineInstr &, int) "
  4851. "const;\n"
  4852. << " const ISelInfoTy<PredicateBitset, ComplexMatcherMemFn, "
  4853. "CustomRendererFn> "
  4854. "ISelInfo;\n";
  4855. OS << " static " << Target.getName()
  4856. << "InstructionSelector::ComplexMatcherMemFn ComplexPredicateFns[];\n"
  4857. << " static " << Target.getName()
  4858. << "InstructionSelector::CustomRendererFn CustomRenderers[];\n"
  4859. << " bool testImmPredicate_I64(unsigned PredicateID, int64_t Imm) const "
  4860. "override;\n"
  4861. << " bool testImmPredicate_APInt(unsigned PredicateID, const APInt &Imm) "
  4862. "const override;\n"
  4863. << " bool testImmPredicate_APFloat(unsigned PredicateID, const APFloat "
  4864. "&Imm) const override;\n"
  4865. << " const int64_t *getMatchTable() const override;\n"
  4866. << " bool testMIPredicate_MI(unsigned PredicateID, const MachineInstr &MI"
  4867. ", const std::array<const MachineOperand *, 3> &Operands) "
  4868. "const override;\n"
  4869. << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n\n";
  4870. OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n"
  4871. << ", State(" << MaxTemporaries << "),\n"
  4872. << "ISelInfo(TypeObjects, NumTypeObjects, FeatureBitsets"
  4873. << ", ComplexPredicateFns, CustomRenderers)\n"
  4874. << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n\n";
  4875. OS << "#ifdef GET_GLOBALISEL_IMPL\n";
  4876. SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures,
  4877. OS);
  4878. // Separate subtarget features by how often they must be recomputed.
  4879. SubtargetFeatureInfoMap ModuleFeatures;
  4880. std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
  4881. std::inserter(ModuleFeatures, ModuleFeatures.end()),
  4882. [](const SubtargetFeatureInfoMap::value_type &X) {
  4883. return !X.second.mustRecomputePerFunction();
  4884. });
  4885. SubtargetFeatureInfoMap FunctionFeatures;
  4886. std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
  4887. std::inserter(FunctionFeatures, FunctionFeatures.end()),
  4888. [](const SubtargetFeatureInfoMap::value_type &X) {
  4889. return X.second.mustRecomputePerFunction();
  4890. });
  4891. SubtargetFeatureInfo::emitComputeAvailableFeatures(
  4892. Target.getName(), "InstructionSelector", "computeAvailableModuleFeatures",
  4893. ModuleFeatures, OS);
  4894. OS << "void " << Target.getName() << "InstructionSelector"
  4895. "::setupGeneratedPerFunctionState(MachineFunction &MF) {\n"
  4896. " AvailableFunctionFeatures = computeAvailableFunctionFeatures("
  4897. "(const " << Target.getName() << "Subtarget *)&MF.getSubtarget(), &MF);\n"
  4898. "}\n";
  4899. SubtargetFeatureInfo::emitComputeAvailableFeatures(
  4900. Target.getName(), "InstructionSelector",
  4901. "computeAvailableFunctionFeatures", FunctionFeatures, OS,
  4902. "const MachineFunction *MF");
  4903. // Emit a table containing the LLT objects needed by the matcher and an enum
  4904. // for the matcher to reference them with.
  4905. std::vector<LLTCodeGen> TypeObjects;
  4906. append_range(TypeObjects, KnownTypes);
  4907. llvm::sort(TypeObjects);
  4908. OS << "// LLT Objects.\n"
  4909. << "enum {\n";
  4910. for (const auto &TypeObject : TypeObjects) {
  4911. OS << " ";
  4912. TypeObject.emitCxxEnumValue(OS);
  4913. OS << ",\n";
  4914. }
  4915. OS << "};\n";
  4916. OS << "const static size_t NumTypeObjects = " << TypeObjects.size() << ";\n"
  4917. << "const static LLT TypeObjects[] = {\n";
  4918. for (const auto &TypeObject : TypeObjects) {
  4919. OS << " ";
  4920. TypeObject.emitCxxConstructorCall(OS);
  4921. OS << ",\n";
  4922. }
  4923. OS << "};\n\n";
  4924. // Emit a table containing the PredicateBitsets objects needed by the matcher
  4925. // and an enum for the matcher to reference them with.
  4926. std::vector<std::vector<Record *>> FeatureBitsets;
  4927. for (auto &Rule : Rules)
  4928. FeatureBitsets.push_back(Rule.getRequiredFeatures());
  4929. llvm::sort(FeatureBitsets, [&](const std::vector<Record *> &A,
  4930. const std::vector<Record *> &B) {
  4931. if (A.size() < B.size())
  4932. return true;
  4933. if (A.size() > B.size())
  4934. return false;
  4935. for (auto Pair : zip(A, B)) {
  4936. if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName())
  4937. return true;
  4938. if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName())
  4939. return false;
  4940. }
  4941. return false;
  4942. });
  4943. FeatureBitsets.erase(
  4944. std::unique(FeatureBitsets.begin(), FeatureBitsets.end()),
  4945. FeatureBitsets.end());
  4946. OS << "// Feature bitsets.\n"
  4947. << "enum {\n"
  4948. << " GIFBS_Invalid,\n";
  4949. for (const auto &FeatureBitset : FeatureBitsets) {
  4950. if (FeatureBitset.empty())
  4951. continue;
  4952. OS << " " << getNameForFeatureBitset(FeatureBitset) << ",\n";
  4953. }
  4954. OS << "};\n"
  4955. << "const static PredicateBitset FeatureBitsets[] {\n"
  4956. << " {}, // GIFBS_Invalid\n";
  4957. for (const auto &FeatureBitset : FeatureBitsets) {
  4958. if (FeatureBitset.empty())
  4959. continue;
  4960. OS << " {";
  4961. for (const auto &Feature : FeatureBitset) {
  4962. const auto &I = SubtargetFeatures.find(Feature);
  4963. assert(I != SubtargetFeatures.end() && "Didn't import predicate?");
  4964. OS << I->second.getEnumBitName() << ", ";
  4965. }
  4966. OS << "},\n";
  4967. }
  4968. OS << "};\n\n";
  4969. // Emit complex predicate table and an enum to reference them with.
  4970. OS << "// ComplexPattern predicates.\n"
  4971. << "enum {\n"
  4972. << " GICP_Invalid,\n";
  4973. for (const auto &Record : ComplexPredicates)
  4974. OS << " GICP_" << Record->getName() << ",\n";
  4975. OS << "};\n"
  4976. << "// See constructor for table contents\n\n";
  4977. emitImmPredicateFns(OS, "I64", "int64_t", [](const Record *R) {
  4978. bool Unset;
  4979. return !R->getValueAsBitOrUnset("IsAPFloat", Unset) &&
  4980. !R->getValueAsBit("IsAPInt");
  4981. });
  4982. emitImmPredicateFns(OS, "APFloat", "const APFloat &", [](const Record *R) {
  4983. bool Unset;
  4984. return R->getValueAsBitOrUnset("IsAPFloat", Unset);
  4985. });
  4986. emitImmPredicateFns(OS, "APInt", "const APInt &", [](const Record *R) {
  4987. return R->getValueAsBit("IsAPInt");
  4988. });
  4989. emitMIPredicateFns(OS);
  4990. OS << "\n";
  4991. OS << Target.getName() << "InstructionSelector::ComplexMatcherMemFn\n"
  4992. << Target.getName() << "InstructionSelector::ComplexPredicateFns[] = {\n"
  4993. << " nullptr, // GICP_Invalid\n";
  4994. for (const auto &Record : ComplexPredicates)
  4995. OS << " &" << Target.getName()
  4996. << "InstructionSelector::" << Record->getValueAsString("MatcherFn")
  4997. << ", // " << Record->getName() << "\n";
  4998. OS << "};\n\n";
  4999. OS << "// Custom renderers.\n"
  5000. << "enum {\n"
  5001. << " GICR_Invalid,\n";
  5002. for (const auto &Fn : CustomRendererFns)
  5003. OS << " GICR_" << Fn << ",\n";
  5004. OS << "};\n";
  5005. OS << Target.getName() << "InstructionSelector::CustomRendererFn\n"
  5006. << Target.getName() << "InstructionSelector::CustomRenderers[] = {\n"
  5007. << " nullptr, // GICR_Invalid\n";
  5008. for (const auto &Fn : CustomRendererFns)
  5009. OS << " &" << Target.getName() << "InstructionSelector::" << Fn << ",\n";
  5010. OS << "};\n\n";
  5011. llvm::stable_sort(Rules, [&](const RuleMatcher &A, const RuleMatcher &B) {
  5012. int ScoreA = RuleMatcherScores[A.getRuleID()];
  5013. int ScoreB = RuleMatcherScores[B.getRuleID()];
  5014. if (ScoreA > ScoreB)
  5015. return true;
  5016. if (ScoreB > ScoreA)
  5017. return false;
  5018. if (A.isHigherPriorityThan(B)) {
  5019. assert(!B.isHigherPriorityThan(A) && "Cannot be more important "
  5020. "and less important at "
  5021. "the same time");
  5022. return true;
  5023. }
  5024. return false;
  5025. });
  5026. OS << "bool " << Target.getName()
  5027. << "InstructionSelector::selectImpl(MachineInstr &I, CodeGenCoverage "
  5028. "&CoverageInfo) const {\n"
  5029. << " MachineFunction &MF = *I.getParent()->getParent();\n"
  5030. << " MachineRegisterInfo &MRI = MF.getRegInfo();\n"
  5031. << " const PredicateBitset AvailableFeatures = getAvailableFeatures();\n"
  5032. << " NewMIVector OutMIs;\n"
  5033. << " State.MIs.clear();\n"
  5034. << " State.MIs.push_back(&I);\n\n"
  5035. << " if (executeMatchTable(*this, OutMIs, State, ISelInfo"
  5036. << ", getMatchTable(), TII, MRI, TRI, RBI, AvailableFeatures"
  5037. << ", CoverageInfo)) {\n"
  5038. << " return true;\n"
  5039. << " }\n\n"
  5040. << " return false;\n"
  5041. << "}\n\n";
  5042. const MatchTable Table =
  5043. buildMatchTable(Rules, OptimizeMatchTable, GenerateCoverage);
  5044. OS << "const int64_t *" << Target.getName()
  5045. << "InstructionSelector::getMatchTable() const {\n";
  5046. Table.emitDeclaration(OS);
  5047. OS << " return ";
  5048. Table.emitUse(OS);
  5049. OS << ";\n}\n";
  5050. OS << "#endif // ifdef GET_GLOBALISEL_IMPL\n";
  5051. OS << "#ifdef GET_GLOBALISEL_PREDICATES_DECL\n"
  5052. << "PredicateBitset AvailableModuleFeatures;\n"
  5053. << "mutable PredicateBitset AvailableFunctionFeatures;\n"
  5054. << "PredicateBitset getAvailableFeatures() const {\n"
  5055. << " return AvailableModuleFeatures | AvailableFunctionFeatures;\n"
  5056. << "}\n"
  5057. << "PredicateBitset\n"
  5058. << "computeAvailableModuleFeatures(const " << Target.getName()
  5059. << "Subtarget *Subtarget) const;\n"
  5060. << "PredicateBitset\n"
  5061. << "computeAvailableFunctionFeatures(const " << Target.getName()
  5062. << "Subtarget *Subtarget,\n"
  5063. << " const MachineFunction *MF) const;\n"
  5064. << "void setupGeneratedPerFunctionState(MachineFunction &MF) override;\n"
  5065. << "#endif // ifdef GET_GLOBALISEL_PREDICATES_DECL\n";
  5066. OS << "#ifdef GET_GLOBALISEL_PREDICATES_INIT\n"
  5067. << "AvailableModuleFeatures(computeAvailableModuleFeatures(&STI)),\n"
  5068. << "AvailableFunctionFeatures()\n"
  5069. << "#endif // ifdef GET_GLOBALISEL_PREDICATES_INIT\n";
  5070. }
  5071. void GlobalISelEmitter::declareSubtargetFeature(Record *Predicate) {
  5072. if (SubtargetFeatures.count(Predicate) == 0)
  5073. SubtargetFeatures.emplace(
  5074. Predicate, SubtargetFeatureInfo(Predicate, SubtargetFeatures.size()));
  5075. }
  5076. void RuleMatcher::optimize() {
  5077. for (auto &Item : InsnVariableIDs) {
  5078. InstructionMatcher &InsnMatcher = *Item.first;
  5079. for (auto &OM : InsnMatcher.operands()) {
  5080. // Complex Patterns are usually expensive and they relatively rarely fail
  5081. // on their own: more often we end up throwing away all the work done by a
  5082. // matching part of a complex pattern because some other part of the
  5083. // enclosing pattern didn't match. All of this makes it beneficial to
  5084. // delay complex patterns until the very end of the rule matching,
  5085. // especially for targets having lots of complex patterns.
  5086. for (auto &OP : OM->predicates())
  5087. if (isa<ComplexPatternOperandMatcher>(OP))
  5088. EpilogueMatchers.emplace_back(std::move(OP));
  5089. OM->eraseNullPredicates();
  5090. }
  5091. InsnMatcher.optimize();
  5092. }
  5093. llvm::sort(EpilogueMatchers, [](const std::unique_ptr<PredicateMatcher> &L,
  5094. const std::unique_ptr<PredicateMatcher> &R) {
  5095. return std::make_tuple(L->getKind(), L->getInsnVarID(), L->getOpIdx()) <
  5096. std::make_tuple(R->getKind(), R->getInsnVarID(), R->getOpIdx());
  5097. });
  5098. }
  5099. bool RuleMatcher::hasFirstCondition() const {
  5100. if (insnmatchers_empty())
  5101. return false;
  5102. InstructionMatcher &Matcher = insnmatchers_front();
  5103. if (!Matcher.predicates_empty())
  5104. return true;
  5105. for (auto &OM : Matcher.operands())
  5106. for (auto &OP : OM->predicates())
  5107. if (!isa<InstructionOperandMatcher>(OP))
  5108. return true;
  5109. return false;
  5110. }
  5111. const PredicateMatcher &RuleMatcher::getFirstCondition() const {
  5112. assert(!insnmatchers_empty() &&
  5113. "Trying to get a condition from an empty RuleMatcher");
  5114. InstructionMatcher &Matcher = insnmatchers_front();
  5115. if (!Matcher.predicates_empty())
  5116. return **Matcher.predicates_begin();
  5117. // If there is no more predicate on the instruction itself, look at its
  5118. // operands.
  5119. for (auto &OM : Matcher.operands())
  5120. for (auto &OP : OM->predicates())
  5121. if (!isa<InstructionOperandMatcher>(OP))
  5122. return *OP;
  5123. llvm_unreachable("Trying to get a condition from an InstructionMatcher with "
  5124. "no conditions");
  5125. }
  5126. std::unique_ptr<PredicateMatcher> RuleMatcher::popFirstCondition() {
  5127. assert(!insnmatchers_empty() &&
  5128. "Trying to pop a condition from an empty RuleMatcher");
  5129. InstructionMatcher &Matcher = insnmatchers_front();
  5130. if (!Matcher.predicates_empty())
  5131. return Matcher.predicates_pop_front();
  5132. // If there is no more predicate on the instruction itself, look at its
  5133. // operands.
  5134. for (auto &OM : Matcher.operands())
  5135. for (auto &OP : OM->predicates())
  5136. if (!isa<InstructionOperandMatcher>(OP)) {
  5137. std::unique_ptr<PredicateMatcher> Result = std::move(OP);
  5138. OM->eraseNullPredicates();
  5139. return Result;
  5140. }
  5141. llvm_unreachable("Trying to pop a condition from an InstructionMatcher with "
  5142. "no conditions");
  5143. }
  5144. bool GroupMatcher::candidateConditionMatches(
  5145. const PredicateMatcher &Predicate) const {
  5146. if (empty()) {
  5147. // Sharing predicates for nested instructions is not supported yet as we
  5148. // currently don't hoist the GIM_RecordInsn's properly, therefore we can
  5149. // only work on the original root instruction (InsnVarID == 0):
  5150. if (Predicate.getInsnVarID() != 0)
  5151. return false;
  5152. // ... otherwise an empty group can handle any predicate with no specific
  5153. // requirements:
  5154. return true;
  5155. }
  5156. const Matcher &Representative = **Matchers.begin();
  5157. const auto &RepresentativeCondition = Representative.getFirstCondition();
  5158. // ... if not empty, the group can only accomodate matchers with the exact
  5159. // same first condition:
  5160. return Predicate.isIdentical(RepresentativeCondition);
  5161. }
  5162. bool GroupMatcher::addMatcher(Matcher &Candidate) {
  5163. if (!Candidate.hasFirstCondition())
  5164. return false;
  5165. const PredicateMatcher &Predicate = Candidate.getFirstCondition();
  5166. if (!candidateConditionMatches(Predicate))
  5167. return false;
  5168. Matchers.push_back(&Candidate);
  5169. return true;
  5170. }
  5171. void GroupMatcher::finalize() {
  5172. assert(Conditions.empty() && "Already finalized?");
  5173. if (empty())
  5174. return;
  5175. Matcher &FirstRule = **Matchers.begin();
  5176. for (;;) {
  5177. // All the checks are expected to succeed during the first iteration:
  5178. for (const auto &Rule : Matchers)
  5179. if (!Rule->hasFirstCondition())
  5180. return;
  5181. const auto &FirstCondition = FirstRule.getFirstCondition();
  5182. for (unsigned I = 1, E = Matchers.size(); I < E; ++I)
  5183. if (!Matchers[I]->getFirstCondition().isIdentical(FirstCondition))
  5184. return;
  5185. Conditions.push_back(FirstRule.popFirstCondition());
  5186. for (unsigned I = 1, E = Matchers.size(); I < E; ++I)
  5187. Matchers[I]->popFirstCondition();
  5188. }
  5189. }
  5190. void GroupMatcher::emit(MatchTable &Table) {
  5191. unsigned LabelID = ~0U;
  5192. if (!Conditions.empty()) {
  5193. LabelID = Table.allocateLabelID();
  5194. Table << MatchTable::Opcode("GIM_Try", +1)
  5195. << MatchTable::Comment("On fail goto")
  5196. << MatchTable::JumpTarget(LabelID) << MatchTable::LineBreak;
  5197. }
  5198. for (auto &Condition : Conditions)
  5199. Condition->emitPredicateOpcodes(
  5200. Table, *static_cast<RuleMatcher *>(*Matchers.begin()));
  5201. for (const auto &M : Matchers)
  5202. M->emit(Table);
  5203. // Exit the group
  5204. if (!Conditions.empty())
  5205. Table << MatchTable::Opcode("GIM_Reject", -1) << MatchTable::LineBreak
  5206. << MatchTable::Label(LabelID);
  5207. }
  5208. bool SwitchMatcher::isSupportedPredicateType(const PredicateMatcher &P) {
  5209. return isa<InstructionOpcodeMatcher>(P) || isa<LLTOperandMatcher>(P);
  5210. }
  5211. bool SwitchMatcher::candidateConditionMatches(
  5212. const PredicateMatcher &Predicate) const {
  5213. if (empty()) {
  5214. // Sharing predicates for nested instructions is not supported yet as we
  5215. // currently don't hoist the GIM_RecordInsn's properly, therefore we can
  5216. // only work on the original root instruction (InsnVarID == 0):
  5217. if (Predicate.getInsnVarID() != 0)
  5218. return false;
  5219. // ... while an attempt to add even a root matcher to an empty SwitchMatcher
  5220. // could fail as not all the types of conditions are supported:
  5221. if (!isSupportedPredicateType(Predicate))
  5222. return false;
  5223. // ... or the condition might not have a proper implementation of
  5224. // getValue() / isIdenticalDownToValue() yet:
  5225. if (!Predicate.hasValue())
  5226. return false;
  5227. // ... otherwise an empty Switch can accomodate the condition with no
  5228. // further requirements:
  5229. return true;
  5230. }
  5231. const Matcher &CaseRepresentative = **Matchers.begin();
  5232. const auto &RepresentativeCondition = CaseRepresentative.getFirstCondition();
  5233. // Switch-cases must share the same kind of condition and path to the value it
  5234. // checks:
  5235. if (!Predicate.isIdenticalDownToValue(RepresentativeCondition))
  5236. return false;
  5237. const auto Value = Predicate.getValue();
  5238. // ... but be unique with respect to the actual value they check:
  5239. return Values.count(Value) == 0;
  5240. }
  5241. bool SwitchMatcher::addMatcher(Matcher &Candidate) {
  5242. if (!Candidate.hasFirstCondition())
  5243. return false;
  5244. const PredicateMatcher &Predicate = Candidate.getFirstCondition();
  5245. if (!candidateConditionMatches(Predicate))
  5246. return false;
  5247. const auto Value = Predicate.getValue();
  5248. Values.insert(Value);
  5249. Matchers.push_back(&Candidate);
  5250. return true;
  5251. }
  5252. void SwitchMatcher::finalize() {
  5253. assert(Condition == nullptr && "Already finalized");
  5254. assert(Values.size() == Matchers.size() && "Broken SwitchMatcher");
  5255. if (empty())
  5256. return;
  5257. llvm::stable_sort(Matchers, [](const Matcher *L, const Matcher *R) {
  5258. return L->getFirstCondition().getValue() <
  5259. R->getFirstCondition().getValue();
  5260. });
  5261. Condition = Matchers[0]->popFirstCondition();
  5262. for (unsigned I = 1, E = Values.size(); I < E; ++I)
  5263. Matchers[I]->popFirstCondition();
  5264. }
  5265. void SwitchMatcher::emitPredicateSpecificOpcodes(const PredicateMatcher &P,
  5266. MatchTable &Table) {
  5267. assert(isSupportedPredicateType(P) && "Predicate type is not supported");
  5268. if (const auto *Condition = dyn_cast<InstructionOpcodeMatcher>(&P)) {
  5269. Table << MatchTable::Opcode("GIM_SwitchOpcode") << MatchTable::Comment("MI")
  5270. << MatchTable::IntValue(Condition->getInsnVarID());
  5271. return;
  5272. }
  5273. if (const auto *Condition = dyn_cast<LLTOperandMatcher>(&P)) {
  5274. Table << MatchTable::Opcode("GIM_SwitchType") << MatchTable::Comment("MI")
  5275. << MatchTable::IntValue(Condition->getInsnVarID())
  5276. << MatchTable::Comment("Op")
  5277. << MatchTable::IntValue(Condition->getOpIdx());
  5278. return;
  5279. }
  5280. llvm_unreachable("emitPredicateSpecificOpcodes is broken: can not handle a "
  5281. "predicate type that is claimed to be supported");
  5282. }
  5283. void SwitchMatcher::emit(MatchTable &Table) {
  5284. assert(Values.size() == Matchers.size() && "Broken SwitchMatcher");
  5285. if (empty())
  5286. return;
  5287. assert(Condition != nullptr &&
  5288. "Broken SwitchMatcher, hasn't been finalized?");
  5289. std::vector<unsigned> LabelIDs(Values.size());
  5290. std::generate(LabelIDs.begin(), LabelIDs.end(),
  5291. [&Table]() { return Table.allocateLabelID(); });
  5292. const unsigned Default = Table.allocateLabelID();
  5293. const int64_t LowerBound = Values.begin()->getRawValue();
  5294. const int64_t UpperBound = Values.rbegin()->getRawValue() + 1;
  5295. emitPredicateSpecificOpcodes(*Condition, Table);
  5296. Table << MatchTable::Comment("[") << MatchTable::IntValue(LowerBound)
  5297. << MatchTable::IntValue(UpperBound) << MatchTable::Comment(")")
  5298. << MatchTable::Comment("default:") << MatchTable::JumpTarget(Default);
  5299. int64_t J = LowerBound;
  5300. auto VI = Values.begin();
  5301. for (unsigned I = 0, E = Values.size(); I < E; ++I) {
  5302. auto V = *VI++;
  5303. while (J++ < V.getRawValue())
  5304. Table << MatchTable::IntValue(0);
  5305. V.turnIntoComment();
  5306. Table << MatchTable::LineBreak << V << MatchTable::JumpTarget(LabelIDs[I]);
  5307. }
  5308. Table << MatchTable::LineBreak;
  5309. for (unsigned I = 0, E = Values.size(); I < E; ++I) {
  5310. Table << MatchTable::Label(LabelIDs[I]);
  5311. Matchers[I]->emit(Table);
  5312. Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
  5313. }
  5314. Table << MatchTable::Label(Default);
  5315. }
  5316. unsigned OperandMatcher::getInsnVarID() const { return Insn.getInsnVarID(); }
  5317. } // end anonymous namespace
  5318. //===----------------------------------------------------------------------===//
  5319. namespace llvm {
  5320. void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) {
  5321. GlobalISelEmitter(RK).run(OS);
  5322. }
  5323. } // End llvm namespace