AsmMatcherEmitter.cpp 153 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987
  1. //===- AsmMatcherEmitter.cpp - Generate an assembly matcher ---------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This tablegen backend emits a target specifier matcher for converting parsed
  10. // assembly operands in the MCInst structures. It also emits a matcher for
  11. // custom operand parsing.
  12. //
  13. // Converting assembly operands into MCInst structures
  14. // ---------------------------------------------------
  15. //
  16. // The input to the target specific matcher is a list of literal tokens and
  17. // operands. The target specific parser should generally eliminate any syntax
  18. // which is not relevant for matching; for example, comma tokens should have
  19. // already been consumed and eliminated by the parser. Most instructions will
  20. // end up with a single literal token (the instruction name) and some number of
  21. // operands.
  22. //
  23. // Some example inputs, for X86:
  24. // 'addl' (immediate ...) (register ...)
  25. // 'add' (immediate ...) (memory ...)
  26. // 'call' '*' %epc
  27. //
  28. // The assembly matcher is responsible for converting this input into a precise
  29. // machine instruction (i.e., an instruction with a well defined encoding). This
  30. // mapping has several properties which complicate matching:
  31. //
  32. // - It may be ambiguous; many architectures can legally encode particular
  33. // variants of an instruction in different ways (for example, using a smaller
  34. // encoding for small immediates). Such ambiguities should never be
  35. // arbitrarily resolved by the assembler, the assembler is always responsible
  36. // for choosing the "best" available instruction.
  37. //
  38. // - It may depend on the subtarget or the assembler context. Instructions
  39. // which are invalid for the current mode, but otherwise unambiguous (e.g.,
  40. // an SSE instruction in a file being assembled for i486) should be accepted
  41. // and rejected by the assembler front end. However, if the proper encoding
  42. // for an instruction is dependent on the assembler context then the matcher
  43. // is responsible for selecting the correct machine instruction for the
  44. // current mode.
  45. //
  46. // The core matching algorithm attempts to exploit the regularity in most
  47. // instruction sets to quickly determine the set of possibly matching
  48. // instructions, and the simplify the generated code. Additionally, this helps
  49. // to ensure that the ambiguities are intentionally resolved by the user.
  50. //
  51. // The matching is divided into two distinct phases:
  52. //
  53. // 1. Classification: Each operand is mapped to the unique set which (a)
  54. // contains it, and (b) is the largest such subset for which a single
  55. // instruction could match all members.
  56. //
  57. // For register classes, we can generate these subgroups automatically. For
  58. // arbitrary operands, we expect the user to define the classes and their
  59. // relations to one another (for example, 8-bit signed immediates as a
  60. // subset of 32-bit immediates).
  61. //
  62. // By partitioning the operands in this way, we guarantee that for any
  63. // tuple of classes, any single instruction must match either all or none
  64. // of the sets of operands which could classify to that tuple.
  65. //
  66. // In addition, the subset relation amongst classes induces a partial order
  67. // on such tuples, which we use to resolve ambiguities.
  68. //
  69. // 2. The input can now be treated as a tuple of classes (static tokens are
  70. // simple singleton sets). Each such tuple should generally map to a single
  71. // instruction (we currently ignore cases where this isn't true, whee!!!),
  72. // which we can emit a simple matcher for.
  73. //
  74. // Custom Operand Parsing
  75. // ----------------------
  76. //
  77. // Some targets need a custom way to parse operands, some specific instructions
  78. // can contain arguments that can represent processor flags and other kinds of
  79. // identifiers that need to be mapped to specific values in the final encoded
  80. // instructions. The target specific custom operand parsing works in the
  81. // following way:
  82. //
  83. // 1. A operand match table is built, each entry contains a mnemonic, an
  84. // operand class, a mask for all operand positions for that same
  85. // class/mnemonic and target features to be checked while trying to match.
  86. //
  87. // 2. The operand matcher will try every possible entry with the same
  88. // mnemonic and will check if the target feature for this mnemonic also
  89. // matches. After that, if the operand to be matched has its index
  90. // present in the mask, a successful match occurs. Otherwise, fallback
  91. // to the regular operand parsing.
  92. //
  93. // 3. For a match success, each operand class that has a 'ParserMethod'
  94. // becomes part of a switch from where the custom method is called.
  95. //
  96. //===----------------------------------------------------------------------===//
  97. #include "CodeGenTarget.h"
  98. #include "SubtargetFeatureInfo.h"
  99. #include "Types.h"
  100. #include "llvm/ADT/CachedHashString.h"
  101. #include "llvm/ADT/PointerUnion.h"
  102. #include "llvm/ADT/STLExtras.h"
  103. #include "llvm/ADT/SmallPtrSet.h"
  104. #include "llvm/ADT/SmallVector.h"
  105. #include "llvm/ADT/StringExtras.h"
  106. #include "llvm/Config/llvm-config.h"
  107. #include "llvm/Support/CommandLine.h"
  108. #include "llvm/Support/Debug.h"
  109. #include "llvm/Support/ErrorHandling.h"
  110. #include "llvm/TableGen/Error.h"
  111. #include "llvm/TableGen/Record.h"
  112. #include "llvm/TableGen/StringMatcher.h"
  113. #include "llvm/TableGen/StringToOffsetTable.h"
  114. #include "llvm/TableGen/TableGenBackend.h"
  115. #include <cassert>
  116. #include <cctype>
  117. #include <forward_list>
  118. #include <map>
  119. #include <set>
  120. using namespace llvm;
  121. #define DEBUG_TYPE "asm-matcher-emitter"
  122. cl::OptionCategory AsmMatcherEmitterCat("Options for -gen-asm-matcher");
  123. static cl::opt<std::string>
  124. MatchPrefix("match-prefix", cl::init(""),
  125. cl::desc("Only match instructions with the given prefix"),
  126. cl::cat(AsmMatcherEmitterCat));
  127. namespace {
  128. class AsmMatcherInfo;
  129. // Register sets are used as keys in some second-order sets TableGen creates
  130. // when generating its data structures. This means that the order of two
  131. // RegisterSets can be seen in the outputted AsmMatcher tables occasionally, and
  132. // can even affect compiler output (at least seen in diagnostics produced when
  133. // all matches fail). So we use a type that sorts them consistently.
  134. typedef std::set<Record*, LessRecordByID> RegisterSet;
  135. class AsmMatcherEmitter {
  136. RecordKeeper &Records;
  137. public:
  138. AsmMatcherEmitter(RecordKeeper &R) : Records(R) {}
  139. void run(raw_ostream &o);
  140. };
  141. /// ClassInfo - Helper class for storing the information about a particular
  142. /// class of operands which can be matched.
  143. struct ClassInfo {
  144. enum ClassInfoKind {
  145. /// Invalid kind, for use as a sentinel value.
  146. Invalid = 0,
  147. /// The class for a particular token.
  148. Token,
  149. /// The (first) register class, subsequent register classes are
  150. /// RegisterClass0+1, and so on.
  151. RegisterClass0,
  152. /// The (first) user defined class, subsequent user defined classes are
  153. /// UserClass0+1, and so on.
  154. UserClass0 = 1<<16
  155. };
  156. /// Kind - The class kind, which is either a predefined kind, or (UserClass0 +
  157. /// N) for the Nth user defined class.
  158. unsigned Kind;
  159. /// SuperClasses - The super classes of this class. Note that for simplicities
  160. /// sake user operands only record their immediate super class, while register
  161. /// operands include all superclasses.
  162. std::vector<ClassInfo*> SuperClasses;
  163. /// Name - The full class name, suitable for use in an enum.
  164. std::string Name;
  165. /// ClassName - The unadorned generic name for this class (e.g., Token).
  166. std::string ClassName;
  167. /// ValueName - The name of the value this class represents; for a token this
  168. /// is the literal token string, for an operand it is the TableGen class (or
  169. /// empty if this is a derived class).
  170. std::string ValueName;
  171. /// PredicateMethod - The name of the operand method to test whether the
  172. /// operand matches this class; this is not valid for Token or register kinds.
  173. std::string PredicateMethod;
  174. /// RenderMethod - The name of the operand method to add this operand to an
  175. /// MCInst; this is not valid for Token or register kinds.
  176. std::string RenderMethod;
  177. /// ParserMethod - The name of the operand method to do a target specific
  178. /// parsing on the operand.
  179. std::string ParserMethod;
  180. /// For register classes: the records for all the registers in this class.
  181. RegisterSet Registers;
  182. /// For custom match classes: the diagnostic kind for when the predicate fails.
  183. std::string DiagnosticType;
  184. /// For custom match classes: the diagnostic string for when the predicate fails.
  185. std::string DiagnosticString;
  186. /// Is this operand optional and not always required.
  187. bool IsOptional;
  188. /// DefaultMethod - The name of the method that returns the default operand
  189. /// for optional operand
  190. std::string DefaultMethod;
  191. public:
  192. /// isRegisterClass() - Check if this is a register class.
  193. bool isRegisterClass() const {
  194. return Kind >= RegisterClass0 && Kind < UserClass0;
  195. }
  196. /// isUserClass() - Check if this is a user defined class.
  197. bool isUserClass() const {
  198. return Kind >= UserClass0;
  199. }
  200. /// isRelatedTo - Check whether this class is "related" to \p RHS. Classes
  201. /// are related if they are in the same class hierarchy.
  202. bool isRelatedTo(const ClassInfo &RHS) const {
  203. // Tokens are only related to tokens.
  204. if (Kind == Token || RHS.Kind == Token)
  205. return Kind == Token && RHS.Kind == Token;
  206. // Registers classes are only related to registers classes, and only if
  207. // their intersection is non-empty.
  208. if (isRegisterClass() || RHS.isRegisterClass()) {
  209. if (!isRegisterClass() || !RHS.isRegisterClass())
  210. return false;
  211. RegisterSet Tmp;
  212. std::insert_iterator<RegisterSet> II(Tmp, Tmp.begin());
  213. std::set_intersection(Registers.begin(), Registers.end(),
  214. RHS.Registers.begin(), RHS.Registers.end(),
  215. II, LessRecordByID());
  216. return !Tmp.empty();
  217. }
  218. // Otherwise we have two users operands; they are related if they are in the
  219. // same class hierarchy.
  220. //
  221. // FIXME: This is an oversimplification, they should only be related if they
  222. // intersect, however we don't have that information.
  223. assert(isUserClass() && RHS.isUserClass() && "Unexpected class!");
  224. const ClassInfo *Root = this;
  225. while (!Root->SuperClasses.empty())
  226. Root = Root->SuperClasses.front();
  227. const ClassInfo *RHSRoot = &RHS;
  228. while (!RHSRoot->SuperClasses.empty())
  229. RHSRoot = RHSRoot->SuperClasses.front();
  230. return Root == RHSRoot;
  231. }
  232. /// isSubsetOf - Test whether this class is a subset of \p RHS.
  233. bool isSubsetOf(const ClassInfo &RHS) const {
  234. // This is a subset of RHS if it is the same class...
  235. if (this == &RHS)
  236. return true;
  237. // ... or if any of its super classes are a subset of RHS.
  238. SmallVector<const ClassInfo *, 16> Worklist(SuperClasses.begin(),
  239. SuperClasses.end());
  240. SmallPtrSet<const ClassInfo *, 16> Visited;
  241. while (!Worklist.empty()) {
  242. auto *CI = Worklist.pop_back_val();
  243. if (CI == &RHS)
  244. return true;
  245. for (auto *Super : CI->SuperClasses)
  246. if (Visited.insert(Super).second)
  247. Worklist.push_back(Super);
  248. }
  249. return false;
  250. }
  251. int getTreeDepth() const {
  252. int Depth = 0;
  253. const ClassInfo *Root = this;
  254. while (!Root->SuperClasses.empty()) {
  255. Depth++;
  256. Root = Root->SuperClasses.front();
  257. }
  258. return Depth;
  259. }
  260. const ClassInfo *findRoot() const {
  261. const ClassInfo *Root = this;
  262. while (!Root->SuperClasses.empty())
  263. Root = Root->SuperClasses.front();
  264. return Root;
  265. }
  266. /// Compare two classes. This does not produce a total ordering, but does
  267. /// guarantee that subclasses are sorted before their parents, and that the
  268. /// ordering is transitive.
  269. bool operator<(const ClassInfo &RHS) const {
  270. if (this == &RHS)
  271. return false;
  272. // First, enforce the ordering between the three different types of class.
  273. // Tokens sort before registers, which sort before user classes.
  274. if (Kind == Token) {
  275. if (RHS.Kind != Token)
  276. return true;
  277. assert(RHS.Kind == Token);
  278. } else if (isRegisterClass()) {
  279. if (RHS.Kind == Token)
  280. return false;
  281. else if (RHS.isUserClass())
  282. return true;
  283. assert(RHS.isRegisterClass());
  284. } else if (isUserClass()) {
  285. if (!RHS.isUserClass())
  286. return false;
  287. assert(RHS.isUserClass());
  288. } else {
  289. llvm_unreachable("Unknown ClassInfoKind");
  290. }
  291. if (Kind == Token || isUserClass()) {
  292. // Related tokens and user classes get sorted by depth in the inheritence
  293. // tree (so that subclasses are before their parents).
  294. if (isRelatedTo(RHS)) {
  295. if (getTreeDepth() > RHS.getTreeDepth())
  296. return true;
  297. if (getTreeDepth() < RHS.getTreeDepth())
  298. return false;
  299. } else {
  300. // Unrelated tokens and user classes are ordered by the name of their
  301. // root nodes, so that there is a consistent ordering between
  302. // unconnected trees.
  303. return findRoot()->ValueName < RHS.findRoot()->ValueName;
  304. }
  305. } else if (isRegisterClass()) {
  306. // For register sets, sort by number of registers. This guarantees that
  307. // a set will always sort before all of it's strict supersets.
  308. if (Registers.size() != RHS.Registers.size())
  309. return Registers.size() < RHS.Registers.size();
  310. } else {
  311. llvm_unreachable("Unknown ClassInfoKind");
  312. }
  313. // FIXME: We should be able to just return false here, as we only need a
  314. // partial order (we use stable sorts, so this is deterministic) and the
  315. // name of a class shouldn't be significant. However, some of the backends
  316. // accidentally rely on this behaviour, so it will have to stay like this
  317. // until they are fixed.
  318. return ValueName < RHS.ValueName;
  319. }
  320. };
  321. class AsmVariantInfo {
  322. public:
  323. StringRef RegisterPrefix;
  324. StringRef TokenizingCharacters;
  325. StringRef SeparatorCharacters;
  326. StringRef BreakCharacters;
  327. StringRef Name;
  328. int AsmVariantNo;
  329. };
  330. /// MatchableInfo - Helper class for storing the necessary information for an
  331. /// instruction or alias which is capable of being matched.
  332. struct MatchableInfo {
  333. struct AsmOperand {
  334. /// Token - This is the token that the operand came from.
  335. StringRef Token;
  336. /// The unique class instance this operand should match.
  337. ClassInfo *Class;
  338. /// The operand name this is, if anything.
  339. StringRef SrcOpName;
  340. /// The operand name this is, before renaming for tied operands.
  341. StringRef OrigSrcOpName;
  342. /// The suboperand index within SrcOpName, or -1 for the entire operand.
  343. int SubOpIdx;
  344. /// Whether the token is "isolated", i.e., it is preceded and followed
  345. /// by separators.
  346. bool IsIsolatedToken;
  347. /// Register record if this token is singleton register.
  348. Record *SingletonReg;
  349. explicit AsmOperand(bool IsIsolatedToken, StringRef T)
  350. : Token(T), Class(nullptr), SubOpIdx(-1),
  351. IsIsolatedToken(IsIsolatedToken), SingletonReg(nullptr) {}
  352. };
  353. /// ResOperand - This represents a single operand in the result instruction
  354. /// generated by the match. In cases (like addressing modes) where a single
  355. /// assembler operand expands to multiple MCOperands, this represents the
  356. /// single assembler operand, not the MCOperand.
  357. struct ResOperand {
  358. enum {
  359. /// RenderAsmOperand - This represents an operand result that is
  360. /// generated by calling the render method on the assembly operand. The
  361. /// corresponding AsmOperand is specified by AsmOperandNum.
  362. RenderAsmOperand,
  363. /// TiedOperand - This represents a result operand that is a duplicate of
  364. /// a previous result operand.
  365. TiedOperand,
  366. /// ImmOperand - This represents an immediate value that is dumped into
  367. /// the operand.
  368. ImmOperand,
  369. /// RegOperand - This represents a fixed register that is dumped in.
  370. RegOperand
  371. } Kind;
  372. /// Tuple containing the index of the (earlier) result operand that should
  373. /// be copied from, as well as the indices of the corresponding (parsed)
  374. /// operands in the asm string.
  375. struct TiedOperandsTuple {
  376. unsigned ResOpnd;
  377. unsigned SrcOpnd1Idx;
  378. unsigned SrcOpnd2Idx;
  379. };
  380. union {
  381. /// This is the operand # in the AsmOperands list that this should be
  382. /// copied from.
  383. unsigned AsmOperandNum;
  384. /// Description of tied operands.
  385. TiedOperandsTuple TiedOperands;
  386. /// ImmVal - This is the immediate value added to the instruction.
  387. int64_t ImmVal;
  388. /// Register - This is the register record.
  389. Record *Register;
  390. };
  391. /// MINumOperands - The number of MCInst operands populated by this
  392. /// operand.
  393. unsigned MINumOperands;
  394. static ResOperand getRenderedOp(unsigned AsmOpNum, unsigned NumOperands) {
  395. ResOperand X;
  396. X.Kind = RenderAsmOperand;
  397. X.AsmOperandNum = AsmOpNum;
  398. X.MINumOperands = NumOperands;
  399. return X;
  400. }
  401. static ResOperand getTiedOp(unsigned TiedOperandNum, unsigned SrcOperand1,
  402. unsigned SrcOperand2) {
  403. ResOperand X;
  404. X.Kind = TiedOperand;
  405. X.TiedOperands = { TiedOperandNum, SrcOperand1, SrcOperand2 };
  406. X.MINumOperands = 1;
  407. return X;
  408. }
  409. static ResOperand getImmOp(int64_t Val) {
  410. ResOperand X;
  411. X.Kind = ImmOperand;
  412. X.ImmVal = Val;
  413. X.MINumOperands = 1;
  414. return X;
  415. }
  416. static ResOperand getRegOp(Record *Reg) {
  417. ResOperand X;
  418. X.Kind = RegOperand;
  419. X.Register = Reg;
  420. X.MINumOperands = 1;
  421. return X;
  422. }
  423. };
  424. /// AsmVariantID - Target's assembly syntax variant no.
  425. int AsmVariantID;
  426. /// AsmString - The assembly string for this instruction (with variants
  427. /// removed), e.g. "movsx $src, $dst".
  428. std::string AsmString;
  429. /// TheDef - This is the definition of the instruction or InstAlias that this
  430. /// matchable came from.
  431. Record *const TheDef;
  432. /// DefRec - This is the definition that it came from.
  433. PointerUnion<const CodeGenInstruction*, const CodeGenInstAlias*> DefRec;
  434. const CodeGenInstruction *getResultInst() const {
  435. if (DefRec.is<const CodeGenInstruction*>())
  436. return DefRec.get<const CodeGenInstruction*>();
  437. return DefRec.get<const CodeGenInstAlias*>()->ResultInst;
  438. }
  439. /// ResOperands - This is the operand list that should be built for the result
  440. /// MCInst.
  441. SmallVector<ResOperand, 8> ResOperands;
  442. /// Mnemonic - This is the first token of the matched instruction, its
  443. /// mnemonic.
  444. StringRef Mnemonic;
  445. /// AsmOperands - The textual operands that this instruction matches,
  446. /// annotated with a class and where in the OperandList they were defined.
  447. /// This directly corresponds to the tokenized AsmString after the mnemonic is
  448. /// removed.
  449. SmallVector<AsmOperand, 8> AsmOperands;
  450. /// Predicates - The required subtarget features to match this instruction.
  451. SmallVector<const SubtargetFeatureInfo *, 4> RequiredFeatures;
  452. /// ConversionFnKind - The enum value which is passed to the generated
  453. /// convertToMCInst to convert parsed operands into an MCInst for this
  454. /// function.
  455. std::string ConversionFnKind;
  456. /// If this instruction is deprecated in some form.
  457. bool HasDeprecation;
  458. /// If this is an alias, this is use to determine whether or not to using
  459. /// the conversion function defined by the instruction's AsmMatchConverter
  460. /// or to use the function generated by the alias.
  461. bool UseInstAsmMatchConverter;
  462. MatchableInfo(const CodeGenInstruction &CGI)
  463. : AsmVariantID(0), AsmString(CGI.AsmString), TheDef(CGI.TheDef), DefRec(&CGI),
  464. UseInstAsmMatchConverter(true) {
  465. }
  466. MatchableInfo(std::unique_ptr<const CodeGenInstAlias> Alias)
  467. : AsmVariantID(0), AsmString(Alias->AsmString), TheDef(Alias->TheDef),
  468. DefRec(Alias.release()),
  469. UseInstAsmMatchConverter(
  470. TheDef->getValueAsBit("UseInstAsmMatchConverter")) {
  471. }
  472. // Could remove this and the dtor if PointerUnion supported unique_ptr
  473. // elements with a dynamic failure/assertion (like the one below) in the case
  474. // where it was copied while being in an owning state.
  475. MatchableInfo(const MatchableInfo &RHS)
  476. : AsmVariantID(RHS.AsmVariantID), AsmString(RHS.AsmString),
  477. TheDef(RHS.TheDef), DefRec(RHS.DefRec), ResOperands(RHS.ResOperands),
  478. Mnemonic(RHS.Mnemonic), AsmOperands(RHS.AsmOperands),
  479. RequiredFeatures(RHS.RequiredFeatures),
  480. ConversionFnKind(RHS.ConversionFnKind),
  481. HasDeprecation(RHS.HasDeprecation),
  482. UseInstAsmMatchConverter(RHS.UseInstAsmMatchConverter) {
  483. assert(!DefRec.is<const CodeGenInstAlias *>());
  484. }
  485. ~MatchableInfo() {
  486. delete DefRec.dyn_cast<const CodeGenInstAlias*>();
  487. }
  488. // Two-operand aliases clone from the main matchable, but mark the second
  489. // operand as a tied operand of the first for purposes of the assembler.
  490. void formTwoOperandAlias(StringRef Constraint);
  491. void initialize(const AsmMatcherInfo &Info,
  492. SmallPtrSetImpl<Record*> &SingletonRegisters,
  493. AsmVariantInfo const &Variant,
  494. bool HasMnemonicFirst);
  495. /// validate - Return true if this matchable is a valid thing to match against
  496. /// and perform a bunch of validity checking.
  497. bool validate(StringRef CommentDelimiter, bool IsAlias) const;
  498. /// findAsmOperand - Find the AsmOperand with the specified name and
  499. /// suboperand index.
  500. int findAsmOperand(StringRef N, int SubOpIdx) const {
  501. auto I = find_if(AsmOperands, [&](const AsmOperand &Op) {
  502. return Op.SrcOpName == N && Op.SubOpIdx == SubOpIdx;
  503. });
  504. return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1;
  505. }
  506. /// findAsmOperandNamed - Find the first AsmOperand with the specified name.
  507. /// This does not check the suboperand index.
  508. int findAsmOperandNamed(StringRef N, int LastIdx = -1) const {
  509. auto I = std::find_if(AsmOperands.begin() + LastIdx + 1, AsmOperands.end(),
  510. [&](const AsmOperand &Op) { return Op.SrcOpName == N; });
  511. return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1;
  512. }
  513. int findAsmOperandOriginallyNamed(StringRef N) const {
  514. auto I =
  515. find_if(AsmOperands,
  516. [&](const AsmOperand &Op) { return Op.OrigSrcOpName == N; });
  517. return (I != AsmOperands.end()) ? I - AsmOperands.begin() : -1;
  518. }
  519. void buildInstructionResultOperands();
  520. void buildAliasResultOperands(bool AliasConstraintsAreChecked);
  521. /// operator< - Compare two matchables.
  522. bool operator<(const MatchableInfo &RHS) const {
  523. // The primary comparator is the instruction mnemonic.
  524. if (int Cmp = Mnemonic.compare_lower(RHS.Mnemonic))
  525. return Cmp == -1;
  526. if (AsmOperands.size() != RHS.AsmOperands.size())
  527. return AsmOperands.size() < RHS.AsmOperands.size();
  528. // Compare lexicographically by operand. The matcher validates that other
  529. // orderings wouldn't be ambiguous using \see couldMatchAmbiguouslyWith().
  530. for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
  531. if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
  532. return true;
  533. if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
  534. return false;
  535. }
  536. // Give matches that require more features higher precedence. This is useful
  537. // because we cannot define AssemblerPredicates with the negation of
  538. // processor features. For example, ARM v6 "nop" may be either a HINT or
  539. // MOV. With v6, we want to match HINT. The assembler has no way to
  540. // predicate MOV under "NoV6", but HINT will always match first because it
  541. // requires V6 while MOV does not.
  542. if (RequiredFeatures.size() != RHS.RequiredFeatures.size())
  543. return RequiredFeatures.size() > RHS.RequiredFeatures.size();
  544. return false;
  545. }
  546. /// couldMatchAmbiguouslyWith - Check whether this matchable could
  547. /// ambiguously match the same set of operands as \p RHS (without being a
  548. /// strictly superior match).
  549. bool couldMatchAmbiguouslyWith(const MatchableInfo &RHS) const {
  550. // The primary comparator is the instruction mnemonic.
  551. if (Mnemonic != RHS.Mnemonic)
  552. return false;
  553. // Different variants can't conflict.
  554. if (AsmVariantID != RHS.AsmVariantID)
  555. return false;
  556. // The number of operands is unambiguous.
  557. if (AsmOperands.size() != RHS.AsmOperands.size())
  558. return false;
  559. // Otherwise, make sure the ordering of the two instructions is unambiguous
  560. // by checking that either (a) a token or operand kind discriminates them,
  561. // or (b) the ordering among equivalent kinds is consistent.
  562. // Tokens and operand kinds are unambiguous (assuming a correct target
  563. // specific parser).
  564. for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i)
  565. if (AsmOperands[i].Class->Kind != RHS.AsmOperands[i].Class->Kind ||
  566. AsmOperands[i].Class->Kind == ClassInfo::Token)
  567. if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class ||
  568. *RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
  569. return false;
  570. // Otherwise, this operand could commute if all operands are equivalent, or
  571. // there is a pair of operands that compare less than and a pair that
  572. // compare greater than.
  573. bool HasLT = false, HasGT = false;
  574. for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
  575. if (*AsmOperands[i].Class < *RHS.AsmOperands[i].Class)
  576. HasLT = true;
  577. if (*RHS.AsmOperands[i].Class < *AsmOperands[i].Class)
  578. HasGT = true;
  579. }
  580. return HasLT == HasGT;
  581. }
  582. void dump() const;
  583. private:
  584. void tokenizeAsmString(AsmMatcherInfo const &Info,
  585. AsmVariantInfo const &Variant);
  586. void addAsmOperand(StringRef Token, bool IsIsolatedToken = false);
  587. };
  588. struct OperandMatchEntry {
  589. unsigned OperandMask;
  590. const MatchableInfo* MI;
  591. ClassInfo *CI;
  592. static OperandMatchEntry create(const MatchableInfo *mi, ClassInfo *ci,
  593. unsigned opMask) {
  594. OperandMatchEntry X;
  595. X.OperandMask = opMask;
  596. X.CI = ci;
  597. X.MI = mi;
  598. return X;
  599. }
  600. };
  601. class AsmMatcherInfo {
  602. public:
  603. /// Tracked Records
  604. RecordKeeper &Records;
  605. /// The tablegen AsmParser record.
  606. Record *AsmParser;
  607. /// Target - The target information.
  608. CodeGenTarget &Target;
  609. /// The classes which are needed for matching.
  610. std::forward_list<ClassInfo> Classes;
  611. /// The information on the matchables to match.
  612. std::vector<std::unique_ptr<MatchableInfo>> Matchables;
  613. /// Info for custom matching operands by user defined methods.
  614. std::vector<OperandMatchEntry> OperandMatchInfo;
  615. /// Map of Register records to their class information.
  616. typedef std::map<Record*, ClassInfo*, LessRecordByID> RegisterClassesTy;
  617. RegisterClassesTy RegisterClasses;
  618. /// Map of Predicate records to their subtarget information.
  619. std::map<Record *, SubtargetFeatureInfo, LessRecordByID> SubtargetFeatures;
  620. /// Map of AsmOperandClass records to their class information.
  621. std::map<Record*, ClassInfo*> AsmOperandClasses;
  622. /// Map of RegisterClass records to their class information.
  623. std::map<Record*, ClassInfo*> RegisterClassClasses;
  624. private:
  625. /// Map of token to class information which has already been constructed.
  626. std::map<std::string, ClassInfo*> TokenClasses;
  627. private:
  628. /// getTokenClass - Lookup or create the class for the given token.
  629. ClassInfo *getTokenClass(StringRef Token);
  630. /// getOperandClass - Lookup or create the class for the given operand.
  631. ClassInfo *getOperandClass(const CGIOperandList::OperandInfo &OI,
  632. int SubOpIdx);
  633. ClassInfo *getOperandClass(Record *Rec, int SubOpIdx);
  634. /// buildRegisterClasses - Build the ClassInfo* instances for register
  635. /// classes.
  636. void buildRegisterClasses(SmallPtrSetImpl<Record*> &SingletonRegisters);
  637. /// buildOperandClasses - Build the ClassInfo* instances for user defined
  638. /// operand classes.
  639. void buildOperandClasses();
  640. void buildInstructionOperandReference(MatchableInfo *II, StringRef OpName,
  641. unsigned AsmOpIdx);
  642. void buildAliasOperandReference(MatchableInfo *II, StringRef OpName,
  643. MatchableInfo::AsmOperand &Op);
  644. public:
  645. AsmMatcherInfo(Record *AsmParser,
  646. CodeGenTarget &Target,
  647. RecordKeeper &Records);
  648. /// Construct the various tables used during matching.
  649. void buildInfo();
  650. /// buildOperandMatchInfo - Build the necessary information to handle user
  651. /// defined operand parsing methods.
  652. void buildOperandMatchInfo();
  653. /// getSubtargetFeature - Lookup or create the subtarget feature info for the
  654. /// given operand.
  655. const SubtargetFeatureInfo *getSubtargetFeature(Record *Def) const {
  656. assert(Def->isSubClassOf("Predicate") && "Invalid predicate type!");
  657. const auto &I = SubtargetFeatures.find(Def);
  658. return I == SubtargetFeatures.end() ? nullptr : &I->second;
  659. }
  660. RecordKeeper &getRecords() const {
  661. return Records;
  662. }
  663. bool hasOptionalOperands() const {
  664. return any_of(Classes,
  665. [](const ClassInfo &Class) { return Class.IsOptional; });
  666. }
  667. };
  668. } // end anonymous namespace
  669. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  670. LLVM_DUMP_METHOD void MatchableInfo::dump() const {
  671. errs() << TheDef->getName() << " -- " << "flattened:\"" << AsmString <<"\"\n";
  672. errs() << " variant: " << AsmVariantID << "\n";
  673. for (unsigned i = 0, e = AsmOperands.size(); i != e; ++i) {
  674. const AsmOperand &Op = AsmOperands[i];
  675. errs() << " op[" << i << "] = " << Op.Class->ClassName << " - ";
  676. errs() << '\"' << Op.Token << "\"\n";
  677. }
  678. }
  679. #endif
  680. static std::pair<StringRef, StringRef>
  681. parseTwoOperandConstraint(StringRef S, ArrayRef<SMLoc> Loc) {
  682. // Split via the '='.
  683. std::pair<StringRef, StringRef> Ops = S.split('=');
  684. if (Ops.second == "")
  685. PrintFatalError(Loc, "missing '=' in two-operand alias constraint");
  686. // Trim whitespace and the leading '$' on the operand names.
  687. size_t start = Ops.first.find_first_of('$');
  688. if (start == std::string::npos)
  689. PrintFatalError(Loc, "expected '$' prefix on asm operand name");
  690. Ops.first = Ops.first.slice(start + 1, std::string::npos);
  691. size_t end = Ops.first.find_last_of(" \t");
  692. Ops.first = Ops.first.slice(0, end);
  693. // Now the second operand.
  694. start = Ops.second.find_first_of('$');
  695. if (start == std::string::npos)
  696. PrintFatalError(Loc, "expected '$' prefix on asm operand name");
  697. Ops.second = Ops.second.slice(start + 1, std::string::npos);
  698. end = Ops.second.find_last_of(" \t");
  699. Ops.first = Ops.first.slice(0, end);
  700. return Ops;
  701. }
  702. void MatchableInfo::formTwoOperandAlias(StringRef Constraint) {
  703. // Figure out which operands are aliased and mark them as tied.
  704. std::pair<StringRef, StringRef> Ops =
  705. parseTwoOperandConstraint(Constraint, TheDef->getLoc());
  706. // Find the AsmOperands that refer to the operands we're aliasing.
  707. int SrcAsmOperand = findAsmOperandNamed(Ops.first);
  708. int DstAsmOperand = findAsmOperandNamed(Ops.second);
  709. if (SrcAsmOperand == -1)
  710. PrintFatalError(TheDef->getLoc(),
  711. "unknown source two-operand alias operand '" + Ops.first +
  712. "'.");
  713. if (DstAsmOperand == -1)
  714. PrintFatalError(TheDef->getLoc(),
  715. "unknown destination two-operand alias operand '" +
  716. Ops.second + "'.");
  717. // Find the ResOperand that refers to the operand we're aliasing away
  718. // and update it to refer to the combined operand instead.
  719. for (ResOperand &Op : ResOperands) {
  720. if (Op.Kind == ResOperand::RenderAsmOperand &&
  721. Op.AsmOperandNum == (unsigned)SrcAsmOperand) {
  722. Op.AsmOperandNum = DstAsmOperand;
  723. break;
  724. }
  725. }
  726. // Remove the AsmOperand for the alias operand.
  727. AsmOperands.erase(AsmOperands.begin() + SrcAsmOperand);
  728. // Adjust the ResOperand references to any AsmOperands that followed
  729. // the one we just deleted.
  730. for (ResOperand &Op : ResOperands) {
  731. switch(Op.Kind) {
  732. default:
  733. // Nothing to do for operands that don't reference AsmOperands.
  734. break;
  735. case ResOperand::RenderAsmOperand:
  736. if (Op.AsmOperandNum > (unsigned)SrcAsmOperand)
  737. --Op.AsmOperandNum;
  738. break;
  739. }
  740. }
  741. }
  742. /// extractSingletonRegisterForAsmOperand - Extract singleton register,
  743. /// if present, from specified token.
  744. static void
  745. extractSingletonRegisterForAsmOperand(MatchableInfo::AsmOperand &Op,
  746. const AsmMatcherInfo &Info,
  747. StringRef RegisterPrefix) {
  748. StringRef Tok = Op.Token;
  749. // If this token is not an isolated token, i.e., it isn't separated from
  750. // other tokens (e.g. with whitespace), don't interpret it as a register name.
  751. if (!Op.IsIsolatedToken)
  752. return;
  753. if (RegisterPrefix.empty()) {
  754. std::string LoweredTok = Tok.lower();
  755. if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(LoweredTok))
  756. Op.SingletonReg = Reg->TheDef;
  757. return;
  758. }
  759. if (!Tok.startswith(RegisterPrefix))
  760. return;
  761. StringRef RegName = Tok.substr(RegisterPrefix.size());
  762. if (const CodeGenRegister *Reg = Info.Target.getRegisterByName(RegName))
  763. Op.SingletonReg = Reg->TheDef;
  764. // If there is no register prefix (i.e. "%" in "%eax"), then this may
  765. // be some random non-register token, just ignore it.
  766. }
  767. void MatchableInfo::initialize(const AsmMatcherInfo &Info,
  768. SmallPtrSetImpl<Record*> &SingletonRegisters,
  769. AsmVariantInfo const &Variant,
  770. bool HasMnemonicFirst) {
  771. AsmVariantID = Variant.AsmVariantNo;
  772. AsmString =
  773. CodeGenInstruction::FlattenAsmStringVariants(AsmString,
  774. Variant.AsmVariantNo);
  775. tokenizeAsmString(Info, Variant);
  776. // The first token of the instruction is the mnemonic, which must be a
  777. // simple string, not a $foo variable or a singleton register.
  778. if (AsmOperands.empty())
  779. PrintFatalError(TheDef->getLoc(),
  780. "Instruction '" + TheDef->getName() + "' has no tokens");
  781. assert(!AsmOperands[0].Token.empty());
  782. if (HasMnemonicFirst) {
  783. Mnemonic = AsmOperands[0].Token;
  784. if (Mnemonic[0] == '$')
  785. PrintFatalError(TheDef->getLoc(),
  786. "Invalid instruction mnemonic '" + Mnemonic + "'!");
  787. // Remove the first operand, it is tracked in the mnemonic field.
  788. AsmOperands.erase(AsmOperands.begin());
  789. } else if (AsmOperands[0].Token[0] != '$')
  790. Mnemonic = AsmOperands[0].Token;
  791. // Compute the require features.
  792. for (Record *Predicate : TheDef->getValueAsListOfDefs("Predicates"))
  793. if (const SubtargetFeatureInfo *Feature =
  794. Info.getSubtargetFeature(Predicate))
  795. RequiredFeatures.push_back(Feature);
  796. // Collect singleton registers, if used.
  797. for (MatchableInfo::AsmOperand &Op : AsmOperands) {
  798. extractSingletonRegisterForAsmOperand(Op, Info, Variant.RegisterPrefix);
  799. if (Record *Reg = Op.SingletonReg)
  800. SingletonRegisters.insert(Reg);
  801. }
  802. const RecordVal *DepMask = TheDef->getValue("DeprecatedFeatureMask");
  803. if (!DepMask)
  804. DepMask = TheDef->getValue("ComplexDeprecationPredicate");
  805. HasDeprecation =
  806. DepMask ? !DepMask->getValue()->getAsUnquotedString().empty() : false;
  807. }
  808. /// Append an AsmOperand for the given substring of AsmString.
  809. void MatchableInfo::addAsmOperand(StringRef Token, bool IsIsolatedToken) {
  810. AsmOperands.push_back(AsmOperand(IsIsolatedToken, Token));
  811. }
  812. /// tokenizeAsmString - Tokenize a simplified assembly string.
  813. void MatchableInfo::tokenizeAsmString(const AsmMatcherInfo &Info,
  814. AsmVariantInfo const &Variant) {
  815. StringRef String = AsmString;
  816. size_t Prev = 0;
  817. bool InTok = false;
  818. bool IsIsolatedToken = true;
  819. for (size_t i = 0, e = String.size(); i != e; ++i) {
  820. char Char = String[i];
  821. if (Variant.BreakCharacters.find(Char) != std::string::npos) {
  822. if (InTok) {
  823. addAsmOperand(String.slice(Prev, i), false);
  824. Prev = i;
  825. IsIsolatedToken = false;
  826. }
  827. InTok = true;
  828. continue;
  829. }
  830. if (Variant.TokenizingCharacters.find(Char) != std::string::npos) {
  831. if (InTok) {
  832. addAsmOperand(String.slice(Prev, i), IsIsolatedToken);
  833. InTok = false;
  834. IsIsolatedToken = false;
  835. }
  836. addAsmOperand(String.slice(i, i + 1), IsIsolatedToken);
  837. Prev = i + 1;
  838. IsIsolatedToken = true;
  839. continue;
  840. }
  841. if (Variant.SeparatorCharacters.find(Char) != std::string::npos) {
  842. if (InTok) {
  843. addAsmOperand(String.slice(Prev, i), IsIsolatedToken);
  844. InTok = false;
  845. }
  846. Prev = i + 1;
  847. IsIsolatedToken = true;
  848. continue;
  849. }
  850. switch (Char) {
  851. case '\\':
  852. if (InTok) {
  853. addAsmOperand(String.slice(Prev, i), false);
  854. InTok = false;
  855. IsIsolatedToken = false;
  856. }
  857. ++i;
  858. assert(i != String.size() && "Invalid quoted character");
  859. addAsmOperand(String.slice(i, i + 1), IsIsolatedToken);
  860. Prev = i + 1;
  861. IsIsolatedToken = false;
  862. break;
  863. case '$': {
  864. if (InTok) {
  865. addAsmOperand(String.slice(Prev, i), IsIsolatedToken);
  866. InTok = false;
  867. IsIsolatedToken = false;
  868. }
  869. // If this isn't "${", start new identifier looking like "$xxx"
  870. if (i + 1 == String.size() || String[i + 1] != '{') {
  871. Prev = i;
  872. break;
  873. }
  874. size_t EndPos = String.find('}', i);
  875. assert(EndPos != StringRef::npos &&
  876. "Missing brace in operand reference!");
  877. addAsmOperand(String.slice(i, EndPos+1), IsIsolatedToken);
  878. Prev = EndPos + 1;
  879. i = EndPos;
  880. IsIsolatedToken = false;
  881. break;
  882. }
  883. default:
  884. InTok = true;
  885. break;
  886. }
  887. }
  888. if (InTok && Prev != String.size())
  889. addAsmOperand(String.substr(Prev), IsIsolatedToken);
  890. }
  891. bool MatchableInfo::validate(StringRef CommentDelimiter, bool IsAlias) const {
  892. // Reject matchables with no .s string.
  893. if (AsmString.empty())
  894. PrintFatalError(TheDef->getLoc(), "instruction with empty asm string");
  895. // Reject any matchables with a newline in them, they should be marked
  896. // isCodeGenOnly if they are pseudo instructions.
  897. if (AsmString.find('\n') != std::string::npos)
  898. PrintFatalError(TheDef->getLoc(),
  899. "multiline instruction is not valid for the asmparser, "
  900. "mark it isCodeGenOnly");
  901. // Remove comments from the asm string. We know that the asmstring only
  902. // has one line.
  903. if (!CommentDelimiter.empty() &&
  904. StringRef(AsmString).find(CommentDelimiter) != StringRef::npos)
  905. PrintFatalError(TheDef->getLoc(),
  906. "asmstring for instruction has comment character in it, "
  907. "mark it isCodeGenOnly");
  908. // Reject matchables with operand modifiers, these aren't something we can
  909. // handle, the target should be refactored to use operands instead of
  910. // modifiers.
  911. //
  912. // Also, check for instructions which reference the operand multiple times,
  913. // if they don't define a custom AsmMatcher: this implies a constraint that
  914. // the built-in matching code would not honor.
  915. std::set<std::string> OperandNames;
  916. for (const AsmOperand &Op : AsmOperands) {
  917. StringRef Tok = Op.Token;
  918. if (Tok[0] == '$' && Tok.find(':') != StringRef::npos)
  919. PrintFatalError(TheDef->getLoc(),
  920. "matchable with operand modifier '" + Tok +
  921. "' not supported by asm matcher. Mark isCodeGenOnly!");
  922. // Verify that any operand is only mentioned once.
  923. // We reject aliases and ignore instructions for now.
  924. if (!IsAlias && TheDef->getValueAsString("AsmMatchConverter").empty() &&
  925. Tok[0] == '$' && !OperandNames.insert(std::string(Tok)).second) {
  926. LLVM_DEBUG({
  927. errs() << "warning: '" << TheDef->getName() << "': "
  928. << "ignoring instruction with tied operand '"
  929. << Tok << "'\n";
  930. });
  931. return false;
  932. }
  933. }
  934. return true;
  935. }
  936. static std::string getEnumNameForToken(StringRef Str) {
  937. std::string Res;
  938. for (StringRef::iterator it = Str.begin(), ie = Str.end(); it != ie; ++it) {
  939. switch (*it) {
  940. case '*': Res += "_STAR_"; break;
  941. case '%': Res += "_PCT_"; break;
  942. case ':': Res += "_COLON_"; break;
  943. case '!': Res += "_EXCLAIM_"; break;
  944. case '.': Res += "_DOT_"; break;
  945. case '<': Res += "_LT_"; break;
  946. case '>': Res += "_GT_"; break;
  947. case '-': Res += "_MINUS_"; break;
  948. case '#': Res += "_HASH_"; break;
  949. default:
  950. if (isAlnum(*it))
  951. Res += *it;
  952. else
  953. Res += "_" + utostr((unsigned) *it) + "_";
  954. }
  955. }
  956. return Res;
  957. }
  958. ClassInfo *AsmMatcherInfo::getTokenClass(StringRef Token) {
  959. ClassInfo *&Entry = TokenClasses[std::string(Token)];
  960. if (!Entry) {
  961. Classes.emplace_front();
  962. Entry = &Classes.front();
  963. Entry->Kind = ClassInfo::Token;
  964. Entry->ClassName = "Token";
  965. Entry->Name = "MCK_" + getEnumNameForToken(Token);
  966. Entry->ValueName = std::string(Token);
  967. Entry->PredicateMethod = "<invalid>";
  968. Entry->RenderMethod = "<invalid>";
  969. Entry->ParserMethod = "";
  970. Entry->DiagnosticType = "";
  971. Entry->IsOptional = false;
  972. Entry->DefaultMethod = "<invalid>";
  973. }
  974. return Entry;
  975. }
  976. ClassInfo *
  977. AsmMatcherInfo::getOperandClass(const CGIOperandList::OperandInfo &OI,
  978. int SubOpIdx) {
  979. Record *Rec = OI.Rec;
  980. if (SubOpIdx != -1)
  981. Rec = cast<DefInit>(OI.MIOperandInfo->getArg(SubOpIdx))->getDef();
  982. return getOperandClass(Rec, SubOpIdx);
  983. }
  984. ClassInfo *
  985. AsmMatcherInfo::getOperandClass(Record *Rec, int SubOpIdx) {
  986. if (Rec->isSubClassOf("RegisterOperand")) {
  987. // RegisterOperand may have an associated ParserMatchClass. If it does,
  988. // use it, else just fall back to the underlying register class.
  989. const RecordVal *R = Rec->getValue("ParserMatchClass");
  990. if (!R || !R->getValue())
  991. PrintFatalError(Rec->getLoc(),
  992. "Record `" + Rec->getName() +
  993. "' does not have a ParserMatchClass!\n");
  994. if (DefInit *DI= dyn_cast<DefInit>(R->getValue())) {
  995. Record *MatchClass = DI->getDef();
  996. if (ClassInfo *CI = AsmOperandClasses[MatchClass])
  997. return CI;
  998. }
  999. // No custom match class. Just use the register class.
  1000. Record *ClassRec = Rec->getValueAsDef("RegClass");
  1001. if (!ClassRec)
  1002. PrintFatalError(Rec->getLoc(), "RegisterOperand `" + Rec->getName() +
  1003. "' has no associated register class!\n");
  1004. if (ClassInfo *CI = RegisterClassClasses[ClassRec])
  1005. return CI;
  1006. PrintFatalError(Rec->getLoc(), "register class has no class info!");
  1007. }
  1008. if (Rec->isSubClassOf("RegisterClass")) {
  1009. if (ClassInfo *CI = RegisterClassClasses[Rec])
  1010. return CI;
  1011. PrintFatalError(Rec->getLoc(), "register class has no class info!");
  1012. }
  1013. if (!Rec->isSubClassOf("Operand"))
  1014. PrintFatalError(Rec->getLoc(), "Operand `" + Rec->getName() +
  1015. "' does not derive from class Operand!\n");
  1016. Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
  1017. if (ClassInfo *CI = AsmOperandClasses[MatchClass])
  1018. return CI;
  1019. PrintFatalError(Rec->getLoc(), "operand has no match class!");
  1020. }
  1021. struct LessRegisterSet {
  1022. bool operator() (const RegisterSet &LHS, const RegisterSet & RHS) const {
  1023. // std::set<T> defines its own compariso "operator<", but it
  1024. // performs a lexicographical comparison by T's innate comparison
  1025. // for some reason. We don't want non-deterministic pointer
  1026. // comparisons so use this instead.
  1027. return std::lexicographical_compare(LHS.begin(), LHS.end(),
  1028. RHS.begin(), RHS.end(),
  1029. LessRecordByID());
  1030. }
  1031. };
  1032. void AsmMatcherInfo::
  1033. buildRegisterClasses(SmallPtrSetImpl<Record*> &SingletonRegisters) {
  1034. const auto &Registers = Target.getRegBank().getRegisters();
  1035. auto &RegClassList = Target.getRegBank().getRegClasses();
  1036. typedef std::set<RegisterSet, LessRegisterSet> RegisterSetSet;
  1037. // The register sets used for matching.
  1038. RegisterSetSet RegisterSets;
  1039. // Gather the defined sets.
  1040. for (const CodeGenRegisterClass &RC : RegClassList)
  1041. RegisterSets.insert(
  1042. RegisterSet(RC.getOrder().begin(), RC.getOrder().end()));
  1043. // Add any required singleton sets.
  1044. for (Record *Rec : SingletonRegisters) {
  1045. RegisterSets.insert(RegisterSet(&Rec, &Rec + 1));
  1046. }
  1047. // Introduce derived sets where necessary (when a register does not determine
  1048. // a unique register set class), and build the mapping of registers to the set
  1049. // they should classify to.
  1050. std::map<Record*, RegisterSet> RegisterMap;
  1051. for (const CodeGenRegister &CGR : Registers) {
  1052. // Compute the intersection of all sets containing this register.
  1053. RegisterSet ContainingSet;
  1054. for (const RegisterSet &RS : RegisterSets) {
  1055. if (!RS.count(CGR.TheDef))
  1056. continue;
  1057. if (ContainingSet.empty()) {
  1058. ContainingSet = RS;
  1059. continue;
  1060. }
  1061. RegisterSet Tmp;
  1062. std::swap(Tmp, ContainingSet);
  1063. std::insert_iterator<RegisterSet> II(ContainingSet,
  1064. ContainingSet.begin());
  1065. std::set_intersection(Tmp.begin(), Tmp.end(), RS.begin(), RS.end(), II,
  1066. LessRecordByID());
  1067. }
  1068. if (!ContainingSet.empty()) {
  1069. RegisterSets.insert(ContainingSet);
  1070. RegisterMap.insert(std::make_pair(CGR.TheDef, ContainingSet));
  1071. }
  1072. }
  1073. // Construct the register classes.
  1074. std::map<RegisterSet, ClassInfo*, LessRegisterSet> RegisterSetClasses;
  1075. unsigned Index = 0;
  1076. for (const RegisterSet &RS : RegisterSets) {
  1077. Classes.emplace_front();
  1078. ClassInfo *CI = &Classes.front();
  1079. CI->Kind = ClassInfo::RegisterClass0 + Index;
  1080. CI->ClassName = "Reg" + utostr(Index);
  1081. CI->Name = "MCK_Reg" + utostr(Index);
  1082. CI->ValueName = "";
  1083. CI->PredicateMethod = ""; // unused
  1084. CI->RenderMethod = "addRegOperands";
  1085. CI->Registers = RS;
  1086. // FIXME: diagnostic type.
  1087. CI->DiagnosticType = "";
  1088. CI->IsOptional = false;
  1089. CI->DefaultMethod = ""; // unused
  1090. RegisterSetClasses.insert(std::make_pair(RS, CI));
  1091. ++Index;
  1092. }
  1093. // Find the superclasses; we could compute only the subgroup lattice edges,
  1094. // but there isn't really a point.
  1095. for (const RegisterSet &RS : RegisterSets) {
  1096. ClassInfo *CI = RegisterSetClasses[RS];
  1097. for (const RegisterSet &RS2 : RegisterSets)
  1098. if (RS != RS2 &&
  1099. std::includes(RS2.begin(), RS2.end(), RS.begin(), RS.end(),
  1100. LessRecordByID()))
  1101. CI->SuperClasses.push_back(RegisterSetClasses[RS2]);
  1102. }
  1103. // Name the register classes which correspond to a user defined RegisterClass.
  1104. for (const CodeGenRegisterClass &RC : RegClassList) {
  1105. // Def will be NULL for non-user defined register classes.
  1106. Record *Def = RC.getDef();
  1107. if (!Def)
  1108. continue;
  1109. ClassInfo *CI = RegisterSetClasses[RegisterSet(RC.getOrder().begin(),
  1110. RC.getOrder().end())];
  1111. if (CI->ValueName.empty()) {
  1112. CI->ClassName = RC.getName();
  1113. CI->Name = "MCK_" + RC.getName();
  1114. CI->ValueName = RC.getName();
  1115. } else
  1116. CI->ValueName = CI->ValueName + "," + RC.getName();
  1117. Init *DiagnosticType = Def->getValueInit("DiagnosticType");
  1118. if (StringInit *SI = dyn_cast<StringInit>(DiagnosticType))
  1119. CI->DiagnosticType = std::string(SI->getValue());
  1120. Init *DiagnosticString = Def->getValueInit("DiagnosticString");
  1121. if (StringInit *SI = dyn_cast<StringInit>(DiagnosticString))
  1122. CI->DiagnosticString = std::string(SI->getValue());
  1123. // If we have a diagnostic string but the diagnostic type is not specified
  1124. // explicitly, create an anonymous diagnostic type.
  1125. if (!CI->DiagnosticString.empty() && CI->DiagnosticType.empty())
  1126. CI->DiagnosticType = RC.getName();
  1127. RegisterClassClasses.insert(std::make_pair(Def, CI));
  1128. }
  1129. // Populate the map for individual registers.
  1130. for (std::map<Record*, RegisterSet>::iterator it = RegisterMap.begin(),
  1131. ie = RegisterMap.end(); it != ie; ++it)
  1132. RegisterClasses[it->first] = RegisterSetClasses[it->second];
  1133. // Name the register classes which correspond to singleton registers.
  1134. for (Record *Rec : SingletonRegisters) {
  1135. ClassInfo *CI = RegisterClasses[Rec];
  1136. assert(CI && "Missing singleton register class info!");
  1137. if (CI->ValueName.empty()) {
  1138. CI->ClassName = std::string(Rec->getName());
  1139. CI->Name = "MCK_" + Rec->getName().str();
  1140. CI->ValueName = std::string(Rec->getName());
  1141. } else
  1142. CI->ValueName = CI->ValueName + "," + Rec->getName().str();
  1143. }
  1144. }
  1145. void AsmMatcherInfo::buildOperandClasses() {
  1146. std::vector<Record*> AsmOperands =
  1147. Records.getAllDerivedDefinitions("AsmOperandClass");
  1148. // Pre-populate AsmOperandClasses map.
  1149. for (Record *Rec : AsmOperands) {
  1150. Classes.emplace_front();
  1151. AsmOperandClasses[Rec] = &Classes.front();
  1152. }
  1153. unsigned Index = 0;
  1154. for (Record *Rec : AsmOperands) {
  1155. ClassInfo *CI = AsmOperandClasses[Rec];
  1156. CI->Kind = ClassInfo::UserClass0 + Index;
  1157. ListInit *Supers = Rec->getValueAsListInit("SuperClasses");
  1158. for (Init *I : Supers->getValues()) {
  1159. DefInit *DI = dyn_cast<DefInit>(I);
  1160. if (!DI) {
  1161. PrintError(Rec->getLoc(), "Invalid super class reference!");
  1162. continue;
  1163. }
  1164. ClassInfo *SC = AsmOperandClasses[DI->getDef()];
  1165. if (!SC)
  1166. PrintError(Rec->getLoc(), "Invalid super class reference!");
  1167. else
  1168. CI->SuperClasses.push_back(SC);
  1169. }
  1170. CI->ClassName = std::string(Rec->getValueAsString("Name"));
  1171. CI->Name = "MCK_" + CI->ClassName;
  1172. CI->ValueName = std::string(Rec->getName());
  1173. // Get or construct the predicate method name.
  1174. Init *PMName = Rec->getValueInit("PredicateMethod");
  1175. if (StringInit *SI = dyn_cast<StringInit>(PMName)) {
  1176. CI->PredicateMethod = std::string(SI->getValue());
  1177. } else {
  1178. assert(isa<UnsetInit>(PMName) && "Unexpected PredicateMethod field!");
  1179. CI->PredicateMethod = "is" + CI->ClassName;
  1180. }
  1181. // Get or construct the render method name.
  1182. Init *RMName = Rec->getValueInit("RenderMethod");
  1183. if (StringInit *SI = dyn_cast<StringInit>(RMName)) {
  1184. CI->RenderMethod = std::string(SI->getValue());
  1185. } else {
  1186. assert(isa<UnsetInit>(RMName) && "Unexpected RenderMethod field!");
  1187. CI->RenderMethod = "add" + CI->ClassName + "Operands";
  1188. }
  1189. // Get the parse method name or leave it as empty.
  1190. Init *PRMName = Rec->getValueInit("ParserMethod");
  1191. if (StringInit *SI = dyn_cast<StringInit>(PRMName))
  1192. CI->ParserMethod = std::string(SI->getValue());
  1193. // Get the diagnostic type and string or leave them as empty.
  1194. Init *DiagnosticType = Rec->getValueInit("DiagnosticType");
  1195. if (StringInit *SI = dyn_cast<StringInit>(DiagnosticType))
  1196. CI->DiagnosticType = std::string(SI->getValue());
  1197. Init *DiagnosticString = Rec->getValueInit("DiagnosticString");
  1198. if (StringInit *SI = dyn_cast<StringInit>(DiagnosticString))
  1199. CI->DiagnosticString = std::string(SI->getValue());
  1200. // If we have a DiagnosticString, we need a DiagnosticType for use within
  1201. // the matcher.
  1202. if (!CI->DiagnosticString.empty() && CI->DiagnosticType.empty())
  1203. CI->DiagnosticType = CI->ClassName;
  1204. Init *IsOptional = Rec->getValueInit("IsOptional");
  1205. if (BitInit *BI = dyn_cast<BitInit>(IsOptional))
  1206. CI->IsOptional = BI->getValue();
  1207. // Get or construct the default method name.
  1208. Init *DMName = Rec->getValueInit("DefaultMethod");
  1209. if (StringInit *SI = dyn_cast<StringInit>(DMName)) {
  1210. CI->DefaultMethod = std::string(SI->getValue());
  1211. } else {
  1212. assert(isa<UnsetInit>(DMName) && "Unexpected DefaultMethod field!");
  1213. CI->DefaultMethod = "default" + CI->ClassName + "Operands";
  1214. }
  1215. ++Index;
  1216. }
  1217. }
  1218. AsmMatcherInfo::AsmMatcherInfo(Record *asmParser,
  1219. CodeGenTarget &target,
  1220. RecordKeeper &records)
  1221. : Records(records), AsmParser(asmParser), Target(target) {
  1222. }
  1223. /// buildOperandMatchInfo - Build the necessary information to handle user
  1224. /// defined operand parsing methods.
  1225. void AsmMatcherInfo::buildOperandMatchInfo() {
  1226. /// Map containing a mask with all operands indices that can be found for
  1227. /// that class inside a instruction.
  1228. typedef std::map<ClassInfo *, unsigned, deref<std::less<>>> OpClassMaskTy;
  1229. OpClassMaskTy OpClassMask;
  1230. for (const auto &MI : Matchables) {
  1231. OpClassMask.clear();
  1232. // Keep track of all operands of this instructions which belong to the
  1233. // same class.
  1234. for (unsigned i = 0, e = MI->AsmOperands.size(); i != e; ++i) {
  1235. const MatchableInfo::AsmOperand &Op = MI->AsmOperands[i];
  1236. if (Op.Class->ParserMethod.empty())
  1237. continue;
  1238. unsigned &OperandMask = OpClassMask[Op.Class];
  1239. OperandMask |= (1 << i);
  1240. }
  1241. // Generate operand match info for each mnemonic/operand class pair.
  1242. for (const auto &OCM : OpClassMask) {
  1243. unsigned OpMask = OCM.second;
  1244. ClassInfo *CI = OCM.first;
  1245. OperandMatchInfo.push_back(OperandMatchEntry::create(MI.get(), CI,
  1246. OpMask));
  1247. }
  1248. }
  1249. }
  1250. void AsmMatcherInfo::buildInfo() {
  1251. // Build information about all of the AssemblerPredicates.
  1252. const std::vector<std::pair<Record *, SubtargetFeatureInfo>>
  1253. &SubtargetFeaturePairs = SubtargetFeatureInfo::getAll(Records);
  1254. SubtargetFeatures.insert(SubtargetFeaturePairs.begin(),
  1255. SubtargetFeaturePairs.end());
  1256. #ifndef NDEBUG
  1257. for (const auto &Pair : SubtargetFeatures)
  1258. LLVM_DEBUG(Pair.second.dump());
  1259. #endif // NDEBUG
  1260. bool HasMnemonicFirst = AsmParser->getValueAsBit("HasMnemonicFirst");
  1261. bool ReportMultipleNearMisses =
  1262. AsmParser->getValueAsBit("ReportMultipleNearMisses");
  1263. // Parse the instructions; we need to do this first so that we can gather the
  1264. // singleton register classes.
  1265. SmallPtrSet<Record*, 16> SingletonRegisters;
  1266. unsigned VariantCount = Target.getAsmParserVariantCount();
  1267. for (unsigned VC = 0; VC != VariantCount; ++VC) {
  1268. Record *AsmVariant = Target.getAsmParserVariant(VC);
  1269. StringRef CommentDelimiter =
  1270. AsmVariant->getValueAsString("CommentDelimiter");
  1271. AsmVariantInfo Variant;
  1272. Variant.RegisterPrefix = AsmVariant->getValueAsString("RegisterPrefix");
  1273. Variant.TokenizingCharacters =
  1274. AsmVariant->getValueAsString("TokenizingCharacters");
  1275. Variant.SeparatorCharacters =
  1276. AsmVariant->getValueAsString("SeparatorCharacters");
  1277. Variant.BreakCharacters =
  1278. AsmVariant->getValueAsString("BreakCharacters");
  1279. Variant.Name = AsmVariant->getValueAsString("Name");
  1280. Variant.AsmVariantNo = AsmVariant->getValueAsInt("Variant");
  1281. for (const CodeGenInstruction *CGI : Target.getInstructionsByEnumValue()) {
  1282. // If the tblgen -match-prefix option is specified (for tblgen hackers),
  1283. // filter the set of instructions we consider.
  1284. if (!StringRef(CGI->TheDef->getName()).startswith(MatchPrefix))
  1285. continue;
  1286. // Ignore "codegen only" instructions.
  1287. if (CGI->TheDef->getValueAsBit("isCodeGenOnly"))
  1288. continue;
  1289. // Ignore instructions for different instructions
  1290. StringRef V = CGI->TheDef->getValueAsString("AsmVariantName");
  1291. if (!V.empty() && V != Variant.Name)
  1292. continue;
  1293. auto II = std::make_unique<MatchableInfo>(*CGI);
  1294. II->initialize(*this, SingletonRegisters, Variant, HasMnemonicFirst);
  1295. // Ignore instructions which shouldn't be matched and diagnose invalid
  1296. // instruction definitions with an error.
  1297. if (!II->validate(CommentDelimiter, false))
  1298. continue;
  1299. Matchables.push_back(std::move(II));
  1300. }
  1301. // Parse all of the InstAlias definitions and stick them in the list of
  1302. // matchables.
  1303. std::vector<Record*> AllInstAliases =
  1304. Records.getAllDerivedDefinitions("InstAlias");
  1305. for (unsigned i = 0, e = AllInstAliases.size(); i != e; ++i) {
  1306. auto Alias = std::make_unique<CodeGenInstAlias>(AllInstAliases[i],
  1307. Target);
  1308. // If the tblgen -match-prefix option is specified (for tblgen hackers),
  1309. // filter the set of instruction aliases we consider, based on the target
  1310. // instruction.
  1311. if (!StringRef(Alias->ResultInst->TheDef->getName())
  1312. .startswith( MatchPrefix))
  1313. continue;
  1314. StringRef V = Alias->TheDef->getValueAsString("AsmVariantName");
  1315. if (!V.empty() && V != Variant.Name)
  1316. continue;
  1317. auto II = std::make_unique<MatchableInfo>(std::move(Alias));
  1318. II->initialize(*this, SingletonRegisters, Variant, HasMnemonicFirst);
  1319. // Validate the alias definitions.
  1320. II->validate(CommentDelimiter, true);
  1321. Matchables.push_back(std::move(II));
  1322. }
  1323. }
  1324. // Build info for the register classes.
  1325. buildRegisterClasses(SingletonRegisters);
  1326. // Build info for the user defined assembly operand classes.
  1327. buildOperandClasses();
  1328. // Build the information about matchables, now that we have fully formed
  1329. // classes.
  1330. std::vector<std::unique_ptr<MatchableInfo>> NewMatchables;
  1331. for (auto &II : Matchables) {
  1332. // Parse the tokens after the mnemonic.
  1333. // Note: buildInstructionOperandReference may insert new AsmOperands, so
  1334. // don't precompute the loop bound.
  1335. for (unsigned i = 0; i != II->AsmOperands.size(); ++i) {
  1336. MatchableInfo::AsmOperand &Op = II->AsmOperands[i];
  1337. StringRef Token = Op.Token;
  1338. // Check for singleton registers.
  1339. if (Record *RegRecord = Op.SingletonReg) {
  1340. Op.Class = RegisterClasses[RegRecord];
  1341. assert(Op.Class && Op.Class->Registers.size() == 1 &&
  1342. "Unexpected class for singleton register");
  1343. continue;
  1344. }
  1345. // Check for simple tokens.
  1346. if (Token[0] != '$') {
  1347. Op.Class = getTokenClass(Token);
  1348. continue;
  1349. }
  1350. if (Token.size() > 1 && isdigit(Token[1])) {
  1351. Op.Class = getTokenClass(Token);
  1352. continue;
  1353. }
  1354. // Otherwise this is an operand reference.
  1355. StringRef OperandName;
  1356. if (Token[1] == '{')
  1357. OperandName = Token.substr(2, Token.size() - 3);
  1358. else
  1359. OperandName = Token.substr(1);
  1360. if (II->DefRec.is<const CodeGenInstruction*>())
  1361. buildInstructionOperandReference(II.get(), OperandName, i);
  1362. else
  1363. buildAliasOperandReference(II.get(), OperandName, Op);
  1364. }
  1365. if (II->DefRec.is<const CodeGenInstruction*>()) {
  1366. II->buildInstructionResultOperands();
  1367. // If the instruction has a two-operand alias, build up the
  1368. // matchable here. We'll add them in bulk at the end to avoid
  1369. // confusing this loop.
  1370. StringRef Constraint =
  1371. II->TheDef->getValueAsString("TwoOperandAliasConstraint");
  1372. if (Constraint != "") {
  1373. // Start by making a copy of the original matchable.
  1374. auto AliasII = std::make_unique<MatchableInfo>(*II);
  1375. // Adjust it to be a two-operand alias.
  1376. AliasII->formTwoOperandAlias(Constraint);
  1377. // Add the alias to the matchables list.
  1378. NewMatchables.push_back(std::move(AliasII));
  1379. }
  1380. } else
  1381. // FIXME: The tied operands checking is not yet integrated with the
  1382. // framework for reporting multiple near misses. To prevent invalid
  1383. // formats from being matched with an alias if a tied-operands check
  1384. // would otherwise have disallowed it, we just disallow such constructs
  1385. // in TableGen completely.
  1386. II->buildAliasResultOperands(!ReportMultipleNearMisses);
  1387. }
  1388. if (!NewMatchables.empty())
  1389. Matchables.insert(Matchables.end(),
  1390. std::make_move_iterator(NewMatchables.begin()),
  1391. std::make_move_iterator(NewMatchables.end()));
  1392. // Process token alias definitions and set up the associated superclass
  1393. // information.
  1394. std::vector<Record*> AllTokenAliases =
  1395. Records.getAllDerivedDefinitions("TokenAlias");
  1396. for (Record *Rec : AllTokenAliases) {
  1397. ClassInfo *FromClass = getTokenClass(Rec->getValueAsString("FromToken"));
  1398. ClassInfo *ToClass = getTokenClass(Rec->getValueAsString("ToToken"));
  1399. if (FromClass == ToClass)
  1400. PrintFatalError(Rec->getLoc(),
  1401. "error: Destination value identical to source value.");
  1402. FromClass->SuperClasses.push_back(ToClass);
  1403. }
  1404. // Reorder classes so that classes precede super classes.
  1405. Classes.sort();
  1406. #ifdef EXPENSIVE_CHECKS
  1407. // Verify that the table is sorted and operator < works transitively.
  1408. for (auto I = Classes.begin(), E = Classes.end(); I != E; ++I) {
  1409. for (auto J = I; J != E; ++J) {
  1410. assert(!(*J < *I));
  1411. assert(I == J || !J->isSubsetOf(*I));
  1412. }
  1413. }
  1414. #endif
  1415. }
  1416. /// buildInstructionOperandReference - The specified operand is a reference to a
  1417. /// named operand such as $src. Resolve the Class and OperandInfo pointers.
  1418. void AsmMatcherInfo::
  1419. buildInstructionOperandReference(MatchableInfo *II,
  1420. StringRef OperandName,
  1421. unsigned AsmOpIdx) {
  1422. const CodeGenInstruction &CGI = *II->DefRec.get<const CodeGenInstruction*>();
  1423. const CGIOperandList &Operands = CGI.Operands;
  1424. MatchableInfo::AsmOperand *Op = &II->AsmOperands[AsmOpIdx];
  1425. // Map this token to an operand.
  1426. unsigned Idx;
  1427. if (!Operands.hasOperandNamed(OperandName, Idx))
  1428. PrintFatalError(II->TheDef->getLoc(),
  1429. "error: unable to find operand: '" + OperandName + "'");
  1430. // If the instruction operand has multiple suboperands, but the parser
  1431. // match class for the asm operand is still the default "ImmAsmOperand",
  1432. // then handle each suboperand separately.
  1433. if (Op->SubOpIdx == -1 && Operands[Idx].MINumOperands > 1) {
  1434. Record *Rec = Operands[Idx].Rec;
  1435. assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
  1436. Record *MatchClass = Rec->getValueAsDef("ParserMatchClass");
  1437. if (MatchClass && MatchClass->getValueAsString("Name") == "Imm") {
  1438. // Insert remaining suboperands after AsmOpIdx in II->AsmOperands.
  1439. StringRef Token = Op->Token; // save this in case Op gets moved
  1440. for (unsigned SI = 1, SE = Operands[Idx].MINumOperands; SI != SE; ++SI) {
  1441. MatchableInfo::AsmOperand NewAsmOp(/*IsIsolatedToken=*/true, Token);
  1442. NewAsmOp.SubOpIdx = SI;
  1443. II->AsmOperands.insert(II->AsmOperands.begin()+AsmOpIdx+SI, NewAsmOp);
  1444. }
  1445. // Replace Op with first suboperand.
  1446. Op = &II->AsmOperands[AsmOpIdx]; // update the pointer in case it moved
  1447. Op->SubOpIdx = 0;
  1448. }
  1449. }
  1450. // Set up the operand class.
  1451. Op->Class = getOperandClass(Operands[Idx], Op->SubOpIdx);
  1452. Op->OrigSrcOpName = OperandName;
  1453. // If the named operand is tied, canonicalize it to the untied operand.
  1454. // For example, something like:
  1455. // (outs GPR:$dst), (ins GPR:$src)
  1456. // with an asmstring of
  1457. // "inc $src"
  1458. // we want to canonicalize to:
  1459. // "inc $dst"
  1460. // so that we know how to provide the $dst operand when filling in the result.
  1461. int OITied = -1;
  1462. if (Operands[Idx].MINumOperands == 1)
  1463. OITied = Operands[Idx].getTiedRegister();
  1464. if (OITied != -1) {
  1465. // The tied operand index is an MIOperand index, find the operand that
  1466. // contains it.
  1467. std::pair<unsigned, unsigned> Idx = Operands.getSubOperandNumber(OITied);
  1468. OperandName = Operands[Idx.first].Name;
  1469. Op->SubOpIdx = Idx.second;
  1470. }
  1471. Op->SrcOpName = OperandName;
  1472. }
  1473. /// buildAliasOperandReference - When parsing an operand reference out of the
  1474. /// matching string (e.g. "movsx $src, $dst"), determine what the class of the
  1475. /// operand reference is by looking it up in the result pattern definition.
  1476. void AsmMatcherInfo::buildAliasOperandReference(MatchableInfo *II,
  1477. StringRef OperandName,
  1478. MatchableInfo::AsmOperand &Op) {
  1479. const CodeGenInstAlias &CGA = *II->DefRec.get<const CodeGenInstAlias*>();
  1480. // Set up the operand class.
  1481. for (unsigned i = 0, e = CGA.ResultOperands.size(); i != e; ++i)
  1482. if (CGA.ResultOperands[i].isRecord() &&
  1483. CGA.ResultOperands[i].getName() == OperandName) {
  1484. // It's safe to go with the first one we find, because CodeGenInstAlias
  1485. // validates that all operands with the same name have the same record.
  1486. Op.SubOpIdx = CGA.ResultInstOperandIndex[i].second;
  1487. // Use the match class from the Alias definition, not the
  1488. // destination instruction, as we may have an immediate that's
  1489. // being munged by the match class.
  1490. Op.Class = getOperandClass(CGA.ResultOperands[i].getRecord(),
  1491. Op.SubOpIdx);
  1492. Op.SrcOpName = OperandName;
  1493. Op.OrigSrcOpName = OperandName;
  1494. return;
  1495. }
  1496. PrintFatalError(II->TheDef->getLoc(),
  1497. "error: unable to find operand: '" + OperandName + "'");
  1498. }
  1499. void MatchableInfo::buildInstructionResultOperands() {
  1500. const CodeGenInstruction *ResultInst = getResultInst();
  1501. // Loop over all operands of the result instruction, determining how to
  1502. // populate them.
  1503. for (const CGIOperandList::OperandInfo &OpInfo : ResultInst->Operands) {
  1504. // If this is a tied operand, just copy from the previously handled operand.
  1505. int TiedOp = -1;
  1506. if (OpInfo.MINumOperands == 1)
  1507. TiedOp = OpInfo.getTiedRegister();
  1508. if (TiedOp != -1) {
  1509. int TiedSrcOperand = findAsmOperandOriginallyNamed(OpInfo.Name);
  1510. if (TiedSrcOperand != -1 &&
  1511. ResOperands[TiedOp].Kind == ResOperand::RenderAsmOperand)
  1512. ResOperands.push_back(ResOperand::getTiedOp(
  1513. TiedOp, ResOperands[TiedOp].AsmOperandNum, TiedSrcOperand));
  1514. else
  1515. ResOperands.push_back(ResOperand::getTiedOp(TiedOp, 0, 0));
  1516. continue;
  1517. }
  1518. int SrcOperand = findAsmOperandNamed(OpInfo.Name);
  1519. if (OpInfo.Name.empty() || SrcOperand == -1) {
  1520. // This may happen for operands that are tied to a suboperand of a
  1521. // complex operand. Simply use a dummy value here; nobody should
  1522. // use this operand slot.
  1523. // FIXME: The long term goal is for the MCOperand list to not contain
  1524. // tied operands at all.
  1525. ResOperands.push_back(ResOperand::getImmOp(0));
  1526. continue;
  1527. }
  1528. // Check if the one AsmOperand populates the entire operand.
  1529. unsigned NumOperands = OpInfo.MINumOperands;
  1530. if (AsmOperands[SrcOperand].SubOpIdx == -1) {
  1531. ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand, NumOperands));
  1532. continue;
  1533. }
  1534. // Add a separate ResOperand for each suboperand.
  1535. for (unsigned AI = 0; AI < NumOperands; ++AI) {
  1536. assert(AsmOperands[SrcOperand+AI].SubOpIdx == (int)AI &&
  1537. AsmOperands[SrcOperand+AI].SrcOpName == OpInfo.Name &&
  1538. "unexpected AsmOperands for suboperands");
  1539. ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand + AI, 1));
  1540. }
  1541. }
  1542. }
  1543. void MatchableInfo::buildAliasResultOperands(bool AliasConstraintsAreChecked) {
  1544. const CodeGenInstAlias &CGA = *DefRec.get<const CodeGenInstAlias*>();
  1545. const CodeGenInstruction *ResultInst = getResultInst();
  1546. // Map of: $reg -> #lastref
  1547. // where $reg is the name of the operand in the asm string
  1548. // where #lastref is the last processed index where $reg was referenced in
  1549. // the asm string.
  1550. SmallDenseMap<StringRef, int> OperandRefs;
  1551. // Loop over all operands of the result instruction, determining how to
  1552. // populate them.
  1553. unsigned AliasOpNo = 0;
  1554. unsigned LastOpNo = CGA.ResultInstOperandIndex.size();
  1555. for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
  1556. const CGIOperandList::OperandInfo *OpInfo = &ResultInst->Operands[i];
  1557. // If this is a tied operand, just copy from the previously handled operand.
  1558. int TiedOp = -1;
  1559. if (OpInfo->MINumOperands == 1)
  1560. TiedOp = OpInfo->getTiedRegister();
  1561. if (TiedOp != -1) {
  1562. unsigned SrcOp1 = 0;
  1563. unsigned SrcOp2 = 0;
  1564. // If an operand has been specified twice in the asm string,
  1565. // add the two source operand's indices to the TiedOp so that
  1566. // at runtime the 'tied' constraint is checked.
  1567. if (ResOperands[TiedOp].Kind == ResOperand::RenderAsmOperand) {
  1568. SrcOp1 = ResOperands[TiedOp].AsmOperandNum;
  1569. // Find the next operand (similarly named operand) in the string.
  1570. StringRef Name = AsmOperands[SrcOp1].SrcOpName;
  1571. auto Insert = OperandRefs.try_emplace(Name, SrcOp1);
  1572. SrcOp2 = findAsmOperandNamed(Name, Insert.first->second);
  1573. // Not updating the record in OperandRefs will cause TableGen
  1574. // to fail with an error at the end of this function.
  1575. if (AliasConstraintsAreChecked)
  1576. Insert.first->second = SrcOp2;
  1577. // In case it only has one reference in the asm string,
  1578. // it doesn't need to be checked for tied constraints.
  1579. SrcOp2 = (SrcOp2 == (unsigned)-1) ? SrcOp1 : SrcOp2;
  1580. }
  1581. // If the alias operand is of a different operand class, we only want
  1582. // to benefit from the tied-operands check and just match the operand
  1583. // as a normal, but not copy the original (TiedOp) to the result
  1584. // instruction. We do this by passing -1 as the tied operand to copy.
  1585. if (ResultInst->Operands[i].Rec->getName() !=
  1586. ResultInst->Operands[TiedOp].Rec->getName()) {
  1587. SrcOp1 = ResOperands[TiedOp].AsmOperandNum;
  1588. int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second;
  1589. StringRef Name = CGA.ResultOperands[AliasOpNo].getName();
  1590. SrcOp2 = findAsmOperand(Name, SubIdx);
  1591. ResOperands.push_back(
  1592. ResOperand::getTiedOp((unsigned)-1, SrcOp1, SrcOp2));
  1593. } else {
  1594. ResOperands.push_back(ResOperand::getTiedOp(TiedOp, SrcOp1, SrcOp2));
  1595. continue;
  1596. }
  1597. }
  1598. // Handle all the suboperands for this operand.
  1599. const std::string &OpName = OpInfo->Name;
  1600. for ( ; AliasOpNo < LastOpNo &&
  1601. CGA.ResultInstOperandIndex[AliasOpNo].first == i; ++AliasOpNo) {
  1602. int SubIdx = CGA.ResultInstOperandIndex[AliasOpNo].second;
  1603. // Find out what operand from the asmparser that this MCInst operand
  1604. // comes from.
  1605. switch (CGA.ResultOperands[AliasOpNo].Kind) {
  1606. case CodeGenInstAlias::ResultOperand::K_Record: {
  1607. StringRef Name = CGA.ResultOperands[AliasOpNo].getName();
  1608. int SrcOperand = findAsmOperand(Name, SubIdx);
  1609. if (SrcOperand == -1)
  1610. PrintFatalError(TheDef->getLoc(), "Instruction '" +
  1611. TheDef->getName() + "' has operand '" + OpName +
  1612. "' that doesn't appear in asm string!");
  1613. // Add it to the operand references. If it is added a second time, the
  1614. // record won't be updated and it will fail later on.
  1615. OperandRefs.try_emplace(Name, SrcOperand);
  1616. unsigned NumOperands = (SubIdx == -1 ? OpInfo->MINumOperands : 1);
  1617. ResOperands.push_back(ResOperand::getRenderedOp(SrcOperand,
  1618. NumOperands));
  1619. break;
  1620. }
  1621. case CodeGenInstAlias::ResultOperand::K_Imm: {
  1622. int64_t ImmVal = CGA.ResultOperands[AliasOpNo].getImm();
  1623. ResOperands.push_back(ResOperand::getImmOp(ImmVal));
  1624. break;
  1625. }
  1626. case CodeGenInstAlias::ResultOperand::K_Reg: {
  1627. Record *Reg = CGA.ResultOperands[AliasOpNo].getRegister();
  1628. ResOperands.push_back(ResOperand::getRegOp(Reg));
  1629. break;
  1630. }
  1631. }
  1632. }
  1633. }
  1634. // Check that operands are not repeated more times than is supported.
  1635. for (auto &T : OperandRefs) {
  1636. if (T.second != -1 && findAsmOperandNamed(T.first, T.second) != -1)
  1637. PrintFatalError(TheDef->getLoc(),
  1638. "Operand '" + T.first + "' can never be matched");
  1639. }
  1640. }
  1641. static unsigned
  1642. getConverterOperandID(const std::string &Name,
  1643. SmallSetVector<CachedHashString, 16> &Table,
  1644. bool &IsNew) {
  1645. IsNew = Table.insert(CachedHashString(Name));
  1646. unsigned ID = IsNew ? Table.size() - 1 : find(Table, Name) - Table.begin();
  1647. assert(ID < Table.size());
  1648. return ID;
  1649. }
  1650. static unsigned
  1651. emitConvertFuncs(CodeGenTarget &Target, StringRef ClassName,
  1652. std::vector<std::unique_ptr<MatchableInfo>> &Infos,
  1653. bool HasMnemonicFirst, bool HasOptionalOperands,
  1654. raw_ostream &OS) {
  1655. SmallSetVector<CachedHashString, 16> OperandConversionKinds;
  1656. SmallSetVector<CachedHashString, 16> InstructionConversionKinds;
  1657. std::vector<std::vector<uint8_t> > ConversionTable;
  1658. size_t MaxRowLength = 2; // minimum is custom converter plus terminator.
  1659. // TargetOperandClass - This is the target's operand class, like X86Operand.
  1660. std::string TargetOperandClass = Target.getName().str() + "Operand";
  1661. // Write the convert function to a separate stream, so we can drop it after
  1662. // the enum. We'll build up the conversion handlers for the individual
  1663. // operand types opportunistically as we encounter them.
  1664. std::string ConvertFnBody;
  1665. raw_string_ostream CvtOS(ConvertFnBody);
  1666. // Start the unified conversion function.
  1667. if (HasOptionalOperands) {
  1668. CvtOS << "void " << Target.getName() << ClassName << "::\n"
  1669. << "convertToMCInst(unsigned Kind, MCInst &Inst, "
  1670. << "unsigned Opcode,\n"
  1671. << " const OperandVector &Operands,\n"
  1672. << " const SmallBitVector &OptionalOperandsMask) {\n";
  1673. } else {
  1674. CvtOS << "void " << Target.getName() << ClassName << "::\n"
  1675. << "convertToMCInst(unsigned Kind, MCInst &Inst, "
  1676. << "unsigned Opcode,\n"
  1677. << " const OperandVector &Operands) {\n";
  1678. }
  1679. CvtOS << " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n";
  1680. CvtOS << " const uint8_t *Converter = ConversionTable[Kind];\n";
  1681. if (HasOptionalOperands) {
  1682. size_t MaxNumOperands = 0;
  1683. for (const auto &MI : Infos) {
  1684. MaxNumOperands = std::max(MaxNumOperands, MI->AsmOperands.size());
  1685. }
  1686. CvtOS << " unsigned DefaultsOffset[" << (MaxNumOperands + 1)
  1687. << "] = { 0 };\n";
  1688. CvtOS << " assert(OptionalOperandsMask.size() == " << (MaxNumOperands)
  1689. << ");\n";
  1690. CvtOS << " for (unsigned i = 0, NumDefaults = 0; i < " << (MaxNumOperands)
  1691. << "; ++i) {\n";
  1692. CvtOS << " DefaultsOffset[i + 1] = NumDefaults;\n";
  1693. CvtOS << " NumDefaults += (OptionalOperandsMask[i] ? 1 : 0);\n";
  1694. CvtOS << " }\n";
  1695. }
  1696. CvtOS << " unsigned OpIdx;\n";
  1697. CvtOS << " Inst.setOpcode(Opcode);\n";
  1698. CvtOS << " for (const uint8_t *p = Converter; *p; p += 2) {\n";
  1699. if (HasOptionalOperands) {
  1700. CvtOS << " OpIdx = *(p + 1) - DefaultsOffset[*(p + 1)];\n";
  1701. } else {
  1702. CvtOS << " OpIdx = *(p + 1);\n";
  1703. }
  1704. CvtOS << " switch (*p) {\n";
  1705. CvtOS << " default: llvm_unreachable(\"invalid conversion entry!\");\n";
  1706. CvtOS << " case CVT_Reg:\n";
  1707. CvtOS << " static_cast<" << TargetOperandClass
  1708. << " &>(*Operands[OpIdx]).addRegOperands(Inst, 1);\n";
  1709. CvtOS << " break;\n";
  1710. CvtOS << " case CVT_Tied: {\n";
  1711. CvtOS << " assert(OpIdx < (size_t)(std::end(TiedAsmOperandTable) -\n";
  1712. CvtOS << " std::begin(TiedAsmOperandTable)) &&\n";
  1713. CvtOS << " \"Tied operand not found\");\n";
  1714. CvtOS << " unsigned TiedResOpnd = TiedAsmOperandTable[OpIdx][0];\n";
  1715. CvtOS << " if (TiedResOpnd != (uint8_t)-1)\n";
  1716. CvtOS << " Inst.addOperand(Inst.getOperand(TiedResOpnd));\n";
  1717. CvtOS << " break;\n";
  1718. CvtOS << " }\n";
  1719. std::string OperandFnBody;
  1720. raw_string_ostream OpOS(OperandFnBody);
  1721. // Start the operand number lookup function.
  1722. OpOS << "void " << Target.getName() << ClassName << "::\n"
  1723. << "convertToMapAndConstraints(unsigned Kind,\n";
  1724. OpOS.indent(27);
  1725. OpOS << "const OperandVector &Operands) {\n"
  1726. << " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n"
  1727. << " unsigned NumMCOperands = 0;\n"
  1728. << " const uint8_t *Converter = ConversionTable[Kind];\n"
  1729. << " for (const uint8_t *p = Converter; *p; p += 2) {\n"
  1730. << " switch (*p) {\n"
  1731. << " default: llvm_unreachable(\"invalid conversion entry!\");\n"
  1732. << " case CVT_Reg:\n"
  1733. << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
  1734. << " Operands[*(p + 1)]->setConstraint(\"r\");\n"
  1735. << " ++NumMCOperands;\n"
  1736. << " break;\n"
  1737. << " case CVT_Tied:\n"
  1738. << " ++NumMCOperands;\n"
  1739. << " break;\n";
  1740. // Pre-populate the operand conversion kinds with the standard always
  1741. // available entries.
  1742. OperandConversionKinds.insert(CachedHashString("CVT_Done"));
  1743. OperandConversionKinds.insert(CachedHashString("CVT_Reg"));
  1744. OperandConversionKinds.insert(CachedHashString("CVT_Tied"));
  1745. enum { CVT_Done, CVT_Reg, CVT_Tied };
  1746. // Map of e.g. <0, 2, 3> -> "Tie_0_2_3" enum label.
  1747. std::map<std::tuple<uint8_t, uint8_t, uint8_t>, std::string>
  1748. TiedOperandsEnumMap;
  1749. for (auto &II : Infos) {
  1750. // Check if we have a custom match function.
  1751. StringRef AsmMatchConverter =
  1752. II->getResultInst()->TheDef->getValueAsString("AsmMatchConverter");
  1753. if (!AsmMatchConverter.empty() && II->UseInstAsmMatchConverter) {
  1754. std::string Signature = ("ConvertCustom_" + AsmMatchConverter).str();
  1755. II->ConversionFnKind = Signature;
  1756. // Check if we have already generated this signature.
  1757. if (!InstructionConversionKinds.insert(CachedHashString(Signature)))
  1758. continue;
  1759. // Remember this converter for the kind enum.
  1760. unsigned KindID = OperandConversionKinds.size();
  1761. OperandConversionKinds.insert(
  1762. CachedHashString("CVT_" + getEnumNameForToken(AsmMatchConverter)));
  1763. // Add the converter row for this instruction.
  1764. ConversionTable.emplace_back();
  1765. ConversionTable.back().push_back(KindID);
  1766. ConversionTable.back().push_back(CVT_Done);
  1767. // Add the handler to the conversion driver function.
  1768. CvtOS << " case CVT_"
  1769. << getEnumNameForToken(AsmMatchConverter) << ":\n"
  1770. << " " << AsmMatchConverter << "(Inst, Operands);\n"
  1771. << " break;\n";
  1772. // FIXME: Handle the operand number lookup for custom match functions.
  1773. continue;
  1774. }
  1775. // Build the conversion function signature.
  1776. std::string Signature = "Convert";
  1777. std::vector<uint8_t> ConversionRow;
  1778. // Compute the convert enum and the case body.
  1779. MaxRowLength = std::max(MaxRowLength, II->ResOperands.size()*2 + 1 );
  1780. for (unsigned i = 0, e = II->ResOperands.size(); i != e; ++i) {
  1781. const MatchableInfo::ResOperand &OpInfo = II->ResOperands[i];
  1782. // Generate code to populate each result operand.
  1783. switch (OpInfo.Kind) {
  1784. case MatchableInfo::ResOperand::RenderAsmOperand: {
  1785. // This comes from something we parsed.
  1786. const MatchableInfo::AsmOperand &Op =
  1787. II->AsmOperands[OpInfo.AsmOperandNum];
  1788. // Registers are always converted the same, don't duplicate the
  1789. // conversion function based on them.
  1790. Signature += "__";
  1791. std::string Class;
  1792. Class = Op.Class->isRegisterClass() ? "Reg" : Op.Class->ClassName;
  1793. Signature += Class;
  1794. Signature += utostr(OpInfo.MINumOperands);
  1795. Signature += "_" + itostr(OpInfo.AsmOperandNum);
  1796. // Add the conversion kind, if necessary, and get the associated ID
  1797. // the index of its entry in the vector).
  1798. std::string Name = "CVT_" + (Op.Class->isRegisterClass() ? "Reg" :
  1799. Op.Class->RenderMethod);
  1800. if (Op.Class->IsOptional) {
  1801. // For optional operands we must also care about DefaultMethod
  1802. assert(HasOptionalOperands);
  1803. Name += "_" + Op.Class->DefaultMethod;
  1804. }
  1805. Name = getEnumNameForToken(Name);
  1806. bool IsNewConverter = false;
  1807. unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
  1808. IsNewConverter);
  1809. // Add the operand entry to the instruction kind conversion row.
  1810. ConversionRow.push_back(ID);
  1811. ConversionRow.push_back(OpInfo.AsmOperandNum + HasMnemonicFirst);
  1812. if (!IsNewConverter)
  1813. break;
  1814. // This is a new operand kind. Add a handler for it to the
  1815. // converter driver.
  1816. CvtOS << " case " << Name << ":\n";
  1817. if (Op.Class->IsOptional) {
  1818. // If optional operand is not present in actual instruction then we
  1819. // should call its DefaultMethod before RenderMethod
  1820. assert(HasOptionalOperands);
  1821. CvtOS << " if (OptionalOperandsMask[*(p + 1) - 1]) {\n"
  1822. << " " << Op.Class->DefaultMethod << "()"
  1823. << "->" << Op.Class->RenderMethod << "(Inst, "
  1824. << OpInfo.MINumOperands << ");\n"
  1825. << " } else {\n"
  1826. << " static_cast<" << TargetOperandClass
  1827. << " &>(*Operands[OpIdx])." << Op.Class->RenderMethod
  1828. << "(Inst, " << OpInfo.MINumOperands << ");\n"
  1829. << " }\n";
  1830. } else {
  1831. CvtOS << " static_cast<" << TargetOperandClass
  1832. << " &>(*Operands[OpIdx])." << Op.Class->RenderMethod
  1833. << "(Inst, " << OpInfo.MINumOperands << ");\n";
  1834. }
  1835. CvtOS << " break;\n";
  1836. // Add a handler for the operand number lookup.
  1837. OpOS << " case " << Name << ":\n"
  1838. << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n";
  1839. if (Op.Class->isRegisterClass())
  1840. OpOS << " Operands[*(p + 1)]->setConstraint(\"r\");\n";
  1841. else
  1842. OpOS << " Operands[*(p + 1)]->setConstraint(\"m\");\n";
  1843. OpOS << " NumMCOperands += " << OpInfo.MINumOperands << ";\n"
  1844. << " break;\n";
  1845. break;
  1846. }
  1847. case MatchableInfo::ResOperand::TiedOperand: {
  1848. // If this operand is tied to a previous one, just copy the MCInst
  1849. // operand from the earlier one.We can only tie single MCOperand values.
  1850. assert(OpInfo.MINumOperands == 1 && "Not a singular MCOperand");
  1851. uint8_t TiedOp = OpInfo.TiedOperands.ResOpnd;
  1852. uint8_t SrcOp1 =
  1853. OpInfo.TiedOperands.SrcOpnd1Idx + HasMnemonicFirst;
  1854. uint8_t SrcOp2 =
  1855. OpInfo.TiedOperands.SrcOpnd2Idx + HasMnemonicFirst;
  1856. assert((i > TiedOp || TiedOp == (uint8_t)-1) &&
  1857. "Tied operand precedes its target!");
  1858. auto TiedTupleName = std::string("Tie") + utostr(TiedOp) + '_' +
  1859. utostr(SrcOp1) + '_' + utostr(SrcOp2);
  1860. Signature += "__" + TiedTupleName;
  1861. ConversionRow.push_back(CVT_Tied);
  1862. ConversionRow.push_back(TiedOp);
  1863. ConversionRow.push_back(SrcOp1);
  1864. ConversionRow.push_back(SrcOp2);
  1865. // Also create an 'enum' for this combination of tied operands.
  1866. auto Key = std::make_tuple(TiedOp, SrcOp1, SrcOp2);
  1867. TiedOperandsEnumMap.emplace(Key, TiedTupleName);
  1868. break;
  1869. }
  1870. case MatchableInfo::ResOperand::ImmOperand: {
  1871. int64_t Val = OpInfo.ImmVal;
  1872. std::string Ty = "imm_" + itostr(Val);
  1873. Ty = getEnumNameForToken(Ty);
  1874. Signature += "__" + Ty;
  1875. std::string Name = "CVT_" + Ty;
  1876. bool IsNewConverter = false;
  1877. unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
  1878. IsNewConverter);
  1879. // Add the operand entry to the instruction kind conversion row.
  1880. ConversionRow.push_back(ID);
  1881. ConversionRow.push_back(0);
  1882. if (!IsNewConverter)
  1883. break;
  1884. CvtOS << " case " << Name << ":\n"
  1885. << " Inst.addOperand(MCOperand::createImm(" << Val << "));\n"
  1886. << " break;\n";
  1887. OpOS << " case " << Name << ":\n"
  1888. << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
  1889. << " Operands[*(p + 1)]->setConstraint(\"\");\n"
  1890. << " ++NumMCOperands;\n"
  1891. << " break;\n";
  1892. break;
  1893. }
  1894. case MatchableInfo::ResOperand::RegOperand: {
  1895. std::string Reg, Name;
  1896. if (!OpInfo.Register) {
  1897. Name = "reg0";
  1898. Reg = "0";
  1899. } else {
  1900. Reg = getQualifiedName(OpInfo.Register);
  1901. Name = "reg" + OpInfo.Register->getName().str();
  1902. }
  1903. Signature += "__" + Name;
  1904. Name = "CVT_" + Name;
  1905. bool IsNewConverter = false;
  1906. unsigned ID = getConverterOperandID(Name, OperandConversionKinds,
  1907. IsNewConverter);
  1908. // Add the operand entry to the instruction kind conversion row.
  1909. ConversionRow.push_back(ID);
  1910. ConversionRow.push_back(0);
  1911. if (!IsNewConverter)
  1912. break;
  1913. CvtOS << " case " << Name << ":\n"
  1914. << " Inst.addOperand(MCOperand::createReg(" << Reg << "));\n"
  1915. << " break;\n";
  1916. OpOS << " case " << Name << ":\n"
  1917. << " Operands[*(p + 1)]->setMCOperandNum(NumMCOperands);\n"
  1918. << " Operands[*(p + 1)]->setConstraint(\"m\");\n"
  1919. << " ++NumMCOperands;\n"
  1920. << " break;\n";
  1921. }
  1922. }
  1923. }
  1924. // If there were no operands, add to the signature to that effect
  1925. if (Signature == "Convert")
  1926. Signature += "_NoOperands";
  1927. II->ConversionFnKind = Signature;
  1928. // Save the signature. If we already have it, don't add a new row
  1929. // to the table.
  1930. if (!InstructionConversionKinds.insert(CachedHashString(Signature)))
  1931. continue;
  1932. // Add the row to the table.
  1933. ConversionTable.push_back(std::move(ConversionRow));
  1934. }
  1935. // Finish up the converter driver function.
  1936. CvtOS << " }\n }\n}\n\n";
  1937. // Finish up the operand number lookup function.
  1938. OpOS << " }\n }\n}\n\n";
  1939. // Output a static table for tied operands.
  1940. if (TiedOperandsEnumMap.size()) {
  1941. // The number of tied operand combinations will be small in practice,
  1942. // but just add the assert to be sure.
  1943. assert(TiedOperandsEnumMap.size() <= 254 &&
  1944. "Too many tied-operand combinations to reference with "
  1945. "an 8bit offset from the conversion table, where index "
  1946. "'255' is reserved as operand not to be copied.");
  1947. OS << "enum {\n";
  1948. for (auto &KV : TiedOperandsEnumMap) {
  1949. OS << " " << KV.second << ",\n";
  1950. }
  1951. OS << "};\n\n";
  1952. OS << "static const uint8_t TiedAsmOperandTable[][3] = {\n";
  1953. for (auto &KV : TiedOperandsEnumMap) {
  1954. OS << " /* " << KV.second << " */ { "
  1955. << utostr(std::get<0>(KV.first)) << ", "
  1956. << utostr(std::get<1>(KV.first)) << ", "
  1957. << utostr(std::get<2>(KV.first)) << " },\n";
  1958. }
  1959. OS << "};\n\n";
  1960. } else
  1961. OS << "static const uint8_t TiedAsmOperandTable[][3] = "
  1962. "{ /* empty */ {0, 0, 0} };\n\n";
  1963. OS << "namespace {\n";
  1964. // Output the operand conversion kind enum.
  1965. OS << "enum OperatorConversionKind {\n";
  1966. for (const auto &Converter : OperandConversionKinds)
  1967. OS << " " << Converter << ",\n";
  1968. OS << " CVT_NUM_CONVERTERS\n";
  1969. OS << "};\n\n";
  1970. // Output the instruction conversion kind enum.
  1971. OS << "enum InstructionConversionKind {\n";
  1972. for (const auto &Signature : InstructionConversionKinds)
  1973. OS << " " << Signature << ",\n";
  1974. OS << " CVT_NUM_SIGNATURES\n";
  1975. OS << "};\n\n";
  1976. OS << "} // end anonymous namespace\n\n";
  1977. // Output the conversion table.
  1978. OS << "static const uint8_t ConversionTable[CVT_NUM_SIGNATURES]["
  1979. << MaxRowLength << "] = {\n";
  1980. for (unsigned Row = 0, ERow = ConversionTable.size(); Row != ERow; ++Row) {
  1981. assert(ConversionTable[Row].size() % 2 == 0 && "bad conversion row!");
  1982. OS << " // " << InstructionConversionKinds[Row] << "\n";
  1983. OS << " { ";
  1984. for (unsigned i = 0, e = ConversionTable[Row].size(); i != e; i += 2) {
  1985. OS << OperandConversionKinds[ConversionTable[Row][i]] << ", ";
  1986. if (OperandConversionKinds[ConversionTable[Row][i]] !=
  1987. CachedHashString("CVT_Tied")) {
  1988. OS << (unsigned)(ConversionTable[Row][i + 1]) << ", ";
  1989. continue;
  1990. }
  1991. // For a tied operand, emit a reference to the TiedAsmOperandTable
  1992. // that contains the operand to copy, and the parsed operands to
  1993. // check for their tied constraints.
  1994. auto Key = std::make_tuple((uint8_t)ConversionTable[Row][i + 1],
  1995. (uint8_t)ConversionTable[Row][i + 2],
  1996. (uint8_t)ConversionTable[Row][i + 3]);
  1997. auto TiedOpndEnum = TiedOperandsEnumMap.find(Key);
  1998. assert(TiedOpndEnum != TiedOperandsEnumMap.end() &&
  1999. "No record for tied operand pair");
  2000. OS << TiedOpndEnum->second << ", ";
  2001. i += 2;
  2002. }
  2003. OS << "CVT_Done },\n";
  2004. }
  2005. OS << "};\n\n";
  2006. // Spit out the conversion driver function.
  2007. OS << CvtOS.str();
  2008. // Spit out the operand number lookup function.
  2009. OS << OpOS.str();
  2010. return ConversionTable.size();
  2011. }
  2012. /// emitMatchClassEnumeration - Emit the enumeration for match class kinds.
  2013. static void emitMatchClassEnumeration(CodeGenTarget &Target,
  2014. std::forward_list<ClassInfo> &Infos,
  2015. raw_ostream &OS) {
  2016. OS << "namespace {\n\n";
  2017. OS << "/// MatchClassKind - The kinds of classes which participate in\n"
  2018. << "/// instruction matching.\n";
  2019. OS << "enum MatchClassKind {\n";
  2020. OS << " InvalidMatchClass = 0,\n";
  2021. OS << " OptionalMatchClass = 1,\n";
  2022. ClassInfo::ClassInfoKind LastKind = ClassInfo::Token;
  2023. StringRef LastName = "OptionalMatchClass";
  2024. for (const auto &CI : Infos) {
  2025. if (LastKind == ClassInfo::Token && CI.Kind != ClassInfo::Token) {
  2026. OS << " MCK_LAST_TOKEN = " << LastName << ",\n";
  2027. } else if (LastKind < ClassInfo::UserClass0 &&
  2028. CI.Kind >= ClassInfo::UserClass0) {
  2029. OS << " MCK_LAST_REGISTER = " << LastName << ",\n";
  2030. }
  2031. LastKind = (ClassInfo::ClassInfoKind)CI.Kind;
  2032. LastName = CI.Name;
  2033. OS << " " << CI.Name << ", // ";
  2034. if (CI.Kind == ClassInfo::Token) {
  2035. OS << "'" << CI.ValueName << "'\n";
  2036. } else if (CI.isRegisterClass()) {
  2037. if (!CI.ValueName.empty())
  2038. OS << "register class '" << CI.ValueName << "'\n";
  2039. else
  2040. OS << "derived register class\n";
  2041. } else {
  2042. OS << "user defined class '" << CI.ValueName << "'\n";
  2043. }
  2044. }
  2045. OS << " NumMatchClassKinds\n";
  2046. OS << "};\n\n";
  2047. OS << "} // end anonymous namespace\n\n";
  2048. }
  2049. /// emitMatchClassDiagStrings - Emit a function to get the diagnostic text to be
  2050. /// used when an assembly operand does not match the expected operand class.
  2051. static void emitOperandMatchErrorDiagStrings(AsmMatcherInfo &Info, raw_ostream &OS) {
  2052. // If the target does not use DiagnosticString for any operands, don't emit
  2053. // an unused function.
  2054. if (llvm::all_of(Info.Classes, [](const ClassInfo &CI) {
  2055. return CI.DiagnosticString.empty();
  2056. }))
  2057. return;
  2058. OS << "static const char *getMatchKindDiag(" << Info.Target.getName()
  2059. << "AsmParser::" << Info.Target.getName()
  2060. << "MatchResultTy MatchResult) {\n";
  2061. OS << " switch (MatchResult) {\n";
  2062. for (const auto &CI: Info.Classes) {
  2063. if (!CI.DiagnosticString.empty()) {
  2064. assert(!CI.DiagnosticType.empty() &&
  2065. "DiagnosticString set without DiagnosticType");
  2066. OS << " case " << Info.Target.getName()
  2067. << "AsmParser::Match_" << CI.DiagnosticType << ":\n";
  2068. OS << " return \"" << CI.DiagnosticString << "\";\n";
  2069. }
  2070. }
  2071. OS << " default:\n";
  2072. OS << " return nullptr;\n";
  2073. OS << " }\n";
  2074. OS << "}\n\n";
  2075. }
  2076. static void emitRegisterMatchErrorFunc(AsmMatcherInfo &Info, raw_ostream &OS) {
  2077. OS << "static unsigned getDiagKindFromRegisterClass(MatchClassKind "
  2078. "RegisterClass) {\n";
  2079. if (none_of(Info.Classes, [](const ClassInfo &CI) {
  2080. return CI.isRegisterClass() && !CI.DiagnosticType.empty();
  2081. })) {
  2082. OS << " return MCTargetAsmParser::Match_InvalidOperand;\n";
  2083. } else {
  2084. OS << " switch (RegisterClass) {\n";
  2085. for (const auto &CI: Info.Classes) {
  2086. if (CI.isRegisterClass() && !CI.DiagnosticType.empty()) {
  2087. OS << " case " << CI.Name << ":\n";
  2088. OS << " return " << Info.Target.getName() << "AsmParser::Match_"
  2089. << CI.DiagnosticType << ";\n";
  2090. }
  2091. }
  2092. OS << " default:\n";
  2093. OS << " return MCTargetAsmParser::Match_InvalidOperand;\n";
  2094. OS << " }\n";
  2095. }
  2096. OS << "}\n\n";
  2097. }
  2098. /// emitValidateOperandClass - Emit the function to validate an operand class.
  2099. static void emitValidateOperandClass(AsmMatcherInfo &Info,
  2100. raw_ostream &OS) {
  2101. OS << "static unsigned validateOperandClass(MCParsedAsmOperand &GOp, "
  2102. << "MatchClassKind Kind) {\n";
  2103. OS << " " << Info.Target.getName() << "Operand &Operand = ("
  2104. << Info.Target.getName() << "Operand &)GOp;\n";
  2105. // The InvalidMatchClass is not to match any operand.
  2106. OS << " if (Kind == InvalidMatchClass)\n";
  2107. OS << " return MCTargetAsmParser::Match_InvalidOperand;\n\n";
  2108. // Check for Token operands first.
  2109. // FIXME: Use a more specific diagnostic type.
  2110. OS << " if (Operand.isToken() && Kind <= MCK_LAST_TOKEN)\n";
  2111. OS << " return isSubclass(matchTokenString(Operand.getToken()), Kind) ?\n"
  2112. << " MCTargetAsmParser::Match_Success :\n"
  2113. << " MCTargetAsmParser::Match_InvalidOperand;\n\n";
  2114. // Check the user classes. We don't care what order since we're only
  2115. // actually matching against one of them.
  2116. OS << " switch (Kind) {\n"
  2117. " default: break;\n";
  2118. for (const auto &CI : Info.Classes) {
  2119. if (!CI.isUserClass())
  2120. continue;
  2121. OS << " // '" << CI.ClassName << "' class\n";
  2122. OS << " case " << CI.Name << ": {\n";
  2123. OS << " DiagnosticPredicate DP(Operand." << CI.PredicateMethod
  2124. << "());\n";
  2125. OS << " if (DP.isMatch())\n";
  2126. OS << " return MCTargetAsmParser::Match_Success;\n";
  2127. if (!CI.DiagnosticType.empty()) {
  2128. OS << " if (DP.isNearMatch())\n";
  2129. OS << " return " << Info.Target.getName() << "AsmParser::Match_"
  2130. << CI.DiagnosticType << ";\n";
  2131. OS << " break;\n";
  2132. }
  2133. else
  2134. OS << " break;\n";
  2135. OS << " }\n";
  2136. }
  2137. OS << " } // end switch (Kind)\n\n";
  2138. // Check for register operands, including sub-classes.
  2139. OS << " if (Operand.isReg()) {\n";
  2140. OS << " MatchClassKind OpKind;\n";
  2141. OS << " switch (Operand.getReg()) {\n";
  2142. OS << " default: OpKind = InvalidMatchClass; break;\n";
  2143. for (const auto &RC : Info.RegisterClasses)
  2144. OS << " case " << RC.first->getValueAsString("Namespace") << "::"
  2145. << RC.first->getName() << ": OpKind = " << RC.second->Name
  2146. << "; break;\n";
  2147. OS << " }\n";
  2148. OS << " return isSubclass(OpKind, Kind) ? "
  2149. << "(unsigned)MCTargetAsmParser::Match_Success :\n "
  2150. << " getDiagKindFromRegisterClass(Kind);\n }\n\n";
  2151. // Expected operand is a register, but actual is not.
  2152. OS << " if (Kind > MCK_LAST_TOKEN && Kind <= MCK_LAST_REGISTER)\n";
  2153. OS << " return getDiagKindFromRegisterClass(Kind);\n\n";
  2154. // Generic fallthrough match failure case for operands that don't have
  2155. // specialized diagnostic types.
  2156. OS << " return MCTargetAsmParser::Match_InvalidOperand;\n";
  2157. OS << "}\n\n";
  2158. }
  2159. /// emitIsSubclass - Emit the subclass predicate function.
  2160. static void emitIsSubclass(CodeGenTarget &Target,
  2161. std::forward_list<ClassInfo> &Infos,
  2162. raw_ostream &OS) {
  2163. OS << "/// isSubclass - Compute whether \\p A is a subclass of \\p B.\n";
  2164. OS << "static bool isSubclass(MatchClassKind A, MatchClassKind B) {\n";
  2165. OS << " if (A == B)\n";
  2166. OS << " return true;\n\n";
  2167. bool EmittedSwitch = false;
  2168. for (const auto &A : Infos) {
  2169. std::vector<StringRef> SuperClasses;
  2170. if (A.IsOptional)
  2171. SuperClasses.push_back("OptionalMatchClass");
  2172. for (const auto &B : Infos) {
  2173. if (&A != &B && A.isSubsetOf(B))
  2174. SuperClasses.push_back(B.Name);
  2175. }
  2176. if (SuperClasses.empty())
  2177. continue;
  2178. // If this is the first SuperClass, emit the switch header.
  2179. if (!EmittedSwitch) {
  2180. OS << " switch (A) {\n";
  2181. OS << " default:\n";
  2182. OS << " return false;\n";
  2183. EmittedSwitch = true;
  2184. }
  2185. OS << "\n case " << A.Name << ":\n";
  2186. if (SuperClasses.size() == 1) {
  2187. OS << " return B == " << SuperClasses.back() << ";\n";
  2188. continue;
  2189. }
  2190. if (!SuperClasses.empty()) {
  2191. OS << " switch (B) {\n";
  2192. OS << " default: return false;\n";
  2193. for (StringRef SC : SuperClasses)
  2194. OS << " case " << SC << ": return true;\n";
  2195. OS << " }\n";
  2196. } else {
  2197. // No case statement to emit
  2198. OS << " return false;\n";
  2199. }
  2200. }
  2201. // If there were case statements emitted into the string stream write the
  2202. // default.
  2203. if (EmittedSwitch)
  2204. OS << " }\n";
  2205. else
  2206. OS << " return false;\n";
  2207. OS << "}\n\n";
  2208. }
  2209. /// emitMatchTokenString - Emit the function to match a token string to the
  2210. /// appropriate match class value.
  2211. static void emitMatchTokenString(CodeGenTarget &Target,
  2212. std::forward_list<ClassInfo> &Infos,
  2213. raw_ostream &OS) {
  2214. // Construct the match list.
  2215. std::vector<StringMatcher::StringPair> Matches;
  2216. for (const auto &CI : Infos) {
  2217. if (CI.Kind == ClassInfo::Token)
  2218. Matches.emplace_back(CI.ValueName, "return " + CI.Name + ";");
  2219. }
  2220. OS << "static MatchClassKind matchTokenString(StringRef Name) {\n";
  2221. StringMatcher("Name", Matches, OS).Emit();
  2222. OS << " return InvalidMatchClass;\n";
  2223. OS << "}\n\n";
  2224. }
  2225. /// emitMatchRegisterName - Emit the function to match a string to the target
  2226. /// specific register enum.
  2227. static void emitMatchRegisterName(CodeGenTarget &Target, Record *AsmParser,
  2228. raw_ostream &OS) {
  2229. // Construct the match list.
  2230. std::vector<StringMatcher::StringPair> Matches;
  2231. const auto &Regs = Target.getRegBank().getRegisters();
  2232. for (const CodeGenRegister &Reg : Regs) {
  2233. if (Reg.TheDef->getValueAsString("AsmName").empty())
  2234. continue;
  2235. Matches.emplace_back(std::string(Reg.TheDef->getValueAsString("AsmName")),
  2236. "return " + utostr(Reg.EnumValue) + ";");
  2237. }
  2238. OS << "static unsigned MatchRegisterName(StringRef Name) {\n";
  2239. bool IgnoreDuplicates =
  2240. AsmParser->getValueAsBit("AllowDuplicateRegisterNames");
  2241. StringMatcher("Name", Matches, OS).Emit(0, IgnoreDuplicates);
  2242. OS << " return 0;\n";
  2243. OS << "}\n\n";
  2244. }
  2245. /// Emit the function to match a string to the target
  2246. /// specific register enum.
  2247. static void emitMatchRegisterAltName(CodeGenTarget &Target, Record *AsmParser,
  2248. raw_ostream &OS) {
  2249. // Construct the match list.
  2250. std::vector<StringMatcher::StringPair> Matches;
  2251. const auto &Regs = Target.getRegBank().getRegisters();
  2252. for (const CodeGenRegister &Reg : Regs) {
  2253. auto AltNames = Reg.TheDef->getValueAsListOfStrings("AltNames");
  2254. for (auto AltName : AltNames) {
  2255. AltName = StringRef(AltName).trim();
  2256. // don't handle empty alternative names
  2257. if (AltName.empty())
  2258. continue;
  2259. Matches.emplace_back(std::string(AltName),
  2260. "return " + utostr(Reg.EnumValue) + ";");
  2261. }
  2262. }
  2263. OS << "static unsigned MatchRegisterAltName(StringRef Name) {\n";
  2264. bool IgnoreDuplicates =
  2265. AsmParser->getValueAsBit("AllowDuplicateRegisterNames");
  2266. StringMatcher("Name", Matches, OS).Emit(0, IgnoreDuplicates);
  2267. OS << " return 0;\n";
  2268. OS << "}\n\n";
  2269. }
  2270. /// emitOperandDiagnosticTypes - Emit the operand matching diagnostic types.
  2271. static void emitOperandDiagnosticTypes(AsmMatcherInfo &Info, raw_ostream &OS) {
  2272. // Get the set of diagnostic types from all of the operand classes.
  2273. std::set<StringRef> Types;
  2274. for (const auto &OpClassEntry : Info.AsmOperandClasses) {
  2275. if (!OpClassEntry.second->DiagnosticType.empty())
  2276. Types.insert(OpClassEntry.second->DiagnosticType);
  2277. }
  2278. for (const auto &OpClassEntry : Info.RegisterClassClasses) {
  2279. if (!OpClassEntry.second->DiagnosticType.empty())
  2280. Types.insert(OpClassEntry.second->DiagnosticType);
  2281. }
  2282. if (Types.empty()) return;
  2283. // Now emit the enum entries.
  2284. for (StringRef Type : Types)
  2285. OS << " Match_" << Type << ",\n";
  2286. OS << " END_OPERAND_DIAGNOSTIC_TYPES\n";
  2287. }
  2288. /// emitGetSubtargetFeatureName - Emit the helper function to get the
  2289. /// user-level name for a subtarget feature.
  2290. static void emitGetSubtargetFeatureName(AsmMatcherInfo &Info, raw_ostream &OS) {
  2291. OS << "// User-level names for subtarget features that participate in\n"
  2292. << "// instruction matching.\n"
  2293. << "static const char *getSubtargetFeatureName(uint64_t Val) {\n";
  2294. if (!Info.SubtargetFeatures.empty()) {
  2295. OS << " switch(Val) {\n";
  2296. for (const auto &SF : Info.SubtargetFeatures) {
  2297. const SubtargetFeatureInfo &SFI = SF.second;
  2298. // FIXME: Totally just a placeholder name to get the algorithm working.
  2299. OS << " case " << SFI.getEnumBitName() << ": return \""
  2300. << SFI.TheDef->getValueAsString("PredicateName") << "\";\n";
  2301. }
  2302. OS << " default: return \"(unknown)\";\n";
  2303. OS << " }\n";
  2304. } else {
  2305. // Nothing to emit, so skip the switch
  2306. OS << " return \"(unknown)\";\n";
  2307. }
  2308. OS << "}\n\n";
  2309. }
  2310. static std::string GetAliasRequiredFeatures(Record *R,
  2311. const AsmMatcherInfo &Info) {
  2312. std::vector<Record*> ReqFeatures = R->getValueAsListOfDefs("Predicates");
  2313. std::string Result;
  2314. if (ReqFeatures.empty())
  2315. return Result;
  2316. for (unsigned i = 0, e = ReqFeatures.size(); i != e; ++i) {
  2317. const SubtargetFeatureInfo *F = Info.getSubtargetFeature(ReqFeatures[i]);
  2318. if (!F)
  2319. PrintFatalError(R->getLoc(), "Predicate '" + ReqFeatures[i]->getName() +
  2320. "' is not marked as an AssemblerPredicate!");
  2321. if (i)
  2322. Result += " && ";
  2323. Result += "Features.test(" + F->getEnumBitName() + ')';
  2324. }
  2325. return Result;
  2326. }
  2327. static void emitMnemonicAliasVariant(raw_ostream &OS,const AsmMatcherInfo &Info,
  2328. std::vector<Record*> &Aliases,
  2329. unsigned Indent = 0,
  2330. StringRef AsmParserVariantName = StringRef()){
  2331. // Keep track of all the aliases from a mnemonic. Use an std::map so that the
  2332. // iteration order of the map is stable.
  2333. std::map<std::string, std::vector<Record*> > AliasesFromMnemonic;
  2334. for (Record *R : Aliases) {
  2335. // FIXME: Allow AssemblerVariantName to be a comma separated list.
  2336. StringRef AsmVariantName = R->getValueAsString("AsmVariantName");
  2337. if (AsmVariantName != AsmParserVariantName)
  2338. continue;
  2339. AliasesFromMnemonic[std::string(R->getValueAsString("FromMnemonic"))]
  2340. .push_back(R);
  2341. }
  2342. if (AliasesFromMnemonic.empty())
  2343. return;
  2344. // Process each alias a "from" mnemonic at a time, building the code executed
  2345. // by the string remapper.
  2346. std::vector<StringMatcher::StringPair> Cases;
  2347. for (const auto &AliasEntry : AliasesFromMnemonic) {
  2348. const std::vector<Record*> &ToVec = AliasEntry.second;
  2349. // Loop through each alias and emit code that handles each case. If there
  2350. // are two instructions without predicates, emit an error. If there is one,
  2351. // emit it last.
  2352. std::string MatchCode;
  2353. int AliasWithNoPredicate = -1;
  2354. for (unsigned i = 0, e = ToVec.size(); i != e; ++i) {
  2355. Record *R = ToVec[i];
  2356. std::string FeatureMask = GetAliasRequiredFeatures(R, Info);
  2357. // If this unconditionally matches, remember it for later and diagnose
  2358. // duplicates.
  2359. if (FeatureMask.empty()) {
  2360. if (AliasWithNoPredicate != -1) {
  2361. // We can't have two aliases from the same mnemonic with no predicate.
  2362. PrintError(ToVec[AliasWithNoPredicate]->getLoc(),
  2363. "two MnemonicAliases with the same 'from' mnemonic!");
  2364. PrintFatalError(R->getLoc(), "this is the other MnemonicAlias.");
  2365. }
  2366. AliasWithNoPredicate = i;
  2367. continue;
  2368. }
  2369. if (R->getValueAsString("ToMnemonic") == AliasEntry.first)
  2370. PrintFatalError(R->getLoc(), "MnemonicAlias to the same string");
  2371. if (!MatchCode.empty())
  2372. MatchCode += "else ";
  2373. MatchCode += "if (" + FeatureMask + ")\n";
  2374. MatchCode += " Mnemonic = \"";
  2375. MatchCode += R->getValueAsString("ToMnemonic");
  2376. MatchCode += "\";\n";
  2377. }
  2378. if (AliasWithNoPredicate != -1) {
  2379. Record *R = ToVec[AliasWithNoPredicate];
  2380. if (!MatchCode.empty())
  2381. MatchCode += "else\n ";
  2382. MatchCode += "Mnemonic = \"";
  2383. MatchCode += R->getValueAsString("ToMnemonic");
  2384. MatchCode += "\";\n";
  2385. }
  2386. MatchCode += "return;";
  2387. Cases.push_back(std::make_pair(AliasEntry.first, MatchCode));
  2388. }
  2389. StringMatcher("Mnemonic", Cases, OS).Emit(Indent);
  2390. }
  2391. /// emitMnemonicAliases - If the target has any MnemonicAlias<> definitions,
  2392. /// emit a function for them and return true, otherwise return false.
  2393. static bool emitMnemonicAliases(raw_ostream &OS, const AsmMatcherInfo &Info,
  2394. CodeGenTarget &Target) {
  2395. // Ignore aliases when match-prefix is set.
  2396. if (!MatchPrefix.empty())
  2397. return false;
  2398. std::vector<Record*> Aliases =
  2399. Info.getRecords().getAllDerivedDefinitions("MnemonicAlias");
  2400. if (Aliases.empty()) return false;
  2401. OS << "static void applyMnemonicAliases(StringRef &Mnemonic, "
  2402. "const FeatureBitset &Features, unsigned VariantID) {\n";
  2403. OS << " switch (VariantID) {\n";
  2404. unsigned VariantCount = Target.getAsmParserVariantCount();
  2405. for (unsigned VC = 0; VC != VariantCount; ++VC) {
  2406. Record *AsmVariant = Target.getAsmParserVariant(VC);
  2407. int AsmParserVariantNo = AsmVariant->getValueAsInt("Variant");
  2408. StringRef AsmParserVariantName = AsmVariant->getValueAsString("Name");
  2409. OS << " case " << AsmParserVariantNo << ":\n";
  2410. emitMnemonicAliasVariant(OS, Info, Aliases, /*Indent=*/2,
  2411. AsmParserVariantName);
  2412. OS << " break;\n";
  2413. }
  2414. OS << " }\n";
  2415. // Emit aliases that apply to all variants.
  2416. emitMnemonicAliasVariant(OS, Info, Aliases);
  2417. OS << "}\n\n";
  2418. return true;
  2419. }
  2420. static void emitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Target,
  2421. const AsmMatcherInfo &Info, StringRef ClassName,
  2422. StringToOffsetTable &StringTable,
  2423. unsigned MaxMnemonicIndex,
  2424. unsigned MaxFeaturesIndex,
  2425. bool HasMnemonicFirst) {
  2426. unsigned MaxMask = 0;
  2427. for (const OperandMatchEntry &OMI : Info.OperandMatchInfo) {
  2428. MaxMask |= OMI.OperandMask;
  2429. }
  2430. // Emit the static custom operand parsing table;
  2431. OS << "namespace {\n";
  2432. OS << " struct OperandMatchEntry {\n";
  2433. OS << " " << getMinimalTypeForRange(MaxMnemonicIndex)
  2434. << " Mnemonic;\n";
  2435. OS << " " << getMinimalTypeForRange(MaxMask)
  2436. << " OperandMask;\n";
  2437. OS << " " << getMinimalTypeForRange(std::distance(
  2438. Info.Classes.begin(), Info.Classes.end())) << " Class;\n";
  2439. OS << " " << getMinimalTypeForRange(MaxFeaturesIndex)
  2440. << " RequiredFeaturesIdx;\n\n";
  2441. OS << " StringRef getMnemonic() const {\n";
  2442. OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
  2443. OS << " MnemonicTable[Mnemonic]);\n";
  2444. OS << " }\n";
  2445. OS << " };\n\n";
  2446. OS << " // Predicate for searching for an opcode.\n";
  2447. OS << " struct LessOpcodeOperand {\n";
  2448. OS << " bool operator()(const OperandMatchEntry &LHS, StringRef RHS) {\n";
  2449. OS << " return LHS.getMnemonic() < RHS;\n";
  2450. OS << " }\n";
  2451. OS << " bool operator()(StringRef LHS, const OperandMatchEntry &RHS) {\n";
  2452. OS << " return LHS < RHS.getMnemonic();\n";
  2453. OS << " }\n";
  2454. OS << " bool operator()(const OperandMatchEntry &LHS,";
  2455. OS << " const OperandMatchEntry &RHS) {\n";
  2456. OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
  2457. OS << " }\n";
  2458. OS << " };\n";
  2459. OS << "} // end anonymous namespace\n\n";
  2460. OS << "static const OperandMatchEntry OperandMatchTable["
  2461. << Info.OperandMatchInfo.size() << "] = {\n";
  2462. OS << " /* Operand List Mnemonic, Mask, Operand Class, Features */\n";
  2463. for (const OperandMatchEntry &OMI : Info.OperandMatchInfo) {
  2464. const MatchableInfo &II = *OMI.MI;
  2465. OS << " { ";
  2466. // Store a pascal-style length byte in the mnemonic.
  2467. std::string LenMnemonic = char(II.Mnemonic.size()) + II.Mnemonic.lower();
  2468. OS << StringTable.GetOrAddStringOffset(LenMnemonic, false)
  2469. << " /* " << II.Mnemonic << " */, ";
  2470. OS << OMI.OperandMask;
  2471. OS << " /* ";
  2472. bool printComma = false;
  2473. for (int i = 0, e = 31; i !=e; ++i)
  2474. if (OMI.OperandMask & (1 << i)) {
  2475. if (printComma)
  2476. OS << ", ";
  2477. OS << i;
  2478. printComma = true;
  2479. }
  2480. OS << " */, ";
  2481. OS << OMI.CI->Name;
  2482. // Write the required features mask.
  2483. OS << ", AMFBS";
  2484. if (II.RequiredFeatures.empty())
  2485. OS << "_None";
  2486. else
  2487. for (unsigned i = 0, e = II.RequiredFeatures.size(); i != e; ++i)
  2488. OS << '_' << II.RequiredFeatures[i]->TheDef->getName();
  2489. OS << " },\n";
  2490. }
  2491. OS << "};\n\n";
  2492. // Emit the operand class switch to call the correct custom parser for
  2493. // the found operand class.
  2494. OS << "OperandMatchResultTy " << Target.getName() << ClassName << "::\n"
  2495. << "tryCustomParseOperand(OperandVector"
  2496. << " &Operands,\n unsigned MCK) {\n\n"
  2497. << " switch(MCK) {\n";
  2498. for (const auto &CI : Info.Classes) {
  2499. if (CI.ParserMethod.empty())
  2500. continue;
  2501. OS << " case " << CI.Name << ":\n"
  2502. << " return " << CI.ParserMethod << "(Operands);\n";
  2503. }
  2504. OS << " default:\n";
  2505. OS << " return MatchOperand_NoMatch;\n";
  2506. OS << " }\n";
  2507. OS << " return MatchOperand_NoMatch;\n";
  2508. OS << "}\n\n";
  2509. // Emit the static custom operand parser. This code is very similar with
  2510. // the other matcher. Also use MatchResultTy here just in case we go for
  2511. // a better error handling.
  2512. OS << "OperandMatchResultTy " << Target.getName() << ClassName << "::\n"
  2513. << "MatchOperandParserImpl(OperandVector"
  2514. << " &Operands,\n StringRef Mnemonic,\n"
  2515. << " bool ParseForAllFeatures) {\n";
  2516. // Emit code to get the available features.
  2517. OS << " // Get the current feature set.\n";
  2518. OS << " const FeatureBitset &AvailableFeatures = getAvailableFeatures();\n\n";
  2519. OS << " // Get the next operand index.\n";
  2520. OS << " unsigned NextOpNum = Operands.size()"
  2521. << (HasMnemonicFirst ? " - 1" : "") << ";\n";
  2522. // Emit code to search the table.
  2523. OS << " // Search the table.\n";
  2524. if (HasMnemonicFirst) {
  2525. OS << " auto MnemonicRange =\n";
  2526. OS << " std::equal_range(std::begin(OperandMatchTable), "
  2527. "std::end(OperandMatchTable),\n";
  2528. OS << " Mnemonic, LessOpcodeOperand());\n\n";
  2529. } else {
  2530. OS << " auto MnemonicRange = std::make_pair(std::begin(OperandMatchTable),"
  2531. " std::end(OperandMatchTable));\n";
  2532. OS << " if (!Mnemonic.empty())\n";
  2533. OS << " MnemonicRange =\n";
  2534. OS << " std::equal_range(std::begin(OperandMatchTable), "
  2535. "std::end(OperandMatchTable),\n";
  2536. OS << " Mnemonic, LessOpcodeOperand());\n\n";
  2537. }
  2538. OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
  2539. OS << " return MatchOperand_NoMatch;\n\n";
  2540. OS << " for (const OperandMatchEntry *it = MnemonicRange.first,\n"
  2541. << " *ie = MnemonicRange.second; it != ie; ++it) {\n";
  2542. OS << " // equal_range guarantees that instruction mnemonic matches.\n";
  2543. OS << " assert(Mnemonic == it->getMnemonic());\n\n";
  2544. // Emit check that the required features are available.
  2545. OS << " // check if the available features match\n";
  2546. OS << " const FeatureBitset &RequiredFeatures = "
  2547. "FeatureBitsets[it->RequiredFeaturesIdx];\n";
  2548. OS << " if (!ParseForAllFeatures && (AvailableFeatures & "
  2549. "RequiredFeatures) != RequiredFeatures)\n";
  2550. OS << " continue;\n\n";
  2551. // Emit check to ensure the operand number matches.
  2552. OS << " // check if the operand in question has a custom parser.\n";
  2553. OS << " if (!(it->OperandMask & (1 << NextOpNum)))\n";
  2554. OS << " continue;\n\n";
  2555. // Emit call to the custom parser method
  2556. OS << " // call custom parse method to handle the operand\n";
  2557. OS << " OperandMatchResultTy Result = ";
  2558. OS << "tryCustomParseOperand(Operands, it->Class);\n";
  2559. OS << " if (Result != MatchOperand_NoMatch)\n";
  2560. OS << " return Result;\n";
  2561. OS << " }\n\n";
  2562. OS << " // Okay, we had no match.\n";
  2563. OS << " return MatchOperand_NoMatch;\n";
  2564. OS << "}\n\n";
  2565. }
  2566. static void emitAsmTiedOperandConstraints(CodeGenTarget &Target,
  2567. AsmMatcherInfo &Info,
  2568. raw_ostream &OS) {
  2569. std::string AsmParserName =
  2570. std::string(Info.AsmParser->getValueAsString("AsmParserClassName"));
  2571. OS << "static bool ";
  2572. OS << "checkAsmTiedOperandConstraints(const " << Target.getName()
  2573. << AsmParserName << "&AsmParser,\n";
  2574. OS << " unsigned Kind,\n";
  2575. OS << " const OperandVector &Operands,\n";
  2576. OS << " uint64_t &ErrorInfo) {\n";
  2577. OS << " assert(Kind < CVT_NUM_SIGNATURES && \"Invalid signature!\");\n";
  2578. OS << " const uint8_t *Converter = ConversionTable[Kind];\n";
  2579. OS << " for (const uint8_t *p = Converter; *p; p += 2) {\n";
  2580. OS << " switch (*p) {\n";
  2581. OS << " case CVT_Tied: {\n";
  2582. OS << " unsigned OpIdx = *(p + 1);\n";
  2583. OS << " assert(OpIdx < (size_t)(std::end(TiedAsmOperandTable) -\n";
  2584. OS << " std::begin(TiedAsmOperandTable)) &&\n";
  2585. OS << " \"Tied operand not found\");\n";
  2586. OS << " unsigned OpndNum1 = TiedAsmOperandTable[OpIdx][1];\n";
  2587. OS << " unsigned OpndNum2 = TiedAsmOperandTable[OpIdx][2];\n";
  2588. OS << " if (OpndNum1 != OpndNum2) {\n";
  2589. OS << " auto &SrcOp1 = Operands[OpndNum1];\n";
  2590. OS << " auto &SrcOp2 = Operands[OpndNum2];\n";
  2591. OS << " if (SrcOp1->isReg() && SrcOp2->isReg()) {\n";
  2592. OS << " if (!AsmParser.regsEqual(*SrcOp1, *SrcOp2)) {\n";
  2593. OS << " ErrorInfo = OpndNum2;\n";
  2594. OS << " return false;\n";
  2595. OS << " }\n";
  2596. OS << " }\n";
  2597. OS << " }\n";
  2598. OS << " break;\n";
  2599. OS << " }\n";
  2600. OS << " default:\n";
  2601. OS << " break;\n";
  2602. OS << " }\n";
  2603. OS << " }\n";
  2604. OS << " return true;\n";
  2605. OS << "}\n\n";
  2606. }
  2607. static void emitMnemonicSpellChecker(raw_ostream &OS, CodeGenTarget &Target,
  2608. unsigned VariantCount) {
  2609. OS << "static std::string " << Target.getName()
  2610. << "MnemonicSpellCheck(StringRef S, const FeatureBitset &FBS,"
  2611. << " unsigned VariantID) {\n";
  2612. if (!VariantCount)
  2613. OS << " return \"\";";
  2614. else {
  2615. OS << " const unsigned MaxEditDist = 2;\n";
  2616. OS << " std::vector<StringRef> Candidates;\n";
  2617. OS << " StringRef Prev = \"\";\n\n";
  2618. OS << " // Find the appropriate table for this asm variant.\n";
  2619. OS << " const MatchEntry *Start, *End;\n";
  2620. OS << " switch (VariantID) {\n";
  2621. OS << " default: llvm_unreachable(\"invalid variant!\");\n";
  2622. for (unsigned VC = 0; VC != VariantCount; ++VC) {
  2623. Record *AsmVariant = Target.getAsmParserVariant(VC);
  2624. int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
  2625. OS << " case " << AsmVariantNo << ": Start = std::begin(MatchTable" << VC
  2626. << "); End = std::end(MatchTable" << VC << "); break;\n";
  2627. }
  2628. OS << " }\n\n";
  2629. OS << " for (auto I = Start; I < End; I++) {\n";
  2630. OS << " // Ignore unsupported instructions.\n";
  2631. OS << " const FeatureBitset &RequiredFeatures = "
  2632. "FeatureBitsets[I->RequiredFeaturesIdx];\n";
  2633. OS << " if ((FBS & RequiredFeatures) != RequiredFeatures)\n";
  2634. OS << " continue;\n";
  2635. OS << "\n";
  2636. OS << " StringRef T = I->getMnemonic();\n";
  2637. OS << " // Avoid recomputing the edit distance for the same string.\n";
  2638. OS << " if (T.equals(Prev))\n";
  2639. OS << " continue;\n";
  2640. OS << "\n";
  2641. OS << " Prev = T;\n";
  2642. OS << " unsigned Dist = S.edit_distance(T, false, MaxEditDist);\n";
  2643. OS << " if (Dist <= MaxEditDist)\n";
  2644. OS << " Candidates.push_back(T);\n";
  2645. OS << " }\n";
  2646. OS << "\n";
  2647. OS << " if (Candidates.empty())\n";
  2648. OS << " return \"\";\n";
  2649. OS << "\n";
  2650. OS << " std::string Res = \", did you mean: \";\n";
  2651. OS << " unsigned i = 0;\n";
  2652. OS << " for (; i < Candidates.size() - 1; i++)\n";
  2653. OS << " Res += Candidates[i].str() + \", \";\n";
  2654. OS << " return Res + Candidates[i].str() + \"?\";\n";
  2655. }
  2656. OS << "}\n";
  2657. OS << "\n";
  2658. }
  2659. static void emitMnemonicChecker(raw_ostream &OS,
  2660. CodeGenTarget &Target,
  2661. unsigned VariantCount,
  2662. bool HasMnemonicFirst,
  2663. bool HasMnemonicAliases) {
  2664. OS << "static bool " << Target.getName()
  2665. << "CheckMnemonic(StringRef Mnemonic,\n";
  2666. OS << " "
  2667. << "const FeatureBitset &AvailableFeatures,\n";
  2668. OS << " "
  2669. << "unsigned VariantID) {\n";
  2670. if (!VariantCount) {
  2671. OS << " return false;\n";
  2672. } else {
  2673. if (HasMnemonicAliases) {
  2674. OS << " // Process all MnemonicAliases to remap the mnemonic.\n";
  2675. OS << " applyMnemonicAliases(Mnemonic, AvailableFeatures, VariantID);";
  2676. OS << "\n\n";
  2677. }
  2678. OS << " // Find the appropriate table for this asm variant.\n";
  2679. OS << " const MatchEntry *Start, *End;\n";
  2680. OS << " switch (VariantID) {\n";
  2681. OS << " default: llvm_unreachable(\"invalid variant!\");\n";
  2682. for (unsigned VC = 0; VC != VariantCount; ++VC) {
  2683. Record *AsmVariant = Target.getAsmParserVariant(VC);
  2684. int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
  2685. OS << " case " << AsmVariantNo << ": Start = std::begin(MatchTable" << VC
  2686. << "); End = std::end(MatchTable" << VC << "); break;\n";
  2687. }
  2688. OS << " }\n\n";
  2689. OS << " // Search the table.\n";
  2690. if (HasMnemonicFirst) {
  2691. OS << " auto MnemonicRange = "
  2692. "std::equal_range(Start, End, Mnemonic, LessOpcode());\n\n";
  2693. } else {
  2694. OS << " auto MnemonicRange = std::make_pair(Start, End);\n";
  2695. OS << " unsigned SIndex = Mnemonic.empty() ? 0 : 1;\n";
  2696. OS << " if (!Mnemonic.empty())\n";
  2697. OS << " MnemonicRange = "
  2698. << "std::equal_range(Start, End, Mnemonic.lower(), LessOpcode());\n\n";
  2699. }
  2700. OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
  2701. OS << " return false;\n\n";
  2702. OS << " for (const MatchEntry *it = MnemonicRange.first, "
  2703. << "*ie = MnemonicRange.second;\n";
  2704. OS << " it != ie; ++it) {\n";
  2705. OS << " const FeatureBitset &RequiredFeatures =\n";
  2706. OS << " FeatureBitsets[it->RequiredFeaturesIdx];\n";
  2707. OS << " if ((AvailableFeatures & RequiredFeatures) == ";
  2708. OS << "RequiredFeatures)\n";
  2709. OS << " return true;\n";
  2710. OS << " }\n";
  2711. OS << " return false;\n";
  2712. }
  2713. OS << "}\n";
  2714. OS << "\n";
  2715. }
  2716. // Emit a function mapping match classes to strings, for debugging.
  2717. static void emitMatchClassKindNames(std::forward_list<ClassInfo> &Infos,
  2718. raw_ostream &OS) {
  2719. OS << "#ifndef NDEBUG\n";
  2720. OS << "const char *getMatchClassName(MatchClassKind Kind) {\n";
  2721. OS << " switch (Kind) {\n";
  2722. OS << " case InvalidMatchClass: return \"InvalidMatchClass\";\n";
  2723. OS << " case OptionalMatchClass: return \"OptionalMatchClass\";\n";
  2724. for (const auto &CI : Infos) {
  2725. OS << " case " << CI.Name << ": return \"" << CI.Name << "\";\n";
  2726. }
  2727. OS << " case NumMatchClassKinds: return \"NumMatchClassKinds\";\n";
  2728. OS << " }\n";
  2729. OS << " llvm_unreachable(\"unhandled MatchClassKind!\");\n";
  2730. OS << "}\n\n";
  2731. OS << "#endif // NDEBUG\n";
  2732. }
  2733. static std::string
  2734. getNameForFeatureBitset(const std::vector<Record *> &FeatureBitset) {
  2735. std::string Name = "AMFBS";
  2736. for (const auto &Feature : FeatureBitset)
  2737. Name += ("_" + Feature->getName()).str();
  2738. return Name;
  2739. }
  2740. void AsmMatcherEmitter::run(raw_ostream &OS) {
  2741. CodeGenTarget Target(Records);
  2742. Record *AsmParser = Target.getAsmParser();
  2743. StringRef ClassName = AsmParser->getValueAsString("AsmParserClassName");
  2744. // Compute the information on the instructions to match.
  2745. AsmMatcherInfo Info(AsmParser, Target, Records);
  2746. Info.buildInfo();
  2747. // Sort the instruction table using the partial order on classes. We use
  2748. // stable_sort to ensure that ambiguous instructions are still
  2749. // deterministically ordered.
  2750. llvm::stable_sort(
  2751. Info.Matchables,
  2752. [](const std::unique_ptr<MatchableInfo> &a,
  2753. const std::unique_ptr<MatchableInfo> &b) { return *a < *b; });
  2754. #ifdef EXPENSIVE_CHECKS
  2755. // Verify that the table is sorted and operator < works transitively.
  2756. for (auto I = Info.Matchables.begin(), E = Info.Matchables.end(); I != E;
  2757. ++I) {
  2758. for (auto J = I; J != E; ++J) {
  2759. assert(!(**J < **I));
  2760. }
  2761. }
  2762. #endif
  2763. DEBUG_WITH_TYPE("instruction_info", {
  2764. for (const auto &MI : Info.Matchables)
  2765. MI->dump();
  2766. });
  2767. // Check for ambiguous matchables.
  2768. DEBUG_WITH_TYPE("ambiguous_instrs", {
  2769. unsigned NumAmbiguous = 0;
  2770. for (auto I = Info.Matchables.begin(), E = Info.Matchables.end(); I != E;
  2771. ++I) {
  2772. for (auto J = std::next(I); J != E; ++J) {
  2773. const MatchableInfo &A = **I;
  2774. const MatchableInfo &B = **J;
  2775. if (A.couldMatchAmbiguouslyWith(B)) {
  2776. errs() << "warning: ambiguous matchables:\n";
  2777. A.dump();
  2778. errs() << "\nis incomparable with:\n";
  2779. B.dump();
  2780. errs() << "\n\n";
  2781. ++NumAmbiguous;
  2782. }
  2783. }
  2784. }
  2785. if (NumAmbiguous)
  2786. errs() << "warning: " << NumAmbiguous
  2787. << " ambiguous matchables!\n";
  2788. });
  2789. // Compute the information on the custom operand parsing.
  2790. Info.buildOperandMatchInfo();
  2791. bool HasMnemonicFirst = AsmParser->getValueAsBit("HasMnemonicFirst");
  2792. bool HasOptionalOperands = Info.hasOptionalOperands();
  2793. bool ReportMultipleNearMisses =
  2794. AsmParser->getValueAsBit("ReportMultipleNearMisses");
  2795. // Write the output.
  2796. // Information for the class declaration.
  2797. OS << "\n#ifdef GET_ASSEMBLER_HEADER\n";
  2798. OS << "#undef GET_ASSEMBLER_HEADER\n";
  2799. OS << " // This should be included into the middle of the declaration of\n";
  2800. OS << " // your subclasses implementation of MCTargetAsmParser.\n";
  2801. OS << " FeatureBitset ComputeAvailableFeatures(const FeatureBitset &FB) const;\n";
  2802. if (HasOptionalOperands) {
  2803. OS << " void convertToMCInst(unsigned Kind, MCInst &Inst, "
  2804. << "unsigned Opcode,\n"
  2805. << " const OperandVector &Operands,\n"
  2806. << " const SmallBitVector &OptionalOperandsMask);\n";
  2807. } else {
  2808. OS << " void convertToMCInst(unsigned Kind, MCInst &Inst, "
  2809. << "unsigned Opcode,\n"
  2810. << " const OperandVector &Operands);\n";
  2811. }
  2812. OS << " void convertToMapAndConstraints(unsigned Kind,\n ";
  2813. OS << " const OperandVector &Operands) override;\n";
  2814. OS << " unsigned MatchInstructionImpl(const OperandVector &Operands,\n"
  2815. << " MCInst &Inst,\n";
  2816. if (ReportMultipleNearMisses)
  2817. OS << " SmallVectorImpl<NearMissInfo> *NearMisses,\n";
  2818. else
  2819. OS << " uint64_t &ErrorInfo,\n"
  2820. << " FeatureBitset &MissingFeatures,\n";
  2821. OS << " bool matchingInlineAsm,\n"
  2822. << " unsigned VariantID = 0);\n";
  2823. if (!ReportMultipleNearMisses)
  2824. OS << " unsigned MatchInstructionImpl(const OperandVector &Operands,\n"
  2825. << " MCInst &Inst,\n"
  2826. << " uint64_t &ErrorInfo,\n"
  2827. << " bool matchingInlineAsm,\n"
  2828. << " unsigned VariantID = 0) {\n"
  2829. << " FeatureBitset MissingFeatures;\n"
  2830. << " return MatchInstructionImpl(Operands, Inst, ErrorInfo, MissingFeatures,\n"
  2831. << " matchingInlineAsm, VariantID);\n"
  2832. << " }\n\n";
  2833. if (!Info.OperandMatchInfo.empty()) {
  2834. OS << " OperandMatchResultTy MatchOperandParserImpl(\n";
  2835. OS << " OperandVector &Operands,\n";
  2836. OS << " StringRef Mnemonic,\n";
  2837. OS << " bool ParseForAllFeatures = false);\n";
  2838. OS << " OperandMatchResultTy tryCustomParseOperand(\n";
  2839. OS << " OperandVector &Operands,\n";
  2840. OS << " unsigned MCK);\n\n";
  2841. }
  2842. OS << "#endif // GET_ASSEMBLER_HEADER_INFO\n\n";
  2843. // Emit the operand match diagnostic enum names.
  2844. OS << "\n#ifdef GET_OPERAND_DIAGNOSTIC_TYPES\n";
  2845. OS << "#undef GET_OPERAND_DIAGNOSTIC_TYPES\n\n";
  2846. emitOperandDiagnosticTypes(Info, OS);
  2847. OS << "#endif // GET_OPERAND_DIAGNOSTIC_TYPES\n\n";
  2848. OS << "\n#ifdef GET_REGISTER_MATCHER\n";
  2849. OS << "#undef GET_REGISTER_MATCHER\n\n";
  2850. // Emit the subtarget feature enumeration.
  2851. SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(
  2852. Info.SubtargetFeatures, OS);
  2853. // Emit the function to match a register name to number.
  2854. // This should be omitted for Mips target
  2855. if (AsmParser->getValueAsBit("ShouldEmitMatchRegisterName"))
  2856. emitMatchRegisterName(Target, AsmParser, OS);
  2857. if (AsmParser->getValueAsBit("ShouldEmitMatchRegisterAltName"))
  2858. emitMatchRegisterAltName(Target, AsmParser, OS);
  2859. OS << "#endif // GET_REGISTER_MATCHER\n\n";
  2860. OS << "\n#ifdef GET_SUBTARGET_FEATURE_NAME\n";
  2861. OS << "#undef GET_SUBTARGET_FEATURE_NAME\n\n";
  2862. // Generate the helper function to get the names for subtarget features.
  2863. emitGetSubtargetFeatureName(Info, OS);
  2864. OS << "#endif // GET_SUBTARGET_FEATURE_NAME\n\n";
  2865. OS << "\n#ifdef GET_MATCHER_IMPLEMENTATION\n";
  2866. OS << "#undef GET_MATCHER_IMPLEMENTATION\n\n";
  2867. // Generate the function that remaps for mnemonic aliases.
  2868. bool HasMnemonicAliases = emitMnemonicAliases(OS, Info, Target);
  2869. // Generate the convertToMCInst function to convert operands into an MCInst.
  2870. // Also, generate the convertToMapAndConstraints function for MS-style inline
  2871. // assembly. The latter doesn't actually generate a MCInst.
  2872. unsigned NumConverters = emitConvertFuncs(Target, ClassName, Info.Matchables,
  2873. HasMnemonicFirst,
  2874. HasOptionalOperands, OS);
  2875. // Emit the enumeration for classes which participate in matching.
  2876. emitMatchClassEnumeration(Target, Info.Classes, OS);
  2877. // Emit a function to get the user-visible string to describe an operand
  2878. // match failure in diagnostics.
  2879. emitOperandMatchErrorDiagStrings(Info, OS);
  2880. // Emit a function to map register classes to operand match failure codes.
  2881. emitRegisterMatchErrorFunc(Info, OS);
  2882. // Emit the routine to match token strings to their match class.
  2883. emitMatchTokenString(Target, Info.Classes, OS);
  2884. // Emit the subclass predicate routine.
  2885. emitIsSubclass(Target, Info.Classes, OS);
  2886. // Emit the routine to validate an operand against a match class.
  2887. emitValidateOperandClass(Info, OS);
  2888. emitMatchClassKindNames(Info.Classes, OS);
  2889. // Emit the available features compute function.
  2890. SubtargetFeatureInfo::emitComputeAssemblerAvailableFeatures(
  2891. Info.Target.getName(), ClassName, "ComputeAvailableFeatures",
  2892. Info.SubtargetFeatures, OS);
  2893. if (!ReportMultipleNearMisses)
  2894. emitAsmTiedOperandConstraints(Target, Info, OS);
  2895. StringToOffsetTable StringTable;
  2896. size_t MaxNumOperands = 0;
  2897. unsigned MaxMnemonicIndex = 0;
  2898. bool HasDeprecation = false;
  2899. for (const auto &MI : Info.Matchables) {
  2900. MaxNumOperands = std::max(MaxNumOperands, MI->AsmOperands.size());
  2901. HasDeprecation |= MI->HasDeprecation;
  2902. // Store a pascal-style length byte in the mnemonic.
  2903. std::string LenMnemonic = char(MI->Mnemonic.size()) + MI->Mnemonic.lower();
  2904. MaxMnemonicIndex = std::max(MaxMnemonicIndex,
  2905. StringTable.GetOrAddStringOffset(LenMnemonic, false));
  2906. }
  2907. OS << "static const char *const MnemonicTable =\n";
  2908. StringTable.EmitString(OS);
  2909. OS << ";\n\n";
  2910. std::vector<std::vector<Record *>> FeatureBitsets;
  2911. for (const auto &MI : Info.Matchables) {
  2912. if (MI->RequiredFeatures.empty())
  2913. continue;
  2914. FeatureBitsets.emplace_back();
  2915. for (unsigned I = 0, E = MI->RequiredFeatures.size(); I != E; ++I)
  2916. FeatureBitsets.back().push_back(MI->RequiredFeatures[I]->TheDef);
  2917. }
  2918. llvm::sort(FeatureBitsets, [&](const std::vector<Record *> &A,
  2919. const std::vector<Record *> &B) {
  2920. if (A.size() < B.size())
  2921. return true;
  2922. if (A.size() > B.size())
  2923. return false;
  2924. for (auto Pair : zip(A, B)) {
  2925. if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName())
  2926. return true;
  2927. if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName())
  2928. return false;
  2929. }
  2930. return false;
  2931. });
  2932. FeatureBitsets.erase(
  2933. std::unique(FeatureBitsets.begin(), FeatureBitsets.end()),
  2934. FeatureBitsets.end());
  2935. OS << "// Feature bitsets.\n"
  2936. << "enum : " << getMinimalTypeForRange(FeatureBitsets.size()) << " {\n"
  2937. << " AMFBS_None,\n";
  2938. for (const auto &FeatureBitset : FeatureBitsets) {
  2939. if (FeatureBitset.empty())
  2940. continue;
  2941. OS << " " << getNameForFeatureBitset(FeatureBitset) << ",\n";
  2942. }
  2943. OS << "};\n\n"
  2944. << "static constexpr FeatureBitset FeatureBitsets[] = {\n"
  2945. << " {}, // AMFBS_None\n";
  2946. for (const auto &FeatureBitset : FeatureBitsets) {
  2947. if (FeatureBitset.empty())
  2948. continue;
  2949. OS << " {";
  2950. for (const auto &Feature : FeatureBitset) {
  2951. const auto &I = Info.SubtargetFeatures.find(Feature);
  2952. assert(I != Info.SubtargetFeatures.end() && "Didn't import predicate?");
  2953. OS << I->second.getEnumBitName() << ", ";
  2954. }
  2955. OS << "},\n";
  2956. }
  2957. OS << "};\n\n";
  2958. // Emit the static match table; unused classes get initialized to 0 which is
  2959. // guaranteed to be InvalidMatchClass.
  2960. //
  2961. // FIXME: We can reduce the size of this table very easily. First, we change
  2962. // it so that store the kinds in separate bit-fields for each index, which
  2963. // only needs to be the max width used for classes at that index (we also need
  2964. // to reject based on this during classification). If we then make sure to
  2965. // order the match kinds appropriately (putting mnemonics last), then we
  2966. // should only end up using a few bits for each class, especially the ones
  2967. // following the mnemonic.
  2968. OS << "namespace {\n";
  2969. OS << " struct MatchEntry {\n";
  2970. OS << " " << getMinimalTypeForRange(MaxMnemonicIndex)
  2971. << " Mnemonic;\n";
  2972. OS << " uint16_t Opcode;\n";
  2973. OS << " " << getMinimalTypeForRange(NumConverters)
  2974. << " ConvertFn;\n";
  2975. OS << " " << getMinimalTypeForRange(FeatureBitsets.size())
  2976. << " RequiredFeaturesIdx;\n";
  2977. OS << " " << getMinimalTypeForRange(
  2978. std::distance(Info.Classes.begin(), Info.Classes.end()))
  2979. << " Classes[" << MaxNumOperands << "];\n";
  2980. OS << " StringRef getMnemonic() const {\n";
  2981. OS << " return StringRef(MnemonicTable + Mnemonic + 1,\n";
  2982. OS << " MnemonicTable[Mnemonic]);\n";
  2983. OS << " }\n";
  2984. OS << " };\n\n";
  2985. OS << " // Predicate for searching for an opcode.\n";
  2986. OS << " struct LessOpcode {\n";
  2987. OS << " bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
  2988. OS << " return LHS.getMnemonic() < RHS;\n";
  2989. OS << " }\n";
  2990. OS << " bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
  2991. OS << " return LHS < RHS.getMnemonic();\n";
  2992. OS << " }\n";
  2993. OS << " bool operator()(const MatchEntry &LHS, const MatchEntry &RHS) {\n";
  2994. OS << " return LHS.getMnemonic() < RHS.getMnemonic();\n";
  2995. OS << " }\n";
  2996. OS << " };\n";
  2997. OS << "} // end anonymous namespace\n\n";
  2998. unsigned VariantCount = Target.getAsmParserVariantCount();
  2999. for (unsigned VC = 0; VC != VariantCount; ++VC) {
  3000. Record *AsmVariant = Target.getAsmParserVariant(VC);
  3001. int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
  3002. OS << "static const MatchEntry MatchTable" << VC << "[] = {\n";
  3003. for (const auto &MI : Info.Matchables) {
  3004. if (MI->AsmVariantID != AsmVariantNo)
  3005. continue;
  3006. // Store a pascal-style length byte in the mnemonic.
  3007. std::string LenMnemonic =
  3008. char(MI->Mnemonic.size()) + MI->Mnemonic.lower();
  3009. OS << " { " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
  3010. << " /* " << MI->Mnemonic << " */, "
  3011. << Target.getInstNamespace() << "::"
  3012. << MI->getResultInst()->TheDef->getName() << ", "
  3013. << MI->ConversionFnKind << ", ";
  3014. // Write the required features mask.
  3015. OS << "AMFBS";
  3016. if (MI->RequiredFeatures.empty())
  3017. OS << "_None";
  3018. else
  3019. for (unsigned i = 0, e = MI->RequiredFeatures.size(); i != e; ++i)
  3020. OS << '_' << MI->RequiredFeatures[i]->TheDef->getName();
  3021. OS << ", { ";
  3022. for (unsigned i = 0, e = MI->AsmOperands.size(); i != e; ++i) {
  3023. const MatchableInfo::AsmOperand &Op = MI->AsmOperands[i];
  3024. if (i) OS << ", ";
  3025. OS << Op.Class->Name;
  3026. }
  3027. OS << " }, },\n";
  3028. }
  3029. OS << "};\n\n";
  3030. }
  3031. OS << "#include \"llvm/Support/Debug.h\"\n";
  3032. OS << "#include \"llvm/Support/Format.h\"\n\n";
  3033. // Finally, build the match function.
  3034. OS << "unsigned " << Target.getName() << ClassName << "::\n"
  3035. << "MatchInstructionImpl(const OperandVector &Operands,\n";
  3036. OS << " MCInst &Inst,\n";
  3037. if (ReportMultipleNearMisses)
  3038. OS << " SmallVectorImpl<NearMissInfo> *NearMisses,\n";
  3039. else
  3040. OS << " uint64_t &ErrorInfo,\n"
  3041. << " FeatureBitset &MissingFeatures,\n";
  3042. OS << " bool matchingInlineAsm, unsigned VariantID) {\n";
  3043. if (!ReportMultipleNearMisses) {
  3044. OS << " // Eliminate obvious mismatches.\n";
  3045. OS << " if (Operands.size() > "
  3046. << (MaxNumOperands + HasMnemonicFirst) << ") {\n";
  3047. OS << " ErrorInfo = "
  3048. << (MaxNumOperands + HasMnemonicFirst) << ";\n";
  3049. OS << " return Match_InvalidOperand;\n";
  3050. OS << " }\n\n";
  3051. }
  3052. // Emit code to get the available features.
  3053. OS << " // Get the current feature set.\n";
  3054. OS << " const FeatureBitset &AvailableFeatures = getAvailableFeatures();\n\n";
  3055. OS << " // Get the instruction mnemonic, which is the first token.\n";
  3056. if (HasMnemonicFirst) {
  3057. OS << " StringRef Mnemonic = ((" << Target.getName()
  3058. << "Operand &)*Operands[0]).getToken();\n\n";
  3059. } else {
  3060. OS << " StringRef Mnemonic;\n";
  3061. OS << " if (Operands[0]->isToken())\n";
  3062. OS << " Mnemonic = ((" << Target.getName()
  3063. << "Operand &)*Operands[0]).getToken();\n\n";
  3064. }
  3065. if (HasMnemonicAliases) {
  3066. OS << " // Process all MnemonicAliases to remap the mnemonic.\n";
  3067. OS << " applyMnemonicAliases(Mnemonic, AvailableFeatures, VariantID);\n\n";
  3068. }
  3069. // Emit code to compute the class list for this operand vector.
  3070. if (!ReportMultipleNearMisses) {
  3071. OS << " // Some state to try to produce better error messages.\n";
  3072. OS << " bool HadMatchOtherThanFeatures = false;\n";
  3073. OS << " bool HadMatchOtherThanPredicate = false;\n";
  3074. OS << " unsigned RetCode = Match_InvalidOperand;\n";
  3075. OS << " MissingFeatures.set();\n";
  3076. OS << " // Set ErrorInfo to the operand that mismatches if it is\n";
  3077. OS << " // wrong for all instances of the instruction.\n";
  3078. OS << " ErrorInfo = ~0ULL;\n";
  3079. }
  3080. if (HasOptionalOperands) {
  3081. OS << " SmallBitVector OptionalOperandsMask(" << MaxNumOperands << ");\n";
  3082. }
  3083. // Emit code to search the table.
  3084. OS << " // Find the appropriate table for this asm variant.\n";
  3085. OS << " const MatchEntry *Start, *End;\n";
  3086. OS << " switch (VariantID) {\n";
  3087. OS << " default: llvm_unreachable(\"invalid variant!\");\n";
  3088. for (unsigned VC = 0; VC != VariantCount; ++VC) {
  3089. Record *AsmVariant = Target.getAsmParserVariant(VC);
  3090. int AsmVariantNo = AsmVariant->getValueAsInt("Variant");
  3091. OS << " case " << AsmVariantNo << ": Start = std::begin(MatchTable" << VC
  3092. << "); End = std::end(MatchTable" << VC << "); break;\n";
  3093. }
  3094. OS << " }\n";
  3095. OS << " // Search the table.\n";
  3096. if (HasMnemonicFirst) {
  3097. OS << " auto MnemonicRange = "
  3098. "std::equal_range(Start, End, Mnemonic, LessOpcode());\n\n";
  3099. } else {
  3100. OS << " auto MnemonicRange = std::make_pair(Start, End);\n";
  3101. OS << " unsigned SIndex = Mnemonic.empty() ? 0 : 1;\n";
  3102. OS << " if (!Mnemonic.empty())\n";
  3103. OS << " MnemonicRange = "
  3104. "std::equal_range(Start, End, Mnemonic.lower(), LessOpcode());\n\n";
  3105. }
  3106. OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"AsmMatcher: found \" <<\n"
  3107. << " std::distance(MnemonicRange.first, MnemonicRange.second) <<\n"
  3108. << " \" encodings with mnemonic '\" << Mnemonic << \"'\\n\");\n\n";
  3109. OS << " // Return a more specific error code if no mnemonics match.\n";
  3110. OS << " if (MnemonicRange.first == MnemonicRange.second)\n";
  3111. OS << " return Match_MnemonicFail;\n\n";
  3112. OS << " for (const MatchEntry *it = MnemonicRange.first, "
  3113. << "*ie = MnemonicRange.second;\n";
  3114. OS << " it != ie; ++it) {\n";
  3115. OS << " const FeatureBitset &RequiredFeatures = "
  3116. "FeatureBitsets[it->RequiredFeaturesIdx];\n";
  3117. OS << " bool HasRequiredFeatures =\n";
  3118. OS << " (AvailableFeatures & RequiredFeatures) == RequiredFeatures;\n";
  3119. OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Trying to match opcode \"\n";
  3120. OS << " << MII.getName(it->Opcode) << \"\\n\");\n";
  3121. if (ReportMultipleNearMisses) {
  3122. OS << " // Some state to record ways in which this instruction did not match.\n";
  3123. OS << " NearMissInfo OperandNearMiss = NearMissInfo::getSuccess();\n";
  3124. OS << " NearMissInfo FeaturesNearMiss = NearMissInfo::getSuccess();\n";
  3125. OS << " NearMissInfo EarlyPredicateNearMiss = NearMissInfo::getSuccess();\n";
  3126. OS << " NearMissInfo LatePredicateNearMiss = NearMissInfo::getSuccess();\n";
  3127. OS << " bool MultipleInvalidOperands = false;\n";
  3128. }
  3129. if (HasMnemonicFirst) {
  3130. OS << " // equal_range guarantees that instruction mnemonic matches.\n";
  3131. OS << " assert(Mnemonic == it->getMnemonic());\n";
  3132. }
  3133. // Emit check that the subclasses match.
  3134. if (!ReportMultipleNearMisses)
  3135. OS << " bool OperandsValid = true;\n";
  3136. if (HasOptionalOperands) {
  3137. OS << " OptionalOperandsMask.reset(0, " << MaxNumOperands << ");\n";
  3138. }
  3139. OS << " for (unsigned FormalIdx = " << (HasMnemonicFirst ? "0" : "SIndex")
  3140. << ", ActualIdx = " << (HasMnemonicFirst ? "1" : "SIndex")
  3141. << "; FormalIdx != " << MaxNumOperands << "; ++FormalIdx) {\n";
  3142. OS << " auto Formal = "
  3143. << "static_cast<MatchClassKind>(it->Classes[FormalIdx]);\n";
  3144. OS << " DEBUG_WITH_TYPE(\"asm-matcher\",\n";
  3145. OS << " dbgs() << \" Matching formal operand class \" << getMatchClassName(Formal)\n";
  3146. OS << " << \" against actual operand at index \" << ActualIdx);\n";
  3147. OS << " if (ActualIdx < Operands.size())\n";
  3148. OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \" (\";\n";
  3149. OS << " Operands[ActualIdx]->print(dbgs()); dbgs() << \"): \");\n";
  3150. OS << " else\n";
  3151. OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \": \");\n";
  3152. OS << " if (ActualIdx >= Operands.size()) {\n";
  3153. OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"actual operand index out of range \");\n";
  3154. if (ReportMultipleNearMisses) {
  3155. OS << " bool ThisOperandValid = (Formal == " <<"InvalidMatchClass) || "
  3156. "isSubclass(Formal, OptionalMatchClass);\n";
  3157. OS << " if (!ThisOperandValid) {\n";
  3158. OS << " if (!OperandNearMiss) {\n";
  3159. OS << " // Record info about match failure for later use.\n";
  3160. OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"recording too-few-operands near miss\\n\");\n";
  3161. OS << " OperandNearMiss =\n";
  3162. OS << " NearMissInfo::getTooFewOperands(Formal, it->Opcode);\n";
  3163. OS << " } else if (OperandNearMiss.getKind() != NearMissInfo::NearMissTooFewOperands) {\n";
  3164. OS << " // If more than one operand is invalid, give up on this match entry.\n";
  3165. OS << " DEBUG_WITH_TYPE(\n";
  3166. OS << " \"asm-matcher\",\n";
  3167. OS << " dbgs() << \"second invalid operand, giving up on this opcode\\n\");\n";
  3168. OS << " MultipleInvalidOperands = true;\n";
  3169. OS << " break;\n";
  3170. OS << " }\n";
  3171. OS << " } else {\n";
  3172. OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"but formal operand not required\\n\");\n";
  3173. OS << " break;\n";
  3174. OS << " }\n";
  3175. OS << " continue;\n";
  3176. } else {
  3177. OS << " OperandsValid = (Formal == InvalidMatchClass) || isSubclass(Formal, OptionalMatchClass);\n";
  3178. OS << " if (!OperandsValid) ErrorInfo = ActualIdx;\n";
  3179. if (HasOptionalOperands) {
  3180. OS << " OptionalOperandsMask.set(FormalIdx, " << MaxNumOperands
  3181. << ");\n";
  3182. }
  3183. OS << " break;\n";
  3184. }
  3185. OS << " }\n";
  3186. OS << " MCParsedAsmOperand &Actual = *Operands[ActualIdx];\n";
  3187. OS << " unsigned Diag = validateOperandClass(Actual, Formal);\n";
  3188. OS << " if (Diag == Match_Success) {\n";
  3189. OS << " DEBUG_WITH_TYPE(\"asm-matcher\",\n";
  3190. OS << " dbgs() << \"match success using generic matcher\\n\");\n";
  3191. OS << " ++ActualIdx;\n";
  3192. OS << " continue;\n";
  3193. OS << " }\n";
  3194. OS << " // If the generic handler indicates an invalid operand\n";
  3195. OS << " // failure, check for a special case.\n";
  3196. OS << " if (Diag != Match_Success) {\n";
  3197. OS << " unsigned TargetDiag = validateTargetOperandClass(Actual, Formal);\n";
  3198. OS << " if (TargetDiag == Match_Success) {\n";
  3199. OS << " DEBUG_WITH_TYPE(\"asm-matcher\",\n";
  3200. OS << " dbgs() << \"match success using target matcher\\n\");\n";
  3201. OS << " ++ActualIdx;\n";
  3202. OS << " continue;\n";
  3203. OS << " }\n";
  3204. OS << " // If the target matcher returned a specific error code use\n";
  3205. OS << " // that, else use the one from the generic matcher.\n";
  3206. OS << " if (TargetDiag != Match_InvalidOperand && "
  3207. "HasRequiredFeatures)\n";
  3208. OS << " Diag = TargetDiag;\n";
  3209. OS << " }\n";
  3210. OS << " // If current formal operand wasn't matched and it is optional\n"
  3211. << " // then try to match next formal operand\n";
  3212. OS << " if (Diag == Match_InvalidOperand "
  3213. << "&& isSubclass(Formal, OptionalMatchClass)) {\n";
  3214. if (HasOptionalOperands) {
  3215. OS << " OptionalOperandsMask.set(FormalIdx);\n";
  3216. }
  3217. OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"ignoring optional operand\\n\");\n";
  3218. OS << " continue;\n";
  3219. OS << " }\n";
  3220. if (ReportMultipleNearMisses) {
  3221. OS << " if (!OperandNearMiss) {\n";
  3222. OS << " // If this is the first invalid operand we have seen, record some\n";
  3223. OS << " // information about it.\n";
  3224. OS << " DEBUG_WITH_TYPE(\n";
  3225. OS << " \"asm-matcher\",\n";
  3226. OS << " dbgs()\n";
  3227. OS << " << \"operand match failed, recording near-miss with diag code \"\n";
  3228. OS << " << Diag << \"\\n\");\n";
  3229. OS << " OperandNearMiss =\n";
  3230. OS << " NearMissInfo::getMissedOperand(Diag, Formal, it->Opcode, ActualIdx);\n";
  3231. OS << " ++ActualIdx;\n";
  3232. OS << " } else {\n";
  3233. OS << " // If more than one operand is invalid, give up on this match entry.\n";
  3234. OS << " DEBUG_WITH_TYPE(\n";
  3235. OS << " \"asm-matcher\",\n";
  3236. OS << " dbgs() << \"second operand mismatch, skipping this opcode\\n\");\n";
  3237. OS << " MultipleInvalidOperands = true;\n";
  3238. OS << " break;\n";
  3239. OS << " }\n";
  3240. OS << " }\n\n";
  3241. } else {
  3242. OS << " // If this operand is broken for all of the instances of this\n";
  3243. OS << " // mnemonic, keep track of it so we can report loc info.\n";
  3244. OS << " // If we already had a match that only failed due to a\n";
  3245. OS << " // target predicate, that diagnostic is preferred.\n";
  3246. OS << " if (!HadMatchOtherThanPredicate &&\n";
  3247. OS << " (it == MnemonicRange.first || ErrorInfo <= ActualIdx)) {\n";
  3248. OS << " if (HasRequiredFeatures && (ErrorInfo != ActualIdx || Diag "
  3249. "!= Match_InvalidOperand))\n";
  3250. OS << " RetCode = Diag;\n";
  3251. OS << " ErrorInfo = ActualIdx;\n";
  3252. OS << " }\n";
  3253. OS << " // Otherwise, just reject this instance of the mnemonic.\n";
  3254. OS << " OperandsValid = false;\n";
  3255. OS << " break;\n";
  3256. OS << " }\n\n";
  3257. }
  3258. if (ReportMultipleNearMisses)
  3259. OS << " if (MultipleInvalidOperands) {\n";
  3260. else
  3261. OS << " if (!OperandsValid) {\n";
  3262. OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: multiple \"\n";
  3263. OS << " \"operand mismatches, ignoring \"\n";
  3264. OS << " \"this opcode\\n\");\n";
  3265. OS << " continue;\n";
  3266. OS << " }\n";
  3267. // Emit check that the required features are available.
  3268. OS << " if (!HasRequiredFeatures) {\n";
  3269. if (!ReportMultipleNearMisses)
  3270. OS << " HadMatchOtherThanFeatures = true;\n";
  3271. OS << " FeatureBitset NewMissingFeatures = RequiredFeatures & "
  3272. "~AvailableFeatures;\n";
  3273. OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Missing target features:\";\n";
  3274. OS << " for (unsigned I = 0, E = NewMissingFeatures.size(); I != E; ++I)\n";
  3275. OS << " if (NewMissingFeatures[I])\n";
  3276. OS << " dbgs() << ' ' << I;\n";
  3277. OS << " dbgs() << \"\\n\");\n";
  3278. if (ReportMultipleNearMisses) {
  3279. OS << " FeaturesNearMiss = NearMissInfo::getMissedFeature(NewMissingFeatures);\n";
  3280. } else {
  3281. OS << " if (NewMissingFeatures.count() <=\n"
  3282. " MissingFeatures.count())\n";
  3283. OS << " MissingFeatures = NewMissingFeatures;\n";
  3284. OS << " continue;\n";
  3285. }
  3286. OS << " }\n";
  3287. OS << "\n";
  3288. OS << " Inst.clear();\n\n";
  3289. OS << " Inst.setOpcode(it->Opcode);\n";
  3290. // Verify the instruction with the target-specific match predicate function.
  3291. OS << " // We have a potential match but have not rendered the operands.\n"
  3292. << " // Check the target predicate to handle any context sensitive\n"
  3293. " // constraints.\n"
  3294. << " // For example, Ties that are referenced multiple times must be\n"
  3295. " // checked here to ensure the input is the same for each match\n"
  3296. " // constraints. If we leave it any later the ties will have been\n"
  3297. " // canonicalized\n"
  3298. << " unsigned MatchResult;\n"
  3299. << " if ((MatchResult = checkEarlyTargetMatchPredicate(Inst, "
  3300. "Operands)) != Match_Success) {\n"
  3301. << " Inst.clear();\n";
  3302. OS << " DEBUG_WITH_TYPE(\n";
  3303. OS << " \"asm-matcher\",\n";
  3304. OS << " dbgs() << \"Early target match predicate failed with diag code \"\n";
  3305. OS << " << MatchResult << \"\\n\");\n";
  3306. if (ReportMultipleNearMisses) {
  3307. OS << " EarlyPredicateNearMiss = NearMissInfo::getMissedPredicate(MatchResult);\n";
  3308. } else {
  3309. OS << " RetCode = MatchResult;\n"
  3310. << " HadMatchOtherThanPredicate = true;\n"
  3311. << " continue;\n";
  3312. }
  3313. OS << " }\n\n";
  3314. if (ReportMultipleNearMisses) {
  3315. OS << " // If we did not successfully match the operands, then we can't convert to\n";
  3316. OS << " // an MCInst, so bail out on this instruction variant now.\n";
  3317. OS << " if (OperandNearMiss) {\n";
  3318. OS << " // If the operand mismatch was the only problem, reprrt it as a near-miss.\n";
  3319. OS << " if (NearMisses && !FeaturesNearMiss && !EarlyPredicateNearMiss) {\n";
  3320. OS << " DEBUG_WITH_TYPE(\n";
  3321. OS << " \"asm-matcher\",\n";
  3322. OS << " dbgs()\n";
  3323. OS << " << \"Opcode result: one mismatched operand, adding near-miss\\n\");\n";
  3324. OS << " NearMisses->push_back(OperandNearMiss);\n";
  3325. OS << " } else {\n";
  3326. OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: multiple \"\n";
  3327. OS << " \"types of mismatch, so not \"\n";
  3328. OS << " \"reporting near-miss\\n\");\n";
  3329. OS << " }\n";
  3330. OS << " continue;\n";
  3331. OS << " }\n\n";
  3332. }
  3333. OS << " if (matchingInlineAsm) {\n";
  3334. OS << " convertToMapAndConstraints(it->ConvertFn, Operands);\n";
  3335. if (!ReportMultipleNearMisses) {
  3336. OS << " if (!checkAsmTiedOperandConstraints(*this, it->ConvertFn, "
  3337. "Operands, ErrorInfo))\n";
  3338. OS << " return Match_InvalidTiedOperand;\n";
  3339. OS << "\n";
  3340. }
  3341. OS << " return Match_Success;\n";
  3342. OS << " }\n\n";
  3343. OS << " // We have selected a definite instruction, convert the parsed\n"
  3344. << " // operands into the appropriate MCInst.\n";
  3345. if (HasOptionalOperands) {
  3346. OS << " convertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands,\n"
  3347. << " OptionalOperandsMask);\n";
  3348. } else {
  3349. OS << " convertToMCInst(it->ConvertFn, Inst, it->Opcode, Operands);\n";
  3350. }
  3351. OS << "\n";
  3352. // Verify the instruction with the target-specific match predicate function.
  3353. OS << " // We have a potential match. Check the target predicate to\n"
  3354. << " // handle any context sensitive constraints.\n"
  3355. << " if ((MatchResult = checkTargetMatchPredicate(Inst)) !="
  3356. << " Match_Success) {\n"
  3357. << " DEBUG_WITH_TYPE(\"asm-matcher\",\n"
  3358. << " dbgs() << \"Target match predicate failed with diag code \"\n"
  3359. << " << MatchResult << \"\\n\");\n"
  3360. << " Inst.clear();\n";
  3361. if (ReportMultipleNearMisses) {
  3362. OS << " LatePredicateNearMiss = NearMissInfo::getMissedPredicate(MatchResult);\n";
  3363. } else {
  3364. OS << " RetCode = MatchResult;\n"
  3365. << " HadMatchOtherThanPredicate = true;\n"
  3366. << " continue;\n";
  3367. }
  3368. OS << " }\n\n";
  3369. if (ReportMultipleNearMisses) {
  3370. OS << " int NumNearMisses = ((int)(bool)OperandNearMiss +\n";
  3371. OS << " (int)(bool)FeaturesNearMiss +\n";
  3372. OS << " (int)(bool)EarlyPredicateNearMiss +\n";
  3373. OS << " (int)(bool)LatePredicateNearMiss);\n";
  3374. OS << " if (NumNearMisses == 1) {\n";
  3375. OS << " // We had exactly one type of near-miss, so add that to the list.\n";
  3376. OS << " assert(!OperandNearMiss && \"OperandNearMiss was handled earlier\");\n";
  3377. OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: found one type of \"\n";
  3378. OS << " \"mismatch, so reporting a \"\n";
  3379. OS << " \"near-miss\\n\");\n";
  3380. OS << " if (NearMisses && FeaturesNearMiss)\n";
  3381. OS << " NearMisses->push_back(FeaturesNearMiss);\n";
  3382. OS << " else if (NearMisses && EarlyPredicateNearMiss)\n";
  3383. OS << " NearMisses->push_back(EarlyPredicateNearMiss);\n";
  3384. OS << " else if (NearMisses && LatePredicateNearMiss)\n";
  3385. OS << " NearMisses->push_back(LatePredicateNearMiss);\n";
  3386. OS << "\n";
  3387. OS << " continue;\n";
  3388. OS << " } else if (NumNearMisses > 1) {\n";
  3389. OS << " // This instruction missed in more than one way, so ignore it.\n";
  3390. OS << " DEBUG_WITH_TYPE(\"asm-matcher\", dbgs() << \"Opcode result: multiple \"\n";
  3391. OS << " \"types of mismatch, so not \"\n";
  3392. OS << " \"reporting near-miss\\n\");\n";
  3393. OS << " continue;\n";
  3394. OS << " }\n";
  3395. }
  3396. // Call the post-processing function, if used.
  3397. StringRef InsnCleanupFn = AsmParser->getValueAsString("AsmParserInstCleanup");
  3398. if (!InsnCleanupFn.empty())
  3399. OS << " " << InsnCleanupFn << "(Inst);\n";
  3400. if (HasDeprecation) {
  3401. OS << " std::string Info;\n";
  3402. OS << " if (!getParser().getTargetParser().\n";
  3403. OS << " getTargetOptions().MCNoDeprecatedWarn &&\n";
  3404. OS << " MII.getDeprecatedInfo(Inst, getSTI(), Info)) {\n";
  3405. OS << " SMLoc Loc = ((" << Target.getName()
  3406. << "Operand &)*Operands[0]).getStartLoc();\n";
  3407. OS << " getParser().Warning(Loc, Info, None);\n";
  3408. OS << " }\n";
  3409. }
  3410. if (!ReportMultipleNearMisses) {
  3411. OS << " if (!checkAsmTiedOperandConstraints(*this, it->ConvertFn, "
  3412. "Operands, ErrorInfo))\n";
  3413. OS << " return Match_InvalidTiedOperand;\n";
  3414. OS << "\n";
  3415. }
  3416. OS << " DEBUG_WITH_TYPE(\n";
  3417. OS << " \"asm-matcher\",\n";
  3418. OS << " dbgs() << \"Opcode result: complete match, selecting this opcode\\n\");\n";
  3419. OS << " return Match_Success;\n";
  3420. OS << " }\n\n";
  3421. if (ReportMultipleNearMisses) {
  3422. OS << " // No instruction variants matched exactly.\n";
  3423. OS << " return Match_NearMisses;\n";
  3424. } else {
  3425. OS << " // Okay, we had no match. Try to return a useful error code.\n";
  3426. OS << " if (HadMatchOtherThanPredicate || !HadMatchOtherThanFeatures)\n";
  3427. OS << " return RetCode;\n\n";
  3428. OS << " ErrorInfo = 0;\n";
  3429. OS << " return Match_MissingFeature;\n";
  3430. }
  3431. OS << "}\n\n";
  3432. if (!Info.OperandMatchInfo.empty())
  3433. emitCustomOperandParsing(OS, Target, Info, ClassName, StringTable,
  3434. MaxMnemonicIndex, FeatureBitsets.size(),
  3435. HasMnemonicFirst);
  3436. OS << "#endif // GET_MATCHER_IMPLEMENTATION\n\n";
  3437. OS << "\n#ifdef GET_MNEMONIC_SPELL_CHECKER\n";
  3438. OS << "#undef GET_MNEMONIC_SPELL_CHECKER\n\n";
  3439. emitMnemonicSpellChecker(OS, Target, VariantCount);
  3440. OS << "#endif // GET_MNEMONIC_SPELL_CHECKER\n\n";
  3441. OS << "\n#ifdef GET_MNEMONIC_CHECKER\n";
  3442. OS << "#undef GET_MNEMONIC_CHECKER\n\n";
  3443. emitMnemonicChecker(OS, Target, VariantCount,
  3444. HasMnemonicFirst, HasMnemonicAliases);
  3445. OS << "#endif // GET_MNEMONIC_CHECKER\n\n";
  3446. }
  3447. namespace llvm {
  3448. void EmitAsmMatcher(RecordKeeper &RK, raw_ostream &OS) {
  3449. emitSourceFileHeader("Assembly Matcher Source Fragment", OS);
  3450. AsmMatcherEmitter(RK).run(OS);
  3451. }
  3452. } // end namespace llvm