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