GlobalISelEmitter.cpp 228 KB

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