FixedLenDecoderEmitter.cpp 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224
  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;
  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. // Called from Filter::recurse() when singleton exists. For debug purpose.
  828. void FilterChooser::SingletonExists(unsigned Opc) const {
  829. insn_t Insn0;
  830. insnWithID(Insn0, Opc);
  831. errs() << "Singleton exists: " << nameWithID(Opc)
  832. << " with its decoding dominating ";
  833. for (unsigned i = 0; i < Opcodes.size(); ++i) {
  834. if (Opcodes[i] == Opc) continue;
  835. errs() << nameWithID(Opcodes[i]) << ' ';
  836. }
  837. errs() << '\n';
  838. dumpStack(errs(), "\t\t");
  839. for (unsigned i = 0; i < Opcodes.size(); ++i) {
  840. const std::string &Name = nameWithID(Opcodes[i]);
  841. errs() << '\t' << Name << " ";
  842. dumpBits(errs(),
  843. getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
  844. errs() << '\n';
  845. }
  846. }
  847. // Calculates the island(s) needed to decode the instruction.
  848. // This returns a list of undecoded bits of an instructions, for example,
  849. // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
  850. // decoded bits in order to verify that the instruction matches the Opcode.
  851. unsigned FilterChooser::getIslands(std::vector<unsigned> &StartBits,
  852. std::vector<unsigned> &EndBits,
  853. std::vector<uint64_t> &FieldVals,
  854. const insn_t &Insn) const {
  855. unsigned Num, BitNo;
  856. Num = BitNo = 0;
  857. uint64_t FieldVal = 0;
  858. // 0: Init
  859. // 1: Water (the bit value does not affect decoding)
  860. // 2: Island (well-known bit value needed for decoding)
  861. int State = 0;
  862. int Val = -1;
  863. for (unsigned i = 0; i < BitWidth; ++i) {
  864. Val = Value(Insn[i]);
  865. bool Filtered = PositionFiltered(i);
  866. switch (State) {
  867. default: llvm_unreachable("Unreachable code!");
  868. case 0:
  869. case 1:
  870. if (Filtered || Val == -1)
  871. State = 1; // Still in Water
  872. else {
  873. State = 2; // Into the Island
  874. BitNo = 0;
  875. StartBits.push_back(i);
  876. FieldVal = Val;
  877. }
  878. break;
  879. case 2:
  880. if (Filtered || Val == -1) {
  881. State = 1; // Into the Water
  882. EndBits.push_back(i - 1);
  883. FieldVals.push_back(FieldVal);
  884. ++Num;
  885. } else {
  886. State = 2; // Still in Island
  887. ++BitNo;
  888. FieldVal = FieldVal | Val << BitNo;
  889. }
  890. break;
  891. }
  892. }
  893. // If we are still in Island after the loop, do some housekeeping.
  894. if (State == 2) {
  895. EndBits.push_back(BitWidth - 1);
  896. FieldVals.push_back(FieldVal);
  897. ++Num;
  898. }
  899. assert(StartBits.size() == Num && EndBits.size() == Num &&
  900. FieldVals.size() == Num);
  901. return Num;
  902. }
  903. void FilterChooser::emitBinaryParser(raw_ostream &o, unsigned &Indentation,
  904. const OperandInfo &OpInfo) const {
  905. const std::string &Decoder = OpInfo.Decoder;
  906. if (OpInfo.numFields() != 1)
  907. o.indent(Indentation) << "tmp = 0;\n";
  908. for (const EncodingField &EF : OpInfo) {
  909. o.indent(Indentation) << "tmp ";
  910. if (OpInfo.numFields() != 1) o << '|';
  911. o << "= fieldFromInstruction"
  912. << "(insn, " << EF.Base << ", " << EF.Width << ')';
  913. if (OpInfo.numFields() != 1 || EF.Offset != 0)
  914. o << " << " << EF.Offset;
  915. o << ";\n";
  916. }
  917. if (Decoder != "")
  918. o.indent(Indentation) << Emitter->GuardPrefix << Decoder
  919. << "(MI, tmp, Address, Decoder)"
  920. << Emitter->GuardPostfix << "\n";
  921. else
  922. o.indent(Indentation) << "MI.addOperand(MCOperand::createImm(tmp));\n";
  923. }
  924. void FilterChooser::emitDecoder(raw_ostream &OS, unsigned Indentation,
  925. unsigned Opc) const {
  926. for (const auto &Op : Operands.find(Opc)->second) {
  927. // If a custom instruction decoder was specified, use that.
  928. if (Op.numFields() == 0 && Op.Decoder.size()) {
  929. OS.indent(Indentation) << Emitter->GuardPrefix << Op.Decoder
  930. << "(MI, insn, Address, Decoder)"
  931. << Emitter->GuardPostfix << "\n";
  932. break;
  933. }
  934. emitBinaryParser(OS, Indentation, Op);
  935. }
  936. }
  937. unsigned FilterChooser::getDecoderIndex(DecoderSet &Decoders,
  938. unsigned Opc) const {
  939. // Build up the predicate string.
  940. SmallString<256> Decoder;
  941. // FIXME: emitDecoder() function can take a buffer directly rather than
  942. // a stream.
  943. raw_svector_ostream S(Decoder);
  944. unsigned I = 4;
  945. emitDecoder(S, I, Opc);
  946. S.flush();
  947. // Using the full decoder string as the key value here is a bit
  948. // heavyweight, but is effective. If the string comparisons become a
  949. // performance concern, we can implement a mangling of the predicate
  950. // data easilly enough with a map back to the actual string. That's
  951. // overkill for now, though.
  952. // Make sure the predicate is in the table.
  953. Decoders.insert(StringRef(Decoder));
  954. // Now figure out the index for when we write out the table.
  955. DecoderSet::const_iterator P = std::find(Decoders.begin(),
  956. Decoders.end(),
  957. Decoder.str());
  958. return (unsigned)(P - Decoders.begin());
  959. }
  960. static void emitSinglePredicateMatch(raw_ostream &o, StringRef str,
  961. const std::string &PredicateNamespace) {
  962. if (str[0] == '!')
  963. o << "!Bits[" << PredicateNamespace << "::"
  964. << str.slice(1,str.size()) << "]";
  965. else
  966. o << "Bits[" << PredicateNamespace << "::" << str << "]";
  967. }
  968. bool FilterChooser::emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
  969. unsigned Opc) const {
  970. ListInit *Predicates =
  971. AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
  972. bool IsFirstEmission = true;
  973. for (unsigned i = 0; i < Predicates->size(); ++i) {
  974. Record *Pred = Predicates->getElementAsRecord(i);
  975. if (!Pred->getValue("AssemblerMatcherPredicate"))
  976. continue;
  977. std::string P = Pred->getValueAsString("AssemblerCondString");
  978. if (!P.length())
  979. continue;
  980. if (!IsFirstEmission)
  981. o << " && ";
  982. StringRef SR(P);
  983. std::pair<StringRef, StringRef> pairs = SR.split(',');
  984. while (pairs.second.size()) {
  985. emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
  986. o << " && ";
  987. pairs = pairs.second.split(',');
  988. }
  989. emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
  990. IsFirstEmission = false;
  991. }
  992. return !Predicates->empty();
  993. }
  994. bool FilterChooser::doesOpcodeNeedPredicate(unsigned Opc) const {
  995. ListInit *Predicates =
  996. AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
  997. for (unsigned i = 0; i < Predicates->size(); ++i) {
  998. Record *Pred = Predicates->getElementAsRecord(i);
  999. if (!Pred->getValue("AssemblerMatcherPredicate"))
  1000. continue;
  1001. std::string P = Pred->getValueAsString("AssemblerCondString");
  1002. if (!P.length())
  1003. continue;
  1004. return true;
  1005. }
  1006. return false;
  1007. }
  1008. unsigned FilterChooser::getPredicateIndex(DecoderTableInfo &TableInfo,
  1009. StringRef Predicate) const {
  1010. // Using the full predicate string as the key value here is a bit
  1011. // heavyweight, but is effective. If the string comparisons become a
  1012. // performance concern, we can implement a mangling of the predicate
  1013. // data easilly enough with a map back to the actual string. That's
  1014. // overkill for now, though.
  1015. // Make sure the predicate is in the table.
  1016. TableInfo.Predicates.insert(Predicate.str());
  1017. // Now figure out the index for when we write out the table.
  1018. PredicateSet::const_iterator P = std::find(TableInfo.Predicates.begin(),
  1019. TableInfo.Predicates.end(),
  1020. Predicate.str());
  1021. return (unsigned)(P - TableInfo.Predicates.begin());
  1022. }
  1023. void FilterChooser::emitPredicateTableEntry(DecoderTableInfo &TableInfo,
  1024. unsigned Opc) const {
  1025. if (!doesOpcodeNeedPredicate(Opc))
  1026. return;
  1027. // Build up the predicate string.
  1028. SmallString<256> Predicate;
  1029. // FIXME: emitPredicateMatch() functions can take a buffer directly rather
  1030. // than a stream.
  1031. raw_svector_ostream PS(Predicate);
  1032. unsigned I = 0;
  1033. emitPredicateMatch(PS, I, Opc);
  1034. // Figure out the index into the predicate table for the predicate just
  1035. // computed.
  1036. unsigned PIdx = getPredicateIndex(TableInfo, PS.str());
  1037. SmallString<16> PBytes;
  1038. raw_svector_ostream S(PBytes);
  1039. encodeULEB128(PIdx, S);
  1040. S.flush();
  1041. TableInfo.Table.push_back(MCD::OPC_CheckPredicate);
  1042. // Predicate index
  1043. for (unsigned i = 0, e = PBytes.size(); i != e; ++i)
  1044. TableInfo.Table.push_back(PBytes[i]);
  1045. // Push location for NumToSkip backpatching.
  1046. TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
  1047. TableInfo.Table.push_back(0);
  1048. TableInfo.Table.push_back(0);
  1049. }
  1050. void FilterChooser::emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
  1051. unsigned Opc) const {
  1052. BitsInit *SFBits =
  1053. AllInstructions[Opc]->TheDef->getValueAsBitsInit("SoftFail");
  1054. if (!SFBits) return;
  1055. BitsInit *InstBits = AllInstructions[Opc]->TheDef->getValueAsBitsInit("Inst");
  1056. APInt PositiveMask(BitWidth, 0ULL);
  1057. APInt NegativeMask(BitWidth, 0ULL);
  1058. for (unsigned i = 0; i < BitWidth; ++i) {
  1059. bit_value_t B = bitFromBits(*SFBits, i);
  1060. bit_value_t IB = bitFromBits(*InstBits, i);
  1061. if (B != BIT_TRUE) continue;
  1062. switch (IB) {
  1063. case BIT_FALSE:
  1064. // The bit is meant to be false, so emit a check to see if it is true.
  1065. PositiveMask.setBit(i);
  1066. break;
  1067. case BIT_TRUE:
  1068. // The bit is meant to be true, so emit a check to see if it is false.
  1069. NegativeMask.setBit(i);
  1070. break;
  1071. default:
  1072. // The bit is not set; this must be an error!
  1073. StringRef Name = AllInstructions[Opc]->TheDef->getName();
  1074. errs() << "SoftFail Conflict: bit SoftFail{" << i << "} in " << Name
  1075. << " is set but Inst{" << i << "} is unset!\n"
  1076. << " - You can only mark a bit as SoftFail if it is fully defined"
  1077. << " (1/0 - not '?') in Inst\n";
  1078. return;
  1079. }
  1080. }
  1081. bool NeedPositiveMask = PositiveMask.getBoolValue();
  1082. bool NeedNegativeMask = NegativeMask.getBoolValue();
  1083. if (!NeedPositiveMask && !NeedNegativeMask)
  1084. return;
  1085. TableInfo.Table.push_back(MCD::OPC_SoftFail);
  1086. SmallString<16> MaskBytes;
  1087. raw_svector_ostream S(MaskBytes);
  1088. if (NeedPositiveMask) {
  1089. encodeULEB128(PositiveMask.getZExtValue(), S);
  1090. S.flush();
  1091. for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
  1092. TableInfo.Table.push_back(MaskBytes[i]);
  1093. } else
  1094. TableInfo.Table.push_back(0);
  1095. if (NeedNegativeMask) {
  1096. MaskBytes.clear();
  1097. S.resync();
  1098. encodeULEB128(NegativeMask.getZExtValue(), S);
  1099. S.flush();
  1100. for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
  1101. TableInfo.Table.push_back(MaskBytes[i]);
  1102. } else
  1103. TableInfo.Table.push_back(0);
  1104. }
  1105. // Emits table entries to decode the singleton.
  1106. void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
  1107. unsigned Opc) const {
  1108. std::vector<unsigned> StartBits;
  1109. std::vector<unsigned> EndBits;
  1110. std::vector<uint64_t> FieldVals;
  1111. insn_t Insn;
  1112. insnWithID(Insn, Opc);
  1113. // Look for islands of undecoded bits of the singleton.
  1114. getIslands(StartBits, EndBits, FieldVals, Insn);
  1115. unsigned Size = StartBits.size();
  1116. // Emit the predicate table entry if one is needed.
  1117. emitPredicateTableEntry(TableInfo, Opc);
  1118. // Check any additional encoding fields needed.
  1119. for (unsigned I = Size; I != 0; --I) {
  1120. unsigned NumBits = EndBits[I-1] - StartBits[I-1] + 1;
  1121. TableInfo.Table.push_back(MCD::OPC_CheckField);
  1122. TableInfo.Table.push_back(StartBits[I-1]);
  1123. TableInfo.Table.push_back(NumBits);
  1124. uint8_t Buffer[8], *p;
  1125. encodeULEB128(FieldVals[I-1], Buffer);
  1126. for (p = Buffer; *p >= 128 ; ++p)
  1127. TableInfo.Table.push_back(*p);
  1128. TableInfo.Table.push_back(*p);
  1129. // Push location for NumToSkip backpatching.
  1130. TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
  1131. // The fixup is always 16-bits, so go ahead and allocate the space
  1132. // in the table so all our relative position calculations work OK even
  1133. // before we fully resolve the real value here.
  1134. TableInfo.Table.push_back(0);
  1135. TableInfo.Table.push_back(0);
  1136. }
  1137. // Check for soft failure of the match.
  1138. emitSoftFailTableEntry(TableInfo, Opc);
  1139. TableInfo.Table.push_back(MCD::OPC_Decode);
  1140. uint8_t Buffer[8], *p;
  1141. encodeULEB128(Opc, Buffer);
  1142. for (p = Buffer; *p >= 128 ; ++p)
  1143. TableInfo.Table.push_back(*p);
  1144. TableInfo.Table.push_back(*p);
  1145. unsigned DIdx = getDecoderIndex(TableInfo.Decoders, Opc);
  1146. SmallString<16> Bytes;
  1147. raw_svector_ostream S(Bytes);
  1148. encodeULEB128(DIdx, S);
  1149. S.flush();
  1150. // Decoder index
  1151. for (unsigned i = 0, e = Bytes.size(); i != e; ++i)
  1152. TableInfo.Table.push_back(Bytes[i]);
  1153. }
  1154. // Emits table entries to decode the singleton, and then to decode the rest.
  1155. void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
  1156. const Filter &Best) const {
  1157. unsigned Opc = Best.getSingletonOpc();
  1158. // complex singletons need predicate checks from the first singleton
  1159. // to refer forward to the variable filterchooser that follows.
  1160. TableInfo.FixupStack.emplace_back();
  1161. emitSingletonTableEntry(TableInfo, Opc);
  1162. resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
  1163. TableInfo.Table.size());
  1164. TableInfo.FixupStack.pop_back();
  1165. Best.getVariableFC().emitTableEntries(TableInfo);
  1166. }
  1167. // Assign a single filter and run with it. Top level API client can initialize
  1168. // with a single filter to start the filtering process.
  1169. void FilterChooser::runSingleFilter(unsigned startBit, unsigned numBit,
  1170. bool mixed) {
  1171. Filters.clear();
  1172. Filters.emplace_back(*this, startBit, numBit, true);
  1173. BestIndex = 0; // Sole Filter instance to choose from.
  1174. bestFilter().recurse();
  1175. }
  1176. // reportRegion is a helper function for filterProcessor to mark a region as
  1177. // eligible for use as a filter region.
  1178. void FilterChooser::reportRegion(bitAttr_t RA, unsigned StartBit,
  1179. unsigned BitIndex, bool AllowMixed) {
  1180. if (RA == ATTR_MIXED && AllowMixed)
  1181. Filters.emplace_back(*this, StartBit, BitIndex - StartBit, true);
  1182. else if (RA == ATTR_ALL_SET && !AllowMixed)
  1183. Filters.emplace_back(*this, StartBit, BitIndex - StartBit, false);
  1184. }
  1185. // FilterProcessor scans the well-known encoding bits of the instructions and
  1186. // builds up a list of candidate filters. It chooses the best filter and
  1187. // recursively descends down the decoding tree.
  1188. bool FilterChooser::filterProcessor(bool AllowMixed, bool Greedy) {
  1189. Filters.clear();
  1190. BestIndex = -1;
  1191. unsigned numInstructions = Opcodes.size();
  1192. assert(numInstructions && "Filter created with no instructions");
  1193. // No further filtering is necessary.
  1194. if (numInstructions == 1)
  1195. return true;
  1196. // Heuristics. See also doFilter()'s "Heuristics" comment when num of
  1197. // instructions is 3.
  1198. if (AllowMixed && !Greedy) {
  1199. assert(numInstructions == 3);
  1200. for (unsigned i = 0; i < Opcodes.size(); ++i) {
  1201. std::vector<unsigned> StartBits;
  1202. std::vector<unsigned> EndBits;
  1203. std::vector<uint64_t> FieldVals;
  1204. insn_t Insn;
  1205. insnWithID(Insn, Opcodes[i]);
  1206. // Look for islands of undecoded bits of any instruction.
  1207. if (getIslands(StartBits, EndBits, FieldVals, Insn) > 0) {
  1208. // Found an instruction with island(s). Now just assign a filter.
  1209. runSingleFilter(StartBits[0], EndBits[0] - StartBits[0] + 1, true);
  1210. return true;
  1211. }
  1212. }
  1213. }
  1214. unsigned BitIndex;
  1215. // We maintain BIT_WIDTH copies of the bitAttrs automaton.
  1216. // The automaton consumes the corresponding bit from each
  1217. // instruction.
  1218. //
  1219. // Input symbols: 0, 1, and _ (unset).
  1220. // States: NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED.
  1221. // Initial state: NONE.
  1222. //
  1223. // (NONE) ------- [01] -> (ALL_SET)
  1224. // (NONE) ------- _ ----> (ALL_UNSET)
  1225. // (ALL_SET) ---- [01] -> (ALL_SET)
  1226. // (ALL_SET) ---- _ ----> (MIXED)
  1227. // (ALL_UNSET) -- [01] -> (MIXED)
  1228. // (ALL_UNSET) -- _ ----> (ALL_UNSET)
  1229. // (MIXED) ------ . ----> (MIXED)
  1230. // (FILTERED)---- . ----> (FILTERED)
  1231. std::vector<bitAttr_t> bitAttrs;
  1232. // FILTERED bit positions provide no entropy and are not worthy of pursuing.
  1233. // Filter::recurse() set either BIT_TRUE or BIT_FALSE for each position.
  1234. for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex)
  1235. if (FilterBitValues[BitIndex] == BIT_TRUE ||
  1236. FilterBitValues[BitIndex] == BIT_FALSE)
  1237. bitAttrs.push_back(ATTR_FILTERED);
  1238. else
  1239. bitAttrs.push_back(ATTR_NONE);
  1240. for (unsigned InsnIndex = 0; InsnIndex < numInstructions; ++InsnIndex) {
  1241. insn_t insn;
  1242. insnWithID(insn, Opcodes[InsnIndex]);
  1243. for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
  1244. switch (bitAttrs[BitIndex]) {
  1245. case ATTR_NONE:
  1246. if (insn[BitIndex] == BIT_UNSET)
  1247. bitAttrs[BitIndex] = ATTR_ALL_UNSET;
  1248. else
  1249. bitAttrs[BitIndex] = ATTR_ALL_SET;
  1250. break;
  1251. case ATTR_ALL_SET:
  1252. if (insn[BitIndex] == BIT_UNSET)
  1253. bitAttrs[BitIndex] = ATTR_MIXED;
  1254. break;
  1255. case ATTR_ALL_UNSET:
  1256. if (insn[BitIndex] != BIT_UNSET)
  1257. bitAttrs[BitIndex] = ATTR_MIXED;
  1258. break;
  1259. case ATTR_MIXED:
  1260. case ATTR_FILTERED:
  1261. break;
  1262. }
  1263. }
  1264. }
  1265. // The regionAttr automaton consumes the bitAttrs automatons' state,
  1266. // lowest-to-highest.
  1267. //
  1268. // Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed)
  1269. // States: NONE, ALL_SET, MIXED
  1270. // Initial state: NONE
  1271. //
  1272. // (NONE) ----- F --> (NONE)
  1273. // (NONE) ----- S --> (ALL_SET) ; and set region start
  1274. // (NONE) ----- U --> (NONE)
  1275. // (NONE) ----- M --> (MIXED) ; and set region start
  1276. // (ALL_SET) -- F --> (NONE) ; and report an ALL_SET region
  1277. // (ALL_SET) -- S --> (ALL_SET)
  1278. // (ALL_SET) -- U --> (NONE) ; and report an ALL_SET region
  1279. // (ALL_SET) -- M --> (MIXED) ; and report an ALL_SET region
  1280. // (MIXED) ---- F --> (NONE) ; and report a MIXED region
  1281. // (MIXED) ---- S --> (ALL_SET) ; and report a MIXED region
  1282. // (MIXED) ---- U --> (NONE) ; and report a MIXED region
  1283. // (MIXED) ---- M --> (MIXED)
  1284. bitAttr_t RA = ATTR_NONE;
  1285. unsigned StartBit = 0;
  1286. for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
  1287. bitAttr_t bitAttr = bitAttrs[BitIndex];
  1288. assert(bitAttr != ATTR_NONE && "Bit without attributes");
  1289. switch (RA) {
  1290. case ATTR_NONE:
  1291. switch (bitAttr) {
  1292. case ATTR_FILTERED:
  1293. break;
  1294. case ATTR_ALL_SET:
  1295. StartBit = BitIndex;
  1296. RA = ATTR_ALL_SET;
  1297. break;
  1298. case ATTR_ALL_UNSET:
  1299. break;
  1300. case ATTR_MIXED:
  1301. StartBit = BitIndex;
  1302. RA = ATTR_MIXED;
  1303. break;
  1304. default:
  1305. llvm_unreachable("Unexpected bitAttr!");
  1306. }
  1307. break;
  1308. case ATTR_ALL_SET:
  1309. switch (bitAttr) {
  1310. case ATTR_FILTERED:
  1311. reportRegion(RA, StartBit, BitIndex, AllowMixed);
  1312. RA = ATTR_NONE;
  1313. break;
  1314. case ATTR_ALL_SET:
  1315. break;
  1316. case ATTR_ALL_UNSET:
  1317. reportRegion(RA, StartBit, BitIndex, AllowMixed);
  1318. RA = ATTR_NONE;
  1319. break;
  1320. case ATTR_MIXED:
  1321. reportRegion(RA, StartBit, BitIndex, AllowMixed);
  1322. StartBit = BitIndex;
  1323. RA = ATTR_MIXED;
  1324. break;
  1325. default:
  1326. llvm_unreachable("Unexpected bitAttr!");
  1327. }
  1328. break;
  1329. case ATTR_MIXED:
  1330. switch (bitAttr) {
  1331. case ATTR_FILTERED:
  1332. reportRegion(RA, StartBit, BitIndex, AllowMixed);
  1333. StartBit = BitIndex;
  1334. RA = ATTR_NONE;
  1335. break;
  1336. case ATTR_ALL_SET:
  1337. reportRegion(RA, StartBit, BitIndex, AllowMixed);
  1338. StartBit = BitIndex;
  1339. RA = ATTR_ALL_SET;
  1340. break;
  1341. case ATTR_ALL_UNSET:
  1342. reportRegion(RA, StartBit, BitIndex, AllowMixed);
  1343. RA = ATTR_NONE;
  1344. break;
  1345. case ATTR_MIXED:
  1346. break;
  1347. default:
  1348. llvm_unreachable("Unexpected bitAttr!");
  1349. }
  1350. break;
  1351. case ATTR_ALL_UNSET:
  1352. llvm_unreachable("regionAttr state machine has no ATTR_UNSET state");
  1353. case ATTR_FILTERED:
  1354. llvm_unreachable("regionAttr state machine has no ATTR_FILTERED state");
  1355. }
  1356. }
  1357. // At the end, if we're still in ALL_SET or MIXED states, report a region
  1358. switch (RA) {
  1359. case ATTR_NONE:
  1360. break;
  1361. case ATTR_FILTERED:
  1362. break;
  1363. case ATTR_ALL_SET:
  1364. reportRegion(RA, StartBit, BitIndex, AllowMixed);
  1365. break;
  1366. case ATTR_ALL_UNSET:
  1367. break;
  1368. case ATTR_MIXED:
  1369. reportRegion(RA, StartBit, BitIndex, AllowMixed);
  1370. break;
  1371. }
  1372. // We have finished with the filter processings. Now it's time to choose
  1373. // the best performing filter.
  1374. BestIndex = 0;
  1375. bool AllUseless = true;
  1376. unsigned BestScore = 0;
  1377. for (unsigned i = 0, e = Filters.size(); i != e; ++i) {
  1378. unsigned Usefulness = Filters[i].usefulness();
  1379. if (Usefulness)
  1380. AllUseless = false;
  1381. if (Usefulness > BestScore) {
  1382. BestIndex = i;
  1383. BestScore = Usefulness;
  1384. }
  1385. }
  1386. if (!AllUseless)
  1387. bestFilter().recurse();
  1388. return !AllUseless;
  1389. } // end of FilterChooser::filterProcessor(bool)
  1390. // Decides on the best configuration of filter(s) to use in order to decode
  1391. // the instructions. A conflict of instructions may occur, in which case we
  1392. // dump the conflict set to the standard error.
  1393. void FilterChooser::doFilter() {
  1394. unsigned Num = Opcodes.size();
  1395. assert(Num && "FilterChooser created with no instructions");
  1396. // Try regions of consecutive known bit values first.
  1397. if (filterProcessor(false))
  1398. return;
  1399. // Then regions of mixed bits (both known and unitialized bit values allowed).
  1400. if (filterProcessor(true))
  1401. return;
  1402. // Heuristics to cope with conflict set {t2CMPrs, t2SUBSrr, t2SUBSrs} where
  1403. // no single instruction for the maximum ATTR_MIXED region Inst{14-4} has a
  1404. // well-known encoding pattern. In such case, we backtrack and scan for the
  1405. // the very first consecutive ATTR_ALL_SET region and assign a filter to it.
  1406. if (Num == 3 && filterProcessor(true, false))
  1407. return;
  1408. // If we come to here, the instruction decoding has failed.
  1409. // Set the BestIndex to -1 to indicate so.
  1410. BestIndex = -1;
  1411. }
  1412. // emitTableEntries - Emit state machine entries to decode our share of
  1413. // instructions.
  1414. void FilterChooser::emitTableEntries(DecoderTableInfo &TableInfo) const {
  1415. if (Opcodes.size() == 1) {
  1416. // There is only one instruction in the set, which is great!
  1417. // Call emitSingletonDecoder() to see whether there are any remaining
  1418. // encodings bits.
  1419. emitSingletonTableEntry(TableInfo, Opcodes[0]);
  1420. return;
  1421. }
  1422. // Choose the best filter to do the decodings!
  1423. if (BestIndex != -1) {
  1424. const Filter &Best = Filters[BestIndex];
  1425. if (Best.getNumFiltered() == 1)
  1426. emitSingletonTableEntry(TableInfo, Best);
  1427. else
  1428. Best.emitTableEntry(TableInfo);
  1429. return;
  1430. }
  1431. // We don't know how to decode these instructions! Dump the
  1432. // conflict set and bail.
  1433. // Print out useful conflict information for postmortem analysis.
  1434. errs() << "Decoding Conflict:\n";
  1435. dumpStack(errs(), "\t\t");
  1436. for (unsigned i = 0; i < Opcodes.size(); ++i) {
  1437. const std::string &Name = nameWithID(Opcodes[i]);
  1438. errs() << '\t' << Name << " ";
  1439. dumpBits(errs(),
  1440. getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
  1441. errs() << '\n';
  1442. }
  1443. }
  1444. static bool populateInstruction(CodeGenTarget &Target,
  1445. const CodeGenInstruction &CGI, unsigned Opc,
  1446. std::map<unsigned, std::vector<OperandInfo> > &Operands){
  1447. const Record &Def = *CGI.TheDef;
  1448. // If all the bit positions are not specified; do not decode this instruction.
  1449. // We are bound to fail! For proper disassembly, the well-known encoding bits
  1450. // of the instruction must be fully specified.
  1451. BitsInit &Bits = getBitsField(Def, "Inst");
  1452. if (Bits.allInComplete()) return false;
  1453. std::vector<OperandInfo> InsnOperands;
  1454. // If the instruction has specified a custom decoding hook, use that instead
  1455. // of trying to auto-generate the decoder.
  1456. std::string InstDecoder = Def.getValueAsString("DecoderMethod");
  1457. if (InstDecoder != "") {
  1458. InsnOperands.push_back(OperandInfo(InstDecoder));
  1459. Operands[Opc] = InsnOperands;
  1460. return true;
  1461. }
  1462. // Generate a description of the operand of the instruction that we know
  1463. // how to decode automatically.
  1464. // FIXME: We'll need to have a way to manually override this as needed.
  1465. // Gather the outputs/inputs of the instruction, so we can find their
  1466. // positions in the encoding. This assumes for now that they appear in the
  1467. // MCInst in the order that they're listed.
  1468. std::vector<std::pair<Init*, std::string> > InOutOperands;
  1469. DagInit *Out = Def.getValueAsDag("OutOperandList");
  1470. DagInit *In = Def.getValueAsDag("InOperandList");
  1471. for (unsigned i = 0; i < Out->getNumArgs(); ++i)
  1472. InOutOperands.push_back(std::make_pair(Out->getArg(i), Out->getArgName(i)));
  1473. for (unsigned i = 0; i < In->getNumArgs(); ++i)
  1474. InOutOperands.push_back(std::make_pair(In->getArg(i), In->getArgName(i)));
  1475. // Search for tied operands, so that we can correctly instantiate
  1476. // operands that are not explicitly represented in the encoding.
  1477. std::map<std::string, std::string> TiedNames;
  1478. for (unsigned i = 0; i < CGI.Operands.size(); ++i) {
  1479. int tiedTo = CGI.Operands[i].getTiedRegister();
  1480. if (tiedTo != -1) {
  1481. std::pair<unsigned, unsigned> SO =
  1482. CGI.Operands.getSubOperandNumber(tiedTo);
  1483. TiedNames[InOutOperands[i].second] = InOutOperands[SO.first].second;
  1484. TiedNames[InOutOperands[SO.first].second] = InOutOperands[i].second;
  1485. }
  1486. }
  1487. std::map<std::string, std::vector<OperandInfo> > NumberedInsnOperands;
  1488. std::set<std::string> NumberedInsnOperandsNoTie;
  1489. if (Target.getInstructionSet()->
  1490. getValueAsBit("decodePositionallyEncodedOperands")) {
  1491. const std::vector<RecordVal> &Vals = Def.getValues();
  1492. unsigned NumberedOp = 0;
  1493. std::set<unsigned> NamedOpIndices;
  1494. if (Target.getInstructionSet()->
  1495. getValueAsBit("noNamedPositionallyEncodedOperands"))
  1496. // Collect the set of operand indices that might correspond to named
  1497. // operand, and skip these when assigning operands based on position.
  1498. for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
  1499. unsigned OpIdx;
  1500. if (!CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
  1501. continue;
  1502. NamedOpIndices.insert(OpIdx);
  1503. }
  1504. for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
  1505. // Ignore fixed fields in the record, we're looking for values like:
  1506. // bits<5> RST = { ?, ?, ?, ?, ? };
  1507. if (Vals[i].getPrefix() || Vals[i].getValue()->isComplete())
  1508. continue;
  1509. // Determine if Vals[i] actually contributes to the Inst encoding.
  1510. unsigned bi = 0;
  1511. for (; bi < Bits.getNumBits(); ++bi) {
  1512. VarInit *Var = nullptr;
  1513. VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
  1514. if (BI)
  1515. Var = dyn_cast<VarInit>(BI->getBitVar());
  1516. else
  1517. Var = dyn_cast<VarInit>(Bits.getBit(bi));
  1518. if (Var && Var->getName() == Vals[i].getName())
  1519. break;
  1520. }
  1521. if (bi == Bits.getNumBits())
  1522. continue;
  1523. // Skip variables that correspond to explicitly-named operands.
  1524. unsigned OpIdx;
  1525. if (CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
  1526. continue;
  1527. // Get the bit range for this operand:
  1528. unsigned bitStart = bi++, bitWidth = 1;
  1529. for (; bi < Bits.getNumBits(); ++bi) {
  1530. VarInit *Var = nullptr;
  1531. VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
  1532. if (BI)
  1533. Var = dyn_cast<VarInit>(BI->getBitVar());
  1534. else
  1535. Var = dyn_cast<VarInit>(Bits.getBit(bi));
  1536. if (!Var)
  1537. break;
  1538. if (Var->getName() != Vals[i].getName())
  1539. break;
  1540. ++bitWidth;
  1541. }
  1542. unsigned NumberOps = CGI.Operands.size();
  1543. while (NumberedOp < NumberOps &&
  1544. (CGI.Operands.isFlatOperandNotEmitted(NumberedOp) ||
  1545. (!NamedOpIndices.empty() && NamedOpIndices.count(
  1546. CGI.Operands.getSubOperandNumber(NumberedOp).first))))
  1547. ++NumberedOp;
  1548. OpIdx = NumberedOp++;
  1549. // OpIdx now holds the ordered operand number of Vals[i].
  1550. std::pair<unsigned, unsigned> SO =
  1551. CGI.Operands.getSubOperandNumber(OpIdx);
  1552. const std::string &Name = CGI.Operands[SO.first].Name;
  1553. DEBUG(dbgs() << "Numbered operand mapping for " << Def.getName() << ": " <<
  1554. Name << "(" << SO.first << ", " << SO.second << ") => " <<
  1555. Vals[i].getName() << "\n");
  1556. std::string Decoder = "";
  1557. Record *TypeRecord = CGI.Operands[SO.first].Rec;
  1558. RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
  1559. StringInit *String = DecoderString ?
  1560. dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
  1561. if (String && String->getValue() != "")
  1562. Decoder = String->getValue();
  1563. if (Decoder == "" &&
  1564. CGI.Operands[SO.first].MIOperandInfo &&
  1565. CGI.Operands[SO.first].MIOperandInfo->getNumArgs()) {
  1566. Init *Arg = CGI.Operands[SO.first].MIOperandInfo->
  1567. getArg(SO.second);
  1568. if (TypedInit *TI = cast<TypedInit>(Arg)) {
  1569. RecordRecTy *Type = cast<RecordRecTy>(TI->getType());
  1570. TypeRecord = Type->getRecord();
  1571. }
  1572. }
  1573. bool isReg = false;
  1574. if (TypeRecord->isSubClassOf("RegisterOperand"))
  1575. TypeRecord = TypeRecord->getValueAsDef("RegClass");
  1576. if (TypeRecord->isSubClassOf("RegisterClass")) {
  1577. Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
  1578. isReg = true;
  1579. } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) {
  1580. Decoder = "DecodePointerLikeRegClass" +
  1581. utostr(TypeRecord->getValueAsInt("RegClassKind"));
  1582. isReg = true;
  1583. }
  1584. DecoderString = TypeRecord->getValue("DecoderMethod");
  1585. String = DecoderString ?
  1586. dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
  1587. if (!isReg && String && String->getValue() != "")
  1588. Decoder = String->getValue();
  1589. OperandInfo OpInfo(Decoder);
  1590. OpInfo.addField(bitStart, bitWidth, 0);
  1591. NumberedInsnOperands[Name].push_back(OpInfo);
  1592. // FIXME: For complex operands with custom decoders we can't handle tied
  1593. // sub-operands automatically. Skip those here and assume that this is
  1594. // fixed up elsewhere.
  1595. if (CGI.Operands[SO.first].MIOperandInfo &&
  1596. CGI.Operands[SO.first].MIOperandInfo->getNumArgs() > 1 &&
  1597. String && String->getValue() != "")
  1598. NumberedInsnOperandsNoTie.insert(Name);
  1599. }
  1600. }
  1601. // For each operand, see if we can figure out where it is encoded.
  1602. for (const auto &Op : InOutOperands) {
  1603. if (!NumberedInsnOperands[Op.second].empty()) {
  1604. InsnOperands.insert(InsnOperands.end(),
  1605. NumberedInsnOperands[Op.second].begin(),
  1606. NumberedInsnOperands[Op.second].end());
  1607. continue;
  1608. }
  1609. if (!NumberedInsnOperands[TiedNames[Op.second]].empty()) {
  1610. if (!NumberedInsnOperandsNoTie.count(TiedNames[Op.second])) {
  1611. // Figure out to which (sub)operand we're tied.
  1612. unsigned i = CGI.Operands.getOperandNamed(TiedNames[Op.second]);
  1613. int tiedTo = CGI.Operands[i].getTiedRegister();
  1614. if (tiedTo == -1) {
  1615. i = CGI.Operands.getOperandNamed(Op.second);
  1616. tiedTo = CGI.Operands[i].getTiedRegister();
  1617. }
  1618. if (tiedTo != -1) {
  1619. std::pair<unsigned, unsigned> SO =
  1620. CGI.Operands.getSubOperandNumber(tiedTo);
  1621. InsnOperands.push_back(NumberedInsnOperands[TiedNames[Op.second]]
  1622. [SO.second]);
  1623. }
  1624. }
  1625. continue;
  1626. }
  1627. std::string Decoder = "";
  1628. // At this point, we can locate the field, but we need to know how to
  1629. // interpret it. As a first step, require the target to provide callbacks
  1630. // for decoding register classes.
  1631. // FIXME: This need to be extended to handle instructions with custom
  1632. // decoder methods, and operands with (simple) MIOperandInfo's.
  1633. TypedInit *TI = cast<TypedInit>(Op.first);
  1634. RecordRecTy *Type = cast<RecordRecTy>(TI->getType());
  1635. Record *TypeRecord = Type->getRecord();
  1636. bool isReg = false;
  1637. if (TypeRecord->isSubClassOf("RegisterOperand"))
  1638. TypeRecord = TypeRecord->getValueAsDef("RegClass");
  1639. if (TypeRecord->isSubClassOf("RegisterClass")) {
  1640. Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
  1641. isReg = true;
  1642. } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) {
  1643. Decoder = "DecodePointerLikeRegClass" +
  1644. utostr(TypeRecord->getValueAsInt("RegClassKind"));
  1645. isReg = true;
  1646. }
  1647. RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
  1648. StringInit *String = DecoderString ?
  1649. dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
  1650. if (!isReg && String && String->getValue() != "")
  1651. Decoder = String->getValue();
  1652. OperandInfo OpInfo(Decoder);
  1653. unsigned Base = ~0U;
  1654. unsigned Width = 0;
  1655. unsigned Offset = 0;
  1656. for (unsigned bi = 0; bi < Bits.getNumBits(); ++bi) {
  1657. VarInit *Var = nullptr;
  1658. VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
  1659. if (BI)
  1660. Var = dyn_cast<VarInit>(BI->getBitVar());
  1661. else
  1662. Var = dyn_cast<VarInit>(Bits.getBit(bi));
  1663. if (!Var) {
  1664. if (Base != ~0U) {
  1665. OpInfo.addField(Base, Width, Offset);
  1666. Base = ~0U;
  1667. Width = 0;
  1668. Offset = 0;
  1669. }
  1670. continue;
  1671. }
  1672. if (Var->getName() != Op.second &&
  1673. Var->getName() != TiedNames[Op.second]) {
  1674. if (Base != ~0U) {
  1675. OpInfo.addField(Base, Width, Offset);
  1676. Base = ~0U;
  1677. Width = 0;
  1678. Offset = 0;
  1679. }
  1680. continue;
  1681. }
  1682. if (Base == ~0U) {
  1683. Base = bi;
  1684. Width = 1;
  1685. Offset = BI ? BI->getBitNum() : 0;
  1686. } else if (BI && BI->getBitNum() != Offset + Width) {
  1687. OpInfo.addField(Base, Width, Offset);
  1688. Base = bi;
  1689. Width = 1;
  1690. Offset = BI->getBitNum();
  1691. } else {
  1692. ++Width;
  1693. }
  1694. }
  1695. if (Base != ~0U)
  1696. OpInfo.addField(Base, Width, Offset);
  1697. if (OpInfo.numFields() > 0)
  1698. InsnOperands.push_back(OpInfo);
  1699. }
  1700. Operands[Opc] = InsnOperands;
  1701. #if 0
  1702. DEBUG({
  1703. // Dumps the instruction encoding bits.
  1704. dumpBits(errs(), Bits);
  1705. errs() << '\n';
  1706. // Dumps the list of operand info.
  1707. for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
  1708. const CGIOperandList::OperandInfo &Info = CGI.Operands[i];
  1709. const std::string &OperandName = Info.Name;
  1710. const Record &OperandDef = *Info.Rec;
  1711. errs() << "\t" << OperandName << " (" << OperandDef.getName() << ")\n";
  1712. }
  1713. });
  1714. #endif
  1715. return true;
  1716. }
  1717. // emitFieldFromInstruction - Emit the templated helper function
  1718. // fieldFromInstruction().
  1719. static void emitFieldFromInstruction(formatted_raw_ostream &OS) {
  1720. OS << "// Helper function for extracting fields from encoded instructions.\n"
  1721. << "template<typename InsnType>\n"
  1722. << "static InsnType fieldFromInstruction(InsnType insn, unsigned startBit,\n"
  1723. << " unsigned numBits) {\n"
  1724. << " assert(startBit + numBits <= (sizeof(InsnType)*8) &&\n"
  1725. << " \"Instruction field out of bounds!\");\n"
  1726. << " InsnType fieldMask;\n"
  1727. << " if (numBits == sizeof(InsnType)*8)\n"
  1728. << " fieldMask = (InsnType)(-1LL);\n"
  1729. << " else\n"
  1730. << " fieldMask = (((InsnType)1 << numBits) - 1) << startBit;\n"
  1731. << " return (insn & fieldMask) >> startBit;\n"
  1732. << "}\n\n";
  1733. }
  1734. // emitDecodeInstruction - Emit the templated helper function
  1735. // decodeInstruction().
  1736. static void emitDecodeInstruction(formatted_raw_ostream &OS) {
  1737. OS << "template<typename InsnType>\n"
  1738. << "static DecodeStatus decodeInstruction(const uint8_t DecodeTable[], MCInst &MI,\n"
  1739. << " InsnType insn, uint64_t Address,\n"
  1740. << " const void *DisAsm,\n"
  1741. << " const MCSubtargetInfo &STI) {\n"
  1742. << " const FeatureBitset& Bits = STI.getFeatureBits();\n"
  1743. << "\n"
  1744. << " const uint8_t *Ptr = DecodeTable;\n"
  1745. << " uint32_t CurFieldValue = 0;\n"
  1746. << " DecodeStatus S = MCDisassembler::Success;\n"
  1747. << " for (;;) {\n"
  1748. << " ptrdiff_t Loc = Ptr - DecodeTable;\n"
  1749. << " switch (*Ptr) {\n"
  1750. << " default:\n"
  1751. << " errs() << Loc << \": Unexpected decode table opcode!\\n\";\n"
  1752. << " return MCDisassembler::Fail;\n"
  1753. << " case MCD::OPC_ExtractField: {\n"
  1754. << " unsigned Start = *++Ptr;\n"
  1755. << " unsigned Len = *++Ptr;\n"
  1756. << " ++Ptr;\n"
  1757. << " CurFieldValue = fieldFromInstruction(insn, Start, Len);\n"
  1758. << " DEBUG(dbgs() << Loc << \": OPC_ExtractField(\" << Start << \", \"\n"
  1759. << " << Len << \"): \" << CurFieldValue << \"\\n\");\n"
  1760. << " break;\n"
  1761. << " }\n"
  1762. << " case MCD::OPC_FilterValue: {\n"
  1763. << " // Decode the field value.\n"
  1764. << " unsigned Len;\n"
  1765. << " InsnType Val = decodeULEB128(++Ptr, &Len);\n"
  1766. << " Ptr += Len;\n"
  1767. << " // NumToSkip is a plain 16-bit integer.\n"
  1768. << " unsigned NumToSkip = *Ptr++;\n"
  1769. << " NumToSkip |= (*Ptr++) << 8;\n"
  1770. << "\n"
  1771. << " // Perform the filter operation.\n"
  1772. << " if (Val != CurFieldValue)\n"
  1773. << " Ptr += NumToSkip;\n"
  1774. << " DEBUG(dbgs() << Loc << \": OPC_FilterValue(\" << Val << \", \" << NumToSkip\n"
  1775. << " << \"): \" << ((Val != CurFieldValue) ? \"FAIL:\" : \"PASS:\")\n"
  1776. << " << \" continuing at \" << (Ptr - DecodeTable) << \"\\n\");\n"
  1777. << "\n"
  1778. << " break;\n"
  1779. << " }\n"
  1780. << " case MCD::OPC_CheckField: {\n"
  1781. << " unsigned Start = *++Ptr;\n"
  1782. << " unsigned Len = *++Ptr;\n"
  1783. << " InsnType FieldValue = fieldFromInstruction(insn, Start, Len);\n"
  1784. << " // Decode the field value.\n"
  1785. << " uint32_t ExpectedValue = decodeULEB128(++Ptr, &Len);\n"
  1786. << " Ptr += Len;\n"
  1787. << " // NumToSkip is a plain 16-bit integer.\n"
  1788. << " unsigned NumToSkip = *Ptr++;\n"
  1789. << " NumToSkip |= (*Ptr++) << 8;\n"
  1790. << "\n"
  1791. << " // If the actual and expected values don't match, skip.\n"
  1792. << " if (ExpectedValue != FieldValue)\n"
  1793. << " Ptr += NumToSkip;\n"
  1794. << " DEBUG(dbgs() << Loc << \": OPC_CheckField(\" << Start << \", \"\n"
  1795. << " << Len << \", \" << ExpectedValue << \", \" << NumToSkip\n"
  1796. << " << \"): FieldValue = \" << FieldValue << \", ExpectedValue = \"\n"
  1797. << " << ExpectedValue << \": \"\n"
  1798. << " << ((ExpectedValue == FieldValue) ? \"PASS\\n\" : \"FAIL\\n\"));\n"
  1799. << " break;\n"
  1800. << " }\n"
  1801. << " case MCD::OPC_CheckPredicate: {\n"
  1802. << " unsigned Len;\n"
  1803. << " // Decode the Predicate Index value.\n"
  1804. << " unsigned PIdx = decodeULEB128(++Ptr, &Len);\n"
  1805. << " Ptr += Len;\n"
  1806. << " // NumToSkip is a plain 16-bit integer.\n"
  1807. << " unsigned NumToSkip = *Ptr++;\n"
  1808. << " NumToSkip |= (*Ptr++) << 8;\n"
  1809. << " // Check the predicate.\n"
  1810. << " bool Pred;\n"
  1811. << " if (!(Pred = checkDecoderPredicate(PIdx, Bits)))\n"
  1812. << " Ptr += NumToSkip;\n"
  1813. << " (void)Pred;\n"
  1814. << " DEBUG(dbgs() << Loc << \": OPC_CheckPredicate(\" << PIdx << \"): \"\n"
  1815. << " << (Pred ? \"PASS\\n\" : \"FAIL\\n\"));\n"
  1816. << "\n"
  1817. << " break;\n"
  1818. << " }\n"
  1819. << " case MCD::OPC_Decode: {\n"
  1820. << " unsigned Len;\n"
  1821. << " // Decode the Opcode value.\n"
  1822. << " unsigned Opc = decodeULEB128(++Ptr, &Len);\n"
  1823. << " Ptr += Len;\n"
  1824. << " unsigned DecodeIdx = decodeULEB128(Ptr, &Len);\n"
  1825. << " Ptr += Len;\n"
  1826. << " DEBUG(dbgs() << Loc << \": OPC_Decode: opcode \" << Opc\n"
  1827. << " << \", using decoder \" << DecodeIdx << \"\\n\" );\n"
  1828. << " DEBUG(dbgs() << \"----- DECODE SUCCESSFUL -----\\n\");\n"
  1829. << "\n"
  1830. << " MI.setOpcode(Opc);\n"
  1831. << " return decodeToMCInst(S, DecodeIdx, insn, MI, Address, DisAsm);\n"
  1832. << " }\n"
  1833. << " case MCD::OPC_SoftFail: {\n"
  1834. << " // Decode the mask values.\n"
  1835. << " unsigned Len;\n"
  1836. << " InsnType PositiveMask = decodeULEB128(++Ptr, &Len);\n"
  1837. << " Ptr += Len;\n"
  1838. << " InsnType NegativeMask = decodeULEB128(Ptr, &Len);\n"
  1839. << " Ptr += Len;\n"
  1840. << " bool Fail = (insn & PositiveMask) || (~insn & NegativeMask);\n"
  1841. << " if (Fail)\n"
  1842. << " S = MCDisassembler::SoftFail;\n"
  1843. << " DEBUG(dbgs() << Loc << \": OPC_SoftFail: \" << (Fail ? \"FAIL\\n\":\"PASS\\n\"));\n"
  1844. << " break;\n"
  1845. << " }\n"
  1846. << " case MCD::OPC_Fail: {\n"
  1847. << " DEBUG(dbgs() << Loc << \": OPC_Fail\\n\");\n"
  1848. << " return MCDisassembler::Fail;\n"
  1849. << " }\n"
  1850. << " }\n"
  1851. << " }\n"
  1852. << " llvm_unreachable(\"bogosity detected in disassembler state machine!\");\n"
  1853. << "}\n\n";
  1854. }
  1855. // Emits disassembler code for instruction decoding.
  1856. void FixedLenDecoderEmitter::run(raw_ostream &o) {
  1857. formatted_raw_ostream OS(o);
  1858. OS << "#include \"llvm/MC/MCInst.h\"\n";
  1859. OS << "#include \"llvm/Support/Debug.h\"\n";
  1860. OS << "#include \"llvm/Support/DataTypes.h\"\n";
  1861. OS << "#include \"llvm/Support/LEB128.h\"\n";
  1862. OS << "#include \"llvm/Support/raw_ostream.h\"\n";
  1863. OS << "#include <assert.h>\n";
  1864. OS << '\n';
  1865. OS << "namespace llvm {\n\n";
  1866. emitFieldFromInstruction(OS);
  1867. Target.reverseBitsForLittleEndianEncoding();
  1868. // Parameterize the decoders based on namespace and instruction width.
  1869. NumberedInstructions = &Target.getInstructionsByEnumValue();
  1870. std::map<std::pair<std::string, unsigned>,
  1871. std::vector<unsigned> > OpcMap;
  1872. std::map<unsigned, std::vector<OperandInfo> > Operands;
  1873. for (unsigned i = 0; i < NumberedInstructions->size(); ++i) {
  1874. const CodeGenInstruction *Inst = NumberedInstructions->at(i);
  1875. const Record *Def = Inst->TheDef;
  1876. unsigned Size = Def->getValueAsInt("Size");
  1877. if (Def->getValueAsString("Namespace") == "TargetOpcode" ||
  1878. Def->getValueAsBit("isPseudo") ||
  1879. Def->getValueAsBit("isAsmParserOnly") ||
  1880. Def->getValueAsBit("isCodeGenOnly"))
  1881. continue;
  1882. std::string DecoderNamespace = Def->getValueAsString("DecoderNamespace");
  1883. if (Size) {
  1884. if (populateInstruction(Target, *Inst, i, Operands)) {
  1885. OpcMap[std::make_pair(DecoderNamespace, Size)].push_back(i);
  1886. }
  1887. }
  1888. }
  1889. DecoderTableInfo TableInfo;
  1890. for (const auto &Opc : OpcMap) {
  1891. // Emit the decoder for this namespace+width combination.
  1892. FilterChooser FC(*NumberedInstructions, Opc.second, Operands,
  1893. 8*Opc.first.second, this);
  1894. // The decode table is cleared for each top level decoder function. The
  1895. // predicates and decoders themselves, however, are shared across all
  1896. // decoders to give more opportunities for uniqueing.
  1897. TableInfo.Table.clear();
  1898. TableInfo.FixupStack.clear();
  1899. TableInfo.Table.reserve(16384);
  1900. TableInfo.FixupStack.emplace_back();
  1901. FC.emitTableEntries(TableInfo);
  1902. // Any NumToSkip fixups in the top level scope can resolve to the
  1903. // OPC_Fail at the end of the table.
  1904. assert(TableInfo.FixupStack.size() == 1 && "fixup stack phasing error!");
  1905. // Resolve any NumToSkip fixups in the current scope.
  1906. resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
  1907. TableInfo.Table.size());
  1908. TableInfo.FixupStack.clear();
  1909. TableInfo.Table.push_back(MCD::OPC_Fail);
  1910. // Print the table to the output stream.
  1911. emitTable(OS, TableInfo.Table, 0, FC.getBitWidth(), Opc.first.first);
  1912. OS.flush();
  1913. }
  1914. // Emit the predicate function.
  1915. emitPredicateFunction(OS, TableInfo.Predicates, 0);
  1916. // Emit the decoder function.
  1917. emitDecoderFunction(OS, TableInfo.Decoders, 0);
  1918. // Emit the main entry point for the decoder, decodeInstruction().
  1919. emitDecodeInstruction(OS);
  1920. OS << "\n} // End llvm namespace\n";
  1921. }
  1922. namespace llvm {
  1923. void EmitFixedLenDecoder(RecordKeeper &RK, raw_ostream &OS,
  1924. std::string PredicateNamespace,
  1925. std::string GPrefix,
  1926. std::string GPostfix,
  1927. std::string ROK,
  1928. std::string RFail,
  1929. std::string L) {
  1930. FixedLenDecoderEmitter(RK, PredicateNamespace, GPrefix, GPostfix,
  1931. ROK, RFail, L).run(OS);
  1932. }
  1933. } // End llvm namespace