FixedLenDecoderEmitter.cpp 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226
  1. //===------------ FixedLenDecoderEmitter.cpp - Decoder Generator ----------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // It contains the tablegen backend that emits the decoder functions for
  11. // targets with fixed length instruction set.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "CodeGenTarget.h"
  15. #include "llvm/ADT/APInt.h"
  16. #include "llvm/ADT/SmallString.h"
  17. #include "llvm/ADT/StringExtras.h"
  18. #include "llvm/ADT/StringRef.h"
  19. #include "llvm/ADT/Twine.h"
  20. #include "llvm/MC/MCFixedLenDisassembler.h"
  21. #include "llvm/Support/DataTypes.h"
  22. #include "llvm/Support/Debug.h"
  23. #include "llvm/Support/FormattedStream.h"
  24. #include "llvm/Support/LEB128.h"
  25. #include "llvm/Support/raw_ostream.h"
  26. #include "llvm/TableGen/Error.h"
  27. #include "llvm/TableGen/Record.h"
  28. #include <map>
  29. #include <string>
  30. #include <vector>
  31. using namespace llvm;
  32. #define DEBUG_TYPE "decoder-emitter"
  33. namespace {
  34. struct EncodingField {
  35. unsigned Base, Width, Offset;
  36. EncodingField(unsigned B, unsigned W, unsigned O)
  37. : Base(B), Width(W), Offset(O) { }
  38. };
  39. struct OperandInfo {
  40. std::vector<EncodingField> Fields;
  41. std::string Decoder;
  42. OperandInfo(std::string D)
  43. : Decoder(D) { }
  44. void addField(unsigned Base, unsigned Width, unsigned Offset) {
  45. Fields.push_back(EncodingField(Base, Width, Offset));
  46. }
  47. unsigned numFields() const { return Fields.size(); }
  48. typedef std::vector<EncodingField>::const_iterator const_iterator;
  49. const_iterator begin() const { return Fields.begin(); }
  50. const_iterator end() const { return Fields.end(); }
  51. };
  52. typedef std::vector<uint8_t> DecoderTable;
  53. typedef uint32_t DecoderFixup;
  54. typedef std::vector<DecoderFixup> FixupList;
  55. typedef std::vector<FixupList> FixupScopeList;
  56. typedef SetVector<std::string> PredicateSet;
  57. typedef SetVector<std::string> DecoderSet;
  58. struct DecoderTableInfo {
  59. DecoderTable Table;
  60. FixupScopeList FixupStack;
  61. PredicateSet Predicates;
  62. DecoderSet Decoders;
  63. };
  64. } // End anonymous namespace
  65. namespace {
  66. class FixedLenDecoderEmitter {
  67. const std::vector<const CodeGenInstruction*> *NumberedInstructions;
  68. public:
  69. // Defaults preserved here for documentation, even though they aren't
  70. // strictly necessary given the way that this is currently being called.
  71. FixedLenDecoderEmitter(RecordKeeper &R,
  72. std::string PredicateNamespace,
  73. std::string GPrefix = "if (",
  74. std::string GPostfix = " == MCDisassembler::Fail)"
  75. " return MCDisassembler::Fail;",
  76. std::string ROK = "MCDisassembler::Success",
  77. std::string RFail = "MCDisassembler::Fail",
  78. std::string L = "") :
  79. Target(R),
  80. PredicateNamespace(PredicateNamespace),
  81. GuardPrefix(GPrefix), GuardPostfix(GPostfix),
  82. ReturnOK(ROK), ReturnFail(RFail), Locals(L) {}
  83. // Emit the decoder state machine table.
  84. void emitTable(formatted_raw_ostream &o, DecoderTable &Table,
  85. unsigned Indentation, unsigned BitWidth,
  86. StringRef Namespace) const;
  87. void emitPredicateFunction(formatted_raw_ostream &OS,
  88. PredicateSet &Predicates,
  89. unsigned Indentation) const;
  90. void emitDecoderFunction(formatted_raw_ostream &OS,
  91. DecoderSet &Decoders,
  92. unsigned Indentation) const;
  93. // run - Output the code emitter
  94. void run(raw_ostream &o);
  95. private:
  96. CodeGenTarget Target;
  97. public:
  98. std::string PredicateNamespace;
  99. std::string GuardPrefix, GuardPostfix;
  100. std::string ReturnOK, ReturnFail;
  101. std::string Locals;
  102. };
  103. } // End anonymous namespace
  104. // The set (BIT_TRUE, BIT_FALSE, BIT_UNSET) represents a ternary logic system
  105. // for a bit value.
  106. //
  107. // BIT_UNFILTERED is used as the init value for a filter position. It is used
  108. // only for filter processings.
  109. typedef enum {
  110. BIT_TRUE, // '1'
  111. BIT_FALSE, // '0'
  112. BIT_UNSET, // '?'
  113. BIT_UNFILTERED // unfiltered
  114. } bit_value_t;
  115. static bool ValueSet(bit_value_t V) {
  116. return (V == BIT_TRUE || V == BIT_FALSE);
  117. }
  118. static bool ValueNotSet(bit_value_t V) {
  119. return (V == BIT_UNSET);
  120. }
  121. static int Value(bit_value_t V) {
  122. return ValueNotSet(V) ? -1 : (V == BIT_FALSE ? 0 : 1);
  123. }
  124. static bit_value_t bitFromBits(const BitsInit &bits, unsigned index) {
  125. if (BitInit *bit = dyn_cast<BitInit>(bits.getBit(index)))
  126. return bit->getValue() ? BIT_TRUE : BIT_FALSE;
  127. // The bit is uninitialized.
  128. return BIT_UNSET;
  129. }
  130. // Prints the bit value for each position.
  131. static void dumpBits(raw_ostream &o, const BitsInit &bits) {
  132. for (unsigned index = bits.getNumBits(); index > 0; --index) {
  133. switch (bitFromBits(bits, index - 1)) {
  134. case BIT_TRUE:
  135. o << "1";
  136. break;
  137. case BIT_FALSE:
  138. o << "0";
  139. break;
  140. case BIT_UNSET:
  141. o << "_";
  142. break;
  143. default:
  144. llvm_unreachable("unexpected return value from bitFromBits");
  145. }
  146. }
  147. }
  148. static BitsInit &getBitsField(const Record &def, const char *str) {
  149. BitsInit *bits = def.getValueAsBitsInit(str);
  150. return *bits;
  151. }
  152. // Forward declaration.
  153. namespace {
  154. class FilterChooser;
  155. } // End anonymous namespace
  156. // Representation of the instruction to work on.
  157. typedef std::vector<bit_value_t> insn_t;
  158. /// Filter - Filter works with FilterChooser to produce the decoding tree for
  159. /// the ISA.
  160. ///
  161. /// It is useful to think of a Filter as governing the switch stmts of the
  162. /// decoding tree in a certain level. Each case stmt delegates to an inferior
  163. /// FilterChooser to decide what further decoding logic to employ, or in another
  164. /// words, what other remaining bits to look at. The FilterChooser eventually
  165. /// chooses a best Filter to do its job.
  166. ///
  167. /// This recursive scheme ends when the number of Opcodes assigned to the
  168. /// FilterChooser becomes 1 or if there is a conflict. A conflict happens when
  169. /// the Filter/FilterChooser combo does not know how to distinguish among the
  170. /// Opcodes assigned.
  171. ///
  172. /// An example of a conflict is
  173. ///
  174. /// Conflict:
  175. /// 111101000.00........00010000....
  176. /// 111101000.00........0001........
  177. /// 1111010...00........0001........
  178. /// 1111010...00....................
  179. /// 1111010.........................
  180. /// 1111............................
  181. /// ................................
  182. /// VST4q8a 111101000_00________00010000____
  183. /// VST4q8b 111101000_00________00010000____
  184. ///
  185. /// The Debug output shows the path that the decoding tree follows to reach the
  186. /// the conclusion that there is a conflict. VST4q8a is a vst4 to double-spaced
  187. /// even registers, while VST4q8b is a vst4 to double-spaced odd registers.
  188. ///
  189. /// The encoding info in the .td files does not specify this meta information,
  190. /// which could have been used by the decoder to resolve the conflict. The
  191. /// decoder could try to decode the even/odd register numbering and assign to
  192. /// VST4q8a or VST4q8b, but for the time being, the decoder chooses the "a"
  193. /// version and return the Opcode since the two have the same Asm format string.
  194. namespace {
  195. class Filter {
  196. protected:
  197. const FilterChooser *Owner;// points to the FilterChooser who owns this filter
  198. unsigned StartBit; // the starting bit position
  199. unsigned NumBits; // number of bits to filter
  200. bool Mixed; // a mixed region contains both set and unset bits
  201. // Map of well-known segment value to the set of uid's with that value.
  202. std::map<uint64_t, std::vector<unsigned> > FilteredInstructions;
  203. // Set of uid's with non-constant segment values.
  204. std::vector<unsigned> VariableInstructions;
  205. // Map of well-known segment value to its delegate.
  206. std::map<unsigned, std::unique_ptr<const FilterChooser>> FilterChooserMap;
  207. // Number of instructions which fall under FilteredInstructions category.
  208. unsigned NumFiltered;
  209. // Keeps track of the last opcode in the filtered bucket.
  210. unsigned LastOpcFiltered;
  211. public:
  212. unsigned getNumFiltered() const { return NumFiltered; }
  213. unsigned getSingletonOpc() const {
  214. assert(NumFiltered == 1);
  215. return LastOpcFiltered;
  216. }
  217. // Return the filter chooser for the group of instructions without constant
  218. // segment values.
  219. const FilterChooser &getVariableFC() const {
  220. assert(NumFiltered == 1);
  221. assert(FilterChooserMap.size() == 1);
  222. return *(FilterChooserMap.find((unsigned)-1)->second);
  223. }
  224. Filter(Filter &&f);
  225. Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, bool mixed);
  226. ~Filter();
  227. // Divides the decoding task into sub tasks and delegates them to the
  228. // inferior FilterChooser's.
  229. //
  230. // A special case arises when there's only one entry in the filtered
  231. // instructions. In order to unambiguously decode the singleton, we need to
  232. // match the remaining undecoded encoding bits against the singleton.
  233. void recurse();
  234. // Emit table entries to decode instructions given a segment or segments of
  235. // bits.
  236. void emitTableEntry(DecoderTableInfo &TableInfo) const;
  237. // Returns the number of fanout produced by the filter. More fanout implies
  238. // the filter distinguishes more categories of instructions.
  239. unsigned usefulness() const;
  240. }; // End of class Filter
  241. } // End anonymous namespace
  242. // These are states of our finite state machines used in FilterChooser's
  243. // filterProcessor() which produces the filter candidates to use.
  244. typedef enum {
  245. ATTR_NONE,
  246. ATTR_FILTERED,
  247. ATTR_ALL_SET,
  248. ATTR_ALL_UNSET,
  249. ATTR_MIXED
  250. } bitAttr_t;
  251. /// FilterChooser - FilterChooser chooses the best filter among a set of Filters
  252. /// in order to perform the decoding of instructions at the current level.
  253. ///
  254. /// Decoding proceeds from the top down. Based on the well-known encoding bits
  255. /// of instructions available, FilterChooser builds up the possible Filters that
  256. /// can further the task of decoding by distinguishing among the remaining
  257. /// candidate instructions.
  258. ///
  259. /// Once a filter has been chosen, it is called upon to divide the decoding task
  260. /// into sub-tasks and delegates them to its inferior FilterChoosers for further
  261. /// processings.
  262. ///
  263. /// It is useful to think of a Filter as governing the switch stmts of the
  264. /// decoding tree. And each case is delegated to an inferior FilterChooser to
  265. /// decide what further remaining bits to look at.
  266. namespace {
  267. class FilterChooser {
  268. protected:
  269. friend class Filter;
  270. // Vector of codegen instructions to choose our filter.
  271. const std::vector<const CodeGenInstruction*> &AllInstructions;
  272. // Vector of uid's for this filter chooser to work on.
  273. const std::vector<unsigned> &Opcodes;
  274. // Lookup table for the operand decoding of instructions.
  275. const std::map<unsigned, std::vector<OperandInfo> > &Operands;
  276. // Vector of candidate filters.
  277. std::vector<Filter> Filters;
  278. // Array of bit values passed down from our parent.
  279. // Set to all BIT_UNFILTERED's for Parent == NULL.
  280. std::vector<bit_value_t> FilterBitValues;
  281. // Links to the FilterChooser above us in the decoding tree.
  282. const FilterChooser *Parent;
  283. // Index of the best filter from Filters.
  284. int BestIndex;
  285. // Width of instructions
  286. unsigned BitWidth;
  287. // Parent emitter
  288. const FixedLenDecoderEmitter *Emitter;
  289. FilterChooser(const FilterChooser &) = delete;
  290. void operator=(const FilterChooser &) = delete;
  291. public:
  292. FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
  293. const std::vector<unsigned> &IDs,
  294. const std::map<unsigned, std::vector<OperandInfo> > &Ops,
  295. unsigned BW,
  296. const FixedLenDecoderEmitter *E)
  297. : AllInstructions(Insts), Opcodes(IDs), Operands(Ops), Filters(),
  298. FilterBitValues(BW, BIT_UNFILTERED), Parent(nullptr), BestIndex(-1),
  299. BitWidth(BW), Emitter(E) {
  300. doFilter();
  301. }
  302. FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
  303. const std::vector<unsigned> &IDs,
  304. const std::map<unsigned, std::vector<OperandInfo> > &Ops,
  305. const std::vector<bit_value_t> &ParentFilterBitValues,
  306. const FilterChooser &parent)
  307. : AllInstructions(Insts), Opcodes(IDs), Operands(Ops),
  308. Filters(), FilterBitValues(ParentFilterBitValues),
  309. Parent(&parent), BestIndex(-1), BitWidth(parent.BitWidth),
  310. Emitter(parent.Emitter) {
  311. doFilter();
  312. }
  313. unsigned getBitWidth() const { return BitWidth; }
  314. protected:
  315. // Populates the insn given the uid.
  316. void insnWithID(insn_t &Insn, unsigned Opcode) const {
  317. BitsInit &Bits = getBitsField(*AllInstructions[Opcode]->TheDef, "Inst");
  318. // We may have a SoftFail bitmask, which specifies a mask where an encoding
  319. // may differ from the value in "Inst" and yet still be valid, but the
  320. // disassembler should return SoftFail instead of Success.
  321. //
  322. // This is used for marking UNPREDICTABLE instructions in the ARM world.
  323. BitsInit *SFBits =
  324. AllInstructions[Opcode]->TheDef->getValueAsBitsInit("SoftFail");
  325. for (unsigned i = 0; i < BitWidth; ++i) {
  326. if (SFBits && bitFromBits(*SFBits, i) == BIT_TRUE)
  327. Insn.push_back(BIT_UNSET);
  328. else
  329. Insn.push_back(bitFromBits(Bits, i));
  330. }
  331. }
  332. // Returns the record name.
  333. const std::string &nameWithID(unsigned Opcode) const {
  334. return AllInstructions[Opcode]->TheDef->getName();
  335. }
  336. // Populates the field of the insn given the start position and the number of
  337. // consecutive bits to scan for.
  338. //
  339. // Returns false if there exists any uninitialized bit value in the range.
  340. // Returns true, otherwise.
  341. bool fieldFromInsn(uint64_t &Field, insn_t &Insn, unsigned StartBit,
  342. unsigned NumBits) const;
  343. /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
  344. /// filter array as a series of chars.
  345. void dumpFilterArray(raw_ostream &o,
  346. const std::vector<bit_value_t> & filter) const;
  347. /// dumpStack - dumpStack traverses the filter chooser chain and calls
  348. /// dumpFilterArray on each filter chooser up to the top level one.
  349. void dumpStack(raw_ostream &o, const char *prefix) const;
  350. Filter &bestFilter() {
  351. assert(BestIndex != -1 && "BestIndex not set");
  352. return Filters[BestIndex];
  353. }
  354. // Called from Filter::recurse() when singleton exists. For debug purpose.
  355. //void SingletonExists(unsigned Opc) const; // HLSL Change - Unused
  356. bool PositionFiltered(unsigned i) const {
  357. return ValueSet(FilterBitValues[i]);
  358. }
  359. // Calculates the island(s) needed to decode the instruction.
  360. // This returns a lit of undecoded bits of an instructions, for example,
  361. // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
  362. // decoded bits in order to verify that the instruction matches the Opcode.
  363. unsigned getIslands(std::vector<unsigned> &StartBits,
  364. std::vector<unsigned> &EndBits,
  365. std::vector<uint64_t> &FieldVals,
  366. const insn_t &Insn) const;
  367. // Emits code to check the Predicates member of an instruction are true.
  368. // Returns true if predicate matches were emitted, false otherwise.
  369. bool emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
  370. unsigned Opc) const;
  371. bool doesOpcodeNeedPredicate(unsigned Opc) const;
  372. unsigned getPredicateIndex(DecoderTableInfo &TableInfo, StringRef P) const;
  373. void emitPredicateTableEntry(DecoderTableInfo &TableInfo,
  374. unsigned Opc) const;
  375. void emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
  376. unsigned Opc) const;
  377. // Emits table entries to decode the singleton.
  378. void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
  379. unsigned Opc) const;
  380. // Emits code to decode the singleton, and then to decode the rest.
  381. void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
  382. const Filter &Best) const;
  383. void emitBinaryParser(raw_ostream &o, unsigned &Indentation,
  384. const OperandInfo &OpInfo) const;
  385. void emitDecoder(raw_ostream &OS, unsigned Indentation, unsigned Opc) const;
  386. unsigned getDecoderIndex(DecoderSet &Decoders, unsigned Opc) const;
  387. // Assign a single filter and run with it.
  388. void runSingleFilter(unsigned startBit, unsigned numBit, bool mixed);
  389. // reportRegion is a helper function for filterProcessor to mark a region as
  390. // eligible for use as a filter region.
  391. void reportRegion(bitAttr_t RA, unsigned StartBit, unsigned BitIndex,
  392. bool AllowMixed);
  393. // FilterProcessor scans the well-known encoding bits of the instructions and
  394. // builds up a list of candidate filters. It chooses the best filter and
  395. // recursively descends down the decoding tree.
  396. bool filterProcessor(bool AllowMixed, bool Greedy = true);
  397. // Decides on the best configuration of filter(s) to use in order to decode
  398. // the instructions. A conflict of instructions may occur, in which case we
  399. // dump the conflict set to the standard error.
  400. void doFilter();
  401. public:
  402. // emitTableEntries - Emit state machine entries to decode our share of
  403. // instructions.
  404. void emitTableEntries(DecoderTableInfo &TableInfo) const;
  405. };
  406. } // End anonymous namespace
  407. ///////////////////////////
  408. // //
  409. // Filter Implementation //
  410. // //
  411. ///////////////////////////
  412. Filter::Filter(Filter &&f)
  413. : Owner(f.Owner), StartBit(f.StartBit), NumBits(f.NumBits), Mixed(f.Mixed),
  414. FilteredInstructions(std::move(f.FilteredInstructions)),
  415. VariableInstructions(std::move(f.VariableInstructions)),
  416. FilterChooserMap(std::move(f.FilterChooserMap)), NumFiltered(f.NumFiltered),
  417. LastOpcFiltered(f.LastOpcFiltered) {
  418. }
  419. Filter::Filter(FilterChooser &owner, unsigned startBit, unsigned numBits,
  420. bool mixed)
  421. : Owner(&owner), StartBit(startBit), NumBits(numBits), Mixed(mixed) {
  422. assert(StartBit + NumBits - 1 < Owner->BitWidth);
  423. NumFiltered = 0;
  424. LastOpcFiltered = 0;
  425. for (unsigned i = 0, e = Owner->Opcodes.size(); i != e; ++i) {
  426. insn_t Insn;
  427. // Populates the insn given the uid.
  428. Owner->insnWithID(Insn, Owner->Opcodes[i]);
  429. uint64_t Field;
  430. // Scans the segment for possibly well-specified encoding bits.
  431. bool ok = Owner->fieldFromInsn(Field, Insn, StartBit, NumBits);
  432. if (ok) {
  433. // The encoding bits are well-known. Lets add the uid of the
  434. // instruction into the bucket keyed off the constant field value.
  435. LastOpcFiltered = Owner->Opcodes[i];
  436. FilteredInstructions[Field].push_back(LastOpcFiltered);
  437. ++NumFiltered;
  438. } else {
  439. // Some of the encoding bit(s) are unspecified. This contributes to
  440. // one additional member of "Variable" instructions.
  441. VariableInstructions.push_back(Owner->Opcodes[i]);
  442. }
  443. }
  444. assert((FilteredInstructions.size() + VariableInstructions.size() > 0)
  445. && "Filter returns no instruction categories");
  446. }
  447. Filter::~Filter() {
  448. }
  449. // Divides the decoding task into sub tasks and delegates them to the
  450. // inferior FilterChooser's.
  451. //
  452. // A special case arises when there's only one entry in the filtered
  453. // instructions. In order to unambiguously decode the singleton, we need to
  454. // match the remaining undecoded encoding bits against the singleton.
  455. void Filter::recurse() {
  456. // Starts by inheriting our parent filter chooser's filter bit values.
  457. std::vector<bit_value_t> BitValueArray(Owner->FilterBitValues);
  458. if (!VariableInstructions.empty()) {
  459. // Conservatively marks each segment position as BIT_UNSET.
  460. for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex)
  461. BitValueArray[StartBit + bitIndex] = BIT_UNSET;
  462. // Delegates to an inferior filter chooser for further processing on this
  463. // group of instructions whose segment values are variable.
  464. FilterChooserMap.insert(
  465. std::make_pair(-1U, llvm::make_unique<FilterChooser>(
  466. Owner->AllInstructions, VariableInstructions,
  467. Owner->Operands, BitValueArray, *Owner)));
  468. }
  469. // No need to recurse for a singleton filtered instruction.
  470. // See also Filter::emit*().
  471. if (getNumFiltered() == 1) {
  472. //Owner->SingletonExists(LastOpcFiltered);
  473. assert(FilterChooserMap.size() == 1);
  474. return;
  475. }
  476. // Otherwise, create sub choosers.
  477. for (const auto &Inst : FilteredInstructions) {
  478. // Marks all the segment positions with either BIT_TRUE or BIT_FALSE.
  479. for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex) {
  480. if (Inst.first & (1ULL << bitIndex))
  481. BitValueArray[StartBit + bitIndex] = BIT_TRUE;
  482. else
  483. BitValueArray[StartBit + bitIndex] = BIT_FALSE;
  484. }
  485. // Delegates to an inferior filter chooser for further processing on this
  486. // category of instructions.
  487. FilterChooserMap.insert(std::make_pair(
  488. Inst.first, llvm::make_unique<FilterChooser>(
  489. Owner->AllInstructions, Inst.second,
  490. Owner->Operands, BitValueArray, *Owner)));
  491. }
  492. }
  493. static void resolveTableFixups(DecoderTable &Table, const FixupList &Fixups,
  494. uint32_t DestIdx) {
  495. // Any NumToSkip fixups in the current scope can resolve to the
  496. // current location.
  497. for (FixupList::const_reverse_iterator I = Fixups.rbegin(),
  498. E = Fixups.rend();
  499. I != E; ++I) {
  500. // Calculate the distance from the byte following the fixup entry byte
  501. // to the destination. The Target is calculated from after the 16-bit
  502. // NumToSkip entry itself, so subtract two from the displacement here
  503. // to account for that.
  504. uint32_t FixupIdx = *I;
  505. uint32_t Delta = DestIdx - FixupIdx - 2;
  506. // Our NumToSkip entries are 16-bits. Make sure our table isn't too
  507. // big.
  508. assert(Delta < 65536U && "disassembler decoding table too large!");
  509. Table[FixupIdx] = (uint8_t)Delta;
  510. Table[FixupIdx + 1] = (uint8_t)(Delta >> 8);
  511. }
  512. }
  513. // Emit table entries to decode instructions given a segment or segments
  514. // of bits.
  515. void Filter::emitTableEntry(DecoderTableInfo &TableInfo) const {
  516. TableInfo.Table.push_back(MCD::OPC_ExtractField);
  517. TableInfo.Table.push_back(StartBit);
  518. TableInfo.Table.push_back(NumBits);
  519. // A new filter entry begins a new scope for fixup resolution.
  520. TableInfo.FixupStack.emplace_back();
  521. DecoderTable &Table = TableInfo.Table;
  522. size_t PrevFilter = 0;
  523. bool HasFallthrough = false;
  524. for (auto &Filter : FilterChooserMap) {
  525. // Field value -1 implies a non-empty set of variable instructions.
  526. // See also recurse().
  527. if (Filter.first == (unsigned)-1) {
  528. HasFallthrough = true;
  529. // Each scope should always have at least one filter value to check
  530. // for.
  531. assert(PrevFilter != 0 && "empty filter set!");
  532. FixupList &CurScope = TableInfo.FixupStack.back();
  533. // Resolve any NumToSkip fixups in the current scope.
  534. resolveTableFixups(Table, CurScope, Table.size());
  535. CurScope.clear();
  536. PrevFilter = 0; // Don't re-process the filter's fallthrough.
  537. } else {
  538. Table.push_back(MCD::OPC_FilterValue);
  539. // Encode and emit the value to filter against.
  540. uint8_t Buffer[8];
  541. unsigned Len = encodeULEB128(Filter.first, Buffer);
  542. Table.insert(Table.end(), Buffer, Buffer + Len);
  543. // Reserve space for the NumToSkip entry. We'll backpatch the value
  544. // later.
  545. PrevFilter = Table.size();
  546. Table.push_back(0);
  547. Table.push_back(0);
  548. }
  549. // We arrive at a category of instructions with the same segment value.
  550. // Now delegate to the sub filter chooser for further decodings.
  551. // The case may fallthrough, which happens if the remaining well-known
  552. // encoding bits do not match exactly.
  553. Filter.second->emitTableEntries(TableInfo);
  554. // Now that we've emitted the body of the handler, update the NumToSkip
  555. // of the filter itself to be able to skip forward when false. Subtract
  556. // two as to account for the width of the NumToSkip field itself.
  557. if (PrevFilter) {
  558. uint32_t NumToSkip = Table.size() - PrevFilter - 2;
  559. assert(NumToSkip < 65536U && "disassembler decoding table too large!");
  560. Table[PrevFilter] = (uint8_t)NumToSkip;
  561. Table[PrevFilter + 1] = (uint8_t)(NumToSkip >> 8);
  562. }
  563. }
  564. // Any remaining unresolved fixups bubble up to the parent fixup scope.
  565. assert(TableInfo.FixupStack.size() > 1 && "fixup stack underflow!");
  566. FixupScopeList::iterator Source = TableInfo.FixupStack.end() - 1;
  567. FixupScopeList::iterator Dest = Source - 1;
  568. Dest->insert(Dest->end(), Source->begin(), Source->end());
  569. TableInfo.FixupStack.pop_back();
  570. // If there is no fallthrough, then the final filter should get fixed
  571. // up according to the enclosing scope rather than the current position.
  572. if (!HasFallthrough)
  573. TableInfo.FixupStack.back().push_back(PrevFilter);
  574. }
  575. // Returns the number of fanout produced by the filter. More fanout implies
  576. // the filter distinguishes more categories of instructions.
  577. unsigned Filter::usefulness() const {
  578. if (!VariableInstructions.empty())
  579. return FilteredInstructions.size();
  580. else
  581. return FilteredInstructions.size() + 1;
  582. }
  583. //////////////////////////////////
  584. // //
  585. // Filterchooser Implementation //
  586. // //
  587. //////////////////////////////////
  588. // Emit the decoder state machine table.
  589. void FixedLenDecoderEmitter::emitTable(formatted_raw_ostream &OS,
  590. DecoderTable &Table,
  591. unsigned Indentation,
  592. unsigned BitWidth,
  593. StringRef Namespace) const {
  594. OS.indent(Indentation) << "static const uint8_t DecoderTable" << Namespace
  595. << BitWidth << "[] = {\n";
  596. Indentation += 2;
  597. // FIXME: We may be able to use the NumToSkip values to recover
  598. // appropriate indentation levels.
  599. DecoderTable::const_iterator I = Table.begin();
  600. DecoderTable::const_iterator E = Table.end();
  601. while (I != E) {
  602. assert (I < E && "incomplete decode table entry!");
  603. uint64_t Pos = I - Table.begin();
  604. OS << "/* " << Pos << " */";
  605. OS.PadToColumn(12);
  606. switch (*I) {
  607. default:
  608. PrintFatalError("invalid decode table opcode");
  609. case MCD::OPC_ExtractField: {
  610. ++I;
  611. unsigned Start = *I++;
  612. unsigned Len = *I++;
  613. OS.indent(Indentation) << "MCD::OPC_ExtractField, " << Start << ", "
  614. << Len << ", // Inst{";
  615. if (Len > 1)
  616. OS << (Start + Len - 1) << "-";
  617. OS << Start << "} ...\n";
  618. break;
  619. }
  620. case MCD::OPC_FilterValue: {
  621. ++I;
  622. OS.indent(Indentation) << "MCD::OPC_FilterValue, ";
  623. // The filter value is ULEB128 encoded.
  624. while (*I >= 128)
  625. OS << utostr(*I++) << ", ";
  626. OS << utostr(*I++) << ", ";
  627. // 16-bit numtoskip value.
  628. uint8_t Byte = *I++;
  629. uint32_t NumToSkip = Byte;
  630. OS << utostr(Byte) << ", ";
  631. Byte = *I++;
  632. OS << utostr(Byte) << ", ";
  633. NumToSkip |= Byte << 8;
  634. OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
  635. break;
  636. }
  637. case MCD::OPC_CheckField: {
  638. ++I;
  639. unsigned Start = *I++;
  640. unsigned Len = *I++;
  641. OS.indent(Indentation) << "MCD::OPC_CheckField, " << Start << ", "
  642. << Len << ", ";// << Val << ", " << NumToSkip << ",\n";
  643. // ULEB128 encoded field value.
  644. for (; *I >= 128; ++I)
  645. OS << utostr(*I) << ", ";
  646. OS << utostr(*I++) << ", ";
  647. // 16-bit numtoskip value.
  648. uint8_t Byte = *I++;
  649. uint32_t NumToSkip = Byte;
  650. OS << utostr(Byte) << ", ";
  651. Byte = *I++;
  652. OS << utostr(Byte) << ", ";
  653. NumToSkip |= Byte << 8;
  654. OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
  655. break;
  656. }
  657. case MCD::OPC_CheckPredicate: {
  658. ++I;
  659. OS.indent(Indentation) << "MCD::OPC_CheckPredicate, ";
  660. for (; *I >= 128; ++I)
  661. OS << utostr(*I) << ", ";
  662. OS << utostr(*I++) << ", ";
  663. // 16-bit numtoskip value.
  664. uint8_t Byte = *I++;
  665. uint32_t NumToSkip = Byte;
  666. OS << utostr(Byte) << ", ";
  667. Byte = *I++;
  668. OS << utostr(Byte) << ", ";
  669. NumToSkip |= Byte << 8;
  670. OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
  671. break;
  672. }
  673. case MCD::OPC_Decode: {
  674. ++I;
  675. // Extract the ULEB128 encoded Opcode to a buffer.
  676. uint8_t Buffer[8], *p = Buffer;
  677. while ((*p++ = *I++) >= 128)
  678. assert((p - Buffer) <= (ptrdiff_t)sizeof(Buffer)
  679. && "ULEB128 value too large!");
  680. // Decode the Opcode value.
  681. unsigned Opc = decodeULEB128(Buffer);
  682. OS.indent(Indentation) << "MCD::OPC_Decode, ";
  683. for (p = Buffer; *p >= 128; ++p)
  684. OS << utostr(*p) << ", ";
  685. OS << utostr(*p) << ", ";
  686. // Decoder index.
  687. for (; *I >= 128; ++I)
  688. OS << utostr(*I) << ", ";
  689. OS << utostr(*I++) << ", ";
  690. OS << "// Opcode: "
  691. << NumberedInstructions->at(Opc)->TheDef->getName() << "\n";
  692. break;
  693. }
  694. case MCD::OPC_SoftFail: {
  695. ++I;
  696. OS.indent(Indentation) << "MCD::OPC_SoftFail";
  697. // Positive mask
  698. uint64_t Value = 0;
  699. unsigned Shift = 0;
  700. do {
  701. OS << ", " << utostr(*I);
  702. Value += (*I & 0x7f) << Shift;
  703. Shift += 7;
  704. } while (*I++ >= 128);
  705. if (Value > 127)
  706. OS << " /* 0x" << utohexstr(Value) << " */";
  707. // Negative mask
  708. Value = 0;
  709. Shift = 0;
  710. do {
  711. OS << ", " << utostr(*I);
  712. Value += (*I & 0x7f) << Shift;
  713. Shift += 7;
  714. } while (*I++ >= 128);
  715. if (Value > 127)
  716. OS << " /* 0x" << utohexstr(Value) << " */";
  717. OS << ",\n";
  718. break;
  719. }
  720. case MCD::OPC_Fail: {
  721. ++I;
  722. OS.indent(Indentation) << "MCD::OPC_Fail,\n";
  723. break;
  724. }
  725. }
  726. }
  727. OS.indent(Indentation) << "0\n";
  728. Indentation -= 2;
  729. OS.indent(Indentation) << "};\n\n";
  730. }
  731. void FixedLenDecoderEmitter::
  732. emitPredicateFunction(formatted_raw_ostream &OS, PredicateSet &Predicates,
  733. unsigned Indentation) const {
  734. // The predicate function is just a big switch statement based on the
  735. // input predicate index.
  736. OS.indent(Indentation) << "static bool checkDecoderPredicate(unsigned Idx, "
  737. << "const FeatureBitset& Bits) {\n";
  738. Indentation += 2;
  739. if (!Predicates.empty()) {
  740. OS.indent(Indentation) << "switch (Idx) {\n";
  741. OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
  742. unsigned Index = 0;
  743. for (const auto &Predicate : Predicates) {
  744. OS.indent(Indentation) << "case " << Index++ << ":\n";
  745. OS.indent(Indentation+2) << "return (" << Predicate << ");\n";
  746. }
  747. OS.indent(Indentation) << "}\n";
  748. } else {
  749. // No case statement to emit
  750. OS.indent(Indentation) << "llvm_unreachable(\"Invalid index!\");\n";
  751. }
  752. Indentation -= 2;
  753. OS.indent(Indentation) << "}\n\n";
  754. }
  755. void FixedLenDecoderEmitter::
  756. emitDecoderFunction(formatted_raw_ostream &OS, DecoderSet &Decoders,
  757. unsigned Indentation) const {
  758. // The decoder function is just a big switch statement based on the
  759. // input decoder index.
  760. OS.indent(Indentation) << "template<typename InsnType>\n";
  761. OS.indent(Indentation) << "static DecodeStatus decodeToMCInst(DecodeStatus S,"
  762. << " unsigned Idx, InsnType insn, MCInst &MI,\n";
  763. OS.indent(Indentation) << " uint64_t "
  764. << "Address, const void *Decoder) {\n";
  765. Indentation += 2;
  766. OS.indent(Indentation) << "InsnType tmp;\n";
  767. OS.indent(Indentation) << "switch (Idx) {\n";
  768. OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
  769. unsigned Index = 0;
  770. for (const auto &Decoder : Decoders) {
  771. OS.indent(Indentation) << "case " << Index++ << ":\n";
  772. OS << Decoder;
  773. OS.indent(Indentation+2) << "return S;\n";
  774. }
  775. OS.indent(Indentation) << "}\n";
  776. Indentation -= 2;
  777. OS.indent(Indentation) << "}\n\n";
  778. }
  779. // Populates the field of the insn given the start position and the number of
  780. // consecutive bits to scan for.
  781. //
  782. // Returns false if and on the first uninitialized bit value encountered.
  783. // Returns true, otherwise.
  784. bool FilterChooser::fieldFromInsn(uint64_t &Field, insn_t &Insn,
  785. unsigned StartBit, unsigned NumBits) const {
  786. Field = 0;
  787. for (unsigned i = 0; i < NumBits; ++i) {
  788. if (Insn[StartBit + i] == BIT_UNSET)
  789. return false;
  790. if (Insn[StartBit + i] == BIT_TRUE)
  791. Field = Field | (1ULL << i);
  792. }
  793. return true;
  794. }
  795. /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
  796. /// filter array as a series of chars.
  797. void FilterChooser::dumpFilterArray(raw_ostream &o,
  798. const std::vector<bit_value_t> &filter) const {
  799. for (unsigned bitIndex = BitWidth; bitIndex > 0; bitIndex--) {
  800. switch (filter[bitIndex - 1]) {
  801. case BIT_UNFILTERED:
  802. o << ".";
  803. break;
  804. case BIT_UNSET:
  805. o << "_";
  806. break;
  807. case BIT_TRUE:
  808. o << "1";
  809. break;
  810. case BIT_FALSE:
  811. o << "0";
  812. break;
  813. }
  814. }
  815. }
  816. /// dumpStack - dumpStack traverses the filter chooser chain and calls
  817. /// dumpFilterArray on each filter chooser up to the top level one.
  818. void FilterChooser::dumpStack(raw_ostream &o, const char *prefix) const {
  819. const FilterChooser *current = this;
  820. while (current) {
  821. o << prefix;
  822. dumpFilterArray(o, current->FilterBitValues);
  823. o << '\n';
  824. current = current->Parent;
  825. }
  826. }
  827. #if 0 // HLSL Change Unused
  828. // Called from Filter::recurse() when singleton exists. For debug purpose.
  829. void FilterChooser::SingletonExists(unsigned Opc) const {
  830. insn_t Insn0;
  831. insnWithID(Insn0, Opc);
  832. errs() << "Singleton exists: " << nameWithID(Opc)
  833. << " with its decoding dominating ";
  834. for (unsigned i = 0; i < Opcodes.size(); ++i) {
  835. if (Opcodes[i] == Opc) continue;
  836. errs() << nameWithID(Opcodes[i]) << ' ';
  837. }
  838. errs() << '\n';
  839. dumpStack(errs(), "\t\t");
  840. for (unsigned i = 0; i < Opcodes.size(); ++i) {
  841. const std::string &Name = nameWithID(Opcodes[i]);
  842. errs() << '\t' << Name << " ";
  843. dumpBits(errs(),
  844. getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
  845. errs() << '\n';
  846. }
  847. }
  848. #endif // HLSL Change Ends - Unused
  849. // Calculates the island(s) needed to decode the instruction.
  850. // This returns a list of undecoded bits of an instructions, for example,
  851. // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
  852. // decoded bits in order to verify that the instruction matches the Opcode.
  853. unsigned FilterChooser::getIslands(std::vector<unsigned> &StartBits,
  854. std::vector<unsigned> &EndBits,
  855. std::vector<uint64_t> &FieldVals,
  856. const insn_t &Insn) const {
  857. unsigned Num, BitNo;
  858. Num = BitNo = 0;
  859. uint64_t FieldVal = 0;
  860. // 0: Init
  861. // 1: Water (the bit value does not affect decoding)
  862. // 2: Island (well-known bit value needed for decoding)
  863. int State = 0;
  864. int Val = -1;
  865. for (unsigned i = 0; i < BitWidth; ++i) {
  866. Val = Value(Insn[i]);
  867. bool Filtered = PositionFiltered(i);
  868. switch (State) {
  869. default: llvm_unreachable("Unreachable code!");
  870. case 0:
  871. case 1:
  872. if (Filtered || Val == -1)
  873. State = 1; // Still in Water
  874. else {
  875. State = 2; // Into the Island
  876. BitNo = 0;
  877. StartBits.push_back(i);
  878. FieldVal = Val;
  879. }
  880. break;
  881. case 2:
  882. if (Filtered || Val == -1) {
  883. State = 1; // Into the Water
  884. EndBits.push_back(i - 1);
  885. FieldVals.push_back(FieldVal);
  886. ++Num;
  887. } else {
  888. State = 2; // Still in Island
  889. ++BitNo;
  890. FieldVal = FieldVal | Val << BitNo;
  891. }
  892. break;
  893. }
  894. }
  895. // If we are still in Island after the loop, do some housekeeping.
  896. if (State == 2) {
  897. EndBits.push_back(BitWidth - 1);
  898. FieldVals.push_back(FieldVal);
  899. ++Num;
  900. }
  901. assert(StartBits.size() == Num && EndBits.size() == Num &&
  902. FieldVals.size() == Num);
  903. return Num;
  904. }
  905. void FilterChooser::emitBinaryParser(raw_ostream &o, unsigned &Indentation,
  906. const OperandInfo &OpInfo) const {
  907. const std::string &Decoder = OpInfo.Decoder;
  908. if (OpInfo.numFields() != 1)
  909. o.indent(Indentation) << "tmp = 0;\n";
  910. for (const EncodingField &EF : OpInfo) {
  911. o.indent(Indentation) << "tmp ";
  912. if (OpInfo.numFields() != 1) o << '|';
  913. o << "= fieldFromInstruction"
  914. << "(insn, " << EF.Base << ", " << EF.Width << ')';
  915. if (OpInfo.numFields() != 1 || EF.Offset != 0)
  916. o << " << " << EF.Offset;
  917. o << ";\n";
  918. }
  919. if (Decoder != "")
  920. o.indent(Indentation) << Emitter->GuardPrefix << Decoder
  921. << "(MI, tmp, Address, Decoder)"
  922. << Emitter->GuardPostfix << "\n";
  923. else
  924. o.indent(Indentation) << "MI.addOperand(MCOperand::createImm(tmp));\n";
  925. }
  926. void FilterChooser::emitDecoder(raw_ostream &OS, unsigned Indentation,
  927. unsigned Opc) const {
  928. for (const auto &Op : Operands.find(Opc)->second) {
  929. // If a custom instruction decoder was specified, use that.
  930. if (Op.numFields() == 0 && Op.Decoder.size()) {
  931. OS.indent(Indentation) << Emitter->GuardPrefix << Op.Decoder
  932. << "(MI, insn, Address, Decoder)"
  933. << Emitter->GuardPostfix << "\n";
  934. break;
  935. }
  936. emitBinaryParser(OS, Indentation, Op);
  937. }
  938. }
  939. unsigned FilterChooser::getDecoderIndex(DecoderSet &Decoders,
  940. unsigned Opc) const {
  941. // Build up the predicate string.
  942. SmallString<256> Decoder;
  943. // FIXME: emitDecoder() function can take a buffer directly rather than
  944. // a stream.
  945. raw_svector_ostream S(Decoder);
  946. unsigned I = 4;
  947. emitDecoder(S, I, Opc);
  948. S.flush();
  949. // Using the full decoder string as the key value here is a bit
  950. // heavyweight, but is effective. If the string comparisons become a
  951. // performance concern, we can implement a mangling of the predicate
  952. // data easilly enough with a map back to the actual string. That's
  953. // overkill for now, though.
  954. // Make sure the predicate is in the table.
  955. Decoders.insert(StringRef(Decoder));
  956. // Now figure out the index for when we write out the table.
  957. DecoderSet::const_iterator P = std::find(Decoders.begin(),
  958. Decoders.end(),
  959. Decoder.str());
  960. return (unsigned)(P - Decoders.begin());
  961. }
  962. static void emitSinglePredicateMatch(raw_ostream &o, StringRef str,
  963. const std::string &PredicateNamespace) {
  964. if (str[0] == '!')
  965. o << "!Bits[" << PredicateNamespace << "::"
  966. << str.slice(1,str.size()) << "]";
  967. else
  968. o << "Bits[" << PredicateNamespace << "::" << str << "]";
  969. }
  970. bool FilterChooser::emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
  971. unsigned Opc) const {
  972. ListInit *Predicates =
  973. AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
  974. bool IsFirstEmission = true;
  975. for (unsigned i = 0; i < Predicates->size(); ++i) {
  976. Record *Pred = Predicates->getElementAsRecord(i);
  977. if (!Pred->getValue("AssemblerMatcherPredicate"))
  978. continue;
  979. std::string P = Pred->getValueAsString("AssemblerCondString");
  980. if (!P.length())
  981. continue;
  982. if (!IsFirstEmission)
  983. o << " && ";
  984. StringRef SR(P);
  985. std::pair<StringRef, StringRef> pairs = SR.split(',');
  986. while (pairs.second.size()) {
  987. emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
  988. o << " && ";
  989. pairs = pairs.second.split(',');
  990. }
  991. emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
  992. IsFirstEmission = false;
  993. }
  994. return !Predicates->empty();
  995. }
  996. bool FilterChooser::doesOpcodeNeedPredicate(unsigned Opc) const {
  997. ListInit *Predicates =
  998. AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
  999. for (unsigned i = 0; i < Predicates->size(); ++i) {
  1000. Record *Pred = Predicates->getElementAsRecord(i);
  1001. if (!Pred->getValue("AssemblerMatcherPredicate"))
  1002. continue;
  1003. std::string P = Pred->getValueAsString("AssemblerCondString");
  1004. if (!P.length())
  1005. continue;
  1006. return true;
  1007. }
  1008. return false;
  1009. }
  1010. unsigned FilterChooser::getPredicateIndex(DecoderTableInfo &TableInfo,
  1011. StringRef Predicate) const {
  1012. // Using the full predicate string as the key value here is a bit
  1013. // heavyweight, but is effective. If the string comparisons become a
  1014. // performance concern, we can implement a mangling of the predicate
  1015. // data easilly enough with a map back to the actual string. That's
  1016. // overkill for now, though.
  1017. // Make sure the predicate is in the table.
  1018. TableInfo.Predicates.insert(Predicate.str());
  1019. // Now figure out the index for when we write out the table.
  1020. PredicateSet::const_iterator P = std::find(TableInfo.Predicates.begin(),
  1021. TableInfo.Predicates.end(),
  1022. Predicate.str());
  1023. return (unsigned)(P - TableInfo.Predicates.begin());
  1024. }
  1025. void FilterChooser::emitPredicateTableEntry(DecoderTableInfo &TableInfo,
  1026. unsigned Opc) const {
  1027. if (!doesOpcodeNeedPredicate(Opc))
  1028. return;
  1029. // Build up the predicate string.
  1030. SmallString<256> Predicate;
  1031. // FIXME: emitPredicateMatch() functions can take a buffer directly rather
  1032. // than a stream.
  1033. raw_svector_ostream PS(Predicate);
  1034. unsigned I = 0;
  1035. emitPredicateMatch(PS, I, Opc);
  1036. // Figure out the index into the predicate table for the predicate just
  1037. // computed.
  1038. unsigned PIdx = getPredicateIndex(TableInfo, PS.str());
  1039. SmallString<16> PBytes;
  1040. raw_svector_ostream S(PBytes);
  1041. encodeULEB128(PIdx, S);
  1042. S.flush();
  1043. TableInfo.Table.push_back(MCD::OPC_CheckPredicate);
  1044. // Predicate index
  1045. for (unsigned i = 0, e = PBytes.size(); i != e; ++i)
  1046. TableInfo.Table.push_back(PBytes[i]);
  1047. // Push location for NumToSkip backpatching.
  1048. TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
  1049. TableInfo.Table.push_back(0);
  1050. TableInfo.Table.push_back(0);
  1051. }
  1052. void FilterChooser::emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
  1053. unsigned Opc) const {
  1054. BitsInit *SFBits =
  1055. AllInstructions[Opc]->TheDef->getValueAsBitsInit("SoftFail");
  1056. if (!SFBits) return;
  1057. BitsInit *InstBits = AllInstructions[Opc]->TheDef->getValueAsBitsInit("Inst");
  1058. APInt PositiveMask(BitWidth, 0ULL);
  1059. APInt NegativeMask(BitWidth, 0ULL);
  1060. for (unsigned i = 0; i < BitWidth; ++i) {
  1061. bit_value_t B = bitFromBits(*SFBits, i);
  1062. bit_value_t IB = bitFromBits(*InstBits, i);
  1063. if (B != BIT_TRUE) continue;
  1064. switch (IB) {
  1065. case BIT_FALSE:
  1066. // The bit is meant to be false, so emit a check to see if it is true.
  1067. PositiveMask.setBit(i);
  1068. break;
  1069. case BIT_TRUE:
  1070. // The bit is meant to be true, so emit a check to see if it is false.
  1071. NegativeMask.setBit(i);
  1072. break;
  1073. default:
  1074. // The bit is not set; this must be an error!
  1075. StringRef Name = AllInstructions[Opc]->TheDef->getName();
  1076. errs() << "SoftFail Conflict: bit SoftFail{" << i << "} in " << Name
  1077. << " is set but Inst{" << i << "} is unset!\n"
  1078. << " - You can only mark a bit as SoftFail if it is fully defined"
  1079. << " (1/0 - not '?') in Inst\n";
  1080. return;
  1081. }
  1082. }
  1083. bool NeedPositiveMask = PositiveMask.getBoolValue();
  1084. bool NeedNegativeMask = NegativeMask.getBoolValue();
  1085. if (!NeedPositiveMask && !NeedNegativeMask)
  1086. return;
  1087. TableInfo.Table.push_back(MCD::OPC_SoftFail);
  1088. SmallString<16> MaskBytes;
  1089. raw_svector_ostream S(MaskBytes);
  1090. if (NeedPositiveMask) {
  1091. encodeULEB128(PositiveMask.getZExtValue(), S);
  1092. S.flush();
  1093. for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
  1094. TableInfo.Table.push_back(MaskBytes[i]);
  1095. } else
  1096. TableInfo.Table.push_back(0);
  1097. if (NeedNegativeMask) {
  1098. MaskBytes.clear();
  1099. S.resync();
  1100. encodeULEB128(NegativeMask.getZExtValue(), S);
  1101. S.flush();
  1102. for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
  1103. TableInfo.Table.push_back(MaskBytes[i]);
  1104. } else
  1105. TableInfo.Table.push_back(0);
  1106. }
  1107. // Emits table entries to decode the singleton.
  1108. void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
  1109. unsigned Opc) const {
  1110. std::vector<unsigned> StartBits;
  1111. std::vector<unsigned> EndBits;
  1112. std::vector<uint64_t> FieldVals;
  1113. insn_t Insn;
  1114. insnWithID(Insn, Opc);
  1115. // Look for islands of undecoded bits of the singleton.
  1116. getIslands(StartBits, EndBits, FieldVals, Insn);
  1117. unsigned Size = StartBits.size();
  1118. // Emit the predicate table entry if one is needed.
  1119. emitPredicateTableEntry(TableInfo, Opc);
  1120. // Check any additional encoding fields needed.
  1121. for (unsigned I = Size; I != 0; --I) {
  1122. unsigned NumBits = EndBits[I-1] - StartBits[I-1] + 1;
  1123. TableInfo.Table.push_back(MCD::OPC_CheckField);
  1124. TableInfo.Table.push_back(StartBits[I-1]);
  1125. TableInfo.Table.push_back(NumBits);
  1126. uint8_t Buffer[8], *p;
  1127. encodeULEB128(FieldVals[I-1], Buffer);
  1128. for (p = Buffer; *p >= 128 ; ++p)
  1129. TableInfo.Table.push_back(*p);
  1130. TableInfo.Table.push_back(*p);
  1131. // Push location for NumToSkip backpatching.
  1132. TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
  1133. // The fixup is always 16-bits, so go ahead and allocate the space
  1134. // in the table so all our relative position calculations work OK even
  1135. // before we fully resolve the real value here.
  1136. TableInfo.Table.push_back(0);
  1137. TableInfo.Table.push_back(0);
  1138. }
  1139. // Check for soft failure of the match.
  1140. emitSoftFailTableEntry(TableInfo, Opc);
  1141. TableInfo.Table.push_back(MCD::OPC_Decode);
  1142. uint8_t Buffer[8], *p;
  1143. encodeULEB128(Opc, Buffer);
  1144. for (p = Buffer; *p >= 128 ; ++p)
  1145. TableInfo.Table.push_back(*p);
  1146. TableInfo.Table.push_back(*p);
  1147. unsigned DIdx = getDecoderIndex(TableInfo.Decoders, Opc);
  1148. SmallString<16> Bytes;
  1149. raw_svector_ostream S(Bytes);
  1150. encodeULEB128(DIdx, S);
  1151. S.flush();
  1152. // Decoder index
  1153. for (unsigned i = 0, e = Bytes.size(); i != e; ++i)
  1154. TableInfo.Table.push_back(Bytes[i]);
  1155. }
  1156. // Emits table entries to decode the singleton, and then to decode the rest.
  1157. void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
  1158. const Filter &Best) const {
  1159. unsigned Opc = Best.getSingletonOpc();
  1160. // complex singletons need predicate checks from the first singleton
  1161. // to refer forward to the variable filterchooser that follows.
  1162. TableInfo.FixupStack.emplace_back();
  1163. emitSingletonTableEntry(TableInfo, Opc);
  1164. resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
  1165. TableInfo.Table.size());
  1166. TableInfo.FixupStack.pop_back();
  1167. Best.getVariableFC().emitTableEntries(TableInfo);
  1168. }
  1169. // Assign a single filter and run with it. Top level API client can initialize
  1170. // with a single filter to start the filtering process.
  1171. void FilterChooser::runSingleFilter(unsigned startBit, unsigned numBit,
  1172. bool mixed) {
  1173. Filters.clear();
  1174. Filters.emplace_back(*this, startBit, numBit, true);
  1175. BestIndex = 0; // Sole Filter instance to choose from.
  1176. bestFilter().recurse();
  1177. }
  1178. // reportRegion is a helper function for filterProcessor to mark a region as
  1179. // eligible for use as a filter region.
  1180. void FilterChooser::reportRegion(bitAttr_t RA, unsigned StartBit,
  1181. unsigned BitIndex, bool AllowMixed) {
  1182. if (RA == ATTR_MIXED && AllowMixed)
  1183. Filters.emplace_back(*this, StartBit, BitIndex - StartBit, true);
  1184. else if (RA == ATTR_ALL_SET && !AllowMixed)
  1185. Filters.emplace_back(*this, StartBit, BitIndex - StartBit, false);
  1186. }
  1187. // FilterProcessor scans the well-known encoding bits of the instructions and
  1188. // builds up a list of candidate filters. It chooses the best filter and
  1189. // recursively descends down the decoding tree.
  1190. bool FilterChooser::filterProcessor(bool AllowMixed, bool Greedy) {
  1191. Filters.clear();
  1192. BestIndex = -1;
  1193. unsigned numInstructions = Opcodes.size();
  1194. assert(numInstructions && "Filter created with no instructions");
  1195. // No further filtering is necessary.
  1196. if (numInstructions == 1)
  1197. return true;
  1198. // Heuristics. See also doFilter()'s "Heuristics" comment when num of
  1199. // instructions is 3.
  1200. if (AllowMixed && !Greedy) {
  1201. assert(numInstructions == 3);
  1202. for (unsigned i = 0; i < Opcodes.size(); ++i) {
  1203. std::vector<unsigned> StartBits;
  1204. std::vector<unsigned> EndBits;
  1205. std::vector<uint64_t> FieldVals;
  1206. insn_t Insn;
  1207. insnWithID(Insn, Opcodes[i]);
  1208. // Look for islands of undecoded bits of any instruction.
  1209. if (getIslands(StartBits, EndBits, FieldVals, Insn) > 0) {
  1210. // Found an instruction with island(s). Now just assign a filter.
  1211. runSingleFilter(StartBits[0], EndBits[0] - StartBits[0] + 1, true);
  1212. return true;
  1213. }
  1214. }
  1215. }
  1216. unsigned BitIndex;
  1217. // We maintain BIT_WIDTH copies of the bitAttrs automaton.
  1218. // The automaton consumes the corresponding bit from each
  1219. // instruction.
  1220. //
  1221. // Input symbols: 0, 1, and _ (unset).
  1222. // States: NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED.
  1223. // Initial state: NONE.
  1224. //
  1225. // (NONE) ------- [01] -> (ALL_SET)
  1226. // (NONE) ------- _ ----> (ALL_UNSET)
  1227. // (ALL_SET) ---- [01] -> (ALL_SET)
  1228. // (ALL_SET) ---- _ ----> (MIXED)
  1229. // (ALL_UNSET) -- [01] -> (MIXED)
  1230. // (ALL_UNSET) -- _ ----> (ALL_UNSET)
  1231. // (MIXED) ------ . ----> (MIXED)
  1232. // (FILTERED)---- . ----> (FILTERED)
  1233. std::vector<bitAttr_t> bitAttrs;
  1234. // FILTERED bit positions provide no entropy and are not worthy of pursuing.
  1235. // Filter::recurse() set either BIT_TRUE or BIT_FALSE for each position.
  1236. for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex)
  1237. if (FilterBitValues[BitIndex] == BIT_TRUE ||
  1238. FilterBitValues[BitIndex] == BIT_FALSE)
  1239. bitAttrs.push_back(ATTR_FILTERED);
  1240. else
  1241. bitAttrs.push_back(ATTR_NONE);
  1242. for (unsigned InsnIndex = 0; InsnIndex < numInstructions; ++InsnIndex) {
  1243. insn_t insn;
  1244. insnWithID(insn, Opcodes[InsnIndex]);
  1245. for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
  1246. switch (bitAttrs[BitIndex]) {
  1247. case ATTR_NONE:
  1248. if (insn[BitIndex] == BIT_UNSET)
  1249. bitAttrs[BitIndex] = ATTR_ALL_UNSET;
  1250. else
  1251. bitAttrs[BitIndex] = ATTR_ALL_SET;
  1252. break;
  1253. case ATTR_ALL_SET:
  1254. if (insn[BitIndex] == BIT_UNSET)
  1255. bitAttrs[BitIndex] = ATTR_MIXED;
  1256. break;
  1257. case ATTR_ALL_UNSET:
  1258. if (insn[BitIndex] != BIT_UNSET)
  1259. bitAttrs[BitIndex] = ATTR_MIXED;
  1260. break;
  1261. case ATTR_MIXED:
  1262. case ATTR_FILTERED:
  1263. break;
  1264. }
  1265. }
  1266. }
  1267. // The regionAttr automaton consumes the bitAttrs automatons' state,
  1268. // lowest-to-highest.
  1269. //
  1270. // Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed)
  1271. // States: NONE, ALL_SET, MIXED
  1272. // Initial state: NONE
  1273. //
  1274. // (NONE) ----- F --> (NONE)
  1275. // (NONE) ----- S --> (ALL_SET) ; and set region start
  1276. // (NONE) ----- U --> (NONE)
  1277. // (NONE) ----- M --> (MIXED) ; and set region start
  1278. // (ALL_SET) -- F --> (NONE) ; and report an ALL_SET region
  1279. // (ALL_SET) -- S --> (ALL_SET)
  1280. // (ALL_SET) -- U --> (NONE) ; and report an ALL_SET region
  1281. // (ALL_SET) -- M --> (MIXED) ; and report an ALL_SET region
  1282. // (MIXED) ---- F --> (NONE) ; and report a MIXED region
  1283. // (MIXED) ---- S --> (ALL_SET) ; and report a MIXED region
  1284. // (MIXED) ---- U --> (NONE) ; and report a MIXED region
  1285. // (MIXED) ---- M --> (MIXED)
  1286. bitAttr_t RA = ATTR_NONE;
  1287. unsigned StartBit = 0;
  1288. for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
  1289. bitAttr_t bitAttr = bitAttrs[BitIndex];
  1290. assert(bitAttr != ATTR_NONE && "Bit without attributes");
  1291. switch (RA) {
  1292. case ATTR_NONE:
  1293. switch (bitAttr) {
  1294. case ATTR_FILTERED:
  1295. break;
  1296. case ATTR_ALL_SET:
  1297. StartBit = BitIndex;
  1298. RA = ATTR_ALL_SET;
  1299. break;
  1300. case ATTR_ALL_UNSET:
  1301. break;
  1302. case ATTR_MIXED:
  1303. StartBit = BitIndex;
  1304. RA = ATTR_MIXED;
  1305. break;
  1306. default:
  1307. llvm_unreachable("Unexpected bitAttr!");
  1308. }
  1309. break;
  1310. case ATTR_ALL_SET:
  1311. switch (bitAttr) {
  1312. case ATTR_FILTERED:
  1313. reportRegion(RA, StartBit, BitIndex, AllowMixed);
  1314. RA = ATTR_NONE;
  1315. break;
  1316. case ATTR_ALL_SET:
  1317. break;
  1318. case ATTR_ALL_UNSET:
  1319. reportRegion(RA, StartBit, BitIndex, AllowMixed);
  1320. RA = ATTR_NONE;
  1321. break;
  1322. case ATTR_MIXED:
  1323. reportRegion(RA, StartBit, BitIndex, AllowMixed);
  1324. StartBit = BitIndex;
  1325. RA = ATTR_MIXED;
  1326. break;
  1327. default:
  1328. llvm_unreachable("Unexpected bitAttr!");
  1329. }
  1330. break;
  1331. case ATTR_MIXED:
  1332. switch (bitAttr) {
  1333. case ATTR_FILTERED:
  1334. reportRegion(RA, StartBit, BitIndex, AllowMixed);
  1335. StartBit = BitIndex;
  1336. RA = ATTR_NONE;
  1337. break;
  1338. case ATTR_ALL_SET:
  1339. reportRegion(RA, StartBit, BitIndex, AllowMixed);
  1340. StartBit = BitIndex;
  1341. RA = ATTR_ALL_SET;
  1342. break;
  1343. case ATTR_ALL_UNSET:
  1344. reportRegion(RA, StartBit, BitIndex, AllowMixed);
  1345. RA = ATTR_NONE;
  1346. break;
  1347. case ATTR_MIXED:
  1348. break;
  1349. default:
  1350. llvm_unreachable("Unexpected bitAttr!");
  1351. }
  1352. break;
  1353. case ATTR_ALL_UNSET:
  1354. llvm_unreachable("regionAttr state machine has no ATTR_UNSET state");
  1355. case ATTR_FILTERED:
  1356. llvm_unreachable("regionAttr state machine has no ATTR_FILTERED state");
  1357. }
  1358. }
  1359. // At the end, if we're still in ALL_SET or MIXED states, report a region
  1360. switch (RA) {
  1361. case ATTR_NONE:
  1362. break;
  1363. case ATTR_FILTERED:
  1364. break;
  1365. case ATTR_ALL_SET:
  1366. reportRegion(RA, StartBit, BitIndex, AllowMixed);
  1367. break;
  1368. case ATTR_ALL_UNSET:
  1369. break;
  1370. case ATTR_MIXED:
  1371. reportRegion(RA, StartBit, BitIndex, AllowMixed);
  1372. break;
  1373. }
  1374. // We have finished with the filter processings. Now it's time to choose
  1375. // the best performing filter.
  1376. BestIndex = 0;
  1377. bool AllUseless = true;
  1378. unsigned BestScore = 0;
  1379. for (unsigned i = 0, e = Filters.size(); i != e; ++i) {
  1380. unsigned Usefulness = Filters[i].usefulness();
  1381. if (Usefulness)
  1382. AllUseless = false;
  1383. if (Usefulness > BestScore) {
  1384. BestIndex = i;
  1385. BestScore = Usefulness;
  1386. }
  1387. }
  1388. if (!AllUseless)
  1389. bestFilter().recurse();
  1390. return !AllUseless;
  1391. } // end of FilterChooser::filterProcessor(bool)
  1392. // Decides on the best configuration of filter(s) to use in order to decode
  1393. // the instructions. A conflict of instructions may occur, in which case we
  1394. // dump the conflict set to the standard error.
  1395. void FilterChooser::doFilter() {
  1396. unsigned Num = Opcodes.size();
  1397. assert(Num && "FilterChooser created with no instructions");
  1398. // Try regions of consecutive known bit values first.
  1399. if (filterProcessor(false))
  1400. return;
  1401. // Then regions of mixed bits (both known and unitialized bit values allowed).
  1402. if (filterProcessor(true))
  1403. return;
  1404. // Heuristics to cope with conflict set {t2CMPrs, t2SUBSrr, t2SUBSrs} where
  1405. // no single instruction for the maximum ATTR_MIXED region Inst{14-4} has a
  1406. // well-known encoding pattern. In such case, we backtrack and scan for the
  1407. // the very first consecutive ATTR_ALL_SET region and assign a filter to it.
  1408. if (Num == 3 && filterProcessor(true, false))
  1409. return;
  1410. // If we come to here, the instruction decoding has failed.
  1411. // Set the BestIndex to -1 to indicate so.
  1412. BestIndex = -1;
  1413. }
  1414. // emitTableEntries - Emit state machine entries to decode our share of
  1415. // instructions.
  1416. void FilterChooser::emitTableEntries(DecoderTableInfo &TableInfo) const {
  1417. if (Opcodes.size() == 1) {
  1418. // There is only one instruction in the set, which is great!
  1419. // Call emitSingletonDecoder() to see whether there are any remaining
  1420. // encodings bits.
  1421. emitSingletonTableEntry(TableInfo, Opcodes[0]);
  1422. return;
  1423. }
  1424. // Choose the best filter to do the decodings!
  1425. if (BestIndex != -1) {
  1426. const Filter &Best = Filters[BestIndex];
  1427. if (Best.getNumFiltered() == 1)
  1428. emitSingletonTableEntry(TableInfo, Best);
  1429. else
  1430. Best.emitTableEntry(TableInfo);
  1431. return;
  1432. }
  1433. // We don't know how to decode these instructions! Dump the
  1434. // conflict set and bail.
  1435. // Print out useful conflict information for postmortem analysis.
  1436. errs() << "Decoding Conflict:\n";
  1437. dumpStack(errs(), "\t\t");
  1438. for (unsigned i = 0; i < Opcodes.size(); ++i) {
  1439. const std::string &Name = nameWithID(Opcodes[i]);
  1440. errs() << '\t' << Name << " ";
  1441. dumpBits(errs(),
  1442. getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
  1443. errs() << '\n';
  1444. }
  1445. }
  1446. static bool populateInstruction(CodeGenTarget &Target,
  1447. const CodeGenInstruction &CGI, unsigned Opc,
  1448. std::map<unsigned, std::vector<OperandInfo> > &Operands){
  1449. const Record &Def = *CGI.TheDef;
  1450. // If all the bit positions are not specified; do not decode this instruction.
  1451. // We are bound to fail! For proper disassembly, the well-known encoding bits
  1452. // of the instruction must be fully specified.
  1453. BitsInit &Bits = getBitsField(Def, "Inst");
  1454. if (Bits.allInComplete()) return false;
  1455. std::vector<OperandInfo> InsnOperands;
  1456. // If the instruction has specified a custom decoding hook, use that instead
  1457. // of trying to auto-generate the decoder.
  1458. std::string InstDecoder = Def.getValueAsString("DecoderMethod");
  1459. if (InstDecoder != "") {
  1460. InsnOperands.push_back(OperandInfo(InstDecoder));
  1461. Operands[Opc] = InsnOperands;
  1462. return true;
  1463. }
  1464. // Generate a description of the operand of the instruction that we know
  1465. // how to decode automatically.
  1466. // FIXME: We'll need to have a way to manually override this as needed.
  1467. // Gather the outputs/inputs of the instruction, so we can find their
  1468. // positions in the encoding. This assumes for now that they appear in the
  1469. // MCInst in the order that they're listed.
  1470. std::vector<std::pair<Init*, std::string> > InOutOperands;
  1471. DagInit *Out = Def.getValueAsDag("OutOperandList");
  1472. DagInit *In = Def.getValueAsDag("InOperandList");
  1473. for (unsigned i = 0; i < Out->getNumArgs(); ++i)
  1474. InOutOperands.push_back(std::make_pair(Out->getArg(i), Out->getArgName(i)));
  1475. for (unsigned i = 0; i < In->getNumArgs(); ++i)
  1476. InOutOperands.push_back(std::make_pair(In->getArg(i), In->getArgName(i)));
  1477. // Search for tied operands, so that we can correctly instantiate
  1478. // operands that are not explicitly represented in the encoding.
  1479. std::map<std::string, std::string> TiedNames;
  1480. for (unsigned i = 0; i < CGI.Operands.size(); ++i) {
  1481. int tiedTo = CGI.Operands[i].getTiedRegister();
  1482. if (tiedTo != -1) {
  1483. std::pair<unsigned, unsigned> SO =
  1484. CGI.Operands.getSubOperandNumber(tiedTo);
  1485. TiedNames[InOutOperands[i].second] = InOutOperands[SO.first].second;
  1486. TiedNames[InOutOperands[SO.first].second] = InOutOperands[i].second;
  1487. }
  1488. }
  1489. std::map<std::string, std::vector<OperandInfo> > NumberedInsnOperands;
  1490. std::set<std::string> NumberedInsnOperandsNoTie;
  1491. if (Target.getInstructionSet()->
  1492. getValueAsBit("decodePositionallyEncodedOperands")) {
  1493. const std::vector<RecordVal> &Vals = Def.getValues();
  1494. unsigned NumberedOp = 0;
  1495. std::set<unsigned> NamedOpIndices;
  1496. if (Target.getInstructionSet()->
  1497. getValueAsBit("noNamedPositionallyEncodedOperands"))
  1498. // Collect the set of operand indices that might correspond to named
  1499. // operand, and skip these when assigning operands based on position.
  1500. for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
  1501. unsigned OpIdx;
  1502. if (!CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
  1503. continue;
  1504. NamedOpIndices.insert(OpIdx);
  1505. }
  1506. for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
  1507. // Ignore fixed fields in the record, we're looking for values like:
  1508. // bits<5> RST = { ?, ?, ?, ?, ? };
  1509. if (Vals[i].getPrefix() || Vals[i].getValue()->isComplete())
  1510. continue;
  1511. // Determine if Vals[i] actually contributes to the Inst encoding.
  1512. unsigned bi = 0;
  1513. for (; bi < Bits.getNumBits(); ++bi) {
  1514. VarInit *Var = nullptr;
  1515. VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
  1516. if (BI)
  1517. Var = dyn_cast<VarInit>(BI->getBitVar());
  1518. else
  1519. Var = dyn_cast<VarInit>(Bits.getBit(bi));
  1520. if (Var && Var->getName() == Vals[i].getName())
  1521. break;
  1522. }
  1523. if (bi == Bits.getNumBits())
  1524. continue;
  1525. // Skip variables that correspond to explicitly-named operands.
  1526. unsigned OpIdx;
  1527. if (CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
  1528. continue;
  1529. // Get the bit range for this operand:
  1530. unsigned bitStart = bi++, bitWidth = 1;
  1531. for (; bi < Bits.getNumBits(); ++bi) {
  1532. VarInit *Var = nullptr;
  1533. VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
  1534. if (BI)
  1535. Var = dyn_cast<VarInit>(BI->getBitVar());
  1536. else
  1537. Var = dyn_cast<VarInit>(Bits.getBit(bi));
  1538. if (!Var)
  1539. break;
  1540. if (Var->getName() != Vals[i].getName())
  1541. break;
  1542. ++bitWidth;
  1543. }
  1544. unsigned NumberOps = CGI.Operands.size();
  1545. while (NumberedOp < NumberOps &&
  1546. (CGI.Operands.isFlatOperandNotEmitted(NumberedOp) ||
  1547. (!NamedOpIndices.empty() && NamedOpIndices.count(
  1548. CGI.Operands.getSubOperandNumber(NumberedOp).first))))
  1549. ++NumberedOp;
  1550. OpIdx = NumberedOp++;
  1551. // OpIdx now holds the ordered operand number of Vals[i].
  1552. std::pair<unsigned, unsigned> SO =
  1553. CGI.Operands.getSubOperandNumber(OpIdx);
  1554. const std::string &Name = CGI.Operands[SO.first].Name;
  1555. DEBUG(dbgs() << "Numbered operand mapping for " << Def.getName() << ": " <<
  1556. Name << "(" << SO.first << ", " << SO.second << ") => " <<
  1557. Vals[i].getName() << "\n");
  1558. std::string Decoder = "";
  1559. Record *TypeRecord = CGI.Operands[SO.first].Rec;
  1560. RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
  1561. StringInit *String = DecoderString ?
  1562. dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
  1563. if (String && String->getValue() != "")
  1564. Decoder = String->getValue();
  1565. if (Decoder == "" &&
  1566. CGI.Operands[SO.first].MIOperandInfo &&
  1567. CGI.Operands[SO.first].MIOperandInfo->getNumArgs()) {
  1568. Init *Arg = CGI.Operands[SO.first].MIOperandInfo->
  1569. getArg(SO.second);
  1570. if (TypedInit *TI = cast<TypedInit>(Arg)) {
  1571. RecordRecTy *Type = cast<RecordRecTy>(TI->getType());
  1572. TypeRecord = Type->getRecord();
  1573. }
  1574. }
  1575. bool isReg = false;
  1576. if (TypeRecord->isSubClassOf("RegisterOperand"))
  1577. TypeRecord = TypeRecord->getValueAsDef("RegClass");
  1578. if (TypeRecord->isSubClassOf("RegisterClass")) {
  1579. Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
  1580. isReg = true;
  1581. } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) {
  1582. Decoder = "DecodePointerLikeRegClass" +
  1583. utostr(TypeRecord->getValueAsInt("RegClassKind"));
  1584. isReg = true;
  1585. }
  1586. DecoderString = TypeRecord->getValue("DecoderMethod");
  1587. String = DecoderString ?
  1588. dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
  1589. if (!isReg && String && String->getValue() != "")
  1590. Decoder = String->getValue();
  1591. OperandInfo OpInfo(Decoder);
  1592. OpInfo.addField(bitStart, bitWidth, 0);
  1593. NumberedInsnOperands[Name].push_back(OpInfo);
  1594. // FIXME: For complex operands with custom decoders we can't handle tied
  1595. // sub-operands automatically. Skip those here and assume that this is
  1596. // fixed up elsewhere.
  1597. if (CGI.Operands[SO.first].MIOperandInfo &&
  1598. CGI.Operands[SO.first].MIOperandInfo->getNumArgs() > 1 &&
  1599. String && String->getValue() != "")
  1600. NumberedInsnOperandsNoTie.insert(Name);
  1601. }
  1602. }
  1603. // For each operand, see if we can figure out where it is encoded.
  1604. for (const auto &Op : InOutOperands) {
  1605. if (!NumberedInsnOperands[Op.second].empty()) {
  1606. InsnOperands.insert(InsnOperands.end(),
  1607. NumberedInsnOperands[Op.second].begin(),
  1608. NumberedInsnOperands[Op.second].end());
  1609. continue;
  1610. }
  1611. if (!NumberedInsnOperands[TiedNames[Op.second]].empty()) {
  1612. if (!NumberedInsnOperandsNoTie.count(TiedNames[Op.second])) {
  1613. // Figure out to which (sub)operand we're tied.
  1614. unsigned i = CGI.Operands.getOperandNamed(TiedNames[Op.second]);
  1615. int tiedTo = CGI.Operands[i].getTiedRegister();
  1616. if (tiedTo == -1) {
  1617. i = CGI.Operands.getOperandNamed(Op.second);
  1618. tiedTo = CGI.Operands[i].getTiedRegister();
  1619. }
  1620. if (tiedTo != -1) {
  1621. std::pair<unsigned, unsigned> SO =
  1622. CGI.Operands.getSubOperandNumber(tiedTo);
  1623. InsnOperands.push_back(NumberedInsnOperands[TiedNames[Op.second]]
  1624. [SO.second]);
  1625. }
  1626. }
  1627. continue;
  1628. }
  1629. std::string Decoder = "";
  1630. // At this point, we can locate the field, but we need to know how to
  1631. // interpret it. As a first step, require the target to provide callbacks
  1632. // for decoding register classes.
  1633. // FIXME: This need to be extended to handle instructions with custom
  1634. // decoder methods, and operands with (simple) MIOperandInfo's.
  1635. TypedInit *TI = cast<TypedInit>(Op.first);
  1636. RecordRecTy *Type = cast<RecordRecTy>(TI->getType());
  1637. Record *TypeRecord = Type->getRecord();
  1638. bool isReg = false;
  1639. if (TypeRecord->isSubClassOf("RegisterOperand"))
  1640. TypeRecord = TypeRecord->getValueAsDef("RegClass");
  1641. if (TypeRecord->isSubClassOf("RegisterClass")) {
  1642. Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
  1643. isReg = true;
  1644. } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) {
  1645. Decoder = "DecodePointerLikeRegClass" +
  1646. utostr(TypeRecord->getValueAsInt("RegClassKind"));
  1647. isReg = true;
  1648. }
  1649. RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
  1650. StringInit *String = DecoderString ?
  1651. dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
  1652. if (!isReg && String && String->getValue() != "")
  1653. Decoder = String->getValue();
  1654. OperandInfo OpInfo(Decoder);
  1655. unsigned Base = ~0U;
  1656. unsigned Width = 0;
  1657. unsigned Offset = 0;
  1658. for (unsigned bi = 0; bi < Bits.getNumBits(); ++bi) {
  1659. VarInit *Var = nullptr;
  1660. VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
  1661. if (BI)
  1662. Var = dyn_cast<VarInit>(BI->getBitVar());
  1663. else
  1664. Var = dyn_cast<VarInit>(Bits.getBit(bi));
  1665. if (!Var) {
  1666. if (Base != ~0U) {
  1667. OpInfo.addField(Base, Width, Offset);
  1668. Base = ~0U;
  1669. Width = 0;
  1670. Offset = 0;
  1671. }
  1672. continue;
  1673. }
  1674. if (Var->getName() != Op.second &&
  1675. Var->getName() != TiedNames[Op.second]) {
  1676. if (Base != ~0U) {
  1677. OpInfo.addField(Base, Width, Offset);
  1678. Base = ~0U;
  1679. Width = 0;
  1680. Offset = 0;
  1681. }
  1682. continue;
  1683. }
  1684. if (Base == ~0U) {
  1685. Base = bi;
  1686. Width = 1;
  1687. Offset = BI ? BI->getBitNum() : 0;
  1688. } else if (BI && BI->getBitNum() != Offset + Width) {
  1689. OpInfo.addField(Base, Width, Offset);
  1690. Base = bi;
  1691. Width = 1;
  1692. Offset = BI->getBitNum();
  1693. } else {
  1694. ++Width;
  1695. }
  1696. }
  1697. if (Base != ~0U)
  1698. OpInfo.addField(Base, Width, Offset);
  1699. if (OpInfo.numFields() > 0)
  1700. InsnOperands.push_back(OpInfo);
  1701. }
  1702. Operands[Opc] = InsnOperands;
  1703. #if 0
  1704. DEBUG({
  1705. // Dumps the instruction encoding bits.
  1706. dumpBits(errs(), Bits);
  1707. errs() << '\n';
  1708. // Dumps the list of operand info.
  1709. for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
  1710. const CGIOperandList::OperandInfo &Info = CGI.Operands[i];
  1711. const std::string &OperandName = Info.Name;
  1712. const Record &OperandDef = *Info.Rec;
  1713. errs() << "\t" << OperandName << " (" << OperandDef.getName() << ")\n";
  1714. }
  1715. });
  1716. #endif
  1717. return true;
  1718. }
  1719. // emitFieldFromInstruction - Emit the templated helper function
  1720. // fieldFromInstruction().
  1721. static void emitFieldFromInstruction(formatted_raw_ostream &OS) {
  1722. OS << "// Helper function for extracting fields from encoded instructions.\n"
  1723. << "template<typename InsnType>\n"
  1724. << "static InsnType fieldFromInstruction(InsnType insn, unsigned startBit,\n"
  1725. << " unsigned numBits) {\n"
  1726. << " assert(startBit + numBits <= (sizeof(InsnType)*8) &&\n"
  1727. << " \"Instruction field out of bounds!\");\n"
  1728. << " InsnType fieldMask;\n"
  1729. << " if (numBits == sizeof(InsnType)*8)\n"
  1730. << " fieldMask = (InsnType)(-1LL);\n"
  1731. << " else\n"
  1732. << " fieldMask = (((InsnType)1 << numBits) - 1) << startBit;\n"
  1733. << " return (insn & fieldMask) >> startBit;\n"
  1734. << "}\n\n";
  1735. }
  1736. // emitDecodeInstruction - Emit the templated helper function
  1737. // decodeInstruction().
  1738. static void emitDecodeInstruction(formatted_raw_ostream &OS) {
  1739. OS << "template<typename InsnType>\n"
  1740. << "static DecodeStatus decodeInstruction(const uint8_t DecodeTable[], MCInst &MI,\n"
  1741. << " InsnType insn, uint64_t Address,\n"
  1742. << " const void *DisAsm,\n"
  1743. << " const MCSubtargetInfo &STI) {\n"
  1744. << " const FeatureBitset& Bits = STI.getFeatureBits();\n"
  1745. << "\n"
  1746. << " const uint8_t *Ptr = DecodeTable;\n"
  1747. << " uint32_t CurFieldValue = 0;\n"
  1748. << " DecodeStatus S = MCDisassembler::Success;\n"
  1749. << " for (;;) {\n"
  1750. << " ptrdiff_t Loc = Ptr - DecodeTable;\n"
  1751. << " switch (*Ptr) {\n"
  1752. << " default:\n"
  1753. << " errs() << Loc << \": Unexpected decode table opcode!\\n\";\n"
  1754. << " return MCDisassembler::Fail;\n"
  1755. << " case MCD::OPC_ExtractField: {\n"
  1756. << " unsigned Start = *++Ptr;\n"
  1757. << " unsigned Len = *++Ptr;\n"
  1758. << " ++Ptr;\n"
  1759. << " CurFieldValue = fieldFromInstruction(insn, Start, Len);\n"
  1760. << " DEBUG(dbgs() << Loc << \": OPC_ExtractField(\" << Start << \", \"\n"
  1761. << " << Len << \"): \" << CurFieldValue << \"\\n\");\n"
  1762. << " break;\n"
  1763. << " }\n"
  1764. << " case MCD::OPC_FilterValue: {\n"
  1765. << " // Decode the field value.\n"
  1766. << " unsigned Len;\n"
  1767. << " InsnType Val = decodeULEB128(++Ptr, &Len);\n"
  1768. << " Ptr += Len;\n"
  1769. << " // NumToSkip is a plain 16-bit integer.\n"
  1770. << " unsigned NumToSkip = *Ptr++;\n"
  1771. << " NumToSkip |= (*Ptr++) << 8;\n"
  1772. << "\n"
  1773. << " // Perform the filter operation.\n"
  1774. << " if (Val != CurFieldValue)\n"
  1775. << " Ptr += NumToSkip;\n"
  1776. << " DEBUG(dbgs() << Loc << \": OPC_FilterValue(\" << Val << \", \" << NumToSkip\n"
  1777. << " << \"): \" << ((Val != CurFieldValue) ? \"FAIL:\" : \"PASS:\")\n"
  1778. << " << \" continuing at \" << (Ptr - DecodeTable) << \"\\n\");\n"
  1779. << "\n"
  1780. << " break;\n"
  1781. << " }\n"
  1782. << " case MCD::OPC_CheckField: {\n"
  1783. << " unsigned Start = *++Ptr;\n"
  1784. << " unsigned Len = *++Ptr;\n"
  1785. << " InsnType FieldValue = fieldFromInstruction(insn, Start, Len);\n"
  1786. << " // Decode the field value.\n"
  1787. << " uint32_t ExpectedValue = decodeULEB128(++Ptr, &Len);\n"
  1788. << " Ptr += Len;\n"
  1789. << " // NumToSkip is a plain 16-bit integer.\n"
  1790. << " unsigned NumToSkip = *Ptr++;\n"
  1791. << " NumToSkip |= (*Ptr++) << 8;\n"
  1792. << "\n"
  1793. << " // If the actual and expected values don't match, skip.\n"
  1794. << " if (ExpectedValue != FieldValue)\n"
  1795. << " Ptr += NumToSkip;\n"
  1796. << " DEBUG(dbgs() << Loc << \": OPC_CheckField(\" << Start << \", \"\n"
  1797. << " << Len << \", \" << ExpectedValue << \", \" << NumToSkip\n"
  1798. << " << \"): FieldValue = \" << FieldValue << \", ExpectedValue = \"\n"
  1799. << " << ExpectedValue << \": \"\n"
  1800. << " << ((ExpectedValue == FieldValue) ? \"PASS\\n\" : \"FAIL\\n\"));\n"
  1801. << " break;\n"
  1802. << " }\n"
  1803. << " case MCD::OPC_CheckPredicate: {\n"
  1804. << " unsigned Len;\n"
  1805. << " // Decode the Predicate Index value.\n"
  1806. << " unsigned PIdx = decodeULEB128(++Ptr, &Len);\n"
  1807. << " Ptr += Len;\n"
  1808. << " // NumToSkip is a plain 16-bit integer.\n"
  1809. << " unsigned NumToSkip = *Ptr++;\n"
  1810. << " NumToSkip |= (*Ptr++) << 8;\n"
  1811. << " // Check the predicate.\n"
  1812. << " bool Pred;\n"
  1813. << " if (!(Pred = checkDecoderPredicate(PIdx, Bits)))\n"
  1814. << " Ptr += NumToSkip;\n"
  1815. << " (void)Pred;\n"
  1816. << " DEBUG(dbgs() << Loc << \": OPC_CheckPredicate(\" << PIdx << \"): \"\n"
  1817. << " << (Pred ? \"PASS\\n\" : \"FAIL\\n\"));\n"
  1818. << "\n"
  1819. << " break;\n"
  1820. << " }\n"
  1821. << " case MCD::OPC_Decode: {\n"
  1822. << " unsigned Len;\n"
  1823. << " // Decode the Opcode value.\n"
  1824. << " unsigned Opc = decodeULEB128(++Ptr, &Len);\n"
  1825. << " Ptr += Len;\n"
  1826. << " unsigned DecodeIdx = decodeULEB128(Ptr, &Len);\n"
  1827. << " Ptr += Len;\n"
  1828. << " DEBUG(dbgs() << Loc << \": OPC_Decode: opcode \" << Opc\n"
  1829. << " << \", using decoder \" << DecodeIdx << \"\\n\" );\n"
  1830. << " DEBUG(dbgs() << \"----- DECODE SUCCESSFUL -----\\n\");\n"
  1831. << "\n"
  1832. << " MI.setOpcode(Opc);\n"
  1833. << " return decodeToMCInst(S, DecodeIdx, insn, MI, Address, DisAsm);\n"
  1834. << " }\n"
  1835. << " case MCD::OPC_SoftFail: {\n"
  1836. << " // Decode the mask values.\n"
  1837. << " unsigned Len;\n"
  1838. << " InsnType PositiveMask = decodeULEB128(++Ptr, &Len);\n"
  1839. << " Ptr += Len;\n"
  1840. << " InsnType NegativeMask = decodeULEB128(Ptr, &Len);\n"
  1841. << " Ptr += Len;\n"
  1842. << " bool Fail = (insn & PositiveMask) || (~insn & NegativeMask);\n"
  1843. << " if (Fail)\n"
  1844. << " S = MCDisassembler::SoftFail;\n"
  1845. << " DEBUG(dbgs() << Loc << \": OPC_SoftFail: \" << (Fail ? \"FAIL\\n\":\"PASS\\n\"));\n"
  1846. << " break;\n"
  1847. << " }\n"
  1848. << " case MCD::OPC_Fail: {\n"
  1849. << " DEBUG(dbgs() << Loc << \": OPC_Fail\\n\");\n"
  1850. << " return MCDisassembler::Fail;\n"
  1851. << " }\n"
  1852. << " }\n"
  1853. << " }\n"
  1854. << " llvm_unreachable(\"bogosity detected in disassembler state machine!\");\n"
  1855. << "}\n\n";
  1856. }
  1857. // Emits disassembler code for instruction decoding.
  1858. void FixedLenDecoderEmitter::run(raw_ostream &o) {
  1859. formatted_raw_ostream OS(o);
  1860. OS << "#include \"llvm/MC/MCInst.h\"\n";
  1861. OS << "#include \"llvm/Support/Debug.h\"\n";
  1862. OS << "#include \"llvm/Support/DataTypes.h\"\n";
  1863. OS << "#include \"llvm/Support/LEB128.h\"\n";
  1864. OS << "#include \"llvm/Support/raw_ostream.h\"\n";
  1865. OS << "#include <assert.h>\n";
  1866. OS << '\n';
  1867. OS << "namespace llvm {\n\n";
  1868. emitFieldFromInstruction(OS);
  1869. Target.reverseBitsForLittleEndianEncoding();
  1870. // Parameterize the decoders based on namespace and instruction width.
  1871. NumberedInstructions = &Target.getInstructionsByEnumValue();
  1872. std::map<std::pair<std::string, unsigned>,
  1873. std::vector<unsigned> > OpcMap;
  1874. std::map<unsigned, std::vector<OperandInfo> > Operands;
  1875. for (unsigned i = 0; i < NumberedInstructions->size(); ++i) {
  1876. const CodeGenInstruction *Inst = NumberedInstructions->at(i);
  1877. const Record *Def = Inst->TheDef;
  1878. unsigned Size = Def->getValueAsInt("Size");
  1879. if (Def->getValueAsString("Namespace") == "TargetOpcode" ||
  1880. Def->getValueAsBit("isPseudo") ||
  1881. Def->getValueAsBit("isAsmParserOnly") ||
  1882. Def->getValueAsBit("isCodeGenOnly"))
  1883. continue;
  1884. std::string DecoderNamespace = Def->getValueAsString("DecoderNamespace");
  1885. if (Size) {
  1886. if (populateInstruction(Target, *Inst, i, Operands)) {
  1887. OpcMap[std::make_pair(DecoderNamespace, Size)].push_back(i);
  1888. }
  1889. }
  1890. }
  1891. DecoderTableInfo TableInfo;
  1892. for (const auto &Opc : OpcMap) {
  1893. // Emit the decoder for this namespace+width combination.
  1894. FilterChooser FC(*NumberedInstructions, Opc.second, Operands,
  1895. 8*Opc.first.second, this);
  1896. // The decode table is cleared for each top level decoder function. The
  1897. // predicates and decoders themselves, however, are shared across all
  1898. // decoders to give more opportunities for uniqueing.
  1899. TableInfo.Table.clear();
  1900. TableInfo.FixupStack.clear();
  1901. TableInfo.Table.reserve(16384);
  1902. TableInfo.FixupStack.emplace_back();
  1903. FC.emitTableEntries(TableInfo);
  1904. // Any NumToSkip fixups in the top level scope can resolve to the
  1905. // OPC_Fail at the end of the table.
  1906. assert(TableInfo.FixupStack.size() == 1 && "fixup stack phasing error!");
  1907. // Resolve any NumToSkip fixups in the current scope.
  1908. resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
  1909. TableInfo.Table.size());
  1910. TableInfo.FixupStack.clear();
  1911. TableInfo.Table.push_back(MCD::OPC_Fail);
  1912. // Print the table to the output stream.
  1913. emitTable(OS, TableInfo.Table, 0, FC.getBitWidth(), Opc.first.first);
  1914. OS.flush();
  1915. }
  1916. // Emit the predicate function.
  1917. emitPredicateFunction(OS, TableInfo.Predicates, 0);
  1918. // Emit the decoder function.
  1919. emitDecoderFunction(OS, TableInfo.Decoders, 0);
  1920. // Emit the main entry point for the decoder, decodeInstruction().
  1921. emitDecodeInstruction(OS);
  1922. OS << "\n} // End llvm namespace\n";
  1923. }
  1924. namespace llvm {
  1925. void EmitFixedLenDecoder(RecordKeeper &RK, raw_ostream &OS,
  1926. std::string PredicateNamespace,
  1927. std::string GPrefix,
  1928. std::string GPostfix,
  1929. std::string ROK,
  1930. std::string RFail,
  1931. std::string L) {
  1932. FixedLenDecoderEmitter(RK, PredicateNamespace, GPrefix, GPostfix,
  1933. ROK, RFail, L).run(OS);
  1934. }
  1935. } // End llvm namespace