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