Change from .../Support/DataTypes.h to .../System/DataTypes.h.
[oota-llvm.git] / utils / TableGen / ARMDecoderEmitter.cpp
1 //===------------ ARMDecoderEmitter.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 // This file is part of the ARM Disassembler.
11 // It contains the tablegen backend that emits the decoder functions for ARM and
12 // Thumb.  The disassembler core includes the auto-generated file, invokes the
13 // decoder functions, and builds up the MCInst based on the decoded Opcode.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #define DEBUG_TYPE "arm-decoder-emitter"
18
19 #include "ARMDecoderEmitter.h"
20 #include "CodeGenTarget.h"
21 #include "Record.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/raw_ostream.h"
25
26 #include <vector>
27 #include <map>
28 #include <string>
29
30 using namespace llvm;
31
32 /////////////////////////////////////////////////////
33 //                                                 //
34 //  Enums and Utilities for ARM Instruction Format //
35 //                                                 //
36 /////////////////////////////////////////////////////
37
38 #define ARM_FORMATS                   \
39   ENTRY(ARM_FORMAT_PSEUDO,         0) \
40   ENTRY(ARM_FORMAT_MULFRM,         1) \
41   ENTRY(ARM_FORMAT_BRFRM,          2) \
42   ENTRY(ARM_FORMAT_BRMISCFRM,      3) \
43   ENTRY(ARM_FORMAT_DPFRM,          4) \
44   ENTRY(ARM_FORMAT_DPSOREGFRM,     5) \
45   ENTRY(ARM_FORMAT_LDFRM,          6) \
46   ENTRY(ARM_FORMAT_STFRM,          7) \
47   ENTRY(ARM_FORMAT_LDMISCFRM,      8) \
48   ENTRY(ARM_FORMAT_STMISCFRM,      9) \
49   ENTRY(ARM_FORMAT_LDSTMULFRM,    10) \
50   ENTRY(ARM_FORMAT_LDSTEXFRM,     11) \
51   ENTRY(ARM_FORMAT_ARITHMISCFRM,  12) \
52   ENTRY(ARM_FORMAT_EXTFRM,        13) \
53   ENTRY(ARM_FORMAT_VFPUNARYFRM,   14) \
54   ENTRY(ARM_FORMAT_VFPBINARYFRM,  15) \
55   ENTRY(ARM_FORMAT_VFPCONV1FRM,   16) \
56   ENTRY(ARM_FORMAT_VFPCONV2FRM,   17) \
57   ENTRY(ARM_FORMAT_VFPCONV3FRM,   18) \
58   ENTRY(ARM_FORMAT_VFPCONV4FRM,   19) \
59   ENTRY(ARM_FORMAT_VFPCONV5FRM,   20) \
60   ENTRY(ARM_FORMAT_VFPLDSTFRM,    21) \
61   ENTRY(ARM_FORMAT_VFPLDSTMULFRM, 22) \
62   ENTRY(ARM_FORMAT_VFPMISCFRM,    23) \
63   ENTRY(ARM_FORMAT_THUMBFRM,      24) \
64   ENTRY(ARM_FORMAT_NEONFRM,       25) \
65   ENTRY(ARM_FORMAT_NEONGETLNFRM,  26) \
66   ENTRY(ARM_FORMAT_NEONSETLNFRM,  27) \
67   ENTRY(ARM_FORMAT_NEONDUPFRM,    28) \
68   ENTRY(ARM_FORMAT_MISCFRM,       29) \
69   ENTRY(ARM_FORMAT_THUMBMISCFRM,  30) \
70   ENTRY(ARM_FORMAT_NLdSt,         31) \
71   ENTRY(ARM_FORMAT_N1RegModImm,   32) \
72   ENTRY(ARM_FORMAT_N2Reg,         33) \
73   ENTRY(ARM_FORMAT_NVCVT,         34) \
74   ENTRY(ARM_FORMAT_NVecDupLn,     35) \
75   ENTRY(ARM_FORMAT_N2RegVecShL,   36) \
76   ENTRY(ARM_FORMAT_N2RegVecShR,   37) \
77   ENTRY(ARM_FORMAT_N3Reg,         38) \
78   ENTRY(ARM_FORMAT_N3RegVecSh,    39) \
79   ENTRY(ARM_FORMAT_NVecExtract,   40) \
80   ENTRY(ARM_FORMAT_NVecMulScalar, 41) \
81   ENTRY(ARM_FORMAT_NVTBL,         42)
82
83 // ARM instruction format specifies the encoding used by the instruction.
84 #define ENTRY(n, v) n = v,
85 typedef enum {
86   ARM_FORMATS
87   ARM_FORMAT_NA
88 } ARMFormat;
89 #undef ENTRY
90
91 // Converts enum to const char*.
92 static const char *stringForARMFormat(ARMFormat form) {
93 #define ENTRY(n, v) case n: return #n;
94   switch(form) {
95     ARM_FORMATS
96   case ARM_FORMAT_NA:
97   default:
98     return "";
99   }
100 #undef ENTRY
101 }
102
103 typedef enum {
104   IndexModeNone = 0,
105   IndexModePre  = 1,
106   IndexModePost = 2,
107   IndexModeUpd  = 3
108 };
109
110 /////////////////////////
111 //                     //
112 //  Utility functions  //
113 //                     //
114 /////////////////////////
115
116 /// byteFromBitsInit - Return the byte value from a BitsInit.
117 /// Called from getByteField().
118 static uint8_t byteFromBitsInit(BitsInit &init) {
119   int width = init.getNumBits();
120
121   assert(width <= 8 && "Field is too large for uint8_t!");
122
123   int index;
124   uint8_t mask = 0x01;
125
126   uint8_t ret = 0;
127
128   for (index = 0; index < width; index++) {
129     if (static_cast<BitInit*>(init.getBit(index))->getValue())
130       ret |= mask;
131
132     mask <<= 1;
133   }
134
135   return ret;
136 }
137
138 static uint8_t getByteField(const Record &def, const char *str) {
139   BitsInit *bits = def.getValueAsBitsInit(str);
140   return byteFromBitsInit(*bits);
141 }
142
143 static BitsInit &getBitsField(const Record &def, const char *str) {
144   BitsInit *bits = def.getValueAsBitsInit(str);
145   return *bits;
146 }
147
148 /// sameStringExceptSuffix - Return true if the two strings differ only in RHS's
149 /// suffix.  ("VST4d8", "VST4d8_UPD", "_UPD") as input returns true.
150 static
151 bool sameStringExceptSuffix(const StringRef LHS, const StringRef RHS,
152                             const StringRef Suffix) {
153
154   if (RHS.startswith(LHS) && RHS.endswith(Suffix))
155     return RHS.size() == LHS.size() + Suffix.size();
156
157   return false;
158 }
159
160 /// thumbInstruction - Determine whether we have a Thumb instruction.
161 /// See also ARMInstrFormats.td.
162 static bool thumbInstruction(uint8_t Form) {
163   return Form == ARM_FORMAT_THUMBFRM;
164 }
165
166 // The set (BIT_TRUE, BIT_FALSE, BIT_UNSET) represents a ternary logic system
167 // for a bit value.
168 //
169 // BIT_UNFILTERED is used as the init value for a filter position.  It is used
170 // only for filter processings.
171 typedef enum {
172   BIT_TRUE,      // '1'
173   BIT_FALSE,     // '0'
174   BIT_UNSET,     // '?'
175   BIT_UNFILTERED // unfiltered
176 } bit_value_t;
177
178 static bool ValueSet(bit_value_t V) {
179   return (V == BIT_TRUE || V == BIT_FALSE);
180 }
181 static bool ValueNotSet(bit_value_t V) {
182   return (V == BIT_UNSET);
183 }
184 static int Value(bit_value_t V) {
185   return ValueNotSet(V) ? -1 : (V == BIT_FALSE ? 0 : 1);
186 }
187 static bit_value_t bitFromBits(BitsInit &bits, unsigned index) {
188   if (BitInit *bit = dynamic_cast<BitInit*>(bits.getBit(index)))
189     return bit->getValue() ? BIT_TRUE : BIT_FALSE;
190
191   // The bit is uninitialized.
192   return BIT_UNSET;
193 }
194 // Prints the bit value for each position.
195 static void dumpBits(raw_ostream &o, BitsInit &bits) {
196   unsigned index;
197
198   for (index = bits.getNumBits(); index > 0; index--) {
199     switch (bitFromBits(bits, index - 1)) {
200     case BIT_TRUE:
201       o << "1";
202       break;
203     case BIT_FALSE:
204       o << "0";
205       break;
206     case BIT_UNSET:
207       o << "_";
208       break;
209     default:
210       assert(0 && "unexpected return value from bitFromBits");
211     }
212   }
213 }
214
215 // Enums for the available target names.
216 typedef enum {
217   TARGET_ARM = 0,
218   TARGET_THUMB
219 } TARGET_NAME_t;
220
221 // FIXME: Possibly auto-detected?
222 #define BIT_WIDTH 32
223
224 // Forward declaration.
225 class FilterChooser;
226
227 // Representation of the instruction to work on.
228 typedef bit_value_t insn_t[BIT_WIDTH];
229
230 /// Filter - Filter works with FilterChooser to produce the decoding tree for
231 /// the ISA.
232 ///
233 /// It is useful to think of a Filter as governing the switch stmts of the
234 /// decoding tree in a certain level.  Each case stmt delegates to an inferior
235 /// FilterChooser to decide what further decoding logic to employ, or in another
236 /// words, what other remaining bits to look at.  The FilterChooser eventually
237 /// chooses a best Filter to do its job.
238 ///
239 /// This recursive scheme ends when the number of Opcodes assigned to the
240 /// FilterChooser becomes 1 or if there is a conflict.  A conflict happens when
241 /// the Filter/FilterChooser combo does not know how to distinguish among the
242 /// Opcodes assigned.
243 ///
244 /// An example of a conflcit is 
245 ///
246 /// Conflict:
247 ///                     111101000.00........00010000....
248 ///                     111101000.00........0001........
249 ///                     1111010...00........0001........
250 ///                     1111010...00....................
251 ///                     1111010.........................
252 ///                     1111............................
253 ///                     ................................
254 ///     VST4q8a         111101000_00________00010000____
255 ///     VST4q8b         111101000_00________00010000____
256 ///
257 /// The Debug output shows the path that the decoding tree follows to reach the
258 /// the conclusion that there is a conflict.  VST4q8a is a vst4 to double-spaced
259 /// even registers, while VST4q8b is a vst4 to double-spaced odd regsisters.
260 ///
261 /// The encoding info in the .td files does not specify this meta information,
262 /// which could have been used by the decoder to resolve the conflict.  The
263 /// decoder could try to decode the even/odd register numbering and assign to
264 /// VST4q8a or VST4q8b, but for the time being, the decoder chooses the "a"
265 /// version and return the Opcode since the two have the same Asm format string.
266 class Filter {
267 protected:
268   FilterChooser *Owner; // points to the FilterChooser who owns this filter
269   unsigned StartBit; // the starting bit position
270   unsigned NumBits; // number of bits to filter
271   bool Mixed; // a mixed region contains both set and unset bits
272
273   // Map of well-known segment value to the set of uid's with that value. 
274   std::map<uint64_t, std::vector<unsigned> > FilteredInstructions;
275
276   // Set of uid's with non-constant segment values.
277   std::vector<unsigned> VariableInstructions;
278
279   // Map of well-known segment value to its delegate.
280   std::map<unsigned, FilterChooser*> FilterChooserMap;
281
282   // Number of instructions which fall under FilteredInstructions category.
283   unsigned NumFiltered;
284
285   // Keeps track of the last opcode in the filtered bucket.
286   unsigned LastOpcFiltered;
287
288   // Number of instructions which fall under VariableInstructions category.
289   unsigned NumVariable;
290
291 public:
292   unsigned getNumFiltered() { return NumFiltered; }
293   unsigned getNumVariable() { return NumVariable; }
294   unsigned getSingletonOpc() {
295     assert(NumFiltered == 1);
296     return LastOpcFiltered;
297   }
298   // Return the filter chooser for the group of instructions without constant
299   // segment values.
300   FilterChooser &getVariableFC() {
301     assert(NumFiltered == 1);
302     assert(FilterChooserMap.size() == 1);
303     return *(FilterChooserMap.find(-1)->second);
304   }
305
306   Filter(const Filter &f);
307   Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, bool mixed);
308
309   ~Filter();
310
311   // Divides the decoding task into sub tasks and delegates them to the
312   // inferior FilterChooser's.
313   //
314   // A special case arises when there's only one entry in the filtered
315   // instructions.  In order to unambiguously decode the singleton, we need to
316   // match the remaining undecoded encoding bits against the singleton.
317   void recurse();
318
319   // Emit code to decode instructions given a segment or segments of bits.
320   void emit(raw_ostream &o, unsigned &Indentation);
321
322   // Returns the number of fanout produced by the filter.  More fanout implies
323   // the filter distinguishes more categories of instructions.
324   unsigned usefulness() const;
325 }; // End of class Filter
326
327 // These are states of our finite state machines used in FilterChooser's
328 // filterProcessor() which produces the filter candidates to use.
329 typedef enum {
330   ATTR_NONE,
331   ATTR_FILTERED,
332   ATTR_ALL_SET,
333   ATTR_ALL_UNSET,
334   ATTR_MIXED
335 } bitAttr_t;
336
337 /// FilterChooser - FilterChooser chooses the best filter among a set of Filters
338 /// in order to perform the decoding of instructions at the current level.
339 ///
340 /// Decoding proceeds from the top down.  Based on the well-known encoding bits
341 /// of instructions available, FilterChooser builds up the possible Filters that
342 /// can further the task of decoding by distinguishing among the remaining
343 /// candidate instructions.
344 ///
345 /// Once a filter has been chosen, it is called upon to divide the decoding task
346 /// into sub-tasks and delegates them to its inferior FilterChoosers for further
347 /// processings.
348 ///
349 /// It is useful to think of a Filter as governing the switch stmts of the
350 /// decoding tree.  And each case is delegated to an inferior FilterChooser to
351 /// decide what further remaining bits to look at.
352 class FilterChooser {
353   static TARGET_NAME_t TargetName;
354
355 protected:
356   friend class Filter;
357
358   // Vector of codegen instructions to choose our filter.
359   const std::vector<const CodeGenInstruction*> &AllInstructions;
360
361   // Vector of uid's for this filter chooser to work on.
362   const std::vector<unsigned> Opcodes;
363
364   // Vector of candidate filters.
365   std::vector<Filter> Filters;
366
367   // Array of bit values passed down from our parent.
368   // Set to all BIT_UNFILTERED's for Parent == NULL.
369   bit_value_t FilterBitValues[BIT_WIDTH];
370
371   // Links to the FilterChooser above us in the decoding tree.
372   FilterChooser *Parent;
373   
374   // Index of the best filter from Filters.
375   int BestIndex;
376
377 public:
378   static void setTargetName(TARGET_NAME_t tn) { TargetName = tn; }
379
380   FilterChooser(const FilterChooser &FC) :
381       AllInstructions(FC.AllInstructions), Opcodes(FC.Opcodes),
382       Filters(FC.Filters), Parent(FC.Parent), BestIndex(FC.BestIndex) {
383     memcpy(FilterBitValues, FC.FilterBitValues, sizeof(FilterBitValues));
384   }
385
386   FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
387                 const std::vector<unsigned> &IDs) :
388       AllInstructions(Insts), Opcodes(IDs), Filters(), Parent(NULL),
389       BestIndex(-1) {
390     for (unsigned i = 0; i < BIT_WIDTH; ++i)
391       FilterBitValues[i] = BIT_UNFILTERED;
392
393     doFilter();
394   }
395
396   FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
397                 const std::vector<unsigned> &IDs,
398                 bit_value_t (&ParentFilterBitValues)[BIT_WIDTH],
399                 FilterChooser &parent) :
400       AllInstructions(Insts), Opcodes(IDs), Filters(), Parent(&parent),
401       BestIndex(-1) {
402     for (unsigned i = 0; i < BIT_WIDTH; ++i)
403       FilterBitValues[i] = ParentFilterBitValues[i];
404
405     doFilter();
406   }
407
408   // The top level filter chooser has NULL as its parent.
409   bool isTopLevel() { return Parent == NULL; }
410
411   // This provides an opportunity for target specific code emission.
412   void emitTopHook(raw_ostream &o);
413
414   // Emit the top level typedef and decodeInstruction() function.
415   void emitTop(raw_ostream &o, unsigned &Indentation);
416
417   // This provides an opportunity for target specific code emission after
418   // emitTop().
419   void emitBot(raw_ostream &o, unsigned &Indentation);
420
421 protected:
422   // Populates the insn given the uid.
423   void insnWithID(insn_t &Insn, unsigned Opcode) const {
424     BitsInit &Bits = getBitsField(*AllInstructions[Opcode]->TheDef, "Inst");
425
426     for (unsigned i = 0; i < BIT_WIDTH; ++i)
427       Insn[i] = bitFromBits(Bits, i);
428
429     // Set Inst{21} to 1 (wback) when IndexModeBits == IndexModeUpd.
430     if (getByteField(*AllInstructions[Opcode]->TheDef, "IndexModeBits")
431         == IndexModeUpd)
432       Insn[21] = BIT_TRUE;
433   }
434
435   // Returns the record name.
436   const std::string &nameWithID(unsigned Opcode) const {
437     return AllInstructions[Opcode]->TheDef->getName();
438   }
439
440   // Populates the field of the insn given the start position and the number of
441   // consecutive bits to scan for.
442   //
443   // Returns false if there exists any uninitialized bit value in the range.
444   // Returns true, otherwise.
445   bool fieldFromInsn(uint64_t &Field, insn_t &Insn, unsigned StartBit,
446       unsigned NumBits) const;
447
448   /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
449   /// filter array as a series of chars.
450   void dumpFilterArray(raw_ostream &o, bit_value_t (&filter)[BIT_WIDTH]);
451
452   /// dumpStack - dumpStack traverses the filter chooser chain and calls
453   /// dumpFilterArray on each filter chooser up to the top level one.
454   void dumpStack(raw_ostream &o, const char *prefix);
455
456   Filter &bestFilter() {
457     assert(BestIndex != -1 && "BestIndex not set");
458     return Filters[BestIndex];
459   }
460
461   // Called from Filter::recurse() when singleton exists.  For debug purpose.
462   void SingletonExists(unsigned Opc);
463
464   bool PositionFiltered(unsigned i) {
465     return ValueSet(FilterBitValues[i]);
466   }
467
468   // Calculates the island(s) needed to decode the instruction.
469   // This returns a lit of undecoded bits of an instructions, for example,
470   // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
471   // decoded bits in order to verify that the instruction matches the Opcode.
472   unsigned getIslands(std::vector<unsigned> &StartBits,
473       std::vector<unsigned> &EndBits, std::vector<uint64_t> &FieldVals,
474       insn_t &Insn);
475
476   // The purpose of this function is for the API client to detect possible
477   // Load/Store Coprocessor instructions.  If the coprocessor number is of
478   // the instruction is either 10 or 11, the decoder should not report the
479   // instruction as LDC/LDC2/STC/STC2, but should match against Advanced SIMD or
480   // VFP instructions.
481   bool LdStCopEncoding1(unsigned Opc) {
482     const std::string &Name = nameWithID(Opc);
483     if (Name == "LDC_OFFSET" || Name == "LDC_OPTION" ||
484         Name == "LDC_POST" || Name == "LDC_PRE" ||
485         Name == "LDCL_OFFSET" || Name == "LDCL_OPTION" ||
486         Name == "LDCL_POST" || Name == "LDCL_PRE" ||
487         Name == "STC_OFFSET" || Name == "STC_OPTION" ||
488         Name == "STC_POST" || Name == "STC_PRE" ||
489         Name == "STCL_OFFSET" || Name == "STCL_OPTION" ||
490         Name == "STCL_POST" || Name == "STCL_PRE")
491       return true;
492     else
493       return false;
494   }
495
496   // Emits code to decode the singleton.  Return true if we have matched all the
497   // well-known bits.
498   bool emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,unsigned Opc);
499
500   // Emits code to decode the singleton, and then to decode the rest.
501   void emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,Filter &Best);
502
503   // Assign a single filter and run with it.
504   void runSingleFilter(FilterChooser &owner, unsigned startBit, unsigned numBit,
505       bool mixed);
506
507   // reportRegion is a helper function for filterProcessor to mark a region as
508   // eligible for use as a filter region.
509   void reportRegion(bitAttr_t RA, unsigned StartBit, unsigned BitIndex,
510       bool AllowMixed);
511
512   // FilterProcessor scans the well-known encoding bits of the instructions and
513   // builds up a list of candidate filters.  It chooses the best filter and
514   // recursively descends down the decoding tree.
515   bool filterProcessor(bool AllowMixed, bool Greedy = true);
516
517   // Decides on the best configuration of filter(s) to use in order to decode
518   // the instructions.  A conflict of instructions may occur, in which case we
519   // dump the conflict set to the standard error.
520   void doFilter();
521
522   // Emits code to decode our share of instructions.  Returns true if the
523   // emitted code causes a return, which occurs if we know how to decode
524   // the instruction at this level or the instruction is not decodeable.
525   bool emit(raw_ostream &o, unsigned &Indentation);
526 };
527
528 ///////////////////////////
529 //                       //
530 // Filter Implmenetation //
531 //                       //
532 ///////////////////////////
533
534 Filter::Filter(const Filter &f) :
535   Owner(f.Owner), StartBit(f.StartBit), NumBits(f.NumBits), Mixed(f.Mixed),
536   FilteredInstructions(f.FilteredInstructions),
537   VariableInstructions(f.VariableInstructions),
538   FilterChooserMap(f.FilterChooserMap), NumFiltered(f.NumFiltered),
539   LastOpcFiltered(f.LastOpcFiltered), NumVariable(f.NumVariable) {
540 }
541
542 Filter::Filter(FilterChooser &owner, unsigned startBit, unsigned numBits,
543     bool mixed) : Owner(&owner), StartBit(startBit), NumBits(numBits),
544                   Mixed(mixed) {
545   assert(StartBit + NumBits - 1 < BIT_WIDTH);
546
547   NumFiltered = 0;
548   LastOpcFiltered = 0;
549   NumVariable = 0;
550
551   for (unsigned i = 0, e = Owner->Opcodes.size(); i != e; ++i) {
552     insn_t Insn;
553
554     // Populates the insn given the uid.
555     Owner->insnWithID(Insn, Owner->Opcodes[i]);
556
557     uint64_t Field;
558     // Scans the segment for possibly well-specified encoding bits.
559     bool ok = Owner->fieldFromInsn(Field, Insn, StartBit, NumBits);
560
561     if (ok) {
562       // The encoding bits are well-known.  Lets add the uid of the
563       // instruction into the bucket keyed off the constant field value.
564       LastOpcFiltered = Owner->Opcodes[i];
565       FilteredInstructions[Field].push_back(LastOpcFiltered);
566       ++NumFiltered;
567     } else {
568       // Some of the encoding bit(s) are unspecfied.  This contributes to
569       // one additional member of "Variable" instructions.
570       VariableInstructions.push_back(Owner->Opcodes[i]);
571       ++NumVariable;
572     }
573   }
574
575   assert((FilteredInstructions.size() + VariableInstructions.size() > 0)
576          && "Filter returns no instruction categories");
577 }
578
579 Filter::~Filter() {
580   std::map<unsigned, FilterChooser*>::iterator filterIterator;
581   for (filterIterator = FilterChooserMap.begin();
582        filterIterator != FilterChooserMap.end();
583        filterIterator++) {
584     delete filterIterator->second;
585   }
586 }
587
588 // Divides the decoding task into sub tasks and delegates them to the
589 // inferior FilterChooser's.
590 //
591 // A special case arises when there's only one entry in the filtered
592 // instructions.  In order to unambiguously decode the singleton, we need to
593 // match the remaining undecoded encoding bits against the singleton.
594 void Filter::recurse() {
595   std::map<uint64_t, std::vector<unsigned> >::const_iterator mapIterator;
596
597   bit_value_t BitValueArray[BIT_WIDTH];
598   // Starts by inheriting our parent filter chooser's filter bit values.
599   memcpy(BitValueArray, Owner->FilterBitValues, sizeof(BitValueArray));
600
601   unsigned bitIndex;
602
603   if (VariableInstructions.size()) {
604     // Conservatively marks each segment position as BIT_UNSET.
605     for (bitIndex = 0; bitIndex < NumBits; bitIndex++)
606       BitValueArray[StartBit + bitIndex] = BIT_UNSET;
607
608     // Delegates to an inferior filter chooser for futher processing on this
609     // group of instructions whose segment values are variable.
610     FilterChooserMap.insert(std::pair<unsigned, FilterChooser*>(
611                               (unsigned)-1,
612                               new FilterChooser(Owner->AllInstructions,
613                                                 VariableInstructions,
614                                                 BitValueArray,
615                                                 *Owner)
616                               ));
617   }
618
619   // No need to recurse for a singleton filtered instruction.
620   // See also Filter::emit().
621   if (getNumFiltered() == 1) {
622     //Owner->SingletonExists(LastOpcFiltered);
623     assert(FilterChooserMap.size() == 1);
624     return;
625   }
626         
627   // Otherwise, create sub choosers.
628   for (mapIterator = FilteredInstructions.begin();
629        mapIterator != FilteredInstructions.end();
630        mapIterator++) {
631
632     // Marks all the segment positions with either BIT_TRUE or BIT_FALSE.
633     for (bitIndex = 0; bitIndex < NumBits; bitIndex++) {
634       if (mapIterator->first & (1 << bitIndex))
635         BitValueArray[StartBit + bitIndex] = BIT_TRUE;
636       else
637         BitValueArray[StartBit + bitIndex] = BIT_FALSE;
638     }
639
640     // Delegates to an inferior filter chooser for futher processing on this
641     // category of instructions.
642     FilterChooserMap.insert(std::pair<unsigned, FilterChooser*>(
643                               mapIterator->first,
644                               new FilterChooser(Owner->AllInstructions,
645                                                 mapIterator->second,
646                                                 BitValueArray,
647                                                 *Owner)
648                               ));
649   }
650 }
651
652 // Emit code to decode instructions given a segment or segments of bits.
653 void Filter::emit(raw_ostream &o, unsigned &Indentation) {
654   o.indent(Indentation) << "// Check Inst{";
655
656   if (NumBits > 1)
657     o << (StartBit + NumBits - 1) << '-';
658
659   o << StartBit << "} ...\n";
660
661   o.indent(Indentation) << "switch (fieldFromInstruction(insn, "
662                         << StartBit << ", " << NumBits << ")) {\n";
663
664   std::map<unsigned, FilterChooser*>::iterator filterIterator;
665
666   bool DefaultCase = false;
667   for (filterIterator = FilterChooserMap.begin();
668        filterIterator != FilterChooserMap.end();
669        filterIterator++) {
670
671     // Field value -1 implies a non-empty set of variable instructions.
672     // See also recurse().
673     if (filterIterator->first == (unsigned)-1) {
674       DefaultCase = true;
675
676       o.indent(Indentation) << "default:\n";
677       o.indent(Indentation) << "  break; // fallthrough\n";
678
679       // Closing curly brace for the switch statement.
680       // This is unconventional because we want the default processing to be
681       // performed for the fallthrough cases as well, i.e., when the "cases"
682       // did not prove a decoded instruction.
683       o.indent(Indentation) << "}\n";
684
685     } else
686       o.indent(Indentation) << "case " << filterIterator->first << ":\n";
687
688     // We arrive at a category of instructions with the same segment value.
689     // Now delegate to the sub filter chooser for further decodings.
690     // The case may fallthrough, which happens if the remaining well-known
691     // encoding bits do not match exactly.
692     if (!DefaultCase) { ++Indentation; ++Indentation; }
693
694     bool finished = filterIterator->second->emit(o, Indentation);
695     // For top level default case, there's no need for a break statement.
696     if (Owner->isTopLevel() && DefaultCase)
697       break;
698     if (!finished)
699       o.indent(Indentation) << "break;\n";
700
701     if (!DefaultCase) { --Indentation; --Indentation; }
702   }
703
704   // If there is no default case, we still need to supply a closing brace.
705   if (!DefaultCase) {
706     // Closing curly brace for the switch statement.
707     o.indent(Indentation) << "}\n";
708   }
709 }
710
711 // Returns the number of fanout produced by the filter.  More fanout implies
712 // the filter distinguishes more categories of instructions.
713 unsigned Filter::usefulness() const {
714   if (VariableInstructions.size())
715     return FilteredInstructions.size();
716   else
717     return FilteredInstructions.size() + 1;
718 }
719
720 //////////////////////////////////
721 //                              //
722 // Filterchooser Implementation //
723 //                              //
724 //////////////////////////////////
725
726 // Define the symbol here.
727 TARGET_NAME_t FilterChooser::TargetName;
728
729 // This provides an opportunity for target specific code emission.
730 void FilterChooser::emitTopHook(raw_ostream &o) {
731   if (TargetName == TARGET_ARM) {
732     // Emit code that references the ARMFormat data type.
733     o << "static const ARMFormat ARMFormats[] = {\n";
734     for (unsigned i = 0, e = AllInstructions.size(); i != e; ++i) {
735       const Record &Def = *(AllInstructions[i]->TheDef);
736       const std::string &Name = Def.getName();
737       if (Def.isSubClassOf("InstARM") || Def.isSubClassOf("InstThumb"))
738         o.indent(2) << 
739           stringForARMFormat((ARMFormat)getByteField(Def, "Form"));
740       else
741         o << "  ARM_FORMAT_NA";
742
743       o << ",\t// Inst #" << i << " = " << Name << '\n';
744     }
745     o << "  ARM_FORMAT_NA\t// Unreachable.\n";
746     o << "};\n\n";
747   }
748 }
749
750 // Emit the top level typedef and decodeInstruction() function.
751 void FilterChooser::emitTop(raw_ostream &o, unsigned &Indentation) {
752   // Run the target specific emit hook.
753   emitTopHook(o);
754
755   switch (BIT_WIDTH) {
756   case 8:
757     o.indent(Indentation) << "typedef uint8_t field_t;\n";
758     break;
759   case 16:
760     o.indent(Indentation) << "typedef uint16_t field_t;\n";
761     break;
762   case 32:
763     o.indent(Indentation) << "typedef uint32_t field_t;\n";
764     break;
765   case 64:
766     o.indent(Indentation) << "typedef uint64_t field_t;\n";
767     break;
768   default:
769     assert(0 && "Unexpected instruction size!");
770   }
771
772   o << '\n';
773
774   o.indent(Indentation) << "static field_t " <<
775     "fieldFromInstruction(field_t insn, unsigned startBit, unsigned numBits)\n";
776
777   o.indent(Indentation) << "{\n";
778
779   ++Indentation; ++Indentation;
780   o.indent(Indentation) << "assert(startBit + numBits <= " << BIT_WIDTH
781                         << " && \"Instruction field out of bounds!\");\n";
782   o << '\n';
783   o.indent(Indentation) << "field_t fieldMask;\n";
784   o << '\n';
785   o.indent(Indentation) << "if (numBits == " << BIT_WIDTH << ")\n";
786
787   ++Indentation; ++Indentation;
788   o.indent(Indentation) << "fieldMask = (field_t)-1;\n";
789   --Indentation; --Indentation;
790
791   o.indent(Indentation) << "else\n";
792
793   ++Indentation; ++Indentation;
794   o.indent(Indentation) << "fieldMask = ((1 << numBits) - 1) << startBit;\n";
795   --Indentation; --Indentation;
796
797   o << '\n';
798   o.indent(Indentation) << "return (insn & fieldMask) >> startBit;\n";
799   --Indentation; --Indentation;
800
801   o.indent(Indentation) << "}\n";
802
803   o << '\n';
804
805   o.indent(Indentation) << "static uint16_t decodeInstruction(field_t insn) {\n";
806
807   ++Indentation; ++Indentation;
808   // Emits code to decode the instructions.
809   emit(o, Indentation);
810
811   o << '\n';
812   o.indent(Indentation) << "return 0;\n";
813   --Indentation; --Indentation;
814
815   o.indent(Indentation) << "}\n";
816
817   o << '\n';
818 }
819
820 // This provides an opportunity for target specific code emission after
821 // emitTop().
822 void FilterChooser::emitBot(raw_ostream &o, unsigned &Indentation) {
823   if (TargetName != TARGET_THUMB) return;
824
825   // Emit code that decodes the Thumb ISA.
826   o.indent(Indentation)
827     << "static uint16_t decodeThumbInstruction(field_t insn) {\n";
828
829   ++Indentation; ++Indentation;
830
831   // Emits code to decode the instructions.
832   emit(o, Indentation);
833
834   o << '\n';
835   o.indent(Indentation) << "return 0;\n";
836
837   --Indentation; --Indentation;
838
839   o.indent(Indentation) << "}\n";
840 }
841
842 // Populates the field of the insn given the start position and the number of
843 // consecutive bits to scan for.
844 //
845 // Returns false if and on the first uninitialized bit value encountered.
846 // Returns true, otherwise.
847 bool FilterChooser::fieldFromInsn(uint64_t &Field, insn_t &Insn,
848     unsigned StartBit, unsigned NumBits) const {
849   Field = 0;
850
851   for (unsigned i = 0; i < NumBits; ++i) {
852     if (Insn[StartBit + i] == BIT_UNSET)
853       return false;
854
855     if (Insn[StartBit + i] == BIT_TRUE)
856       Field = Field | (1 << i);
857   }
858
859   return true;
860 }
861
862 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
863 /// filter array as a series of chars.
864 void FilterChooser::dumpFilterArray(raw_ostream &o,
865     bit_value_t (&filter)[BIT_WIDTH]) {
866   unsigned bitIndex;
867
868   for (bitIndex = BIT_WIDTH; bitIndex > 0; bitIndex--) {
869     switch (filter[bitIndex - 1]) {
870     case BIT_UNFILTERED:
871       o << ".";
872       break;
873     case BIT_UNSET:
874       o << "_";
875       break;
876     case BIT_TRUE:
877       o << "1";
878       break;
879     case BIT_FALSE:
880       o << "0";
881       break;
882     }
883   }
884 }
885
886 /// dumpStack - dumpStack traverses the filter chooser chain and calls
887 /// dumpFilterArray on each filter chooser up to the top level one.
888 void FilterChooser::dumpStack(raw_ostream &o, const char *prefix) {
889   FilterChooser *current = this;
890
891   while (current) {
892     o << prefix;
893     dumpFilterArray(o, current->FilterBitValues);
894     o << '\n';
895     current = current->Parent;
896   }
897 }
898
899 // Called from Filter::recurse() when singleton exists.  For debug purpose.
900 void FilterChooser::SingletonExists(unsigned Opc) {
901   insn_t Insn0;
902   insnWithID(Insn0, Opc);
903
904   errs() << "Singleton exists: " << nameWithID(Opc)
905          << " with its decoding dominating ";
906   for (unsigned i = 0; i < Opcodes.size(); ++i) {
907     if (Opcodes[i] == Opc) continue;
908     errs() << nameWithID(Opcodes[i]) << ' ';
909   }
910   errs() << '\n';
911
912   dumpStack(errs(), "\t\t");
913   for (unsigned i = 0; i < Opcodes.size(); i++) {
914     const std::string &Name = nameWithID(Opcodes[i]);
915
916     errs() << '\t' << Name << " ";
917     dumpBits(errs(),
918              getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
919     errs() << '\n';
920   }
921 }
922
923 // Calculates the island(s) needed to decode the instruction.
924 // This returns a list of undecoded bits of an instructions, for example,
925 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
926 // decoded bits in order to verify that the instruction matches the Opcode.
927 unsigned FilterChooser::getIslands(std::vector<unsigned> &StartBits,
928     std::vector<unsigned> &EndBits, std::vector<uint64_t> &FieldVals,
929     insn_t &Insn) {
930   unsigned Num, BitNo;
931   Num = BitNo = 0;
932
933   uint64_t FieldVal = 0;
934
935   // 0: Init
936   // 1: Water (the bit value does not affect decoding)
937   // 2: Island (well-known bit value needed for decoding)
938   int State = 0;
939   int Val = -1;
940
941   for (unsigned i = 0; i < BIT_WIDTH; ++i) {
942     Val = Value(Insn[i]);
943     bool Filtered = PositionFiltered(i);
944     switch (State) {
945     default:
946       assert(0 && "Unreachable code!");
947       break;
948     case 0:
949     case 1:
950       if (Filtered || Val == -1)
951         State = 1; // Still in Water
952       else {
953         State = 2; // Into the Island
954         BitNo = 0;
955         StartBits.push_back(i);
956         FieldVal = Val;
957       }
958       break;
959     case 2:
960       if (Filtered || Val == -1) {
961         State = 1; // Into the Water
962         EndBits.push_back(i - 1);
963         FieldVals.push_back(FieldVal);
964         ++Num;
965       } else {
966         State = 2; // Still in Island
967         ++BitNo;
968         FieldVal = FieldVal | Val << BitNo;
969       }
970       break;
971     }
972   }
973   // If we are still in Island after the loop, do some housekeeping.
974   if (State == 2) {
975     EndBits.push_back(BIT_WIDTH - 1);
976     FieldVals.push_back(FieldVal);
977     ++Num;
978   }
979
980   assert(StartBits.size() == Num && EndBits.size() == Num &&
981          FieldVals.size() == Num);
982   return Num;
983 }
984
985 // Emits code to decode the singleton.  Return true if we have matched all the
986 // well-known bits.
987 bool FilterChooser::emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,
988                                          unsigned Opc) {
989   std::vector<unsigned> StartBits;
990   std::vector<unsigned> EndBits;
991   std::vector<uint64_t> FieldVals;
992   insn_t Insn;
993   insnWithID(Insn, Opc);
994
995   // This provides a good opportunity to check for possible Ld/St Coprocessor
996   // Opcode and escapes if the coproc # is either 10 or 11.  It is a NEON/VFP
997   // instruction is disguise.
998   if (TargetName == TARGET_ARM && LdStCopEncoding1(Opc)) {
999     o.indent(Indentation);
1000     // A8.6.51 & A8.6.188
1001     // If coproc = 0b101?, i.e, slice(insn, 11, 8) = 10 or 11, escape.
1002     o << "if (fieldFromInstruction(insn, 9, 3) == 5) break; // fallthrough\n";
1003   }
1004
1005   // Look for islands of undecoded bits of the singleton.
1006   getIslands(StartBits, EndBits, FieldVals, Insn);
1007
1008   unsigned Size = StartBits.size();
1009   unsigned I, NumBits;
1010
1011   // If we have matched all the well-known bits, just issue a return.
1012   if (Size == 0) {
1013     o.indent(Indentation) << "return " << Opc << "; // " << nameWithID(Opc)
1014                           << '\n';
1015     return true;
1016   }
1017
1018   // Otherwise, there are more decodings to be done!
1019
1020   // Emit code to match the island(s) for the singleton.
1021   o.indent(Indentation) << "// Check ";
1022
1023   for (I = Size; I != 0; --I) {
1024     o << "Inst{" << EndBits[I-1] << '-' << StartBits[I-1] << "} ";
1025     if (I > 1)
1026       o << "&& ";
1027     else
1028       o << "for singleton decoding...\n";
1029   }
1030
1031   o.indent(Indentation) << "if (";
1032
1033   for (I = Size; I != 0; --I) {
1034     NumBits = EndBits[I-1] - StartBits[I-1] + 1;
1035     o << "fieldFromInstruction(insn, " << StartBits[I-1] << ", " << NumBits
1036       << ") == " << FieldVals[I-1];
1037     if (I > 1)
1038       o << " && ";
1039     else
1040       o << ")\n";
1041   }
1042
1043   o.indent(Indentation) << "  return " << Opc << "; // " << nameWithID(Opc)
1044                         << '\n';
1045
1046   return false;
1047 }
1048
1049 // Emits code to decode the singleton, and then to decode the rest.
1050 void FilterChooser::emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,
1051     Filter &Best) {
1052
1053   unsigned Opc = Best.getSingletonOpc();
1054
1055   emitSingletonDecoder(o, Indentation, Opc);
1056
1057   // Emit code for the rest.
1058   o.indent(Indentation) << "else\n";
1059
1060   Indentation += 2;
1061   Best.getVariableFC().emit(o, Indentation);
1062   Indentation -= 2;
1063 }
1064
1065 // Assign a single filter and run with it.  Top level API client can initialize
1066 // with a single filter to start the filtering process.
1067 void FilterChooser::runSingleFilter(FilterChooser &owner, unsigned startBit,
1068     unsigned numBit, bool mixed) {
1069   Filters.clear();
1070   Filter F(*this, startBit, numBit, true);
1071   Filters.push_back(F);
1072   BestIndex = 0; // Sole Filter instance to choose from.
1073   bestFilter().recurse();
1074 }
1075
1076 // reportRegion is a helper function for filterProcessor to mark a region as
1077 // eligible for use as a filter region.
1078 void FilterChooser::reportRegion(bitAttr_t RA, unsigned StartBit,
1079     unsigned BitIndex, bool AllowMixed) {
1080   if (RA == ATTR_MIXED && AllowMixed)
1081     Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, true));   
1082   else if (RA == ATTR_ALL_SET && !AllowMixed)
1083     Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, false));
1084 }
1085
1086 // FilterProcessor scans the well-known encoding bits of the instructions and
1087 // builds up a list of candidate filters.  It chooses the best filter and
1088 // recursively descends down the decoding tree.
1089 bool FilterChooser::filterProcessor(bool AllowMixed, bool Greedy) {
1090   Filters.clear();
1091   BestIndex = -1;
1092   unsigned numInstructions = Opcodes.size();
1093
1094   assert(numInstructions && "Filter created with no instructions");
1095
1096   // No further filtering is necessary.
1097   if (numInstructions == 1)
1098     return true;
1099
1100   // Heuristics.  See also doFilter()'s "Heuristics" comment when num of
1101   // instructions is 3.
1102   if (AllowMixed && !Greedy) {
1103     assert(numInstructions == 3);
1104
1105     for (unsigned i = 0; i < Opcodes.size(); ++i) {
1106       std::vector<unsigned> StartBits;
1107       std::vector<unsigned> EndBits;
1108       std::vector<uint64_t> FieldVals;
1109       insn_t Insn;
1110
1111       insnWithID(Insn, Opcodes[i]);
1112
1113       // Look for islands of undecoded bits of any instruction.
1114       if (getIslands(StartBits, EndBits, FieldVals, Insn) > 0) {
1115         // Found an instruction with island(s).  Now just assign a filter.
1116         runSingleFilter(*this, StartBits[0], EndBits[0] - StartBits[0] + 1,
1117                         true);
1118         return true;
1119       }
1120     }
1121   }
1122
1123   unsigned BitIndex, InsnIndex;
1124
1125   // We maintain BIT_WIDTH copies of the bitAttrs automaton.
1126   // The automaton consumes the corresponding bit from each
1127   // instruction.
1128   //
1129   //   Input symbols: 0, 1, and _ (unset).
1130   //   States:        NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED.
1131   //   Initial state: NONE.
1132   //
1133   // (NONE) ------- [01] -> (ALL_SET)
1134   // (NONE) ------- _ ----> (ALL_UNSET)
1135   // (ALL_SET) ---- [01] -> (ALL_SET)
1136   // (ALL_SET) ---- _ ----> (MIXED)
1137   // (ALL_UNSET) -- [01] -> (MIXED)
1138   // (ALL_UNSET) -- _ ----> (ALL_UNSET)
1139   // (MIXED) ------ . ----> (MIXED)
1140   // (FILTERED)---- . ----> (FILTERED)
1141
1142   bitAttr_t bitAttrs[BIT_WIDTH];
1143
1144   // FILTERED bit positions provide no entropy and are not worthy of pursuing.
1145   // Filter::recurse() set either BIT_TRUE or BIT_FALSE for each position.
1146   for (BitIndex = 0; BitIndex < BIT_WIDTH; ++BitIndex)
1147     if (FilterBitValues[BitIndex] == BIT_TRUE ||
1148         FilterBitValues[BitIndex] == BIT_FALSE)
1149       bitAttrs[BitIndex] = ATTR_FILTERED;
1150     else
1151       bitAttrs[BitIndex] = ATTR_NONE;
1152
1153   for (InsnIndex = 0; InsnIndex < numInstructions; ++InsnIndex) {
1154     insn_t insn;
1155
1156     insnWithID(insn, Opcodes[InsnIndex]);
1157
1158     for (BitIndex = 0; BitIndex < BIT_WIDTH; ++BitIndex) {
1159       switch (bitAttrs[BitIndex]) {
1160       case ATTR_NONE:
1161         if (insn[BitIndex] == BIT_UNSET)
1162           bitAttrs[BitIndex] = ATTR_ALL_UNSET;
1163         else
1164           bitAttrs[BitIndex] = ATTR_ALL_SET;
1165         break;
1166       case ATTR_ALL_SET:
1167         if (insn[BitIndex] == BIT_UNSET)
1168           bitAttrs[BitIndex] = ATTR_MIXED;
1169         break;
1170       case ATTR_ALL_UNSET:
1171         if (insn[BitIndex] != BIT_UNSET)
1172           bitAttrs[BitIndex] = ATTR_MIXED;
1173         break;
1174       case ATTR_MIXED:
1175       case ATTR_FILTERED:
1176         break;
1177       }
1178     }
1179   }
1180
1181   // The regionAttr automaton consumes the bitAttrs automatons' state,
1182   // lowest-to-highest.
1183   //
1184   //   Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed)
1185   //   States:        NONE, ALL_SET, MIXED
1186   //   Initial state: NONE
1187   //
1188   // (NONE) ----- F --> (NONE)
1189   // (NONE) ----- S --> (ALL_SET)     ; and set region start
1190   // (NONE) ----- U --> (NONE)
1191   // (NONE) ----- M --> (MIXED)       ; and set region start
1192   // (ALL_SET) -- F --> (NONE)        ; and report an ALL_SET region
1193   // (ALL_SET) -- S --> (ALL_SET)
1194   // (ALL_SET) -- U --> (NONE)        ; and report an ALL_SET region
1195   // (ALL_SET) -- M --> (MIXED)       ; and report an ALL_SET region
1196   // (MIXED) ---- F --> (NONE)        ; and report a MIXED region
1197   // (MIXED) ---- S --> (ALL_SET)     ; and report a MIXED region
1198   // (MIXED) ---- U --> (NONE)        ; and report a MIXED region
1199   // (MIXED) ---- M --> (MIXED)
1200
1201   bitAttr_t RA = ATTR_NONE;
1202   unsigned StartBit = 0;
1203
1204   for (BitIndex = 0; BitIndex < BIT_WIDTH; BitIndex++) {
1205     bitAttr_t bitAttr = bitAttrs[BitIndex];
1206
1207     assert(bitAttr != ATTR_NONE && "Bit without attributes");
1208
1209     switch (RA) {
1210     case ATTR_NONE:
1211       switch (bitAttr) {
1212       case ATTR_FILTERED:
1213         break;
1214       case ATTR_ALL_SET:
1215         StartBit = BitIndex;
1216         RA = ATTR_ALL_SET;
1217         break;
1218       case ATTR_ALL_UNSET:
1219         break;
1220       case ATTR_MIXED:
1221         StartBit = BitIndex;
1222         RA = ATTR_MIXED;
1223         break;
1224       default:
1225         assert(0 && "Unexpected bitAttr!");
1226       }
1227       break;
1228     case ATTR_ALL_SET:
1229       switch (bitAttr) {
1230       case ATTR_FILTERED:
1231         reportRegion(RA, StartBit, BitIndex, AllowMixed);
1232         RA = ATTR_NONE;
1233         break;
1234       case ATTR_ALL_SET:
1235         break;
1236       case ATTR_ALL_UNSET:
1237         reportRegion(RA, StartBit, BitIndex, AllowMixed);
1238         RA = ATTR_NONE;
1239         break;
1240       case ATTR_MIXED:
1241         reportRegion(RA, StartBit, BitIndex, AllowMixed);
1242         StartBit = BitIndex;
1243         RA = ATTR_MIXED;
1244         break;
1245       default:
1246         assert(0 && "Unexpected bitAttr!");
1247       }
1248       break;
1249     case ATTR_MIXED:
1250       switch (bitAttr) {
1251       case ATTR_FILTERED:
1252         reportRegion(RA, StartBit, BitIndex, AllowMixed);
1253         StartBit = BitIndex;
1254         RA = ATTR_NONE;
1255         break;
1256       case ATTR_ALL_SET:
1257         reportRegion(RA, StartBit, BitIndex, AllowMixed);
1258         StartBit = BitIndex;
1259         RA = ATTR_ALL_SET;
1260         break;
1261       case ATTR_ALL_UNSET:
1262         reportRegion(RA, StartBit, BitIndex, AllowMixed);
1263         RA = ATTR_NONE;
1264         break;
1265       case ATTR_MIXED:
1266         break;
1267       default:
1268         assert(0 && "Unexpected bitAttr!");
1269       }
1270       break;
1271     case ATTR_ALL_UNSET:
1272       assert(0 && "regionAttr state machine has no ATTR_UNSET state");
1273     case ATTR_FILTERED:
1274       assert(0 && "regionAttr state machine has no ATTR_FILTERED state");
1275     }
1276   }
1277
1278   // At the end, if we're still in ALL_SET or MIXED states, report a region
1279   switch (RA) {
1280   case ATTR_NONE:
1281     break;
1282   case ATTR_FILTERED:
1283     break;
1284   case ATTR_ALL_SET:
1285     reportRegion(RA, StartBit, BitIndex, AllowMixed);
1286     break;
1287   case ATTR_ALL_UNSET:
1288     break;
1289   case ATTR_MIXED:
1290     reportRegion(RA, StartBit, BitIndex, AllowMixed);
1291     break;
1292   }
1293
1294   // We have finished with the filter processings.  Now it's time to choose
1295   // the best performing filter.
1296   BestIndex = 0;
1297   bool AllUseless = true;
1298   unsigned BestScore = 0;
1299
1300   for (unsigned i = 0, e = Filters.size(); i != e; ++i) {
1301     unsigned Usefulness = Filters[i].usefulness();
1302
1303     if (Usefulness)
1304       AllUseless = false;
1305
1306     if (Usefulness > BestScore) {
1307       BestIndex = i;
1308       BestScore = Usefulness;
1309     }
1310   }
1311
1312   if (!AllUseless)
1313     bestFilter().recurse();
1314
1315   return !AllUseless;
1316 } // end of FilterChooser::filterProcessor(bool)
1317
1318 // Decides on the best configuration of filter(s) to use in order to decode
1319 // the instructions.  A conflict of instructions may occur, in which case we
1320 // dump the conflict set to the standard error.
1321 void FilterChooser::doFilter() {
1322   unsigned Num = Opcodes.size();
1323   assert(Num && "FilterChooser created with no instructions");
1324
1325   // Heuristics: Use Inst{31-28} as the top level filter for ARM ISA.
1326   if (TargetName == TARGET_ARM && Parent == NULL) {
1327     runSingleFilter(*this, 28, 4, false);
1328     return;
1329   }
1330
1331   // Try regions of consecutive known bit values first. 
1332   if (filterProcessor(false))
1333     return;
1334
1335   // Then regions of mixed bits (both known and unitialized bit values allowed).
1336   if (filterProcessor(true))
1337     return;
1338
1339   // Heuristics to cope with conflict set {t2CMPrs, t2SUBSrr, t2SUBSrs} where
1340   // no single instruction for the maximum ATTR_MIXED region Inst{14-4} has a
1341   // well-known encoding pattern.  In such case, we backtrack and scan for the
1342   // the very first consecutive ATTR_ALL_SET region and assign a filter to it.
1343   if (Num == 3 && filterProcessor(true, false))
1344     return;
1345
1346   // If we come to here, the instruction decoding has failed.
1347   // Print out the instructions in the conflict set...
1348   BestIndex = -1;
1349
1350   DEBUG({
1351       errs() << "Conflict:\n";
1352
1353       dumpStack(errs(), "\t\t");
1354
1355       for (unsigned i = 0; i < Num; i++) {
1356         const std::string &Name = nameWithID(Opcodes[i]);
1357
1358         errs() << '\t' << Name << " ";
1359         dumpBits(errs(),
1360                  getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
1361         errs() << '\n';
1362       }
1363     });
1364 }
1365
1366 // Emits code to decode our share of instructions.  Returns true if the
1367 // emitted code causes a return, which occurs if we know how to decode
1368 // the instruction at this level or the instruction is not decodeable.
1369 bool FilterChooser::emit(raw_ostream &o, unsigned &Indentation) {
1370   if (Opcodes.size() == 1)
1371     // There is only one instruction in the set, which is great!
1372     // Call emitSingletonDecoder() to see whether there are any remaining
1373     // encodings bits.
1374     return emitSingletonDecoder(o, Indentation, Opcodes[0]);
1375
1376   // Choose the best filter to do the decodings!
1377   if (BestIndex != -1) {
1378     Filter &Best = bestFilter();
1379     if (Best.getNumFiltered() == 1)
1380       emitSingletonDecoder(o, Indentation, Best);
1381     else
1382       bestFilter().emit(o, Indentation);
1383     return false;
1384   }
1385
1386   // If we reach here, there is a conflict in decoding.  Let's resolve the known
1387   // conflicts!
1388   if ((TargetName == TARGET_ARM || TargetName == TARGET_THUMB) &&
1389       Opcodes.size() == 2) {
1390     // Resolve the known conflict sets:
1391     //
1392     // 1. source registers are identical => VMOVDneon; otherwise => VORRd
1393     // 2. source registers are identical => VMOVQ; otherwise => VORRq
1394     // 3. LDR, LDRcp => return LDR for now.
1395     // FIXME: How can we distinguish between LDR and LDRcp?  Do we need to?
1396     // 4. tLDM, tLDM_UPD => Rn = Inst{10-8}, reglist = Inst{7-0},
1397     //    wback = registers<Rn> = 0
1398     // NOTE: (tLDM, tLDM_UPD) resolution must come before Advanced SIMD
1399     //       addressing mode resolution!!!
1400     // 5. VLD[234]LN*/VST[234]LN* vs. VLD[234]LN*_UPD/VST[234]LN*_UPD conflicts
1401     //    are resolved returning the non-UPD versions of the instructions if the
1402     //    Rm field, i.e., Inst{3-0} is 0b1111.  This is specified in A7.7.1
1403     //    Advanced SIMD addressing mode.
1404     const std::string &name1 = nameWithID(Opcodes[0]);
1405     const std::string &name2 = nameWithID(Opcodes[1]);
1406     if ((name1 == "VMOVDneon" && name2 == "VORRd") ||
1407         (name1 == "VMOVQ" && name2 == "VORRq")) {
1408       // Inserting the opening curly brace for this case block.
1409       --Indentation; --Indentation;
1410       o.indent(Indentation) << "{\n";
1411       ++Indentation; ++Indentation;
1412
1413       o.indent(Indentation)
1414         << "field_t N = fieldFromInstruction(insn, 7, 1), "
1415         << "M = fieldFromInstruction(insn, 5, 1);\n";
1416       o.indent(Indentation)
1417         << "field_t Vn = fieldFromInstruction(insn, 16, 4), "
1418         << "Vm = fieldFromInstruction(insn, 0, 4);\n";
1419       o.indent(Indentation)
1420         << "return (N == M && Vn == Vm) ? "
1421         << Opcodes[0] << " /* " << name1 << " */ : "
1422         << Opcodes[1] << " /* " << name2 << " */ ;\n";
1423
1424       // Inserting the closing curly brace for this case block.
1425       --Indentation; --Indentation;
1426       o.indent(Indentation) << "}\n";
1427       ++Indentation; ++Indentation;
1428
1429       return true;
1430     }
1431     if (name1 == "LDR" && name2 == "LDRcp") {
1432       o.indent(Indentation)
1433         << "return " << Opcodes[0]
1434         << "; // Returning LDR for {LDR, LDRcp}\n";
1435       return true;
1436     }
1437     if (name1 == "tLDM" && name2 == "tLDM_UPD") {
1438       // Inserting the opening curly brace for this case block.
1439       --Indentation; --Indentation;
1440       o.indent(Indentation) << "{\n";
1441       ++Indentation; ++Indentation;
1442       
1443       o.indent(Indentation)
1444         << "unsigned Rn = fieldFromInstruction(insn, 8, 3), "
1445         << "list = fieldFromInstruction(insn, 0, 8);\n";
1446       o.indent(Indentation)
1447         << "return ((list >> Rn) & 1) == 0 ? "
1448         << Opcodes[1] << " /* " << name2 << " */ : "
1449         << Opcodes[0] << " /* " << name1 << " */ ;\n";
1450
1451       // Inserting the closing curly brace for this case block.
1452       --Indentation; --Indentation;
1453       o.indent(Indentation) << "}\n";
1454       ++Indentation; ++Indentation;
1455
1456       return true;
1457     }
1458     if (sameStringExceptSuffix(name1, name2, "_UPD")) {
1459       o.indent(Indentation)
1460         << "return fieldFromInstruction(insn, 0, 4) == 15 ? " << Opcodes[0]
1461         << " /* " << name1 << " */ : " << Opcodes[1] << "/* " << name2
1462         << " */ ; // Advanced SIMD addressing mode\n";
1463       return true;
1464     }
1465
1466     // Otherwise, it does not belong to the known conflict sets.
1467   }
1468   // We don't know how to decode these instructions!  Dump the conflict set!
1469   o.indent(Indentation) << "return 0;" << " // Conflict set: ";
1470   for (int i = 0, N = Opcodes.size(); i < N; ++i) {
1471     o << nameWithID(Opcodes[i]);
1472     if (i < (N - 1))
1473       o << ", ";
1474     else
1475       o << '\n';
1476   }
1477   return true;
1478 }
1479
1480
1481 ////////////////////////////////////////////
1482 //                                        //
1483 //  ARMDEBackend                          //
1484 //  (Helper class for ARMDecoderEmitter)  //
1485 //                                        //
1486 ////////////////////////////////////////////
1487
1488 class ARMDecoderEmitter::ARMDEBackend {
1489 public:
1490   ARMDEBackend(ARMDecoderEmitter &frontend) :
1491     NumberedInstructions(),
1492     Opcodes(),
1493     Frontend(frontend),
1494     Target(),
1495     FC(NULL)
1496   {
1497     if (Target.getName() == "ARM")
1498       TargetName = TARGET_ARM;
1499     else {
1500       errs() << "Target name " << Target.getName() << " not recognized\n";
1501       assert(0 && "Unknown target");
1502     }
1503
1504     // Populate the instructions for our TargetName.
1505     populateInstructions();
1506   }
1507
1508   ~ARMDEBackend() {
1509     if (FC) {
1510       delete FC;
1511       FC = NULL;
1512     }
1513   }
1514
1515   void getInstructionsByEnumValue(std::vector<const CodeGenInstruction*>
1516                                                 &NumberedInstructions) {
1517     // We must emit the PHI opcode first...
1518     std::string Namespace = Target.getInstNamespace();
1519     assert(!Namespace.empty() && "No instructions defined.");
1520
1521     NumberedInstructions = Target.getInstructionsByEnumValue();
1522   }
1523
1524   bool populateInstruction(const CodeGenInstruction &CGI, TARGET_NAME_t TN);
1525
1526   void populateInstructions();
1527
1528   // Emits disassembler code for instruction decoding.  This delegates to the
1529   // FilterChooser instance to do the heavy lifting.
1530   void emit(raw_ostream &o);
1531
1532 protected:
1533   std::vector<const CodeGenInstruction*> NumberedInstructions;
1534   std::vector<unsigned> Opcodes;
1535   // Special case for the ARM chip, which supports ARM and Thumb ISAs.
1536   // Opcodes2 will be populated with the Thumb opcodes.
1537   std::vector<unsigned> Opcodes2;
1538   ARMDecoderEmitter &Frontend;
1539   CodeGenTarget Target;
1540   FilterChooser *FC;
1541
1542   TARGET_NAME_t TargetName;
1543 };
1544
1545 bool ARMDecoderEmitter::ARMDEBackend::populateInstruction(
1546     const CodeGenInstruction &CGI, TARGET_NAME_t TN) {
1547   const Record &Def = *CGI.TheDef;
1548   const StringRef Name = Def.getName();
1549   uint8_t Form = getByteField(Def, "Form");
1550   BitsInit &Bits = getBitsField(Def, "Inst");
1551
1552   if (TN == TARGET_ARM) {
1553     // FIXME: what about Int_MemBarrierV6 and Int_SyncBarrierV6?
1554     if ((Name != "Int_MemBarrierV7" && Name != "Int_SyncBarrierV7") &&
1555         Form == ARM_FORMAT_PSEUDO)
1556       return false;
1557     if (thumbInstruction(Form))
1558       return false;
1559     if (Name.find("CMPz") != std::string::npos /* ||
1560         Name.find("CMNz") != std::string::npos */)
1561       return false;
1562
1563     // Ignore pseudo instructions.
1564     if (Name == "BXr9" || Name == "BMOVPCRX" || Name == "BMOVPCRXr9")
1565       return false;
1566
1567     // VLDMQ/VSTMQ can be hanlded with the more generic VLDMD/VSTMD.
1568     if (Name == "VLDMQ" || Name == "VLDMQ_UPD" ||
1569         Name == "VSTMQ" || Name == "VSTMQ_UPD")
1570       return false;
1571
1572     //
1573     // The following special cases are for conflict resolutions.
1574     //
1575
1576     // NEON NLdStFrm conflict resolutions:
1577     //
1578     // 1. Ignore suffix "odd" and "odd_UPD", prefer the "even" register-
1579     //    numbered ones which have the same Asm format string.
1580     // 2. Ignore VST2d64_UPD, which conflicts with VST1q64_UPD.
1581     // 3. Ignore VLD2d64_UPD, which conflicts with VLD1q64_UPD.
1582     // 4. Ignore VLD1q[_UPD], which conflicts with VLD1q64[_UPD].
1583     // 5. Ignore VST1q[_UPD], which conflicts with VST1q64[_UPD].
1584     if (Name.endswith("odd") || Name.endswith("odd_UPD") ||
1585         Name == "VST2d64_UPD" || Name == "VLD2d64_UPD" ||
1586         Name == "VLD1q" || Name == "VLD1q_UPD" ||
1587         Name == "VST1q" || Name == "VST1q_UPD")
1588       return false;
1589
1590     // RSCSri and RSCSrs set the 's' bit, but are not predicated.  We are
1591     // better off using the generic RSCri and RSCrs instructions.
1592     if (Name == "RSCSri" || Name == "RSCSrs") return false;
1593
1594     // MOVCCr, MOVCCs, MOVCCi, FCYPScc, FCYPDcc, FNEGScc, and FNEGDcc are used
1595     // in the compiler to implement conditional moves.  We can ignore them in
1596     // favor of their more generic versions of instructions.
1597     // See also SDNode *ARMDAGToDAGISel::Select(SDValue Op).
1598     if (Name == "MOVCCr" || Name == "MOVCCs" || Name == "MOVCCi" ||
1599         Name == "FCPYScc" || Name == "FCPYDcc" ||
1600         Name == "FNEGScc" || Name == "FNEGDcc")
1601       return false;
1602
1603     // Ditto for VMOVDcc, VMOVScc, VNEGDcc, and VNEGScc.
1604     if (Name == "VMOVDcc" || Name == "VMOVScc" || Name == "VNEGDcc" ||
1605         Name == "VNEGScc")
1606       return false;
1607
1608     // Ignore the *_sfp instructions when decoding.  They are used by the
1609     // compiler to implement scalar floating point operations using vector
1610     // operations in order to work around some performance issues.
1611     if (Name.find("_sfp") != std::string::npos) return false;
1612
1613     // LDM_RET is a special case of LDM (Load Multiple) where the registers
1614     // loaded include the PC, causing a branch to a loaded address.  Ignore
1615     // the LDM_RET instruction when decoding.
1616     if (Name == "LDM_RET") return false;
1617
1618     // Bcc is in a more generic form than B.  Ignore B when decoding.
1619     if (Name == "B") return false;
1620
1621     // Ignore the non-Darwin BL instructions and the TPsoft (TLS) instruction.
1622     if (Name == "BL" || Name == "BL_pred" || Name == "BLX" || Name == "BX" ||
1623         Name == "TPsoft")
1624       return false;
1625
1626     // Ignore VDUPf[d|q] instructions known to conflict with VDUP32[d-q] for
1627     // decoding.  The instruction duplicates an element from an ARM core
1628     // register into every element of the destination vector.  There is no
1629     // distinction between data types.
1630     if (Name == "VDUPfd" || Name == "VDUPfq") return false;
1631
1632     // A8-598: VEXT
1633     // Vector Extract extracts elements from the bottom end of the second
1634     // operand vector and the top end of the first, concatenates them and
1635     // places the result in the destination vector.  The elements of the
1636     // vectors are treated as being 8-bit bitfields.  There is no distinction
1637     // between data types.  The size of the operation can be specified in
1638     // assembler as vext.size.  If the value is 16, 32, or 64, the syntax is
1639     // a pseudo-instruction for a VEXT instruction specifying the equivalent
1640     // number of bytes.
1641     //
1642     // Variants VEXTd16, VEXTd32, VEXTd8, and VEXTdf are reduced to VEXTd8;
1643     // variants VEXTq16, VEXTq32, VEXTq8, and VEXTqf are reduced to VEXTq8.
1644     if (Name == "VEXTd16" || Name == "VEXTd32" || Name == "VEXTdf" ||
1645         Name == "VEXTq16" || Name == "VEXTq32" || Name == "VEXTqf")
1646       return false;
1647
1648     // Vector Reverse is similar to Vector Extract.  There is no distinction
1649     // between data types, other than size.
1650     //
1651     // VREV64df is equivalent to VREV64d32.
1652     // VREV64qf is equivalent to VREV64q32.
1653     if (Name == "VREV64df" || Name == "VREV64qf") return false;
1654
1655     // VDUPLNfd is equivalent to VDUPLN32d; VDUPfdf is specialized VDUPLN32d.
1656     // VDUPLNfq is equivalent to VDUPLN32q; VDUPfqf is specialized VDUPLN32q.
1657     // VLD1df is equivalent to VLD1d32.
1658     // VLD1qf is equivalent to VLD1q32.
1659     // VLD2d64 is equivalent to VLD1q64.
1660     // VST1df is equivalent to VST1d32.
1661     // VST1qf is equivalent to VST1q32.
1662     // VST2d64 is equivalent to VST1q64.
1663     if (Name == "VDUPLNfd" || Name == "VDUPfdf" ||
1664         Name == "VDUPLNfq" || Name == "VDUPfqf" ||
1665         Name == "VLD1df" || Name == "VLD1qf" || Name == "VLD2d64" ||
1666         Name == "VST1df" || Name == "VST1qf" || Name == "VST2d64")
1667       return false;
1668   } else if (TN == TARGET_THUMB) {
1669     if (!thumbInstruction(Form))
1670       return false;
1671
1672     // Ignore pseudo instructions.
1673     if (Name == "tInt_eh_sjlj_setjmp" || Name == "t2Int_eh_sjlj_setjmp" ||
1674         Name == "t2MOVi32imm" || Name == "tBX" || Name == "tBXr9")
1675       return false;
1676
1677     // On Darwin R9 is call-clobbered.  Ignore the non-Darwin counterparts.
1678     if (Name == "tBL" || Name == "tBLXi" || Name == "tBLXr")
1679       return false;
1680
1681     // Ignore the TPsoft (TLS) instructions, which conflict with tBLr9.
1682     if (Name == "tTPsoft" || Name == "t2TPsoft")
1683       return false;
1684
1685     // Ignore tLEApcrel and tLEApcrelJT, prefer tADDrPCi.
1686     if (Name == "tLEApcrel" || Name == "tLEApcrelJT")
1687       return false;
1688
1689     // Ignore t2LEApcrel, prefer the generic t2ADD* for disassembly printing.
1690     if (Name == "t2LEApcrel")
1691       return false;
1692
1693     // Ignore tADDrSP, tADDspr, and tPICADD, prefer the generic tADDhirr.
1694     // Ignore t2SUBrSPs, prefer the t2SUB[S]r[r|s].
1695     // Ignore t2ADDrSPs, prefer the t2ADD[S]r[r|s].
1696     if (Name == "tADDrSP" || Name == "tADDspr" || Name == "tPICADD" ||
1697         Name == "t2SUBrSPs" || Name == "t2ADDrSPs")
1698       return false;
1699
1700     // Ignore t2LDRDpci, prefer the generic t2LDRDi8, t2LDRD_PRE, t2LDRD_POST.
1701     if (Name == "t2LDRDpci")
1702       return false;
1703
1704     // Ignore t2TBB, t2TBH and prefer the generic t2TBBgen, t2TBHgen.
1705     if (Name == "t2TBB" || Name == "t2TBH")
1706       return false;
1707
1708     // Resolve conflicts:
1709     //
1710     //   tBfar conflicts with tBLr9
1711     //   tCMNz conflicts with tCMN (with assembly format strings being equal)
1712     //   tPOP_RET/t2LDM_RET conflict with tPOP/t2LDM (ditto)
1713     //   tMOVCCi conflicts with tMOVi8
1714     //   tMOVCCr conflicts with tMOVgpr2gpr
1715     //   tBR_JTr conflicts with tBRIND
1716     //   tSpill conflicts with tSTRspi
1717     //   tLDRcp conflicts with tLDRspi
1718     //   tRestore conflicts with tLDRspi
1719     //   t2LEApcrelJT conflicts with t2LEApcrel
1720     //   t2ADDrSPi/t2SUBrSPi have more generic couterparts
1721     if (Name == "tBfar" ||
1722         /* Name == "tCMNz" || */ Name == "tCMPzi8" || Name == "tCMPzr" ||
1723         Name == "tCMPzhir" || /* Name == "t2CMNzrr" || Name == "t2CMNzrs" ||
1724         Name == "t2CMNzri" || */ Name == "t2CMPzrr" || Name == "t2CMPzrs" ||
1725         Name == "t2CMPzri" || Name == "tPOP_RET" || Name == "t2LDM_RET" ||
1726         Name == "tMOVCCi" || Name == "tMOVCCr" || Name == "tBR_JTr" ||
1727         Name == "tSpill" || Name == "tLDRcp" || Name == "tRestore" ||
1728         Name == "t2LEApcrelJT" || Name == "t2ADDrSPi" || Name == "t2SUBrSPi")
1729       return false;
1730   }
1731
1732   // Dumps the instruction encoding format.
1733   switch (TargetName) {
1734   case TARGET_ARM:
1735   case TARGET_THUMB:
1736     DEBUG(errs() << Name << " " << stringForARMFormat((ARMFormat)Form));
1737     break;
1738   }
1739
1740   DEBUG({
1741       errs() << " ";
1742
1743       // Dumps the instruction encoding bits.
1744       dumpBits(errs(), Bits);
1745
1746       errs() << '\n';
1747
1748       // Dumps the list of operand info.
1749       for (unsigned i = 0, e = CGI.OperandList.size(); i != e; ++i) {
1750         CodeGenInstruction::OperandInfo Info = CGI.OperandList[i];
1751         const std::string &OperandName = Info.Name;
1752         const Record &OperandDef = *Info.Rec;
1753
1754         errs() << "\t" << OperandName << " (" << OperandDef.getName() << ")\n";
1755       }
1756     });
1757
1758   return true;
1759 }
1760
1761 void ARMDecoderEmitter::ARMDEBackend::populateInstructions() {
1762   getInstructionsByEnumValue(NumberedInstructions);
1763
1764   uint16_t numUIDs = NumberedInstructions.size();
1765   uint16_t uid;
1766
1767   const char *instClass = NULL;
1768
1769   switch (TargetName) {
1770   case TARGET_ARM:
1771     instClass = "InstARM";
1772     break;
1773   default:
1774     assert(0 && "Unreachable code!");
1775   }
1776
1777   for (uid = 0; uid < numUIDs; uid++) {
1778     // filter out intrinsics
1779     if (!NumberedInstructions[uid]->TheDef->isSubClassOf(instClass))
1780       continue;
1781
1782     if (populateInstruction(*NumberedInstructions[uid], TargetName))
1783       Opcodes.push_back(uid);
1784   }
1785
1786   // Special handling for the ARM chip, which supports two modes of execution.
1787   // This branch handles the Thumb opcodes.
1788   if (TargetName == TARGET_ARM) {
1789     for (uid = 0; uid < numUIDs; uid++) {
1790       // filter out intrinsics
1791       if (!NumberedInstructions[uid]->TheDef->isSubClassOf("InstARM")
1792           && !NumberedInstructions[uid]->TheDef->isSubClassOf("InstThumb"))
1793         continue;
1794
1795       if (populateInstruction(*NumberedInstructions[uid], TARGET_THUMB))
1796         Opcodes2.push_back(uid);
1797     }
1798   }
1799 }
1800
1801 // Emits disassembler code for instruction decoding.  This delegates to the
1802 // FilterChooser instance to do the heavy lifting.
1803 void ARMDecoderEmitter::ARMDEBackend::emit(raw_ostream &o) {
1804   switch (TargetName) {
1805   case TARGET_ARM:
1806     Frontend.EmitSourceFileHeader("ARM/Thumb Decoders", o);
1807     break;
1808   default:
1809     assert(0 && "Unreachable code!");
1810   }
1811
1812   o << "#include \"llvm/System/DataTypes.h\"\n";
1813   o << "#include <assert.h>\n";
1814   o << '\n';
1815   o << "namespace llvm {\n\n";
1816
1817   FilterChooser::setTargetName(TargetName);
1818
1819   switch (TargetName) {
1820   case TARGET_ARM: {
1821     // Emit common utility and ARM ISA decoder.
1822     FC = new FilterChooser(NumberedInstructions, Opcodes);
1823     // Reset indentation level.
1824     unsigned Indentation = 0;
1825     FC->emitTop(o, Indentation);
1826     delete FC;
1827
1828     // Emit Thumb ISA decoder as well.
1829     FilterChooser::setTargetName(TARGET_THUMB);
1830     FC = new FilterChooser(NumberedInstructions, Opcodes2);
1831     // Reset indentation level.
1832     Indentation = 0;
1833     FC->emitBot(o, Indentation);
1834     break;
1835   }
1836   default:
1837     assert(0 && "Unreachable code!");
1838   }
1839
1840   o << "\n} // End llvm namespace \n";
1841 }
1842
1843 /////////////////////////
1844 //  Backend interface  //
1845 /////////////////////////
1846
1847 void ARMDecoderEmitter::initBackend()
1848 {
1849     Backend = new ARMDEBackend(*this);
1850 }
1851
1852 void ARMDecoderEmitter::run(raw_ostream &o)
1853 {
1854   Backend->emit(o);
1855 }
1856
1857 void ARMDecoderEmitter::shutdownBackend()
1858 {
1859   delete Backend;
1860   Backend = NULL;
1861 }