AsmMatcherEmitter.cpp 153 KB

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