5977eea63a0fcb72dcf05a16ba48f671f6994f53
[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 "FixedLenDecoderEmitter.h"
18 #include "CodeGenTarget.h"
19 #include "llvm/TableGen/Record.h"
20 #include "llvm/ADT/APInt.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/raw_ostream.h"
24
25 #include <vector>
26 #include <map>
27 #include <string>
28
29 using namespace llvm;
30
31 // The set (BIT_TRUE, BIT_FALSE, BIT_UNSET) represents a ternary logic system
32 // for a bit value.
33 //
34 // BIT_UNFILTERED is used as the init value for a filter position.  It is used
35 // only for filter processings.
36 typedef enum {
37   BIT_TRUE,      // '1'
38   BIT_FALSE,     // '0'
39   BIT_UNSET,     // '?'
40   BIT_UNFILTERED // unfiltered
41 } bit_value_t;
42
43 static bool ValueSet(bit_value_t V) {
44   return (V == BIT_TRUE || V == BIT_FALSE);
45 }
46 static bool ValueNotSet(bit_value_t V) {
47   return (V == BIT_UNSET);
48 }
49 static int Value(bit_value_t V) {
50   return ValueNotSet(V) ? -1 : (V == BIT_FALSE ? 0 : 1);
51 }
52 static bit_value_t bitFromBits(BitsInit &bits, unsigned index) {
53   if (BitInit *bit = dynamic_cast<BitInit*>(bits.getBit(index)))
54     return bit->getValue() ? BIT_TRUE : BIT_FALSE;
55
56   // The bit is uninitialized.
57   return BIT_UNSET;
58 }
59 // Prints the bit value for each position.
60 static void dumpBits(raw_ostream &o, BitsInit &bits) {
61   unsigned index;
62
63   for (index = bits.getNumBits(); index > 0; index--) {
64     switch (bitFromBits(bits, index - 1)) {
65     case BIT_TRUE:
66       o << "1";
67       break;
68     case BIT_FALSE:
69       o << "0";
70       break;
71     case BIT_UNSET:
72       o << "_";
73       break;
74     default:
75       llvm_unreachable("unexpected return value from bitFromBits");
76     }
77   }
78 }
79
80 static BitsInit &getBitsField(const Record &def, const char *str) {
81   BitsInit *bits = def.getValueAsBitsInit(str);
82   return *bits;
83 }
84
85 // Forward declaration.
86 class FilterChooser;
87
88 // Representation of the instruction to work on.
89 typedef std::vector<bit_value_t> insn_t;
90
91 /// Filter - Filter works with FilterChooser to produce the decoding tree for
92 /// the ISA.
93 ///
94 /// It is useful to think of a Filter as governing the switch stmts of the
95 /// decoding tree in a certain level.  Each case stmt delegates to an inferior
96 /// FilterChooser to decide what further decoding logic to employ, or in another
97 /// words, what other remaining bits to look at.  The FilterChooser eventually
98 /// chooses a best Filter to do its job.
99 ///
100 /// This recursive scheme ends when the number of Opcodes assigned to the
101 /// FilterChooser becomes 1 or if there is a conflict.  A conflict happens when
102 /// the Filter/FilterChooser combo does not know how to distinguish among the
103 /// Opcodes assigned.
104 ///
105 /// An example of a conflict is
106 ///
107 /// Conflict:
108 ///                     111101000.00........00010000....
109 ///                     111101000.00........0001........
110 ///                     1111010...00........0001........
111 ///                     1111010...00....................
112 ///                     1111010.........................
113 ///                     1111............................
114 ///                     ................................
115 ///     VST4q8a         111101000_00________00010000____
116 ///     VST4q8b         111101000_00________00010000____
117 ///
118 /// The Debug output shows the path that the decoding tree follows to reach the
119 /// the conclusion that there is a conflict.  VST4q8a is a vst4 to double-spaced
120 /// even registers, while VST4q8b is a vst4 to double-spaced odd regsisters.
121 ///
122 /// The encoding info in the .td files does not specify this meta information,
123 /// which could have been used by the decoder to resolve the conflict.  The
124 /// decoder could try to decode the even/odd register numbering and assign to
125 /// VST4q8a or VST4q8b, but for the time being, the decoder chooses the "a"
126 /// version and return the Opcode since the two have the same Asm format string.
127 class Filter {
128 protected:
129   FilterChooser *Owner; // points to the FilterChooser who owns this filter
130   unsigned StartBit; // the starting bit position
131   unsigned NumBits; // number of bits to filter
132   bool Mixed; // a mixed region contains both set and unset bits
133
134   // Map of well-known segment value to the set of uid's with that value.
135   std::map<uint64_t, std::vector<unsigned> > FilteredInstructions;
136
137   // Set of uid's with non-constant segment values.
138   std::vector<unsigned> VariableInstructions;
139
140   // Map of well-known segment value to its delegate.
141   std::map<unsigned, FilterChooser*> FilterChooserMap;
142
143   // Number of instructions which fall under FilteredInstructions category.
144   unsigned NumFiltered;
145
146   // Keeps track of the last opcode in the filtered bucket.
147   unsigned LastOpcFiltered;
148
149 public:
150   unsigned getNumFiltered() { return NumFiltered; }
151   unsigned getSingletonOpc() {
152     assert(NumFiltered == 1);
153     return LastOpcFiltered;
154   }
155   // Return the filter chooser for the group of instructions without constant
156   // segment values.
157   FilterChooser &getVariableFC() {
158     assert(NumFiltered == 1);
159     assert(FilterChooserMap.size() == 1);
160     return *(FilterChooserMap.find((unsigned)-1)->second);
161   }
162
163   Filter(const Filter &f);
164   Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, bool mixed);
165
166   ~Filter();
167
168   // Divides the decoding task into sub tasks and delegates them to the
169   // inferior FilterChooser's.
170   //
171   // A special case arises when there's only one entry in the filtered
172   // instructions.  In order to unambiguously decode the singleton, we need to
173   // match the remaining undecoded encoding bits against the singleton.
174   void recurse();
175
176   // Emit code to decode instructions given a segment or segments of bits.
177   void emit(raw_ostream &o, unsigned &Indentation);
178
179   // Returns the number of fanout produced by the filter.  More fanout implies
180   // the filter distinguishes more categories of instructions.
181   unsigned usefulness() const;
182 }; // End of class Filter
183
184 // These are states of our finite state machines used in FilterChooser's
185 // filterProcessor() which produces the filter candidates to use.
186 typedef enum {
187   ATTR_NONE,
188   ATTR_FILTERED,
189   ATTR_ALL_SET,
190   ATTR_ALL_UNSET,
191   ATTR_MIXED
192 } bitAttr_t;
193
194 /// FilterChooser - FilterChooser chooses the best filter among a set of Filters
195 /// in order to perform the decoding of instructions at the current level.
196 ///
197 /// Decoding proceeds from the top down.  Based on the well-known encoding bits
198 /// of instructions available, FilterChooser builds up the possible Filters that
199 /// can further the task of decoding by distinguishing among the remaining
200 /// candidate instructions.
201 ///
202 /// Once a filter has been chosen, it is called upon to divide the decoding task
203 /// into sub-tasks and delegates them to its inferior FilterChoosers for further
204 /// processings.
205 ///
206 /// It is useful to think of a Filter as governing the switch stmts of the
207 /// decoding tree.  And each case is delegated to an inferior FilterChooser to
208 /// decide what further remaining bits to look at.
209 class FilterChooser {
210 protected:
211   friend class Filter;
212
213   // Vector of codegen instructions to choose our filter.
214   const std::vector<const CodeGenInstruction*> &AllInstructions;
215
216   // Vector of uid's for this filter chooser to work on.
217   const std::vector<unsigned> Opcodes;
218
219   // Lookup table for the operand decoding of instructions.
220   std::map<unsigned, std::vector<OperandInfo> > &Operands;
221
222   // Vector of candidate filters.
223   std::vector<Filter> Filters;
224
225   // Array of bit values passed down from our parent.
226   // Set to all BIT_UNFILTERED's for Parent == NULL.
227   std::vector<bit_value_t> FilterBitValues;
228
229   // Links to the FilterChooser above us in the decoding tree.
230   FilterChooser *Parent;
231
232   // Index of the best filter from Filters.
233   int BestIndex;
234
235   // Width of instructions
236   unsigned BitWidth;
237
238   // Parent emitter
239   const FixedLenDecoderEmitter *Emitter;
240
241 public:
242   FilterChooser(const FilterChooser &FC) :
243     AllInstructions(FC.AllInstructions), Opcodes(FC.Opcodes),
244       Operands(FC.Operands), Filters(FC.Filters),
245       FilterBitValues(FC.FilterBitValues), Parent(FC.Parent),
246     BestIndex(FC.BestIndex), BitWidth(FC.BitWidth),
247     Emitter(FC.Emitter) { }
248
249   FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
250                 const std::vector<unsigned> &IDs,
251     std::map<unsigned, std::vector<OperandInfo> > &Ops,
252                 unsigned BW,
253                 const FixedLenDecoderEmitter *E) :
254       AllInstructions(Insts), Opcodes(IDs), Operands(Ops), Filters(),
255       Parent(NULL), BestIndex(-1), BitWidth(BW), Emitter(E) {
256     for (unsigned i = 0; i < BitWidth; ++i)
257       FilterBitValues.push_back(BIT_UNFILTERED);
258
259     doFilter();
260   }
261
262   FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
263                 const std::vector<unsigned> &IDs,
264         std::map<unsigned, std::vector<OperandInfo> > &Ops,
265                 std::vector<bit_value_t> &ParentFilterBitValues,
266                 FilterChooser &parent) :
267       AllInstructions(Insts), Opcodes(IDs), Operands(Ops),
268       Filters(), FilterBitValues(ParentFilterBitValues),
269       Parent(&parent), BestIndex(-1), BitWidth(parent.BitWidth),
270       Emitter(parent.Emitter) {
271     doFilter();
272   }
273
274   // The top level filter chooser has NULL as its parent.
275   bool isTopLevel() { return Parent == NULL; }
276
277   // Emit the top level typedef and decodeInstruction() function.
278   void emitTop(raw_ostream &o, unsigned Indentation, std::string Namespace);
279
280 protected:
281   // Populates the insn given the uid.
282   void insnWithID(insn_t &Insn, unsigned Opcode) const {
283     BitsInit &Bits = getBitsField(*AllInstructions[Opcode]->TheDef, "Inst");
284
285     // We may have a SoftFail bitmask, which specifies a mask where an encoding
286     // may differ from the value in "Inst" and yet still be valid, but the
287     // disassembler should return SoftFail instead of Success.
288     //
289     // This is used for marking UNPREDICTABLE instructions in the ARM world.
290     BitsInit *SFBits =
291       AllInstructions[Opcode]->TheDef->getValueAsBitsInit("SoftFail");
292
293     for (unsigned i = 0; i < BitWidth; ++i) {
294       if (SFBits && bitFromBits(*SFBits, i) == BIT_TRUE)
295         Insn.push_back(BIT_UNSET);
296       else
297         Insn.push_back(bitFromBits(Bits, i));
298     }
299   }
300
301   // Returns the record name.
302   const std::string &nameWithID(unsigned Opcode) const {
303     return AllInstructions[Opcode]->TheDef->getName();
304   }
305
306   // Populates the field of the insn given the start position and the number of
307   // consecutive bits to scan for.
308   //
309   // Returns false if there exists any uninitialized bit value in the range.
310   // Returns true, otherwise.
311   bool fieldFromInsn(uint64_t &Field, insn_t &Insn, unsigned StartBit,
312       unsigned NumBits) const;
313
314   /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
315   /// filter array as a series of chars.
316   void dumpFilterArray(raw_ostream &o, std::vector<bit_value_t> & filter);
317
318   /// dumpStack - dumpStack traverses the filter chooser chain and calls
319   /// dumpFilterArray on each filter chooser up to the top level one.
320   void dumpStack(raw_ostream &o, const char *prefix);
321
322   Filter &bestFilter() {
323     assert(BestIndex != -1 && "BestIndex not set");
324     return Filters[BestIndex];
325   }
326
327   // Called from Filter::recurse() when singleton exists.  For debug purpose.
328   void SingletonExists(unsigned Opc);
329
330   bool PositionFiltered(unsigned i) {
331     return ValueSet(FilterBitValues[i]);
332   }
333
334   // Calculates the island(s) needed to decode the instruction.
335   // This returns a lit of undecoded bits of an instructions, for example,
336   // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
337   // decoded bits in order to verify that the instruction matches the Opcode.
338   unsigned getIslands(std::vector<unsigned> &StartBits,
339       std::vector<unsigned> &EndBits, std::vector<uint64_t> &FieldVals,
340       insn_t &Insn);
341
342   // Emits code to check the Predicates member of an instruction are true.
343   // Returns true if predicate matches were emitted, false otherwise.
344   bool emitPredicateMatch(raw_ostream &o, unsigned &Indentation,unsigned Opc);
345
346   void emitSoftFailCheck(raw_ostream &o, unsigned Indentation, unsigned Opc);
347
348   // Emits code to decode the singleton.  Return true if we have matched all the
349   // well-known bits.
350   bool emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,unsigned Opc);
351
352   // Emits code to decode the singleton, and then to decode the rest.
353   void emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,Filter &Best);
354
355   void emitBinaryParser(raw_ostream &o , unsigned &Indentation,
356                         OperandInfo &OpInfo);
357
358   // Assign a single filter and run with it.
359   void runSingleFilter(FilterChooser &owner, unsigned startBit, unsigned numBit,
360       bool mixed);
361
362   // reportRegion is a helper function for filterProcessor to mark a region as
363   // eligible for use as a filter region.
364   void reportRegion(bitAttr_t RA, unsigned StartBit, unsigned BitIndex,
365       bool AllowMixed);
366
367   // FilterProcessor scans the well-known encoding bits of the instructions and
368   // builds up a list of candidate filters.  It chooses the best filter and
369   // recursively descends down the decoding tree.
370   bool filterProcessor(bool AllowMixed, bool Greedy = true);
371
372   // Decides on the best configuration of filter(s) to use in order to decode
373   // the instructions.  A conflict of instructions may occur, in which case we
374   // dump the conflict set to the standard error.
375   void doFilter();
376
377   // Emits code to decode our share of instructions.  Returns true if the
378   // emitted code causes a return, which occurs if we know how to decode
379   // the instruction at this level or the instruction is not decodeable.
380   bool emit(raw_ostream &o, unsigned &Indentation);
381 };
382
383 ///////////////////////////
384 //                       //
385 // Filter Implementation //
386 //                       //
387 ///////////////////////////
388
389 Filter::Filter(const Filter &f) :
390   Owner(f.Owner), StartBit(f.StartBit), NumBits(f.NumBits), Mixed(f.Mixed),
391   FilteredInstructions(f.FilteredInstructions),
392   VariableInstructions(f.VariableInstructions),
393   FilterChooserMap(f.FilterChooserMap), NumFiltered(f.NumFiltered),
394   LastOpcFiltered(f.LastOpcFiltered) {
395 }
396
397 Filter::Filter(FilterChooser &owner, unsigned startBit, unsigned numBits,
398     bool mixed) : Owner(&owner), StartBit(startBit), NumBits(numBits),
399                   Mixed(mixed) {
400   assert(StartBit + NumBits - 1 < Owner->BitWidth);
401
402   NumFiltered = 0;
403   LastOpcFiltered = 0;
404
405   for (unsigned i = 0, e = Owner->Opcodes.size(); i != e; ++i) {
406     insn_t Insn;
407
408     // Populates the insn given the uid.
409     Owner->insnWithID(Insn, Owner->Opcodes[i]);
410
411     uint64_t Field;
412     // Scans the segment for possibly well-specified encoding bits.
413     bool ok = Owner->fieldFromInsn(Field, Insn, StartBit, NumBits);
414
415     if (ok) {
416       // The encoding bits are well-known.  Lets add the uid of the
417       // instruction into the bucket keyed off the constant field value.
418       LastOpcFiltered = Owner->Opcodes[i];
419       FilteredInstructions[Field].push_back(LastOpcFiltered);
420       ++NumFiltered;
421     } else {
422       // Some of the encoding bit(s) are unspecified.  This contributes to
423       // one additional member of "Variable" instructions.
424       VariableInstructions.push_back(Owner->Opcodes[i]);
425     }
426   }
427
428   assert((FilteredInstructions.size() + VariableInstructions.size() > 0)
429          && "Filter returns no instruction categories");
430 }
431
432 Filter::~Filter() {
433   std::map<unsigned, FilterChooser*>::iterator filterIterator;
434   for (filterIterator = FilterChooserMap.begin();
435        filterIterator != FilterChooserMap.end();
436        filterIterator++) {
437     delete filterIterator->second;
438   }
439 }
440
441 // Divides the decoding task into sub tasks and delegates them to the
442 // inferior FilterChooser's.
443 //
444 // A special case arises when there's only one entry in the filtered
445 // instructions.  In order to unambiguously decode the singleton, we need to
446 // match the remaining undecoded encoding bits against the singleton.
447 void Filter::recurse() {
448   std::map<uint64_t, std::vector<unsigned> >::const_iterator mapIterator;
449
450   // Starts by inheriting our parent filter chooser's filter bit values.
451   std::vector<bit_value_t> BitValueArray(Owner->FilterBitValues);
452
453   unsigned bitIndex;
454
455   if (VariableInstructions.size()) {
456     // Conservatively marks each segment position as BIT_UNSET.
457     for (bitIndex = 0; bitIndex < NumBits; bitIndex++)
458       BitValueArray[StartBit + bitIndex] = BIT_UNSET;
459
460     // Delegates to an inferior filter chooser for further processing on this
461     // group of instructions whose segment values are variable.
462     FilterChooserMap.insert(std::pair<unsigned, FilterChooser*>(
463                               (unsigned)-1,
464                               new FilterChooser(Owner->AllInstructions,
465                                                 VariableInstructions,
466                                                 Owner->Operands,
467                                                 BitValueArray,
468                                                 *Owner)
469                               ));
470   }
471
472   // No need to recurse for a singleton filtered instruction.
473   // See also Filter::emit().
474   if (getNumFiltered() == 1) {
475     //Owner->SingletonExists(LastOpcFiltered);
476     assert(FilterChooserMap.size() == 1);
477     return;
478   }
479
480   // Otherwise, create sub choosers.
481   for (mapIterator = FilteredInstructions.begin();
482        mapIterator != FilteredInstructions.end();
483        mapIterator++) {
484
485     // Marks all the segment positions with either BIT_TRUE or BIT_FALSE.
486     for (bitIndex = 0; bitIndex < NumBits; bitIndex++) {
487       if (mapIterator->first & (1ULL << bitIndex))
488         BitValueArray[StartBit + bitIndex] = BIT_TRUE;
489       else
490         BitValueArray[StartBit + bitIndex] = BIT_FALSE;
491     }
492
493     // Delegates to an inferior filter chooser for further processing on this
494     // category of instructions.
495     FilterChooserMap.insert(std::pair<unsigned, FilterChooser*>(
496                               mapIterator->first,
497                               new FilterChooser(Owner->AllInstructions,
498                                                 mapIterator->second,
499                                                 Owner->Operands,
500                                                 BitValueArray,
501                                                 *Owner)
502                               ));
503   }
504 }
505
506 // Emit code to decode instructions given a segment or segments of bits.
507 void Filter::emit(raw_ostream &o, unsigned &Indentation) {
508   o.indent(Indentation) << "// Check Inst{";
509
510   if (NumBits > 1)
511     o << (StartBit + NumBits - 1) << '-';
512
513   o << StartBit << "} ...\n";
514
515   o.indent(Indentation) << "switch (fieldFromInstruction" << Owner->BitWidth
516                         << "(insn, " << StartBit << ", "
517                         << NumBits << ")) {\n";
518
519   std::map<unsigned, FilterChooser*>::iterator filterIterator;
520
521   bool DefaultCase = false;
522   for (filterIterator = FilterChooserMap.begin();
523        filterIterator != FilterChooserMap.end();
524        filterIterator++) {
525
526     // Field value -1 implies a non-empty set of variable instructions.
527     // See also recurse().
528     if (filterIterator->first == (unsigned)-1) {
529       DefaultCase = true;
530
531       o.indent(Indentation) << "default:\n";
532       o.indent(Indentation) << "  break; // fallthrough\n";
533
534       // Closing curly brace for the switch statement.
535       // This is unconventional because we want the default processing to be
536       // performed for the fallthrough cases as well, i.e., when the "cases"
537       // did not prove a decoded instruction.
538       o.indent(Indentation) << "}\n";
539
540     } else
541       o.indent(Indentation) << "case " << filterIterator->first << ":\n";
542
543     // We arrive at a category of instructions with the same segment value.
544     // Now delegate to the sub filter chooser for further decodings.
545     // The case may fallthrough, which happens if the remaining well-known
546     // encoding bits do not match exactly.
547     if (!DefaultCase) { ++Indentation; ++Indentation; }
548
549     bool finished = filterIterator->second->emit(o, Indentation);
550     // For top level default case, there's no need for a break statement.
551     if (Owner->isTopLevel() && DefaultCase)
552       break;
553     if (!finished)
554       o.indent(Indentation) << "break;\n";
555
556     if (!DefaultCase) { --Indentation; --Indentation; }
557   }
558
559   // If there is no default case, we still need to supply a closing brace.
560   if (!DefaultCase) {
561     // Closing curly brace for the switch statement.
562     o.indent(Indentation) << "}\n";
563   }
564 }
565
566 // Returns the number of fanout produced by the filter.  More fanout implies
567 // the filter distinguishes more categories of instructions.
568 unsigned Filter::usefulness() const {
569   if (VariableInstructions.size())
570     return FilteredInstructions.size();
571   else
572     return FilteredInstructions.size() + 1;
573 }
574
575 //////////////////////////////////
576 //                              //
577 // Filterchooser Implementation //
578 //                              //
579 //////////////////////////////////
580
581 // Emit the top level typedef and decodeInstruction() function.
582 void FilterChooser::emitTop(raw_ostream &o, unsigned Indentation,
583                             std::string Namespace) {
584   o.indent(Indentation) <<
585     "static MCDisassembler::DecodeStatus decode" << Namespace << "Instruction"
586     << BitWidth << "(MCInst &MI, uint" << BitWidth
587     << "_t insn, uint64_t Address, "
588     << "const void *Decoder, const MCSubtargetInfo &STI) {\n";
589   o.indent(Indentation) << "  unsigned tmp = 0;\n";
590   o.indent(Indentation) << "  (void)tmp;\n";
591   o.indent(Indentation) << Emitter->Locals << "\n";
592   o.indent(Indentation) << "  uint64_t Bits = STI.getFeatureBits();\n";
593   o.indent(Indentation) << "  (void)Bits;\n";
594
595   ++Indentation; ++Indentation;
596   // Emits code to decode the instructions.
597   emit(o, Indentation);
598
599   o << '\n';
600   o.indent(Indentation) << "return " << Emitter->ReturnFail << ";\n";
601   --Indentation; --Indentation;
602
603   o.indent(Indentation) << "}\n";
604
605   o << '\n';
606 }
607
608 // Populates the field of the insn given the start position and the number of
609 // consecutive bits to scan for.
610 //
611 // Returns false if and on the first uninitialized bit value encountered.
612 // Returns true, otherwise.
613 bool FilterChooser::fieldFromInsn(uint64_t &Field, insn_t &Insn,
614     unsigned StartBit, unsigned NumBits) const {
615   Field = 0;
616
617   for (unsigned i = 0; i < NumBits; ++i) {
618     if (Insn[StartBit + i] == BIT_UNSET)
619       return false;
620
621     if (Insn[StartBit + i] == BIT_TRUE)
622       Field = Field | (1ULL << i);
623   }
624
625   return true;
626 }
627
628 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
629 /// filter array as a series of chars.
630 void FilterChooser::dumpFilterArray(raw_ostream &o,
631                                     std::vector<bit_value_t> &filter) {
632   unsigned bitIndex;
633
634   for (bitIndex = BitWidth; bitIndex > 0; bitIndex--) {
635     switch (filter[bitIndex - 1]) {
636     case BIT_UNFILTERED:
637       o << ".";
638       break;
639     case BIT_UNSET:
640       o << "_";
641       break;
642     case BIT_TRUE:
643       o << "1";
644       break;
645     case BIT_FALSE:
646       o << "0";
647       break;
648     }
649   }
650 }
651
652 /// dumpStack - dumpStack traverses the filter chooser chain and calls
653 /// dumpFilterArray on each filter chooser up to the top level one.
654 void FilterChooser::dumpStack(raw_ostream &o, const char *prefix) {
655   FilterChooser *current = this;
656
657   while (current) {
658     o << prefix;
659     dumpFilterArray(o, current->FilterBitValues);
660     o << '\n';
661     current = current->Parent;
662   }
663 }
664
665 // Called from Filter::recurse() when singleton exists.  For debug purpose.
666 void FilterChooser::SingletonExists(unsigned Opc) {
667   insn_t Insn0;
668   insnWithID(Insn0, Opc);
669
670   errs() << "Singleton exists: " << nameWithID(Opc)
671          << " with its decoding dominating ";
672   for (unsigned i = 0; i < Opcodes.size(); ++i) {
673     if (Opcodes[i] == Opc) continue;
674     errs() << nameWithID(Opcodes[i]) << ' ';
675   }
676   errs() << '\n';
677
678   dumpStack(errs(), "\t\t");
679   for (unsigned i = 0; i < Opcodes.size(); i++) {
680     const std::string &Name = nameWithID(Opcodes[i]);
681
682     errs() << '\t' << Name << " ";
683     dumpBits(errs(),
684              getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
685     errs() << '\n';
686   }
687 }
688
689 // Calculates the island(s) needed to decode the instruction.
690 // This returns a list of undecoded bits of an instructions, for example,
691 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
692 // decoded bits in order to verify that the instruction matches the Opcode.
693 unsigned FilterChooser::getIslands(std::vector<unsigned> &StartBits,
694     std::vector<unsigned> &EndBits, std::vector<uint64_t> &FieldVals,
695     insn_t &Insn) {
696   unsigned Num, BitNo;
697   Num = BitNo = 0;
698
699   uint64_t FieldVal = 0;
700
701   // 0: Init
702   // 1: Water (the bit value does not affect decoding)
703   // 2: Island (well-known bit value needed for decoding)
704   int State = 0;
705   int Val = -1;
706
707   for (unsigned i = 0; i < BitWidth; ++i) {
708     Val = Value(Insn[i]);
709     bool Filtered = PositionFiltered(i);
710     switch (State) {
711     default: llvm_unreachable("Unreachable code!");
712     case 0:
713     case 1:
714       if (Filtered || Val == -1)
715         State = 1; // Still in Water
716       else {
717         State = 2; // Into the Island
718         BitNo = 0;
719         StartBits.push_back(i);
720         FieldVal = Val;
721       }
722       break;
723     case 2:
724       if (Filtered || Val == -1) {
725         State = 1; // Into the Water
726         EndBits.push_back(i - 1);
727         FieldVals.push_back(FieldVal);
728         ++Num;
729       } else {
730         State = 2; // Still in Island
731         ++BitNo;
732         FieldVal = FieldVal | Val << BitNo;
733       }
734       break;
735     }
736   }
737   // If we are still in Island after the loop, do some housekeeping.
738   if (State == 2) {
739     EndBits.push_back(BitWidth - 1);
740     FieldVals.push_back(FieldVal);
741     ++Num;
742   }
743
744   assert(StartBits.size() == Num && EndBits.size() == Num &&
745          FieldVals.size() == Num);
746   return Num;
747 }
748
749 void FilterChooser::emitBinaryParser(raw_ostream &o, unsigned &Indentation,
750                          OperandInfo &OpInfo) {
751   std::string &Decoder = OpInfo.Decoder;
752
753   if (OpInfo.numFields() == 1) {
754     OperandInfo::iterator OI = OpInfo.begin();
755     o.indent(Indentation) << "  tmp = fieldFromInstruction" << BitWidth
756                             << "(insn, " << OI->Base << ", " << OI->Width
757                             << ");\n";
758   } else {
759     o.indent(Indentation) << "  tmp = 0;\n";
760     for (OperandInfo::iterator OI = OpInfo.begin(), OE = OpInfo.end();
761          OI != OE; ++OI) {
762       o.indent(Indentation) << "  tmp |= (fieldFromInstruction" << BitWidth
763                             << "(insn, " << OI->Base << ", " << OI->Width
764                             << ") << " << OI->Offset << ");\n";
765     }
766   }
767
768   if (Decoder != "")
769     o.indent(Indentation) << "  " << Emitter->GuardPrefix << Decoder
770                           << "(MI, tmp, Address, Decoder)"
771                           << Emitter->GuardPostfix << "\n";
772   else
773     o.indent(Indentation) << "  MI.addOperand(MCOperand::CreateImm(tmp));\n";
774
775 }
776
777 static void emitSinglePredicateMatch(raw_ostream &o, StringRef str,
778                                      std::string PredicateNamespace) {
779   if (str[0] == '!')
780     o << "!(Bits & " << PredicateNamespace << "::"
781       << str.slice(1,str.size()) << ")";
782   else
783     o << "(Bits & " << PredicateNamespace << "::" << str << ")";
784 }
785
786 bool FilterChooser::emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
787                                            unsigned Opc) {
788   ListInit *Predicates =
789     AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
790   for (unsigned i = 0; i < Predicates->getSize(); ++i) {
791     Record *Pred = Predicates->getElementAsRecord(i);
792     if (!Pred->getValue("AssemblerMatcherPredicate"))
793       continue;
794
795     std::string P = Pred->getValueAsString("AssemblerCondString");
796
797     if (!P.length())
798       continue;
799
800     if (i != 0)
801       o << " && ";
802
803     StringRef SR(P);
804     std::pair<StringRef, StringRef> pairs = SR.split(',');
805     while (pairs.second.size()) {
806       emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
807       o << " && ";
808       pairs = pairs.second.split(',');
809     }
810     emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
811   }
812   return Predicates->getSize() > 0;
813 }
814
815 void FilterChooser::emitSoftFailCheck(raw_ostream &o, unsigned Indentation,
816                                       unsigned Opc) {
817   BitsInit *SFBits =
818     AllInstructions[Opc]->TheDef->getValueAsBitsInit("SoftFail");
819   if (!SFBits) return;
820   BitsInit *InstBits = AllInstructions[Opc]->TheDef->getValueAsBitsInit("Inst");
821
822   APInt PositiveMask(BitWidth, 0ULL);
823   APInt NegativeMask(BitWidth, 0ULL);
824   for (unsigned i = 0; i < BitWidth; ++i) {
825     bit_value_t B = bitFromBits(*SFBits, i);
826     bit_value_t IB = bitFromBits(*InstBits, i);
827
828     if (B != BIT_TRUE) continue;
829
830     switch (IB) {
831     case BIT_FALSE:
832       // The bit is meant to be false, so emit a check to see if it is true.
833       PositiveMask.setBit(i);
834       break;
835     case BIT_TRUE:
836       // The bit is meant to be true, so emit a check to see if it is false.
837       NegativeMask.setBit(i);
838       break;
839     default:
840       // The bit is not set; this must be an error!
841       StringRef Name = AllInstructions[Opc]->TheDef->getName();
842       errs() << "SoftFail Conflict: bit SoftFail{" << i << "} in "
843              << Name
844              << " is set but Inst{" << i <<"} is unset!\n"
845              << "  - You can only mark a bit as SoftFail if it is fully defined"
846              << " (1/0 - not '?') in Inst\n";
847       o << "#error SoftFail Conflict, " << Name << "::SoftFail{" << i 
848         << "} set but Inst{" << i << "} undefined!\n";
849     }
850   }
851
852   bool NeedPositiveMask = PositiveMask.getBoolValue();
853   bool NeedNegativeMask = NegativeMask.getBoolValue();
854
855   if (!NeedPositiveMask && !NeedNegativeMask)
856     return;
857
858   std::string PositiveMaskStr = PositiveMask.toString(16, /*signed=*/false);
859   std::string NegativeMaskStr = NegativeMask.toString(16, /*signed=*/false);
860   StringRef BitExt = "";
861   if (BitWidth > 32)
862     BitExt = "ULL";
863
864   o.indent(Indentation) << "if (";
865   if (NeedPositiveMask)
866     o << "insn & 0x" << PositiveMaskStr << BitExt;
867   if (NeedPositiveMask && NeedNegativeMask)
868     o << " || ";
869   if (NeedNegativeMask)
870     o << "~insn & 0x" << NegativeMaskStr << BitExt;
871   o << ")\n";
872   o.indent(Indentation+2) << "S = MCDisassembler::SoftFail;\n";
873 }
874
875 // Emits code to decode the singleton.  Return true if we have matched all the
876 // well-known bits.
877 bool FilterChooser::emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,
878                                          unsigned Opc) {
879   std::vector<unsigned> StartBits;
880   std::vector<unsigned> EndBits;
881   std::vector<uint64_t> FieldVals;
882   insn_t Insn;
883   insnWithID(Insn, Opc);
884
885   // Look for islands of undecoded bits of the singleton.
886   getIslands(StartBits, EndBits, FieldVals, Insn);
887
888   unsigned Size = StartBits.size();
889   unsigned I, NumBits;
890
891   // If we have matched all the well-known bits, just issue a return.
892   if (Size == 0) {
893     o.indent(Indentation) << "if (";
894     if (!emitPredicateMatch(o, Indentation, Opc))
895       o << "1";
896     o << ") {\n";
897     emitSoftFailCheck(o, Indentation+2, Opc);
898     o.indent(Indentation) << "  MI.setOpcode(" << Opc << ");\n";
899     std::vector<OperandInfo>& InsnOperands = Operands[Opc];
900     for (std::vector<OperandInfo>::iterator
901          I = InsnOperands.begin(), E = InsnOperands.end(); I != E; ++I) {
902       // If a custom instruction decoder was specified, use that.
903       if (I->numFields() == 0 && I->Decoder.size()) {
904         o.indent(Indentation) << "  " << Emitter->GuardPrefix << I->Decoder
905                               << "(MI, insn, Address, Decoder)"
906                               << Emitter->GuardPostfix << "\n";
907         break;
908       }
909
910       emitBinaryParser(o, Indentation, *I);
911     }
912
913     o.indent(Indentation) << "  return " << Emitter->ReturnOK << "; // "
914                           << nameWithID(Opc) << '\n';
915     o.indent(Indentation) << "}\n"; // Closing predicate block.
916     return true;
917   }
918
919   // Otherwise, there are more decodings to be done!
920
921   // Emit code to match the island(s) for the singleton.
922   o.indent(Indentation) << "// Check ";
923
924   for (I = Size; I != 0; --I) {
925     o << "Inst{" << EndBits[I-1] << '-' << StartBits[I-1] << "} ";
926     if (I > 1)
927       o << " && ";
928     else
929       o << "for singleton decoding...\n";
930   }
931
932   o.indent(Indentation) << "if (";
933   if (emitPredicateMatch(o, Indentation, Opc)) {
934     o << " &&\n";
935     o.indent(Indentation+4);
936   }
937
938   for (I = Size; I != 0; --I) {
939     NumBits = EndBits[I-1] - StartBits[I-1] + 1;
940     o << "fieldFromInstruction" << BitWidth << "(insn, "
941       << StartBits[I-1] << ", " << NumBits
942       << ") == " << FieldVals[I-1];
943     if (I > 1)
944       o << " && ";
945     else
946       o << ") {\n";
947   }
948   emitSoftFailCheck(o, Indentation+2, Opc);
949   o.indent(Indentation) << "  MI.setOpcode(" << Opc << ");\n";
950   std::vector<OperandInfo>& InsnOperands = Operands[Opc];
951   for (std::vector<OperandInfo>::iterator
952        I = InsnOperands.begin(), E = InsnOperands.end(); I != E; ++I) {
953     // If a custom instruction decoder was specified, use that.
954     if (I->numFields() == 0 && I->Decoder.size()) {
955       o.indent(Indentation) << "  " << Emitter->GuardPrefix << I->Decoder
956                             << "(MI, insn, Address, Decoder)"
957                             << Emitter->GuardPostfix << "\n";
958       break;
959     }
960
961     emitBinaryParser(o, Indentation, *I);
962   }
963   o.indent(Indentation) << "  return " << Emitter->ReturnOK << "; // "
964                         << nameWithID(Opc) << '\n';
965   o.indent(Indentation) << "}\n";
966
967   return false;
968 }
969
970 // Emits code to decode the singleton, and then to decode the rest.
971 void FilterChooser::emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,
972     Filter &Best) {
973
974   unsigned Opc = Best.getSingletonOpc();
975
976   emitSingletonDecoder(o, Indentation, Opc);
977
978   // Emit code for the rest.
979   o.indent(Indentation) << "else\n";
980
981   Indentation += 2;
982   Best.getVariableFC().emit(o, Indentation);
983   Indentation -= 2;
984 }
985
986 // Assign a single filter and run with it.  Top level API client can initialize
987 // with a single filter to start the filtering process.
988 void FilterChooser::runSingleFilter(FilterChooser &owner, unsigned startBit,
989     unsigned numBit, bool mixed) {
990   Filters.clear();
991   Filter F(*this, startBit, numBit, true);
992   Filters.push_back(F);
993   BestIndex = 0; // Sole Filter instance to choose from.
994   bestFilter().recurse();
995 }
996
997 // reportRegion is a helper function for filterProcessor to mark a region as
998 // eligible for use as a filter region.
999 void FilterChooser::reportRegion(bitAttr_t RA, unsigned StartBit,
1000     unsigned BitIndex, bool AllowMixed) {
1001   if (RA == ATTR_MIXED && AllowMixed)
1002     Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, true));
1003   else if (RA == ATTR_ALL_SET && !AllowMixed)
1004     Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, false));
1005 }
1006
1007 // FilterProcessor scans the well-known encoding bits of the instructions and
1008 // builds up a list of candidate filters.  It chooses the best filter and
1009 // recursively descends down the decoding tree.
1010 bool FilterChooser::filterProcessor(bool AllowMixed, bool Greedy) {
1011   Filters.clear();
1012   BestIndex = -1;
1013   unsigned numInstructions = Opcodes.size();
1014
1015   assert(numInstructions && "Filter created with no instructions");
1016
1017   // No further filtering is necessary.
1018   if (numInstructions == 1)
1019     return true;
1020
1021   // Heuristics.  See also doFilter()'s "Heuristics" comment when num of
1022   // instructions is 3.
1023   if (AllowMixed && !Greedy) {
1024     assert(numInstructions == 3);
1025
1026     for (unsigned i = 0; i < Opcodes.size(); ++i) {
1027       std::vector<unsigned> StartBits;
1028       std::vector<unsigned> EndBits;
1029       std::vector<uint64_t> FieldVals;
1030       insn_t Insn;
1031
1032       insnWithID(Insn, Opcodes[i]);
1033
1034       // Look for islands of undecoded bits of any instruction.
1035       if (getIslands(StartBits, EndBits, FieldVals, Insn) > 0) {
1036         // Found an instruction with island(s).  Now just assign a filter.
1037         runSingleFilter(*this, StartBits[0], EndBits[0] - StartBits[0] + 1,
1038                         true);
1039         return true;
1040       }
1041     }
1042   }
1043
1044   unsigned BitIndex, InsnIndex;
1045
1046   // We maintain BIT_WIDTH copies of the bitAttrs automaton.
1047   // The automaton consumes the corresponding bit from each
1048   // instruction.
1049   //
1050   //   Input symbols: 0, 1, and _ (unset).
1051   //   States:        NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED.
1052   //   Initial state: NONE.
1053   //
1054   // (NONE) ------- [01] -> (ALL_SET)
1055   // (NONE) ------- _ ----> (ALL_UNSET)
1056   // (ALL_SET) ---- [01] -> (ALL_SET)
1057   // (ALL_SET) ---- _ ----> (MIXED)
1058   // (ALL_UNSET) -- [01] -> (MIXED)
1059   // (ALL_UNSET) -- _ ----> (ALL_UNSET)
1060   // (MIXED) ------ . ----> (MIXED)
1061   // (FILTERED)---- . ----> (FILTERED)
1062
1063   std::vector<bitAttr_t> bitAttrs;
1064
1065   // FILTERED bit positions provide no entropy and are not worthy of pursuing.
1066   // Filter::recurse() set either BIT_TRUE or BIT_FALSE for each position.
1067   for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex)
1068     if (FilterBitValues[BitIndex] == BIT_TRUE ||
1069         FilterBitValues[BitIndex] == BIT_FALSE)
1070       bitAttrs.push_back(ATTR_FILTERED);
1071     else
1072       bitAttrs.push_back(ATTR_NONE);
1073
1074   for (InsnIndex = 0; InsnIndex < numInstructions; ++InsnIndex) {
1075     insn_t insn;
1076
1077     insnWithID(insn, Opcodes[InsnIndex]);
1078
1079     for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
1080       switch (bitAttrs[BitIndex]) {
1081       case ATTR_NONE:
1082         if (insn[BitIndex] == BIT_UNSET)
1083           bitAttrs[BitIndex] = ATTR_ALL_UNSET;
1084         else
1085           bitAttrs[BitIndex] = ATTR_ALL_SET;
1086         break;
1087       case ATTR_ALL_SET:
1088         if (insn[BitIndex] == BIT_UNSET)
1089           bitAttrs[BitIndex] = ATTR_MIXED;
1090         break;
1091       case ATTR_ALL_UNSET:
1092         if (insn[BitIndex] != BIT_UNSET)
1093           bitAttrs[BitIndex] = ATTR_MIXED;
1094         break;
1095       case ATTR_MIXED:
1096       case ATTR_FILTERED:
1097         break;
1098       }
1099     }
1100   }
1101
1102   // The regionAttr automaton consumes the bitAttrs automatons' state,
1103   // lowest-to-highest.
1104   //
1105   //   Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed)
1106   //   States:        NONE, ALL_SET, MIXED
1107   //   Initial state: NONE
1108   //
1109   // (NONE) ----- F --> (NONE)
1110   // (NONE) ----- S --> (ALL_SET)     ; and set region start
1111   // (NONE) ----- U --> (NONE)
1112   // (NONE) ----- M --> (MIXED)       ; and set region start
1113   // (ALL_SET) -- F --> (NONE)        ; and report an ALL_SET region
1114   // (ALL_SET) -- S --> (ALL_SET)
1115   // (ALL_SET) -- U --> (NONE)        ; and report an ALL_SET region
1116   // (ALL_SET) -- M --> (MIXED)       ; and report an ALL_SET region
1117   // (MIXED) ---- F --> (NONE)        ; and report a MIXED region
1118   // (MIXED) ---- S --> (ALL_SET)     ; and report a MIXED region
1119   // (MIXED) ---- U --> (NONE)        ; and report a MIXED region
1120   // (MIXED) ---- M --> (MIXED)
1121
1122   bitAttr_t RA = ATTR_NONE;
1123   unsigned StartBit = 0;
1124
1125   for (BitIndex = 0; BitIndex < BitWidth; BitIndex++) {
1126     bitAttr_t bitAttr = bitAttrs[BitIndex];
1127
1128     assert(bitAttr != ATTR_NONE && "Bit without attributes");
1129
1130     switch (RA) {
1131     case ATTR_NONE:
1132       switch (bitAttr) {
1133       case ATTR_FILTERED:
1134         break;
1135       case ATTR_ALL_SET:
1136         StartBit = BitIndex;
1137         RA = ATTR_ALL_SET;
1138         break;
1139       case ATTR_ALL_UNSET:
1140         break;
1141       case ATTR_MIXED:
1142         StartBit = BitIndex;
1143         RA = ATTR_MIXED;
1144         break;
1145       default:
1146         llvm_unreachable("Unexpected bitAttr!");
1147       }
1148       break;
1149     case ATTR_ALL_SET:
1150       switch (bitAttr) {
1151       case ATTR_FILTERED:
1152         reportRegion(RA, StartBit, BitIndex, AllowMixed);
1153         RA = ATTR_NONE;
1154         break;
1155       case ATTR_ALL_SET:
1156         break;
1157       case ATTR_ALL_UNSET:
1158         reportRegion(RA, StartBit, BitIndex, AllowMixed);
1159         RA = ATTR_NONE;
1160         break;
1161       case ATTR_MIXED:
1162         reportRegion(RA, StartBit, BitIndex, AllowMixed);
1163         StartBit = BitIndex;
1164         RA = ATTR_MIXED;
1165         break;
1166       default:
1167         llvm_unreachable("Unexpected bitAttr!");
1168       }
1169       break;
1170     case ATTR_MIXED:
1171       switch (bitAttr) {
1172       case ATTR_FILTERED:
1173         reportRegion(RA, StartBit, BitIndex, AllowMixed);
1174         StartBit = BitIndex;
1175         RA = ATTR_NONE;
1176         break;
1177       case ATTR_ALL_SET:
1178         reportRegion(RA, StartBit, BitIndex, AllowMixed);
1179         StartBit = BitIndex;
1180         RA = ATTR_ALL_SET;
1181         break;
1182       case ATTR_ALL_UNSET:
1183         reportRegion(RA, StartBit, BitIndex, AllowMixed);
1184         RA = ATTR_NONE;
1185         break;
1186       case ATTR_MIXED:
1187         break;
1188       default:
1189         llvm_unreachable("Unexpected bitAttr!");
1190       }
1191       break;
1192     case ATTR_ALL_UNSET:
1193       llvm_unreachable("regionAttr state machine has no ATTR_UNSET state");
1194     case ATTR_FILTERED:
1195       llvm_unreachable("regionAttr state machine has no ATTR_FILTERED state");
1196     }
1197   }
1198
1199   // At the end, if we're still in ALL_SET or MIXED states, report a region
1200   switch (RA) {
1201   case ATTR_NONE:
1202     break;
1203   case ATTR_FILTERED:
1204     break;
1205   case ATTR_ALL_SET:
1206     reportRegion(RA, StartBit, BitIndex, AllowMixed);
1207     break;
1208   case ATTR_ALL_UNSET:
1209     break;
1210   case ATTR_MIXED:
1211     reportRegion(RA, StartBit, BitIndex, AllowMixed);
1212     break;
1213   }
1214
1215   // We have finished with the filter processings.  Now it's time to choose
1216   // the best performing filter.
1217   BestIndex = 0;
1218   bool AllUseless = true;
1219   unsigned BestScore = 0;
1220
1221   for (unsigned i = 0, e = Filters.size(); i != e; ++i) {
1222     unsigned Usefulness = Filters[i].usefulness();
1223
1224     if (Usefulness)
1225       AllUseless = false;
1226
1227     if (Usefulness > BestScore) {
1228       BestIndex = i;
1229       BestScore = Usefulness;
1230     }
1231   }
1232
1233   if (!AllUseless)
1234     bestFilter().recurse();
1235
1236   return !AllUseless;
1237 } // end of FilterChooser::filterProcessor(bool)
1238
1239 // Decides on the best configuration of filter(s) to use in order to decode
1240 // the instructions.  A conflict of instructions may occur, in which case we
1241 // dump the conflict set to the standard error.
1242 void FilterChooser::doFilter() {
1243   unsigned Num = Opcodes.size();
1244   assert(Num && "FilterChooser created with no instructions");
1245
1246   // Try regions of consecutive known bit values first.
1247   if (filterProcessor(false))
1248     return;
1249
1250   // Then regions of mixed bits (both known and unitialized bit values allowed).
1251   if (filterProcessor(true))
1252     return;
1253
1254   // Heuristics to cope with conflict set {t2CMPrs, t2SUBSrr, t2SUBSrs} where
1255   // no single instruction for the maximum ATTR_MIXED region Inst{14-4} has a
1256   // well-known encoding pattern.  In such case, we backtrack and scan for the
1257   // the very first consecutive ATTR_ALL_SET region and assign a filter to it.
1258   if (Num == 3 && filterProcessor(true, false))
1259     return;
1260
1261   // If we come to here, the instruction decoding has failed.
1262   // Set the BestIndex to -1 to indicate so.
1263   BestIndex = -1;
1264 }
1265
1266 // Emits code to decode our share of instructions.  Returns true if the
1267 // emitted code causes a return, which occurs if we know how to decode
1268 // the instruction at this level or the instruction is not decodeable.
1269 bool FilterChooser::emit(raw_ostream &o, unsigned &Indentation) {
1270   if (Opcodes.size() == 1)
1271     // There is only one instruction in the set, which is great!
1272     // Call emitSingletonDecoder() to see whether there are any remaining
1273     // encodings bits.
1274     return emitSingletonDecoder(o, Indentation, Opcodes[0]);
1275
1276   // Choose the best filter to do the decodings!
1277   if (BestIndex != -1) {
1278     Filter &Best = bestFilter();
1279     if (Best.getNumFiltered() == 1)
1280       emitSingletonDecoder(o, Indentation, Best);
1281     else
1282       bestFilter().emit(o, Indentation);
1283     return false;
1284   }
1285
1286   // We don't know how to decode these instructions!  Return 0 and dump the
1287   // conflict set!
1288   o.indent(Indentation) << "return 0;" << " // Conflict set: ";
1289   for (int i = 0, N = Opcodes.size(); i < N; ++i) {
1290     o << nameWithID(Opcodes[i]);
1291     if (i < (N - 1))
1292       o << ", ";
1293     else
1294       o << '\n';
1295   }
1296
1297   // Print out useful conflict information for postmortem analysis.
1298   errs() << "Decoding Conflict:\n";
1299
1300   dumpStack(errs(), "\t\t");
1301
1302   for (unsigned i = 0; i < Opcodes.size(); i++) {
1303     const std::string &Name = nameWithID(Opcodes[i]);
1304
1305     errs() << '\t' << Name << " ";
1306     dumpBits(errs(),
1307              getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
1308     errs() << '\n';
1309   }
1310
1311   return true;
1312 }
1313
1314 static bool populateInstruction(const CodeGenInstruction &CGI,
1315                                 unsigned Opc,
1316                       std::map<unsigned, std::vector<OperandInfo> >& Operands){
1317   const Record &Def = *CGI.TheDef;
1318   // If all the bit positions are not specified; do not decode this instruction.
1319   // We are bound to fail!  For proper disassembly, the well-known encoding bits
1320   // of the instruction must be fully specified.
1321   //
1322   // This also removes pseudo instructions from considerations of disassembly,
1323   // which is a better design and less fragile than the name matchings.
1324   // Ignore "asm parser only" instructions.
1325   if (Def.getValueAsBit("isAsmParserOnly") ||
1326       Def.getValueAsBit("isCodeGenOnly"))
1327     return false;
1328
1329   BitsInit &Bits = getBitsField(Def, "Inst");
1330   if (Bits.allInComplete()) return false;
1331
1332   std::vector<OperandInfo> InsnOperands;
1333
1334   // If the instruction has specified a custom decoding hook, use that instead
1335   // of trying to auto-generate the decoder.
1336   std::string InstDecoder = Def.getValueAsString("DecoderMethod");
1337   if (InstDecoder != "") {
1338     InsnOperands.push_back(OperandInfo(InstDecoder));
1339     Operands[Opc] = InsnOperands;
1340     return true;
1341   }
1342
1343   // Generate a description of the operand of the instruction that we know
1344   // how to decode automatically.
1345   // FIXME: We'll need to have a way to manually override this as needed.
1346
1347   // Gather the outputs/inputs of the instruction, so we can find their
1348   // positions in the encoding.  This assumes for now that they appear in the
1349   // MCInst in the order that they're listed.
1350   std::vector<std::pair<Init*, std::string> > InOutOperands;
1351   DagInit *Out  = Def.getValueAsDag("OutOperandList");
1352   DagInit *In  = Def.getValueAsDag("InOperandList");
1353   for (unsigned i = 0; i < Out->getNumArgs(); ++i)
1354     InOutOperands.push_back(std::make_pair(Out->getArg(i), Out->getArgName(i)));
1355   for (unsigned i = 0; i < In->getNumArgs(); ++i)
1356     InOutOperands.push_back(std::make_pair(In->getArg(i), In->getArgName(i)));
1357
1358   // Search for tied operands, so that we can correctly instantiate
1359   // operands that are not explicitly represented in the encoding.
1360   std::map<std::string, std::string> TiedNames;
1361   for (unsigned i = 0; i < CGI.Operands.size(); ++i) {
1362     int tiedTo = CGI.Operands[i].getTiedRegister();
1363     if (tiedTo != -1) {
1364       TiedNames[InOutOperands[i].second] = InOutOperands[tiedTo].second;
1365       TiedNames[InOutOperands[tiedTo].second] = InOutOperands[i].second;
1366     }
1367   }
1368
1369   // For each operand, see if we can figure out where it is encoded.
1370   for (std::vector<std::pair<Init*, std::string> >::iterator
1371        NI = InOutOperands.begin(), NE = InOutOperands.end(); NI != NE; ++NI) {
1372     std::string Decoder = "";
1373
1374     // At this point, we can locate the field, but we need to know how to
1375     // interpret it.  As a first step, require the target to provide callbacks
1376     // for decoding register classes.
1377     // FIXME: This need to be extended to handle instructions with custom
1378     // decoder methods, and operands with (simple) MIOperandInfo's.
1379     TypedInit *TI = dynamic_cast<TypedInit*>(NI->first);
1380     RecordRecTy *Type = dynamic_cast<RecordRecTy*>(TI->getType());
1381     Record *TypeRecord = Type->getRecord();
1382     bool isReg = false;
1383     if (TypeRecord->isSubClassOf("RegisterOperand"))
1384       TypeRecord = TypeRecord->getValueAsDef("RegClass");
1385     if (TypeRecord->isSubClassOf("RegisterClass")) {
1386       Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
1387       isReg = true;
1388     }
1389
1390     RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
1391     StringInit *String = DecoderString ?
1392       dynamic_cast<StringInit*>(DecoderString->getValue()) : 0;
1393     if (!isReg && String && String->getValue() != "")
1394       Decoder = String->getValue();
1395
1396     OperandInfo OpInfo(Decoder);
1397     unsigned Base = ~0U;
1398     unsigned Width = 0;
1399     unsigned Offset = 0;
1400
1401     for (unsigned bi = 0; bi < Bits.getNumBits(); ++bi) {
1402       VarInit *Var = 0;
1403       VarBitInit *BI = dynamic_cast<VarBitInit*>(Bits.getBit(bi));
1404       if (BI)
1405         Var = dynamic_cast<VarInit*>(BI->getVariable());
1406       else
1407         Var = dynamic_cast<VarInit*>(Bits.getBit(bi));
1408
1409       if (!Var) {
1410         if (Base != ~0U) {
1411           OpInfo.addField(Base, Width, Offset);
1412           Base = ~0U;
1413           Width = 0;
1414           Offset = 0;
1415         }
1416         continue;
1417       }
1418
1419       if (Var->getName() != NI->second &&
1420           Var->getName() != TiedNames[NI->second]) {
1421         if (Base != ~0U) {
1422           OpInfo.addField(Base, Width, Offset);
1423           Base = ~0U;
1424           Width = 0;
1425           Offset = 0;
1426         }
1427         continue;
1428       }
1429
1430       if (Base == ~0U) {
1431         Base = bi;
1432         Width = 1;
1433         Offset = BI ? BI->getBitNum() : 0;
1434       } else if (BI && BI->getBitNum() != Offset + Width) {
1435         OpInfo.addField(Base, Width, Offset);
1436         Base = bi;
1437         Width = 1;
1438         Offset = BI->getBitNum();
1439       } else {
1440         ++Width;
1441       }
1442     }
1443
1444     if (Base != ~0U)
1445       OpInfo.addField(Base, Width, Offset);
1446
1447     if (OpInfo.numFields() > 0)
1448       InsnOperands.push_back(OpInfo);
1449   }
1450
1451   Operands[Opc] = InsnOperands;
1452
1453
1454 #if 0
1455   DEBUG({
1456       // Dumps the instruction encoding bits.
1457       dumpBits(errs(), Bits);
1458
1459       errs() << '\n';
1460
1461       // Dumps the list of operand info.
1462       for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
1463         const CGIOperandList::OperandInfo &Info = CGI.Operands[i];
1464         const std::string &OperandName = Info.Name;
1465         const Record &OperandDef = *Info.Rec;
1466
1467         errs() << "\t" << OperandName << " (" << OperandDef.getName() << ")\n";
1468       }
1469     });
1470 #endif
1471
1472   return true;
1473 }
1474
1475 static void emitHelper(llvm::raw_ostream &o, unsigned BitWidth) {
1476   unsigned Indentation = 0;
1477   std::string WidthStr = "uint" + utostr(BitWidth) + "_t";
1478
1479   o << '\n';
1480
1481   o.indent(Indentation) << "static " << WidthStr <<
1482     " fieldFromInstruction" << BitWidth <<
1483     "(" << WidthStr <<" insn, unsigned startBit, unsigned numBits)\n";
1484
1485   o.indent(Indentation) << "{\n";
1486
1487   ++Indentation; ++Indentation;
1488   o.indent(Indentation) << "assert(startBit + numBits <= " << BitWidth
1489                         << " && \"Instruction field out of bounds!\");\n";
1490   o << '\n';
1491   o.indent(Indentation) << WidthStr << " fieldMask;\n";
1492   o << '\n';
1493   o.indent(Indentation) << "if (numBits == " << BitWidth << ")\n";
1494
1495   ++Indentation; ++Indentation;
1496   o.indent(Indentation) << "fieldMask = (" << WidthStr << ")-1;\n";
1497   --Indentation; --Indentation;
1498
1499   o.indent(Indentation) << "else\n";
1500
1501   ++Indentation; ++Indentation;
1502   o.indent(Indentation) << "fieldMask = ((1 << numBits) - 1) << startBit;\n";
1503   --Indentation; --Indentation;
1504
1505   o << '\n';
1506   o.indent(Indentation) << "return (insn & fieldMask) >> startBit;\n";
1507   --Indentation; --Indentation;
1508
1509   o.indent(Indentation) << "}\n";
1510
1511   o << '\n';
1512 }
1513
1514 // Emits disassembler code for instruction decoding.
1515 void FixedLenDecoderEmitter::run(raw_ostream &o)
1516 {
1517   o << "#include \"llvm/MC/MCInst.h\"\n";
1518   o << "#include \"llvm/Support/DataTypes.h\"\n";
1519   o << "#include <assert.h>\n";
1520   o << '\n';
1521   o << "namespace llvm {\n\n";
1522
1523   // Parameterize the decoders based on namespace and instruction width.
1524   std::vector<const CodeGenInstruction*> NumberedInstructions =
1525     Target.getInstructionsByEnumValue();
1526   std::map<std::pair<std::string, unsigned>,
1527            std::vector<unsigned> > OpcMap;
1528   std::map<unsigned, std::vector<OperandInfo> > Operands;
1529
1530   for (unsigned i = 0; i < NumberedInstructions.size(); ++i) {
1531     const CodeGenInstruction *Inst = NumberedInstructions[i];
1532     Record *Def = Inst->TheDef;
1533     unsigned Size = Def->getValueAsInt("Size");
1534     if (Def->getValueAsString("Namespace") == "TargetOpcode" ||
1535         Def->getValueAsBit("isPseudo") ||
1536         Def->getValueAsBit("isAsmParserOnly") ||
1537         Def->getValueAsBit("isCodeGenOnly"))
1538       continue;
1539
1540     std::string DecoderNamespace = Def->getValueAsString("DecoderNamespace");
1541
1542     if (Size) {
1543       if (populateInstruction(*Inst, i, Operands)) {
1544         OpcMap[std::make_pair(DecoderNamespace, Size)].push_back(i);
1545       }
1546     }
1547   }
1548
1549   std::set<unsigned> Sizes;
1550   for (std::map<std::pair<std::string, unsigned>,
1551                 std::vector<unsigned> >::iterator
1552        I = OpcMap.begin(), E = OpcMap.end(); I != E; ++I) {
1553     // If we haven't visited this instruction width before, emit the
1554     // helper method to extract fields.
1555     if (!Sizes.count(I->first.second)) {
1556       emitHelper(o, 8*I->first.second);
1557       Sizes.insert(I->first.second);
1558     }
1559
1560     // Emit the decoder for this namespace+width combination.
1561     FilterChooser FC(NumberedInstructions, I->second, Operands,
1562                      8*I->first.second, this);
1563     FC.emitTop(o, 0, I->first.first);
1564   }
1565
1566   o << "\n} // End llvm namespace \n";
1567 }