Spacing fixes. Mostly aligning arguments that spilled onto next line with the opening...
[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,
340                       std::vector<uint64_t> &FieldVals, 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)
399   : Owner(&owner), StartBit(startBit), NumBits(numBits), 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,
695                                    std::vector<uint64_t> &FieldVals,
696                                    insn_t &Insn) {
697   unsigned Num, BitNo;
698   Num = BitNo = 0;
699
700   uint64_t FieldVal = 0;
701
702   // 0: Init
703   // 1: Water (the bit value does not affect decoding)
704   // 2: Island (well-known bit value needed for decoding)
705   int State = 0;
706   int Val = -1;
707
708   for (unsigned i = 0; i < BitWidth; ++i) {
709     Val = Value(Insn[i]);
710     bool Filtered = PositionFiltered(i);
711     switch (State) {
712     default: llvm_unreachable("Unreachable code!");
713     case 0:
714     case 1:
715       if (Filtered || Val == -1)
716         State = 1; // Still in Water
717       else {
718         State = 2; // Into the Island
719         BitNo = 0;
720         StartBits.push_back(i);
721         FieldVal = Val;
722       }
723       break;
724     case 2:
725       if (Filtered || Val == -1) {
726         State = 1; // Into the Water
727         EndBits.push_back(i - 1);
728         FieldVals.push_back(FieldVal);
729         ++Num;
730       } else {
731         State = 2; // Still in Island
732         ++BitNo;
733         FieldVal = FieldVal | Val << BitNo;
734       }
735       break;
736     }
737   }
738   // If we are still in Island after the loop, do some housekeeping.
739   if (State == 2) {
740     EndBits.push_back(BitWidth - 1);
741     FieldVals.push_back(FieldVal);
742     ++Num;
743   }
744
745   assert(StartBits.size() == Num && EndBits.size() == Num &&
746          FieldVals.size() == Num);
747   return Num;
748 }
749
750 void FilterChooser::emitBinaryParser(raw_ostream &o, unsigned &Indentation,
751                                      OperandInfo &OpInfo) {
752   std::string &Decoder = OpInfo.Decoder;
753
754   if (OpInfo.numFields() == 1) {
755     OperandInfo::iterator OI = OpInfo.begin();
756     o.indent(Indentation) << "  tmp = fieldFromInstruction" << BitWidth
757                             << "(insn, " << OI->Base << ", " << OI->Width
758                             << ");\n";
759   } else {
760     o.indent(Indentation) << "  tmp = 0;\n";
761     for (OperandInfo::iterator OI = OpInfo.begin(), OE = OpInfo.end();
762          OI != OE; ++OI) {
763       o.indent(Indentation) << "  tmp |= (fieldFromInstruction" << BitWidth
764                             << "(insn, " << OI->Base << ", " << OI->Width
765                             << ") << " << OI->Offset << ");\n";
766     }
767   }
768
769   if (Decoder != "")
770     o.indent(Indentation) << "  " << Emitter->GuardPrefix << Decoder
771                           << "(MI, tmp, Address, Decoder)"
772                           << Emitter->GuardPostfix << "\n";
773   else
774     o.indent(Indentation) << "  MI.addOperand(MCOperand::CreateImm(tmp));\n";
775
776 }
777
778 static void emitSinglePredicateMatch(raw_ostream &o, StringRef str,
779                                      std::string PredicateNamespace) {
780   if (str[0] == '!')
781     o << "!(Bits & " << PredicateNamespace << "::"
782       << str.slice(1,str.size()) << ")";
783   else
784     o << "(Bits & " << PredicateNamespace << "::" << str << ")";
785 }
786
787 bool FilterChooser::emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
788                                        unsigned Opc) {
789   ListInit *Predicates =
790     AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
791   for (unsigned i = 0; i < Predicates->getSize(); ++i) {
792     Record *Pred = Predicates->getElementAsRecord(i);
793     if (!Pred->getValue("AssemblerMatcherPredicate"))
794       continue;
795
796     std::string P = Pred->getValueAsString("AssemblerCondString");
797
798     if (!P.length())
799       continue;
800
801     if (i != 0)
802       o << " && ";
803
804     StringRef SR(P);
805     std::pair<StringRef, StringRef> pairs = SR.split(',');
806     while (pairs.second.size()) {
807       emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
808       o << " && ";
809       pairs = pairs.second.split(',');
810     }
811     emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
812   }
813   return Predicates->getSize() > 0;
814 }
815
816 void FilterChooser::emitSoftFailCheck(raw_ostream &o, unsigned Indentation,
817                                       unsigned Opc) {
818   BitsInit *SFBits =
819     AllInstructions[Opc]->TheDef->getValueAsBitsInit("SoftFail");
820   if (!SFBits) return;
821   BitsInit *InstBits = AllInstructions[Opc]->TheDef->getValueAsBitsInit("Inst");
822
823   APInt PositiveMask(BitWidth, 0ULL);
824   APInt NegativeMask(BitWidth, 0ULL);
825   for (unsigned i = 0; i < BitWidth; ++i) {
826     bit_value_t B = bitFromBits(*SFBits, i);
827     bit_value_t IB = bitFromBits(*InstBits, i);
828
829     if (B != BIT_TRUE) continue;
830
831     switch (IB) {
832     case BIT_FALSE:
833       // The bit is meant to be false, so emit a check to see if it is true.
834       PositiveMask.setBit(i);
835       break;
836     case BIT_TRUE:
837       // The bit is meant to be true, so emit a check to see if it is false.
838       NegativeMask.setBit(i);
839       break;
840     default:
841       // The bit is not set; this must be an error!
842       StringRef Name = AllInstructions[Opc]->TheDef->getName();
843       errs() << "SoftFail Conflict: bit SoftFail{" << i << "} in "
844              << Name
845              << " is set but Inst{" << i <<"} is unset!\n"
846              << "  - You can only mark a bit as SoftFail if it is fully defined"
847              << " (1/0 - not '?') in Inst\n";
848       o << "#error SoftFail Conflict, " << Name << "::SoftFail{" << i 
849         << "} set but Inst{" << i << "} undefined!\n";
850     }
851   }
852
853   bool NeedPositiveMask = PositiveMask.getBoolValue();
854   bool NeedNegativeMask = NegativeMask.getBoolValue();
855
856   if (!NeedPositiveMask && !NeedNegativeMask)
857     return;
858
859   std::string PositiveMaskStr = PositiveMask.toString(16, /*signed=*/false);
860   std::string NegativeMaskStr = NegativeMask.toString(16, /*signed=*/false);
861   StringRef BitExt = "";
862   if (BitWidth > 32)
863     BitExt = "ULL";
864
865   o.indent(Indentation) << "if (";
866   if (NeedPositiveMask)
867     o << "insn & 0x" << PositiveMaskStr << BitExt;
868   if (NeedPositiveMask && NeedNegativeMask)
869     o << " || ";
870   if (NeedNegativeMask)
871     o << "~insn & 0x" << NegativeMaskStr << BitExt;
872   o << ")\n";
873   o.indent(Indentation+2) << "S = MCDisassembler::SoftFail;\n";
874 }
875
876 // Emits code to decode the singleton.  Return true if we have matched all the
877 // well-known bits.
878 bool FilterChooser::emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,
879                                          unsigned Opc) {
880   std::vector<unsigned> StartBits;
881   std::vector<unsigned> EndBits;
882   std::vector<uint64_t> FieldVals;
883   insn_t Insn;
884   insnWithID(Insn, Opc);
885
886   // Look for islands of undecoded bits of the singleton.
887   getIslands(StartBits, EndBits, FieldVals, Insn);
888
889   unsigned Size = StartBits.size();
890   unsigned I, NumBits;
891
892   // If we have matched all the well-known bits, just issue a return.
893   if (Size == 0) {
894     o.indent(Indentation) << "if (";
895     if (!emitPredicateMatch(o, Indentation, Opc))
896       o << "1";
897     o << ") {\n";
898     emitSoftFailCheck(o, Indentation+2, Opc);
899     o.indent(Indentation) << "  MI.setOpcode(" << Opc << ");\n";
900     std::vector<OperandInfo>& InsnOperands = Operands[Opc];
901     for (std::vector<OperandInfo>::iterator
902          I = InsnOperands.begin(), E = InsnOperands.end(); I != E; ++I) {
903       // If a custom instruction decoder was specified, use that.
904       if (I->numFields() == 0 && I->Decoder.size()) {
905         o.indent(Indentation) << "  " << Emitter->GuardPrefix << I->Decoder
906                               << "(MI, insn, Address, Decoder)"
907                               << Emitter->GuardPostfix << "\n";
908         break;
909       }
910
911       emitBinaryParser(o, Indentation, *I);
912     }
913
914     o.indent(Indentation) << "  return " << Emitter->ReturnOK << "; // "
915                           << nameWithID(Opc) << '\n';
916     o.indent(Indentation) << "}\n"; // Closing predicate block.
917     return true;
918   }
919
920   // Otherwise, there are more decodings to be done!
921
922   // Emit code to match the island(s) for the singleton.
923   o.indent(Indentation) << "// Check ";
924
925   for (I = Size; I != 0; --I) {
926     o << "Inst{" << EndBits[I-1] << '-' << StartBits[I-1] << "} ";
927     if (I > 1)
928       o << " && ";
929     else
930       o << "for singleton decoding...\n";
931   }
932
933   o.indent(Indentation) << "if (";
934   if (emitPredicateMatch(o, Indentation, Opc)) {
935     o << " &&\n";
936     o.indent(Indentation+4);
937   }
938
939   for (I = Size; I != 0; --I) {
940     NumBits = EndBits[I-1] - StartBits[I-1] + 1;
941     o << "fieldFromInstruction" << BitWidth << "(insn, "
942       << StartBits[I-1] << ", " << NumBits
943       << ") == " << FieldVals[I-1];
944     if (I > 1)
945       o << " && ";
946     else
947       o << ") {\n";
948   }
949   emitSoftFailCheck(o, Indentation+2, Opc);
950   o.indent(Indentation) << "  MI.setOpcode(" << Opc << ");\n";
951   std::vector<OperandInfo>& InsnOperands = Operands[Opc];
952   for (std::vector<OperandInfo>::iterator
953        I = InsnOperands.begin(), E = InsnOperands.end(); I != E; ++I) {
954     // If a custom instruction decoder was specified, use that.
955     if (I->numFields() == 0 && I->Decoder.size()) {
956       o.indent(Indentation) << "  " << Emitter->GuardPrefix << I->Decoder
957                             << "(MI, insn, Address, Decoder)"
958                             << Emitter->GuardPostfix << "\n";
959       break;
960     }
961
962     emitBinaryParser(o, Indentation, *I);
963   }
964   o.indent(Indentation) << "  return " << Emitter->ReturnOK << "; // "
965                         << nameWithID(Opc) << '\n';
966   o.indent(Indentation) << "}\n";
967
968   return false;
969 }
970
971 // Emits code to decode the singleton, and then to decode the rest.
972 void FilterChooser::emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,
973                                          Filter &Best) {
974
975   unsigned Opc = Best.getSingletonOpc();
976
977   emitSingletonDecoder(o, Indentation, Opc);
978
979   // Emit code for the rest.
980   o.indent(Indentation) << "else\n";
981
982   Indentation += 2;
983   Best.getVariableFC().emit(o, Indentation);
984   Indentation -= 2;
985 }
986
987 // Assign a single filter and run with it.  Top level API client can initialize
988 // with a single filter to start the filtering process.
989 void FilterChooser::runSingleFilter(FilterChooser &owner, unsigned startBit,
990                                     unsigned numBit, bool mixed) {
991   Filters.clear();
992   Filter F(*this, startBit, numBit, true);
993   Filters.push_back(F);
994   BestIndex = 0; // Sole Filter instance to choose from.
995   bestFilter().recurse();
996 }
997
998 // reportRegion is a helper function for filterProcessor to mark a region as
999 // eligible for use as a filter region.
1000 void FilterChooser::reportRegion(bitAttr_t RA, unsigned StartBit,
1001                                  unsigned BitIndex, bool AllowMixed) {
1002   if (RA == ATTR_MIXED && AllowMixed)
1003     Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, true));
1004   else if (RA == ATTR_ALL_SET && !AllowMixed)
1005     Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, false));
1006 }
1007
1008 // FilterProcessor scans the well-known encoding bits of the instructions and
1009 // builds up a list of candidate filters.  It chooses the best filter and
1010 // recursively descends down the decoding tree.
1011 bool FilterChooser::filterProcessor(bool AllowMixed, bool Greedy) {
1012   Filters.clear();
1013   BestIndex = -1;
1014   unsigned numInstructions = Opcodes.size();
1015
1016   assert(numInstructions && "Filter created with no instructions");
1017
1018   // No further filtering is necessary.
1019   if (numInstructions == 1)
1020     return true;
1021
1022   // Heuristics.  See also doFilter()'s "Heuristics" comment when num of
1023   // instructions is 3.
1024   if (AllowMixed && !Greedy) {
1025     assert(numInstructions == 3);
1026
1027     for (unsigned i = 0; i < Opcodes.size(); ++i) {
1028       std::vector<unsigned> StartBits;
1029       std::vector<unsigned> EndBits;
1030       std::vector<uint64_t> FieldVals;
1031       insn_t Insn;
1032
1033       insnWithID(Insn, Opcodes[i]);
1034
1035       // Look for islands of undecoded bits of any instruction.
1036       if (getIslands(StartBits, EndBits, FieldVals, Insn) > 0) {
1037         // Found an instruction with island(s).  Now just assign a filter.
1038         runSingleFilter(*this, StartBits[0], EndBits[0] - StartBits[0] + 1,
1039                         true);
1040         return true;
1041       }
1042     }
1043   }
1044
1045   unsigned BitIndex, InsnIndex;
1046
1047   // We maintain BIT_WIDTH copies of the bitAttrs automaton.
1048   // The automaton consumes the corresponding bit from each
1049   // instruction.
1050   //
1051   //   Input symbols: 0, 1, and _ (unset).
1052   //   States:        NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED.
1053   //   Initial state: NONE.
1054   //
1055   // (NONE) ------- [01] -> (ALL_SET)
1056   // (NONE) ------- _ ----> (ALL_UNSET)
1057   // (ALL_SET) ---- [01] -> (ALL_SET)
1058   // (ALL_SET) ---- _ ----> (MIXED)
1059   // (ALL_UNSET) -- [01] -> (MIXED)
1060   // (ALL_UNSET) -- _ ----> (ALL_UNSET)
1061   // (MIXED) ------ . ----> (MIXED)
1062   // (FILTERED)---- . ----> (FILTERED)
1063
1064   std::vector<bitAttr_t> bitAttrs;
1065
1066   // FILTERED bit positions provide no entropy and are not worthy of pursuing.
1067   // Filter::recurse() set either BIT_TRUE or BIT_FALSE for each position.
1068   for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex)
1069     if (FilterBitValues[BitIndex] == BIT_TRUE ||
1070         FilterBitValues[BitIndex] == BIT_FALSE)
1071       bitAttrs.push_back(ATTR_FILTERED);
1072     else
1073       bitAttrs.push_back(ATTR_NONE);
1074
1075   for (InsnIndex = 0; InsnIndex < numInstructions; ++InsnIndex) {
1076     insn_t insn;
1077
1078     insnWithID(insn, Opcodes[InsnIndex]);
1079
1080     for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
1081       switch (bitAttrs[BitIndex]) {
1082       case ATTR_NONE:
1083         if (insn[BitIndex] == BIT_UNSET)
1084           bitAttrs[BitIndex] = ATTR_ALL_UNSET;
1085         else
1086           bitAttrs[BitIndex] = ATTR_ALL_SET;
1087         break;
1088       case ATTR_ALL_SET:
1089         if (insn[BitIndex] == BIT_UNSET)
1090           bitAttrs[BitIndex] = ATTR_MIXED;
1091         break;
1092       case ATTR_ALL_UNSET:
1093         if (insn[BitIndex] != BIT_UNSET)
1094           bitAttrs[BitIndex] = ATTR_MIXED;
1095         break;
1096       case ATTR_MIXED:
1097       case ATTR_FILTERED:
1098         break;
1099       }
1100     }
1101   }
1102
1103   // The regionAttr automaton consumes the bitAttrs automatons' state,
1104   // lowest-to-highest.
1105   //
1106   //   Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed)
1107   //   States:        NONE, ALL_SET, MIXED
1108   //   Initial state: NONE
1109   //
1110   // (NONE) ----- F --> (NONE)
1111   // (NONE) ----- S --> (ALL_SET)     ; and set region start
1112   // (NONE) ----- U --> (NONE)
1113   // (NONE) ----- M --> (MIXED)       ; and set region start
1114   // (ALL_SET) -- F --> (NONE)        ; and report an ALL_SET region
1115   // (ALL_SET) -- S --> (ALL_SET)
1116   // (ALL_SET) -- U --> (NONE)        ; and report an ALL_SET region
1117   // (ALL_SET) -- M --> (MIXED)       ; and report an ALL_SET region
1118   // (MIXED) ---- F --> (NONE)        ; and report a MIXED region
1119   // (MIXED) ---- S --> (ALL_SET)     ; and report a MIXED region
1120   // (MIXED) ---- U --> (NONE)        ; and report a MIXED region
1121   // (MIXED) ---- M --> (MIXED)
1122
1123   bitAttr_t RA = ATTR_NONE;
1124   unsigned StartBit = 0;
1125
1126   for (BitIndex = 0; BitIndex < BitWidth; BitIndex++) {
1127     bitAttr_t bitAttr = bitAttrs[BitIndex];
1128
1129     assert(bitAttr != ATTR_NONE && "Bit without attributes");
1130
1131     switch (RA) {
1132     case ATTR_NONE:
1133       switch (bitAttr) {
1134       case ATTR_FILTERED:
1135         break;
1136       case ATTR_ALL_SET:
1137         StartBit = BitIndex;
1138         RA = ATTR_ALL_SET;
1139         break;
1140       case ATTR_ALL_UNSET:
1141         break;
1142       case ATTR_MIXED:
1143         StartBit = BitIndex;
1144         RA = ATTR_MIXED;
1145         break;
1146       default:
1147         llvm_unreachable("Unexpected bitAttr!");
1148       }
1149       break;
1150     case ATTR_ALL_SET:
1151       switch (bitAttr) {
1152       case ATTR_FILTERED:
1153         reportRegion(RA, StartBit, BitIndex, AllowMixed);
1154         RA = ATTR_NONE;
1155         break;
1156       case ATTR_ALL_SET:
1157         break;
1158       case ATTR_ALL_UNSET:
1159         reportRegion(RA, StartBit, BitIndex, AllowMixed);
1160         RA = ATTR_NONE;
1161         break;
1162       case ATTR_MIXED:
1163         reportRegion(RA, StartBit, BitIndex, AllowMixed);
1164         StartBit = BitIndex;
1165         RA = ATTR_MIXED;
1166         break;
1167       default:
1168         llvm_unreachable("Unexpected bitAttr!");
1169       }
1170       break;
1171     case ATTR_MIXED:
1172       switch (bitAttr) {
1173       case ATTR_FILTERED:
1174         reportRegion(RA, StartBit, BitIndex, AllowMixed);
1175         StartBit = BitIndex;
1176         RA = ATTR_NONE;
1177         break;
1178       case ATTR_ALL_SET:
1179         reportRegion(RA, StartBit, BitIndex, AllowMixed);
1180         StartBit = BitIndex;
1181         RA = ATTR_ALL_SET;
1182         break;
1183       case ATTR_ALL_UNSET:
1184         reportRegion(RA, StartBit, BitIndex, AllowMixed);
1185         RA = ATTR_NONE;
1186         break;
1187       case ATTR_MIXED:
1188         break;
1189       default:
1190         llvm_unreachable("Unexpected bitAttr!");
1191       }
1192       break;
1193     case ATTR_ALL_UNSET:
1194       llvm_unreachable("regionAttr state machine has no ATTR_UNSET state");
1195     case ATTR_FILTERED:
1196       llvm_unreachable("regionAttr state machine has no ATTR_FILTERED state");
1197     }
1198   }
1199
1200   // At the end, if we're still in ALL_SET or MIXED states, report a region
1201   switch (RA) {
1202   case ATTR_NONE:
1203     break;
1204   case ATTR_FILTERED:
1205     break;
1206   case ATTR_ALL_SET:
1207     reportRegion(RA, StartBit, BitIndex, AllowMixed);
1208     break;
1209   case ATTR_ALL_UNSET:
1210     break;
1211   case ATTR_MIXED:
1212     reportRegion(RA, StartBit, BitIndex, AllowMixed);
1213     break;
1214   }
1215
1216   // We have finished with the filter processings.  Now it's time to choose
1217   // the best performing filter.
1218   BestIndex = 0;
1219   bool AllUseless = true;
1220   unsigned BestScore = 0;
1221
1222   for (unsigned i = 0, e = Filters.size(); i != e; ++i) {
1223     unsigned Usefulness = Filters[i].usefulness();
1224
1225     if (Usefulness)
1226       AllUseless = false;
1227
1228     if (Usefulness > BestScore) {
1229       BestIndex = i;
1230       BestScore = Usefulness;
1231     }
1232   }
1233
1234   if (!AllUseless)
1235     bestFilter().recurse();
1236
1237   return !AllUseless;
1238 } // end of FilterChooser::filterProcessor(bool)
1239
1240 // Decides on the best configuration of filter(s) to use in order to decode
1241 // the instructions.  A conflict of instructions may occur, in which case we
1242 // dump the conflict set to the standard error.
1243 void FilterChooser::doFilter() {
1244   unsigned Num = Opcodes.size();
1245   assert(Num && "FilterChooser created with no instructions");
1246
1247   // Try regions of consecutive known bit values first.
1248   if (filterProcessor(false))
1249     return;
1250
1251   // Then regions of mixed bits (both known and unitialized bit values allowed).
1252   if (filterProcessor(true))
1253     return;
1254
1255   // Heuristics to cope with conflict set {t2CMPrs, t2SUBSrr, t2SUBSrs} where
1256   // no single instruction for the maximum ATTR_MIXED region Inst{14-4} has a
1257   // well-known encoding pattern.  In such case, we backtrack and scan for the
1258   // the very first consecutive ATTR_ALL_SET region and assign a filter to it.
1259   if (Num == 3 && filterProcessor(true, false))
1260     return;
1261
1262   // If we come to here, the instruction decoding has failed.
1263   // Set the BestIndex to -1 to indicate so.
1264   BestIndex = -1;
1265 }
1266
1267 // Emits code to decode our share of instructions.  Returns true if the
1268 // emitted code causes a return, which occurs if we know how to decode
1269 // the instruction at this level or the instruction is not decodeable.
1270 bool FilterChooser::emit(raw_ostream &o, unsigned &Indentation) {
1271   if (Opcodes.size() == 1)
1272     // There is only one instruction in the set, which is great!
1273     // Call emitSingletonDecoder() to see whether there are any remaining
1274     // encodings bits.
1275     return emitSingletonDecoder(o, Indentation, Opcodes[0]);
1276
1277   // Choose the best filter to do the decodings!
1278   if (BestIndex != -1) {
1279     Filter &Best = bestFilter();
1280     if (Best.getNumFiltered() == 1)
1281       emitSingletonDecoder(o, Indentation, Best);
1282     else
1283       bestFilter().emit(o, Indentation);
1284     return false;
1285   }
1286
1287   // We don't know how to decode these instructions!  Return 0 and dump the
1288   // conflict set!
1289   o.indent(Indentation) << "return 0;" << " // Conflict set: ";
1290   for (int i = 0, N = Opcodes.size(); i < N; ++i) {
1291     o << nameWithID(Opcodes[i]);
1292     if (i < (N - 1))
1293       o << ", ";
1294     else
1295       o << '\n';
1296   }
1297
1298   // Print out useful conflict information for postmortem analysis.
1299   errs() << "Decoding Conflict:\n";
1300
1301   dumpStack(errs(), "\t\t");
1302
1303   for (unsigned i = 0; i < Opcodes.size(); ++i) {
1304     const std::string &Name = nameWithID(Opcodes[i]);
1305
1306     errs() << '\t' << Name << " ";
1307     dumpBits(errs(),
1308              getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
1309     errs() << '\n';
1310   }
1311
1312   return true;
1313 }
1314
1315 static bool populateInstruction(const CodeGenInstruction &CGI, 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   o << "#include \"llvm/MC/MCInst.h\"\n";
1517   o << "#include \"llvm/Support/DataTypes.h\"\n";
1518   o << "#include <assert.h>\n";
1519   o << '\n';
1520   o << "namespace llvm {\n\n";
1521
1522   // Parameterize the decoders based on namespace and instruction width.
1523   std::vector<const CodeGenInstruction*> NumberedInstructions =
1524     Target.getInstructionsByEnumValue();
1525   std::map<std::pair<std::string, unsigned>,
1526            std::vector<unsigned> > OpcMap;
1527   std::map<unsigned, std::vector<OperandInfo> > Operands;
1528
1529   for (unsigned i = 0; i < NumberedInstructions.size(); ++i) {
1530     const CodeGenInstruction *Inst = NumberedInstructions[i];
1531     Record *Def = Inst->TheDef;
1532     unsigned Size = Def->getValueAsInt("Size");
1533     if (Def->getValueAsString("Namespace") == "TargetOpcode" ||
1534         Def->getValueAsBit("isPseudo") ||
1535         Def->getValueAsBit("isAsmParserOnly") ||
1536         Def->getValueAsBit("isCodeGenOnly"))
1537       continue;
1538
1539     std::string DecoderNamespace = Def->getValueAsString("DecoderNamespace");
1540
1541     if (Size) {
1542       if (populateInstruction(*Inst, i, Operands)) {
1543         OpcMap[std::make_pair(DecoderNamespace, Size)].push_back(i);
1544       }
1545     }
1546   }
1547
1548   std::set<unsigned> Sizes;
1549   for (std::map<std::pair<std::string, unsigned>,
1550                 std::vector<unsigned> >::iterator
1551        I = OpcMap.begin(), E = OpcMap.end(); I != E; ++I) {
1552     // If we haven't visited this instruction width before, emit the
1553     // helper method to extract fields.
1554     if (!Sizes.count(I->first.second)) {
1555       emitHelper(o, 8*I->first.second);
1556       Sizes.insert(I->first.second);
1557     }
1558
1559     // Emit the decoder for this namespace+width combination.
1560     FilterChooser FC(NumberedInstructions, I->second, Operands,
1561                      8*I->first.second, this);
1562     FC.emitTop(o, 0, I->first.first);
1563   }
1564
1565   o << "\n} // End llvm namespace \n";
1566 }