1 //===------------ FixedLenDecoderEmitter.cpp - Decoder Generator ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // It contains the tablegen backend that emits the decoder functions for
11 // targets with fixed length instruction set.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "decoder-emitter"
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"
31 // The set (BIT_TRUE, BIT_FALSE, BIT_UNSET) represents a ternary logic system
34 // BIT_UNFILTERED is used as the init value for a filter position. It is used
35 // only for filter processings.
40 BIT_UNFILTERED // unfiltered
43 static bool ValueSet(bit_value_t V) {
44 return (V == BIT_TRUE || V == BIT_FALSE);
46 static bool ValueNotSet(bit_value_t V) {
47 return (V == BIT_UNSET);
49 static int Value(bit_value_t V) {
50 return ValueNotSet(V) ? -1 : (V == BIT_FALSE ? 0 : 1);
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;
56 // The bit is uninitialized.
59 // Prints the bit value for each position.
60 static void dumpBits(raw_ostream &o, BitsInit &bits) {
63 for (index = bits.getNumBits(); index > 0; index--) {
64 switch (bitFromBits(bits, index - 1)) {
75 llvm_unreachable("unexpected return value from bitFromBits");
80 static BitsInit &getBitsField(const Record &def, const char *str) {
81 BitsInit *bits = def.getValueAsBitsInit(str);
85 // Forward declaration.
88 // Representation of the instruction to work on.
89 typedef std::vector<bit_value_t> insn_t;
91 /// Filter - Filter works with FilterChooser to produce the decoding tree for
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.
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.
105 /// An example of a conflict is
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____
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.
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.
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
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;
137 // Set of uid's with non-constant segment values.
138 std::vector<unsigned> VariableInstructions;
140 // Map of well-known segment value to its delegate.
141 std::map<unsigned, FilterChooser*> FilterChooserMap;
143 // Number of instructions which fall under FilteredInstructions category.
144 unsigned NumFiltered;
146 // Keeps track of the last opcode in the filtered bucket.
147 unsigned LastOpcFiltered;
150 unsigned getNumFiltered() { return NumFiltered; }
151 unsigned getSingletonOpc() {
152 assert(NumFiltered == 1);
153 return LastOpcFiltered;
155 // Return the filter chooser for the group of instructions without constant
157 FilterChooser &getVariableFC() {
158 assert(NumFiltered == 1);
159 assert(FilterChooserMap.size() == 1);
160 return *(FilterChooserMap.find((unsigned)-1)->second);
163 Filter(const Filter &f);
164 Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, bool mixed);
168 // Divides the decoding task into sub tasks and delegates them to the
169 // inferior FilterChooser's.
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.
176 // Emit code to decode instructions given a segment or segments of bits.
177 void emit(raw_ostream &o, unsigned &Indentation);
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
184 // These are states of our finite state machines used in FilterChooser's
185 // filterProcessor() which produces the filter candidates to use.
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.
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.
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
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 {
213 // Vector of codegen instructions to choose our filter.
214 const std::vector<const CodeGenInstruction*> &AllInstructions;
216 // Vector of uid's for this filter chooser to work on.
217 const std::vector<unsigned> Opcodes;
219 // Lookup table for the operand decoding of instructions.
220 std::map<unsigned, std::vector<OperandInfo> > &Operands;
222 // Vector of candidate filters.
223 std::vector<Filter> Filters;
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;
229 // Links to the FilterChooser above us in the decoding tree.
230 FilterChooser *Parent;
232 // Index of the best filter from Filters.
235 // Width of instructions
239 const FixedLenDecoderEmitter *Emitter;
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) { }
249 FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
250 const std::vector<unsigned> &IDs,
251 std::map<unsigned, std::vector<OperandInfo> > &Ops,
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);
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) {
274 // The top level filter chooser has NULL as its parent.
275 bool isTopLevel() { return Parent == NULL; }
277 // Emit the top level typedef and decodeInstruction() function.
278 void emitTop(raw_ostream &o, unsigned Indentation, std::string Namespace);
281 // Populates the insn given the uid.
282 void insnWithID(insn_t &Insn, unsigned Opcode) const {
283 BitsInit &Bits = getBitsField(*AllInstructions[Opcode]->TheDef, "Inst");
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.
289 // This is used for marking UNPREDICTABLE instructions in the ARM world.
291 AllInstructions[Opcode]->TheDef->getValueAsBitsInit("SoftFail");
293 for (unsigned i = 0; i < BitWidth; ++i) {
294 if (SFBits && bitFromBits(*SFBits, i) == BIT_TRUE)
295 Insn.push_back(BIT_UNSET);
297 Insn.push_back(bitFromBits(Bits, i));
301 // Returns the record name.
302 const std::string &nameWithID(unsigned Opcode) const {
303 return AllInstructions[Opcode]->TheDef->getName();
306 // Populates the field of the insn given the start position and the number of
307 // consecutive bits to scan for.
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;
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);
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);
322 Filter &bestFilter() {
323 assert(BestIndex != -1 && "BestIndex not set");
324 return Filters[BestIndex];
327 // Called from Filter::recurse() when singleton exists. For debug purpose.
328 void SingletonExists(unsigned Opc);
330 bool PositionFiltered(unsigned i) {
331 return ValueSet(FilterBitValues[i]);
334 // Calculates the island(s) needed to decode the instruction.
335 // This returns a lit of undecoded bits of an instructions, for example,
336 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
337 // decoded bits in order to verify that the instruction matches the Opcode.
338 unsigned getIslands(std::vector<unsigned> &StartBits,
339 std::vector<unsigned> &EndBits, std::vector<uint64_t> &FieldVals,
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);
346 void emitSoftFailCheck(raw_ostream &o, unsigned Indentation, unsigned Opc);
348 // Emits code to decode the singleton. Return true if we have matched all the
350 bool emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,unsigned Opc);
352 // Emits code to decode the singleton, and then to decode the rest.
353 void emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,Filter &Best);
355 void emitBinaryParser(raw_ostream &o , unsigned &Indentation,
356 OperandInfo &OpInfo);
358 // Assign a single filter and run with it.
359 void runSingleFilter(FilterChooser &owner, unsigned startBit, unsigned numBit,
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,
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);
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.
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);
383 ///////////////////////////
385 // Filter Implementation //
387 ///////////////////////////
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) {
397 Filter::Filter(FilterChooser &owner, unsigned startBit, unsigned numBits,
398 bool mixed) : Owner(&owner), StartBit(startBit), NumBits(numBits),
400 assert(StartBit + NumBits - 1 < Owner->BitWidth);
405 for (unsigned i = 0, e = Owner->Opcodes.size(); i != e; ++i) {
408 // Populates the insn given the uid.
409 Owner->insnWithID(Insn, Owner->Opcodes[i]);
412 // Scans the segment for possibly well-specified encoding bits.
413 bool ok = Owner->fieldFromInsn(Field, Insn, StartBit, NumBits);
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);
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]);
428 assert((FilteredInstructions.size() + VariableInstructions.size() > 0)
429 && "Filter returns no instruction categories");
433 std::map<unsigned, FilterChooser*>::iterator filterIterator;
434 for (filterIterator = FilterChooserMap.begin();
435 filterIterator != FilterChooserMap.end();
437 delete filterIterator->second;
441 // Divides the decoding task into sub tasks and delegates them to the
442 // inferior FilterChooser's.
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;
450 // Starts by inheriting our parent filter chooser's filter bit values.
451 std::vector<bit_value_t> BitValueArray(Owner->FilterBitValues);
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;
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*>(
464 new FilterChooser(Owner->AllInstructions,
465 VariableInstructions,
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);
480 // Otherwise, create sub choosers.
481 for (mapIterator = FilteredInstructions.begin();
482 mapIterator != FilteredInstructions.end();
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;
490 BitValueArray[StartBit + bitIndex] = BIT_FALSE;
493 // Delegates to an inferior filter chooser for further processing on this
494 // category of instructions.
495 FilterChooserMap.insert(std::pair<unsigned, FilterChooser*>(
497 new FilterChooser(Owner->AllInstructions,
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{";
511 o << (StartBit + NumBits - 1) << '-';
513 o << StartBit << "} ...\n";
515 o.indent(Indentation) << "switch (fieldFromInstruction" << Owner->BitWidth
516 << "(insn, " << StartBit << ", "
517 << NumBits << ")) {\n";
519 std::map<unsigned, FilterChooser*>::iterator filterIterator;
521 bool DefaultCase = false;
522 for (filterIterator = FilterChooserMap.begin();
523 filterIterator != FilterChooserMap.end();
526 // Field value -1 implies a non-empty set of variable instructions.
527 // See also recurse().
528 if (filterIterator->first == (unsigned)-1) {
531 o.indent(Indentation) << "default:\n";
532 o.indent(Indentation) << " break; // fallthrough\n";
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";
541 o.indent(Indentation) << "case " << filterIterator->first << ":\n";
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; }
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)
554 o.indent(Indentation) << "break;\n";
556 if (!DefaultCase) { --Indentation; --Indentation; }
559 // If there is no default case, we still need to supply a closing brace.
561 // Closing curly brace for the switch statement.
562 o.indent(Indentation) << "}\n";
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();
572 return FilteredInstructions.size() + 1;
575 //////////////////////////////////
577 // Filterchooser Implementation //
579 //////////////////////////////////
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";
595 ++Indentation; ++Indentation;
596 // Emits code to decode the instructions.
597 emit(o, Indentation);
600 o.indent(Indentation) << "return " << Emitter->ReturnFail << ";\n";
601 --Indentation; --Indentation;
603 o.indent(Indentation) << "}\n";
608 // Populates the field of the insn given the start position and the number of
609 // consecutive bits to scan for.
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 {
617 for (unsigned i = 0; i < NumBits; ++i) {
618 if (Insn[StartBit + i] == BIT_UNSET)
621 if (Insn[StartBit + i] == BIT_TRUE)
622 Field = Field | (1ULL << i);
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) {
634 for (bitIndex = BitWidth; bitIndex > 0; bitIndex--) {
635 switch (filter[bitIndex - 1]) {
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;
659 dumpFilterArray(o, current->FilterBitValues);
661 current = current->Parent;
665 // Called from Filter::recurse() when singleton exists. For debug purpose.
666 void FilterChooser::SingletonExists(unsigned Opc) {
668 insnWithID(Insn0, Opc);
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]) << ' ';
678 dumpStack(errs(), "\t\t");
679 for (unsigned i = 0; i < Opcodes.size(); i++) {
680 const std::string &Name = nameWithID(Opcodes[i]);
682 errs() << '\t' << Name << " ";
684 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
689 // Calculates the island(s) needed to decode the instruction.
690 // This returns a list of undecoded bits of an instructions, for example,
691 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
692 // decoded bits in order to verify that the instruction matches the Opcode.
693 unsigned FilterChooser::getIslands(std::vector<unsigned> &StartBits,
694 std::vector<unsigned> &EndBits, std::vector<uint64_t> &FieldVals,
699 uint64_t FieldVal = 0;
702 // 1: Water (the bit value does not affect decoding)
703 // 2: Island (well-known bit value needed for decoding)
707 for (unsigned i = 0; i < BitWidth; ++i) {
708 Val = Value(Insn[i]);
709 bool Filtered = PositionFiltered(i);
711 default: llvm_unreachable("Unreachable code!");
714 if (Filtered || Val == -1)
715 State = 1; // Still in Water
717 State = 2; // Into the Island
719 StartBits.push_back(i);
724 if (Filtered || Val == -1) {
725 State = 1; // Into the Water
726 EndBits.push_back(i - 1);
727 FieldVals.push_back(FieldVal);
730 State = 2; // Still in Island
732 FieldVal = FieldVal | Val << BitNo;
737 // If we are still in Island after the loop, do some housekeeping.
739 EndBits.push_back(BitWidth - 1);
740 FieldVals.push_back(FieldVal);
744 assert(StartBits.size() == Num && EndBits.size() == Num &&
745 FieldVals.size() == Num);
749 void FilterChooser::emitBinaryParser(raw_ostream &o, unsigned &Indentation,
750 OperandInfo &OpInfo) {
751 std::string &Decoder = OpInfo.Decoder;
753 if (OpInfo.numFields() == 1) {
754 OperandInfo::iterator OI = OpInfo.begin();
755 o.indent(Indentation) << " tmp = fieldFromInstruction" << BitWidth
756 << "(insn, " << OI->Base << ", " << OI->Width
759 o.indent(Indentation) << " tmp = 0;\n";
760 for (OperandInfo::iterator OI = OpInfo.begin(), OE = OpInfo.end();
762 o.indent(Indentation) << " tmp |= (fieldFromInstruction" << BitWidth
763 << "(insn, " << OI->Base << ", " << OI->Width
764 << ") << " << OI->Offset << ");\n";
769 o.indent(Indentation) << " " << Emitter->GuardPrefix << Decoder
770 << "(MI, tmp, Address, Decoder)"
771 << Emitter->GuardPostfix << "\n";
773 o.indent(Indentation) << " MI.addOperand(MCOperand::CreateImm(tmp));\n";
777 static void emitSinglePredicateMatch(raw_ostream &o, StringRef str,
778 std::string PredicateNamespace) {
780 o << "!(Bits & " << PredicateNamespace << "::"
781 << str.slice(1,str.size()) << ")";
783 o << "(Bits & " << PredicateNamespace << "::" << str << ")";
786 bool FilterChooser::emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
788 ListInit *Predicates =
789 AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
790 for (unsigned i = 0; i < Predicates->getSize(); ++i) {
791 Record *Pred = Predicates->getElementAsRecord(i);
792 if (!Pred->getValue("AssemblerMatcherPredicate"))
795 std::string P = Pred->getValueAsString("AssemblerCondString");
804 std::pair<StringRef, StringRef> pairs = SR.split(',');
805 while (pairs.second.size()) {
806 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
808 pairs = pairs.second.split(',');
810 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
812 return Predicates->getSize() > 0;
815 void FilterChooser::emitSoftFailCheck(raw_ostream &o, unsigned Indentation,
818 AllInstructions[Opc]->TheDef->getValueAsBitsInit("SoftFail");
820 BitsInit *InstBits = AllInstructions[Opc]->TheDef->getValueAsBitsInit("Inst");
822 APInt PositiveMask(BitWidth, 0ULL);
823 APInt NegativeMask(BitWidth, 0ULL);
824 for (unsigned i = 0; i < BitWidth; ++i) {
825 bit_value_t B = bitFromBits(*SFBits, i);
826 bit_value_t IB = bitFromBits(*InstBits, i);
828 if (B != BIT_TRUE) continue;
832 // The bit is meant to be false, so emit a check to see if it is true.
833 PositiveMask.setBit(i);
836 // The bit is meant to be true, so emit a check to see if it is false.
837 NegativeMask.setBit(i);
840 // The bit is not set; this must be an error!
841 StringRef Name = AllInstructions[Opc]->TheDef->getName();
842 errs() << "SoftFail Conflict: bit SoftFail{" << i << "} in "
844 << " is set but Inst{" << i <<"} is unset!\n"
845 << " - You can only mark a bit as SoftFail if it is fully defined"
846 << " (1/0 - not '?') in Inst\n";
847 o << "#error SoftFail Conflict, " << Name << "::SoftFail{" << i
848 << "} set but Inst{" << i << "} undefined!\n";
852 bool NeedPositiveMask = PositiveMask.getBoolValue();
853 bool NeedNegativeMask = NegativeMask.getBoolValue();
855 if (!NeedPositiveMask && !NeedNegativeMask)
858 std::string PositiveMaskStr = PositiveMask.toString(16, /*signed=*/false);
859 std::string NegativeMaskStr = NegativeMask.toString(16, /*signed=*/false);
860 StringRef BitExt = "";
864 o.indent(Indentation) << "if (";
865 if (NeedPositiveMask)
866 o << "insn & 0x" << PositiveMaskStr << BitExt;
867 if (NeedPositiveMask && NeedNegativeMask)
869 if (NeedNegativeMask)
870 o << "~insn & 0x" << NegativeMaskStr << BitExt;
872 o.indent(Indentation+2) << "S = MCDisassembler::SoftFail;\n";
875 // Emits code to decode the singleton. Return true if we have matched all the
877 bool FilterChooser::emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,
879 std::vector<unsigned> StartBits;
880 std::vector<unsigned> EndBits;
881 std::vector<uint64_t> FieldVals;
883 insnWithID(Insn, Opc);
885 // Look for islands of undecoded bits of the singleton.
886 getIslands(StartBits, EndBits, FieldVals, Insn);
888 unsigned Size = StartBits.size();
891 // If we have matched all the well-known bits, just issue a return.
893 o.indent(Indentation) << "if (";
894 if (!emitPredicateMatch(o, Indentation, Opc))
897 emitSoftFailCheck(o, Indentation+2, Opc);
898 o.indent(Indentation) << " MI.setOpcode(" << Opc << ");\n";
899 std::vector<OperandInfo>& InsnOperands = Operands[Opc];
900 for (std::vector<OperandInfo>::iterator
901 I = InsnOperands.begin(), E = InsnOperands.end(); I != E; ++I) {
902 // If a custom instruction decoder was specified, use that.
903 if (I->numFields() == 0 && I->Decoder.size()) {
904 o.indent(Indentation) << " " << Emitter->GuardPrefix << I->Decoder
905 << "(MI, insn, Address, Decoder)"
906 << Emitter->GuardPostfix << "\n";
910 emitBinaryParser(o, Indentation, *I);
913 o.indent(Indentation) << " return " << Emitter->ReturnOK << "; // "
914 << nameWithID(Opc) << '\n';
915 o.indent(Indentation) << "}\n"; // Closing predicate block.
919 // Otherwise, there are more decodings to be done!
921 // Emit code to match the island(s) for the singleton.
922 o.indent(Indentation) << "// Check ";
924 for (I = Size; I != 0; --I) {
925 o << "Inst{" << EndBits[I-1] << '-' << StartBits[I-1] << "} ";
929 o << "for singleton decoding...\n";
932 o.indent(Indentation) << "if (";
933 if (emitPredicateMatch(o, Indentation, Opc)) {
935 o.indent(Indentation+4);
938 for (I = Size; I != 0; --I) {
939 NumBits = EndBits[I-1] - StartBits[I-1] + 1;
940 o << "fieldFromInstruction" << BitWidth << "(insn, "
941 << StartBits[I-1] << ", " << NumBits
942 << ") == " << FieldVals[I-1];
948 emitSoftFailCheck(o, Indentation+2, Opc);
949 o.indent(Indentation) << " MI.setOpcode(" << Opc << ");\n";
950 std::vector<OperandInfo>& InsnOperands = Operands[Opc];
951 for (std::vector<OperandInfo>::iterator
952 I = InsnOperands.begin(), E = InsnOperands.end(); I != E; ++I) {
953 // If a custom instruction decoder was specified, use that.
954 if (I->numFields() == 0 && I->Decoder.size()) {
955 o.indent(Indentation) << " " << Emitter->GuardPrefix << I->Decoder
956 << "(MI, insn, Address, Decoder)"
957 << Emitter->GuardPostfix << "\n";
961 emitBinaryParser(o, Indentation, *I);
963 o.indent(Indentation) << " return " << Emitter->ReturnOK << "; // "
964 << nameWithID(Opc) << '\n';
965 o.indent(Indentation) << "}\n";
970 // Emits code to decode the singleton, and then to decode the rest.
971 void FilterChooser::emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,
974 unsigned Opc = Best.getSingletonOpc();
976 emitSingletonDecoder(o, Indentation, Opc);
978 // Emit code for the rest.
979 o.indent(Indentation) << "else\n";
982 Best.getVariableFC().emit(o, Indentation);
986 // Assign a single filter and run with it. Top level API client can initialize
987 // with a single filter to start the filtering process.
988 void FilterChooser::runSingleFilter(FilterChooser &owner, unsigned startBit,
989 unsigned numBit, bool mixed) {
991 Filter F(*this, startBit, numBit, true);
992 Filters.push_back(F);
993 BestIndex = 0; // Sole Filter instance to choose from.
994 bestFilter().recurse();
997 // reportRegion is a helper function for filterProcessor to mark a region as
998 // eligible for use as a filter region.
999 void FilterChooser::reportRegion(bitAttr_t RA, unsigned StartBit,
1000 unsigned BitIndex, bool AllowMixed) {
1001 if (RA == ATTR_MIXED && AllowMixed)
1002 Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, true));
1003 else if (RA == ATTR_ALL_SET && !AllowMixed)
1004 Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, false));
1007 // FilterProcessor scans the well-known encoding bits of the instructions and
1008 // builds up a list of candidate filters. It chooses the best filter and
1009 // recursively descends down the decoding tree.
1010 bool FilterChooser::filterProcessor(bool AllowMixed, bool Greedy) {
1013 unsigned numInstructions = Opcodes.size();
1015 assert(numInstructions && "Filter created with no instructions");
1017 // No further filtering is necessary.
1018 if (numInstructions == 1)
1021 // Heuristics. See also doFilter()'s "Heuristics" comment when num of
1022 // instructions is 3.
1023 if (AllowMixed && !Greedy) {
1024 assert(numInstructions == 3);
1026 for (unsigned i = 0; i < Opcodes.size(); ++i) {
1027 std::vector<unsigned> StartBits;
1028 std::vector<unsigned> EndBits;
1029 std::vector<uint64_t> FieldVals;
1032 insnWithID(Insn, Opcodes[i]);
1034 // Look for islands of undecoded bits of any instruction.
1035 if (getIslands(StartBits, EndBits, FieldVals, Insn) > 0) {
1036 // Found an instruction with island(s). Now just assign a filter.
1037 runSingleFilter(*this, StartBits[0], EndBits[0] - StartBits[0] + 1,
1044 unsigned BitIndex, InsnIndex;
1046 // We maintain BIT_WIDTH copies of the bitAttrs automaton.
1047 // The automaton consumes the corresponding bit from each
1050 // Input symbols: 0, 1, and _ (unset).
1051 // States: NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED.
1052 // Initial state: NONE.
1054 // (NONE) ------- [01] -> (ALL_SET)
1055 // (NONE) ------- _ ----> (ALL_UNSET)
1056 // (ALL_SET) ---- [01] -> (ALL_SET)
1057 // (ALL_SET) ---- _ ----> (MIXED)
1058 // (ALL_UNSET) -- [01] -> (MIXED)
1059 // (ALL_UNSET) -- _ ----> (ALL_UNSET)
1060 // (MIXED) ------ . ----> (MIXED)
1061 // (FILTERED)---- . ----> (FILTERED)
1063 std::vector<bitAttr_t> bitAttrs;
1065 // FILTERED bit positions provide no entropy and are not worthy of pursuing.
1066 // Filter::recurse() set either BIT_TRUE or BIT_FALSE for each position.
1067 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex)
1068 if (FilterBitValues[BitIndex] == BIT_TRUE ||
1069 FilterBitValues[BitIndex] == BIT_FALSE)
1070 bitAttrs.push_back(ATTR_FILTERED);
1072 bitAttrs.push_back(ATTR_NONE);
1074 for (InsnIndex = 0; InsnIndex < numInstructions; ++InsnIndex) {
1077 insnWithID(insn, Opcodes[InsnIndex]);
1079 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
1080 switch (bitAttrs[BitIndex]) {
1082 if (insn[BitIndex] == BIT_UNSET)
1083 bitAttrs[BitIndex] = ATTR_ALL_UNSET;
1085 bitAttrs[BitIndex] = ATTR_ALL_SET;
1088 if (insn[BitIndex] == BIT_UNSET)
1089 bitAttrs[BitIndex] = ATTR_MIXED;
1091 case ATTR_ALL_UNSET:
1092 if (insn[BitIndex] != BIT_UNSET)
1093 bitAttrs[BitIndex] = ATTR_MIXED;
1102 // The regionAttr automaton consumes the bitAttrs automatons' state,
1103 // lowest-to-highest.
1105 // Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed)
1106 // States: NONE, ALL_SET, MIXED
1107 // Initial state: NONE
1109 // (NONE) ----- F --> (NONE)
1110 // (NONE) ----- S --> (ALL_SET) ; and set region start
1111 // (NONE) ----- U --> (NONE)
1112 // (NONE) ----- M --> (MIXED) ; and set region start
1113 // (ALL_SET) -- F --> (NONE) ; and report an ALL_SET region
1114 // (ALL_SET) -- S --> (ALL_SET)
1115 // (ALL_SET) -- U --> (NONE) ; and report an ALL_SET region
1116 // (ALL_SET) -- M --> (MIXED) ; and report an ALL_SET region
1117 // (MIXED) ---- F --> (NONE) ; and report a MIXED region
1118 // (MIXED) ---- S --> (ALL_SET) ; and report a MIXED region
1119 // (MIXED) ---- U --> (NONE) ; and report a MIXED region
1120 // (MIXED) ---- M --> (MIXED)
1122 bitAttr_t RA = ATTR_NONE;
1123 unsigned StartBit = 0;
1125 for (BitIndex = 0; BitIndex < BitWidth; BitIndex++) {
1126 bitAttr_t bitAttr = bitAttrs[BitIndex];
1128 assert(bitAttr != ATTR_NONE && "Bit without attributes");
1136 StartBit = BitIndex;
1139 case ATTR_ALL_UNSET:
1142 StartBit = BitIndex;
1146 llvm_unreachable("Unexpected bitAttr!");
1152 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1157 case ATTR_ALL_UNSET:
1158 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1162 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1163 StartBit = BitIndex;
1167 llvm_unreachable("Unexpected bitAttr!");
1173 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1174 StartBit = BitIndex;
1178 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1179 StartBit = BitIndex;
1182 case ATTR_ALL_UNSET:
1183 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1189 llvm_unreachable("Unexpected bitAttr!");
1192 case ATTR_ALL_UNSET:
1193 llvm_unreachable("regionAttr state machine has no ATTR_UNSET state");
1195 llvm_unreachable("regionAttr state machine has no ATTR_FILTERED state");
1199 // At the end, if we're still in ALL_SET or MIXED states, report a region
1206 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1208 case ATTR_ALL_UNSET:
1211 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1215 // We have finished with the filter processings. Now it's time to choose
1216 // the best performing filter.
1218 bool AllUseless = true;
1219 unsigned BestScore = 0;
1221 for (unsigned i = 0, e = Filters.size(); i != e; ++i) {
1222 unsigned Usefulness = Filters[i].usefulness();
1227 if (Usefulness > BestScore) {
1229 BestScore = Usefulness;
1234 bestFilter().recurse();
1237 } // end of FilterChooser::filterProcessor(bool)
1239 // Decides on the best configuration of filter(s) to use in order to decode
1240 // the instructions. A conflict of instructions may occur, in which case we
1241 // dump the conflict set to the standard error.
1242 void FilterChooser::doFilter() {
1243 unsigned Num = Opcodes.size();
1244 assert(Num && "FilterChooser created with no instructions");
1246 // Try regions of consecutive known bit values first.
1247 if (filterProcessor(false))
1250 // Then regions of mixed bits (both known and unitialized bit values allowed).
1251 if (filterProcessor(true))
1254 // Heuristics to cope with conflict set {t2CMPrs, t2SUBSrr, t2SUBSrs} where
1255 // no single instruction for the maximum ATTR_MIXED region Inst{14-4} has a
1256 // well-known encoding pattern. In such case, we backtrack and scan for the
1257 // the very first consecutive ATTR_ALL_SET region and assign a filter to it.
1258 if (Num == 3 && filterProcessor(true, false))
1261 // If we come to here, the instruction decoding has failed.
1262 // Set the BestIndex to -1 to indicate so.
1266 // Emits code to decode our share of instructions. Returns true if the
1267 // emitted code causes a return, which occurs if we know how to decode
1268 // the instruction at this level or the instruction is not decodeable.
1269 bool FilterChooser::emit(raw_ostream &o, unsigned &Indentation) {
1270 if (Opcodes.size() == 1)
1271 // There is only one instruction in the set, which is great!
1272 // Call emitSingletonDecoder() to see whether there are any remaining
1274 return emitSingletonDecoder(o, Indentation, Opcodes[0]);
1276 // Choose the best filter to do the decodings!
1277 if (BestIndex != -1) {
1278 Filter &Best = bestFilter();
1279 if (Best.getNumFiltered() == 1)
1280 emitSingletonDecoder(o, Indentation, Best);
1282 bestFilter().emit(o, Indentation);
1286 // We don't know how to decode these instructions! Return 0 and dump the
1288 o.indent(Indentation) << "return 0;" << " // Conflict set: ";
1289 for (int i = 0, N = Opcodes.size(); i < N; ++i) {
1290 o << nameWithID(Opcodes[i]);
1297 // Print out useful conflict information for postmortem analysis.
1298 errs() << "Decoding Conflict:\n";
1300 dumpStack(errs(), "\t\t");
1302 for (unsigned i = 0; i < Opcodes.size(); i++) {
1303 const std::string &Name = nameWithID(Opcodes[i]);
1305 errs() << '\t' << Name << " ";
1307 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
1314 static bool populateInstruction(const CodeGenInstruction &CGI,
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.
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"))
1329 BitsInit &Bits = getBitsField(Def, "Inst");
1330 if (Bits.allInComplete()) return false;
1332 std::vector<OperandInfo> InsnOperands;
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;
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.
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)));
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();
1364 TiedNames[InOutOperands[i].second] = InOutOperands[tiedTo].second;
1365 TiedNames[InOutOperands[tiedTo].second] = InOutOperands[i].second;
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 = "";
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();
1383 if (TypeRecord->isSubClassOf("RegisterOperand"))
1384 TypeRecord = TypeRecord->getValueAsDef("RegClass");
1385 if (TypeRecord->isSubClassOf("RegisterClass")) {
1386 Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
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();
1396 OperandInfo OpInfo(Decoder);
1397 unsigned Base = ~0U;
1399 unsigned Offset = 0;
1401 for (unsigned bi = 0; bi < Bits.getNumBits(); ++bi) {
1403 VarBitInit *BI = dynamic_cast<VarBitInit*>(Bits.getBit(bi));
1405 Var = dynamic_cast<VarInit*>(BI->getVariable());
1407 Var = dynamic_cast<VarInit*>(Bits.getBit(bi));
1411 OpInfo.addField(Base, Width, Offset);
1419 if (Var->getName() != NI->second &&
1420 Var->getName() != TiedNames[NI->second]) {
1422 OpInfo.addField(Base, Width, Offset);
1433 Offset = BI ? BI->getBitNum() : 0;
1434 } else if (BI && BI->getBitNum() != Offset + Width) {
1435 OpInfo.addField(Base, Width, Offset);
1438 Offset = BI->getBitNum();
1445 OpInfo.addField(Base, Width, Offset);
1447 if (OpInfo.numFields() > 0)
1448 InsnOperands.push_back(OpInfo);
1451 Operands[Opc] = InsnOperands;
1456 // Dumps the instruction encoding bits.
1457 dumpBits(errs(), Bits);
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;
1467 errs() << "\t" << OperandName << " (" << OperandDef.getName() << ")\n";
1475 static void emitHelper(llvm::raw_ostream &o, unsigned BitWidth) {
1476 unsigned Indentation = 0;
1477 std::string WidthStr = "uint" + utostr(BitWidth) + "_t";
1481 o.indent(Indentation) << "static " << WidthStr <<
1482 " fieldFromInstruction" << BitWidth <<
1483 "(" << WidthStr <<" insn, unsigned startBit, unsigned numBits)\n";
1485 o.indent(Indentation) << "{\n";
1487 ++Indentation; ++Indentation;
1488 o.indent(Indentation) << "assert(startBit + numBits <= " << BitWidth
1489 << " && \"Instruction field out of bounds!\");\n";
1491 o.indent(Indentation) << WidthStr << " fieldMask;\n";
1493 o.indent(Indentation) << "if (numBits == " << BitWidth << ")\n";
1495 ++Indentation; ++Indentation;
1496 o.indent(Indentation) << "fieldMask = (" << WidthStr << ")-1;\n";
1497 --Indentation; --Indentation;
1499 o.indent(Indentation) << "else\n";
1501 ++Indentation; ++Indentation;
1502 o.indent(Indentation) << "fieldMask = ((1 << numBits) - 1) << startBit;\n";
1503 --Indentation; --Indentation;
1506 o.indent(Indentation) << "return (insn & fieldMask) >> startBit;\n";
1507 --Indentation; --Indentation;
1509 o.indent(Indentation) << "}\n";
1514 // Emits disassembler code for instruction decoding.
1515 void FixedLenDecoderEmitter::run(raw_ostream &o)
1517 o << "#include \"llvm/MC/MCInst.h\"\n";
1518 o << "#include \"llvm/Support/DataTypes.h\"\n";
1519 o << "#include <assert.h>\n";
1521 o << "namespace llvm {\n\n";
1523 // Parameterize the decoders based on namespace and instruction width.
1524 std::vector<const CodeGenInstruction*> NumberedInstructions =
1525 Target.getInstructionsByEnumValue();
1526 std::map<std::pair<std::string, unsigned>,
1527 std::vector<unsigned> > OpcMap;
1528 std::map<unsigned, std::vector<OperandInfo> > Operands;
1530 for (unsigned i = 0; i < NumberedInstructions.size(); ++i) {
1531 const CodeGenInstruction *Inst = NumberedInstructions[i];
1532 Record *Def = Inst->TheDef;
1533 unsigned Size = Def->getValueAsInt("Size");
1534 if (Def->getValueAsString("Namespace") == "TargetOpcode" ||
1535 Def->getValueAsBit("isPseudo") ||
1536 Def->getValueAsBit("isAsmParserOnly") ||
1537 Def->getValueAsBit("isCodeGenOnly"))
1540 std::string DecoderNamespace = Def->getValueAsString("DecoderNamespace");
1543 if (populateInstruction(*Inst, i, Operands)) {
1544 OpcMap[std::make_pair(DecoderNamespace, Size)].push_back(i);
1549 std::set<unsigned> Sizes;
1550 for (std::map<std::pair<std::string, unsigned>,
1551 std::vector<unsigned> >::iterator
1552 I = OpcMap.begin(), E = OpcMap.end(); I != E; ++I) {
1553 // If we haven't visited this instruction width before, emit the
1554 // helper method to extract fields.
1555 if (!Sizes.count(I->first.second)) {
1556 emitHelper(o, 8*I->first.second);
1557 Sizes.insert(I->first.second);
1560 // Emit the decoder for this namespace+width combination.
1561 FilterChooser FC(NumberedInstructions, I->second, Operands,
1562 8*I->first.second, this);
1563 FC.emitTop(o, 0, I->first.first);
1566 o << "\n} // End llvm namespace \n";