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 #include "CodeGenTarget.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/MC/MCFixedLenDisassembler.h"
22 #include "llvm/Support/DataTypes.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/FormattedStream.h"
25 #include "llvm/Support/LEB128.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/TableGen/Error.h"
28 #include "llvm/TableGen/Record.h"
35 #define DEBUG_TYPE "decoder-emitter"
38 struct EncodingField {
39 unsigned Base, Width, Offset;
40 EncodingField(unsigned B, unsigned W, unsigned O)
41 : Base(B), Width(W), Offset(O) { }
45 std::vector<EncodingField> Fields;
48 OperandInfo(std::string D)
51 void addField(unsigned Base, unsigned Width, unsigned Offset) {
52 Fields.push_back(EncodingField(Base, Width, Offset));
55 unsigned numFields() const { return Fields.size(); }
57 typedef std::vector<EncodingField>::const_iterator const_iterator;
59 const_iterator begin() const { return Fields.begin(); }
60 const_iterator end() const { return Fields.end(); }
63 typedef std::vector<uint8_t> DecoderTable;
64 typedef uint32_t DecoderFixup;
65 typedef std::vector<DecoderFixup> FixupList;
66 typedef std::vector<FixupList> FixupScopeList;
67 typedef SetVector<std::string> PredicateSet;
68 typedef SetVector<std::string> DecoderSet;
69 struct DecoderTableInfo {
71 FixupScopeList FixupStack;
72 PredicateSet Predicates;
76 } // End anonymous namespace
79 class FixedLenDecoderEmitter {
80 const std::vector<const CodeGenInstruction*> *NumberedInstructions;
83 // Defaults preserved here for documentation, even though they aren't
84 // strictly necessary given the way that this is currently being called.
85 FixedLenDecoderEmitter(RecordKeeper &R,
86 std::string PredicateNamespace,
87 std::string GPrefix = "if (",
88 std::string GPostfix = " == MCDisassembler::Fail)"
89 " return MCDisassembler::Fail;",
90 std::string ROK = "MCDisassembler::Success",
91 std::string RFail = "MCDisassembler::Fail",
94 PredicateNamespace(PredicateNamespace),
95 GuardPrefix(GPrefix), GuardPostfix(GPostfix),
96 ReturnOK(ROK), ReturnFail(RFail), Locals(L) {}
98 // Emit the decoder state machine table.
99 void emitTable(formatted_raw_ostream &o, DecoderTable &Table,
100 unsigned Indentation, unsigned BitWidth,
101 StringRef Namespace) const;
102 void emitPredicateFunction(formatted_raw_ostream &OS,
103 PredicateSet &Predicates,
104 unsigned Indentation) const;
105 void emitDecoderFunction(formatted_raw_ostream &OS,
106 DecoderSet &Decoders,
107 unsigned Indentation) const;
109 // run - Output the code emitter
110 void run(raw_ostream &o);
113 CodeGenTarget Target;
115 std::string PredicateNamespace;
116 std::string GuardPrefix, GuardPostfix;
117 std::string ReturnOK, ReturnFail;
120 } // End anonymous namespace
122 // The set (BIT_TRUE, BIT_FALSE, BIT_UNSET) represents a ternary logic system
125 // BIT_UNFILTERED is used as the init value for a filter position. It is used
126 // only for filter processings.
131 BIT_UNFILTERED // unfiltered
134 static bool ValueSet(bit_value_t V) {
135 return (V == BIT_TRUE || V == BIT_FALSE);
137 static bool ValueNotSet(bit_value_t V) {
138 return (V == BIT_UNSET);
140 static int Value(bit_value_t V) {
141 return ValueNotSet(V) ? -1 : (V == BIT_FALSE ? 0 : 1);
143 static bit_value_t bitFromBits(const BitsInit &bits, unsigned index) {
144 if (BitInit *bit = dyn_cast<BitInit>(bits.getBit(index)))
145 return bit->getValue() ? BIT_TRUE : BIT_FALSE;
147 // The bit is uninitialized.
150 // Prints the bit value for each position.
151 static void dumpBits(raw_ostream &o, const BitsInit &bits) {
152 for (unsigned index = bits.getNumBits(); index > 0; --index) {
153 switch (bitFromBits(bits, index - 1)) {
164 llvm_unreachable("unexpected return value from bitFromBits");
169 static BitsInit &getBitsField(const Record &def, const char *str) {
170 BitsInit *bits = def.getValueAsBitsInit(str);
174 // Forward declaration.
177 } // End anonymous namespace
179 // Representation of the instruction to work on.
180 typedef std::vector<bit_value_t> insn_t;
182 /// Filter - Filter works with FilterChooser to produce the decoding tree for
185 /// It is useful to think of a Filter as governing the switch stmts of the
186 /// decoding tree in a certain level. Each case stmt delegates to an inferior
187 /// FilterChooser to decide what further decoding logic to employ, or in another
188 /// words, what other remaining bits to look at. The FilterChooser eventually
189 /// chooses a best Filter to do its job.
191 /// This recursive scheme ends when the number of Opcodes assigned to the
192 /// FilterChooser becomes 1 or if there is a conflict. A conflict happens when
193 /// the Filter/FilterChooser combo does not know how to distinguish among the
194 /// Opcodes assigned.
196 /// An example of a conflict is
199 /// 111101000.00........00010000....
200 /// 111101000.00........0001........
201 /// 1111010...00........0001........
202 /// 1111010...00....................
203 /// 1111010.........................
204 /// 1111............................
205 /// ................................
206 /// VST4q8a 111101000_00________00010000____
207 /// VST4q8b 111101000_00________00010000____
209 /// The Debug output shows the path that the decoding tree follows to reach the
210 /// the conclusion that there is a conflict. VST4q8a is a vst4 to double-spaced
211 /// even registers, while VST4q8b is a vst4 to double-spaced odd regsisters.
213 /// The encoding info in the .td files does not specify this meta information,
214 /// which could have been used by the decoder to resolve the conflict. The
215 /// decoder could try to decode the even/odd register numbering and assign to
216 /// VST4q8a or VST4q8b, but for the time being, the decoder chooses the "a"
217 /// version and return the Opcode since the two have the same Asm format string.
221 const FilterChooser *Owner;// points to the FilterChooser who owns this filter
222 unsigned StartBit; // the starting bit position
223 unsigned NumBits; // number of bits to filter
224 bool Mixed; // a mixed region contains both set and unset bits
226 // Map of well-known segment value to the set of uid's with that value.
227 std::map<uint64_t, std::vector<unsigned> > FilteredInstructions;
229 // Set of uid's with non-constant segment values.
230 std::vector<unsigned> VariableInstructions;
232 // Map of well-known segment value to its delegate.
233 std::map<unsigned, std::unique_ptr<const FilterChooser>> FilterChooserMap;
235 // Number of instructions which fall under FilteredInstructions category.
236 unsigned NumFiltered;
238 // Keeps track of the last opcode in the filtered bucket.
239 unsigned LastOpcFiltered;
242 unsigned getNumFiltered() const { return NumFiltered; }
243 unsigned getSingletonOpc() const {
244 assert(NumFiltered == 1);
245 return LastOpcFiltered;
247 // Return the filter chooser for the group of instructions without constant
249 const FilterChooser &getVariableFC() const {
250 assert(NumFiltered == 1);
251 assert(FilterChooserMap.size() == 1);
252 return *(FilterChooserMap.find((unsigned)-1)->second);
256 Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, bool mixed);
260 // Divides the decoding task into sub tasks and delegates them to the
261 // inferior FilterChooser's.
263 // A special case arises when there's only one entry in the filtered
264 // instructions. In order to unambiguously decode the singleton, we need to
265 // match the remaining undecoded encoding bits against the singleton.
268 // Emit table entries to decode instructions given a segment or segments of
270 void emitTableEntry(DecoderTableInfo &TableInfo) const;
272 // Returns the number of fanout produced by the filter. More fanout implies
273 // the filter distinguishes more categories of instructions.
274 unsigned usefulness() const;
275 }; // End of class Filter
276 } // End anonymous namespace
278 // These are states of our finite state machines used in FilterChooser's
279 // filterProcessor() which produces the filter candidates to use.
288 /// FilterChooser - FilterChooser chooses the best filter among a set of Filters
289 /// in order to perform the decoding of instructions at the current level.
291 /// Decoding proceeds from the top down. Based on the well-known encoding bits
292 /// of instructions available, FilterChooser builds up the possible Filters that
293 /// can further the task of decoding by distinguishing among the remaining
294 /// candidate instructions.
296 /// Once a filter has been chosen, it is called upon to divide the decoding task
297 /// into sub-tasks and delegates them to its inferior FilterChoosers for further
300 /// It is useful to think of a Filter as governing the switch stmts of the
301 /// decoding tree. And each case is delegated to an inferior FilterChooser to
302 /// decide what further remaining bits to look at.
304 class FilterChooser {
308 // Vector of codegen instructions to choose our filter.
309 const std::vector<const CodeGenInstruction*> &AllInstructions;
311 // Vector of uid's for this filter chooser to work on.
312 const std::vector<unsigned> &Opcodes;
314 // Lookup table for the operand decoding of instructions.
315 const std::map<unsigned, std::vector<OperandInfo> > &Operands;
317 // Vector of candidate filters.
318 std::vector<Filter> Filters;
320 // Array of bit values passed down from our parent.
321 // Set to all BIT_UNFILTERED's for Parent == NULL.
322 std::vector<bit_value_t> FilterBitValues;
324 // Links to the FilterChooser above us in the decoding tree.
325 const FilterChooser *Parent;
327 // Index of the best filter from Filters.
330 // Width of instructions
334 const FixedLenDecoderEmitter *Emitter;
336 FilterChooser(const FilterChooser &) LLVM_DELETED_FUNCTION;
337 void operator=(const FilterChooser &) LLVM_DELETED_FUNCTION;
340 FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
341 const std::vector<unsigned> &IDs,
342 const std::map<unsigned, std::vector<OperandInfo> > &Ops,
344 const FixedLenDecoderEmitter *E)
345 : AllInstructions(Insts), Opcodes(IDs), Operands(Ops), Filters(),
346 Parent(nullptr), BestIndex(-1), BitWidth(BW), Emitter(E) {
347 for (unsigned i = 0; i < BitWidth; ++i)
348 FilterBitValues.push_back(BIT_UNFILTERED);
353 FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
354 const std::vector<unsigned> &IDs,
355 const std::map<unsigned, std::vector<OperandInfo> > &Ops,
356 const std::vector<bit_value_t> &ParentFilterBitValues,
357 const FilterChooser &parent)
358 : AllInstructions(Insts), Opcodes(IDs), Operands(Ops),
359 Filters(), FilterBitValues(ParentFilterBitValues),
360 Parent(&parent), BestIndex(-1), BitWidth(parent.BitWidth),
361 Emitter(parent.Emitter) {
365 unsigned getBitWidth() const { return BitWidth; }
368 // Populates the insn given the uid.
369 void insnWithID(insn_t &Insn, unsigned Opcode) const {
370 BitsInit &Bits = getBitsField(*AllInstructions[Opcode]->TheDef, "Inst");
372 // We may have a SoftFail bitmask, which specifies a mask where an encoding
373 // may differ from the value in "Inst" and yet still be valid, but the
374 // disassembler should return SoftFail instead of Success.
376 // This is used for marking UNPREDICTABLE instructions in the ARM world.
378 AllInstructions[Opcode]->TheDef->getValueAsBitsInit("SoftFail");
380 for (unsigned i = 0; i < BitWidth; ++i) {
381 if (SFBits && bitFromBits(*SFBits, i) == BIT_TRUE)
382 Insn.push_back(BIT_UNSET);
384 Insn.push_back(bitFromBits(Bits, i));
388 // Returns the record name.
389 const std::string &nameWithID(unsigned Opcode) const {
390 return AllInstructions[Opcode]->TheDef->getName();
393 // Populates the field of the insn given the start position and the number of
394 // consecutive bits to scan for.
396 // Returns false if there exists any uninitialized bit value in the range.
397 // Returns true, otherwise.
398 bool fieldFromInsn(uint64_t &Field, insn_t &Insn, unsigned StartBit,
399 unsigned NumBits) const;
401 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
402 /// filter array as a series of chars.
403 void dumpFilterArray(raw_ostream &o,
404 const std::vector<bit_value_t> & filter) const;
406 /// dumpStack - dumpStack traverses the filter chooser chain and calls
407 /// dumpFilterArray on each filter chooser up to the top level one.
408 void dumpStack(raw_ostream &o, const char *prefix) const;
410 Filter &bestFilter() {
411 assert(BestIndex != -1 && "BestIndex not set");
412 return Filters[BestIndex];
415 // Called from Filter::recurse() when singleton exists. For debug purpose.
416 void SingletonExists(unsigned Opc) const;
418 bool PositionFiltered(unsigned i) const {
419 return ValueSet(FilterBitValues[i]);
422 // Calculates the island(s) needed to decode the instruction.
423 // This returns a lit of undecoded bits of an instructions, for example,
424 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
425 // decoded bits in order to verify that the instruction matches the Opcode.
426 unsigned getIslands(std::vector<unsigned> &StartBits,
427 std::vector<unsigned> &EndBits,
428 std::vector<uint64_t> &FieldVals,
429 const insn_t &Insn) const;
431 // Emits code to check the Predicates member of an instruction are true.
432 // Returns true if predicate matches were emitted, false otherwise.
433 bool emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
436 bool doesOpcodeNeedPredicate(unsigned Opc) const;
437 unsigned getPredicateIndex(DecoderTableInfo &TableInfo, StringRef P) const;
438 void emitPredicateTableEntry(DecoderTableInfo &TableInfo,
441 void emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
444 // Emits table entries to decode the singleton.
445 void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
448 // Emits code to decode the singleton, and then to decode the rest.
449 void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
450 const Filter &Best) const;
452 void emitBinaryParser(raw_ostream &o, unsigned &Indentation,
453 const OperandInfo &OpInfo) const;
455 void emitDecoder(raw_ostream &OS, unsigned Indentation, unsigned Opc) const;
456 unsigned getDecoderIndex(DecoderSet &Decoders, unsigned Opc) const;
458 // Assign a single filter and run with it.
459 void runSingleFilter(unsigned startBit, unsigned numBit, bool mixed);
461 // reportRegion is a helper function for filterProcessor to mark a region as
462 // eligible for use as a filter region.
463 void reportRegion(bitAttr_t RA, unsigned StartBit, unsigned BitIndex,
466 // FilterProcessor scans the well-known encoding bits of the instructions and
467 // builds up a list of candidate filters. It chooses the best filter and
468 // recursively descends down the decoding tree.
469 bool filterProcessor(bool AllowMixed, bool Greedy = true);
471 // Decides on the best configuration of filter(s) to use in order to decode
472 // the instructions. A conflict of instructions may occur, in which case we
473 // dump the conflict set to the standard error.
477 // emitTableEntries - Emit state machine entries to decode our share of
479 void emitTableEntries(DecoderTableInfo &TableInfo) const;
481 } // End anonymous namespace
483 ///////////////////////////
485 // Filter Implementation //
487 ///////////////////////////
489 Filter::Filter(Filter &&f)
490 : Owner(f.Owner), StartBit(f.StartBit), NumBits(f.NumBits), Mixed(f.Mixed),
491 FilteredInstructions(std::move(f.FilteredInstructions)),
492 VariableInstructions(std::move(f.VariableInstructions)),
493 FilterChooserMap(std::move(f.FilterChooserMap)), NumFiltered(f.NumFiltered),
494 LastOpcFiltered(f.LastOpcFiltered) {
497 Filter::Filter(FilterChooser &owner, unsigned startBit, unsigned numBits,
499 : Owner(&owner), StartBit(startBit), NumBits(numBits), Mixed(mixed) {
500 assert(StartBit + NumBits - 1 < Owner->BitWidth);
505 for (unsigned i = 0, e = Owner->Opcodes.size(); i != e; ++i) {
508 // Populates the insn given the uid.
509 Owner->insnWithID(Insn, Owner->Opcodes[i]);
512 // Scans the segment for possibly well-specified encoding bits.
513 bool ok = Owner->fieldFromInsn(Field, Insn, StartBit, NumBits);
516 // The encoding bits are well-known. Lets add the uid of the
517 // instruction into the bucket keyed off the constant field value.
518 LastOpcFiltered = Owner->Opcodes[i];
519 FilteredInstructions[Field].push_back(LastOpcFiltered);
522 // Some of the encoding bit(s) are unspecified. This contributes to
523 // one additional member of "Variable" instructions.
524 VariableInstructions.push_back(Owner->Opcodes[i]);
528 assert((FilteredInstructions.size() + VariableInstructions.size() > 0)
529 && "Filter returns no instruction categories");
535 // Divides the decoding task into sub tasks and delegates them to the
536 // inferior FilterChooser's.
538 // A special case arises when there's only one entry in the filtered
539 // instructions. In order to unambiguously decode the singleton, we need to
540 // match the remaining undecoded encoding bits against the singleton.
541 void Filter::recurse() {
542 std::map<uint64_t, std::vector<unsigned> >::const_iterator mapIterator;
544 // Starts by inheriting our parent filter chooser's filter bit values.
545 std::vector<bit_value_t> BitValueArray(Owner->FilterBitValues);
547 if (VariableInstructions.size()) {
548 // Conservatively marks each segment position as BIT_UNSET.
549 for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex)
550 BitValueArray[StartBit + bitIndex] = BIT_UNSET;
552 // Delegates to an inferior filter chooser for further processing on this
553 // group of instructions whose segment values are variable.
554 FilterChooserMap.emplace((unsigned)-1,
555 make_unique<FilterChooser>(Owner->AllInstructions,
556 VariableInstructions,
562 // No need to recurse for a singleton filtered instruction.
563 // See also Filter::emit*().
564 if (getNumFiltered() == 1) {
565 //Owner->SingletonExists(LastOpcFiltered);
566 assert(FilterChooserMap.size() == 1);
570 // Otherwise, create sub choosers.
571 for (mapIterator = FilteredInstructions.begin();
572 mapIterator != FilteredInstructions.end();
575 // Marks all the segment positions with either BIT_TRUE or BIT_FALSE.
576 for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex) {
577 if (mapIterator->first & (1ULL << bitIndex))
578 BitValueArray[StartBit + bitIndex] = BIT_TRUE;
580 BitValueArray[StartBit + bitIndex] = BIT_FALSE;
583 // Delegates to an inferior filter chooser for further processing on this
584 // category of instructions.
585 FilterChooserMap.emplace(mapIterator->first,
586 make_unique<FilterChooser>(Owner->AllInstructions,
594 static void resolveTableFixups(DecoderTable &Table, const FixupList &Fixups,
596 // Any NumToSkip fixups in the current scope can resolve to the
598 for (FixupList::const_reverse_iterator I = Fixups.rbegin(),
601 // Calculate the distance from the byte following the fixup entry byte
602 // to the destination. The Target is calculated from after the 16-bit
603 // NumToSkip entry itself, so subtract two from the displacement here
604 // to account for that.
605 uint32_t FixupIdx = *I;
606 uint32_t Delta = DestIdx - FixupIdx - 2;
607 // Our NumToSkip entries are 16-bits. Make sure our table isn't too
609 assert(Delta < 65536U && "disassembler decoding table too large!");
610 Table[FixupIdx] = (uint8_t)Delta;
611 Table[FixupIdx + 1] = (uint8_t)(Delta >> 8);
615 // Emit table entries to decode instructions given a segment or segments
617 void Filter::emitTableEntry(DecoderTableInfo &TableInfo) const {
618 TableInfo.Table.push_back(MCD::OPC_ExtractField);
619 TableInfo.Table.push_back(StartBit);
620 TableInfo.Table.push_back(NumBits);
622 // A new filter entry begins a new scope for fixup resolution.
623 TableInfo.FixupStack.push_back(FixupList());
626 std::unique_ptr<const FilterChooser>>::const_iterator filterIterator;
628 DecoderTable &Table = TableInfo.Table;
630 size_t PrevFilter = 0;
631 bool HasFallthrough = false;
632 for (filterIterator = FilterChooserMap.begin();
633 filterIterator != FilterChooserMap.end();
635 // Field value -1 implies a non-empty set of variable instructions.
636 // See also recurse().
637 if (filterIterator->first == (unsigned)-1) {
638 HasFallthrough = true;
640 // Each scope should always have at least one filter value to check
642 assert(PrevFilter != 0 && "empty filter set!");
643 FixupList &CurScope = TableInfo.FixupStack.back();
644 // Resolve any NumToSkip fixups in the current scope.
645 resolveTableFixups(Table, CurScope, Table.size());
647 PrevFilter = 0; // Don't re-process the filter's fallthrough.
649 Table.push_back(MCD::OPC_FilterValue);
650 // Encode and emit the value to filter against.
652 unsigned Len = encodeULEB128(filterIterator->first, Buffer);
653 Table.insert(Table.end(), Buffer, Buffer + Len);
654 // Reserve space for the NumToSkip entry. We'll backpatch the value
656 PrevFilter = Table.size();
661 // We arrive at a category of instructions with the same segment value.
662 // Now delegate to the sub filter chooser for further decodings.
663 // The case may fallthrough, which happens if the remaining well-known
664 // encoding bits do not match exactly.
665 filterIterator->second->emitTableEntries(TableInfo);
667 // Now that we've emitted the body of the handler, update the NumToSkip
668 // of the filter itself to be able to skip forward when false. Subtract
669 // two as to account for the width of the NumToSkip field itself.
671 uint32_t NumToSkip = Table.size() - PrevFilter - 2;
672 assert(NumToSkip < 65536U && "disassembler decoding table too large!");
673 Table[PrevFilter] = (uint8_t)NumToSkip;
674 Table[PrevFilter + 1] = (uint8_t)(NumToSkip >> 8);
678 // Any remaining unresolved fixups bubble up to the parent fixup scope.
679 assert(TableInfo.FixupStack.size() > 1 && "fixup stack underflow!");
680 FixupScopeList::iterator Source = TableInfo.FixupStack.end() - 1;
681 FixupScopeList::iterator Dest = Source - 1;
682 Dest->insert(Dest->end(), Source->begin(), Source->end());
683 TableInfo.FixupStack.pop_back();
685 // If there is no fallthrough, then the final filter should get fixed
686 // up according to the enclosing scope rather than the current position.
688 TableInfo.FixupStack.back().push_back(PrevFilter);
691 // Returns the number of fanout produced by the filter. More fanout implies
692 // the filter distinguishes more categories of instructions.
693 unsigned Filter::usefulness() const {
694 if (VariableInstructions.size())
695 return FilteredInstructions.size();
697 return FilteredInstructions.size() + 1;
700 //////////////////////////////////
702 // Filterchooser Implementation //
704 //////////////////////////////////
706 // Emit the decoder state machine table.
707 void FixedLenDecoderEmitter::emitTable(formatted_raw_ostream &OS,
709 unsigned Indentation,
711 StringRef Namespace) const {
712 OS.indent(Indentation) << "static const uint8_t DecoderTable" << Namespace
713 << BitWidth << "[] = {\n";
717 // FIXME: We may be able to use the NumToSkip values to recover
718 // appropriate indentation levels.
719 DecoderTable::const_iterator I = Table.begin();
720 DecoderTable::const_iterator E = Table.end();
722 assert (I < E && "incomplete decode table entry!");
724 uint64_t Pos = I - Table.begin();
725 OS << "/* " << Pos << " */";
730 PrintFatalError("invalid decode table opcode");
731 case MCD::OPC_ExtractField: {
733 unsigned Start = *I++;
735 OS.indent(Indentation) << "MCD::OPC_ExtractField, " << Start << ", "
736 << Len << ", // Inst{";
738 OS << (Start + Len - 1) << "-";
739 OS << Start << "} ...\n";
742 case MCD::OPC_FilterValue: {
744 OS.indent(Indentation) << "MCD::OPC_FilterValue, ";
745 // The filter value is ULEB128 encoded.
747 OS << utostr(*I++) << ", ";
748 OS << utostr(*I++) << ", ";
750 // 16-bit numtoskip value.
752 uint32_t NumToSkip = Byte;
753 OS << utostr(Byte) << ", ";
755 OS << utostr(Byte) << ", ";
756 NumToSkip |= Byte << 8;
757 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
760 case MCD::OPC_CheckField: {
762 unsigned Start = *I++;
764 OS.indent(Indentation) << "MCD::OPC_CheckField, " << Start << ", "
765 << Len << ", ";// << Val << ", " << NumToSkip << ",\n";
766 // ULEB128 encoded field value.
767 for (; *I >= 128; ++I)
768 OS << utostr(*I) << ", ";
769 OS << utostr(*I++) << ", ";
770 // 16-bit numtoskip value.
772 uint32_t NumToSkip = Byte;
773 OS << utostr(Byte) << ", ";
775 OS << utostr(Byte) << ", ";
776 NumToSkip |= Byte << 8;
777 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
780 case MCD::OPC_CheckPredicate: {
782 OS.indent(Indentation) << "MCD::OPC_CheckPredicate, ";
783 for (; *I >= 128; ++I)
784 OS << utostr(*I) << ", ";
785 OS << utostr(*I++) << ", ";
787 // 16-bit numtoskip value.
789 uint32_t NumToSkip = Byte;
790 OS << utostr(Byte) << ", ";
792 OS << utostr(Byte) << ", ";
793 NumToSkip |= Byte << 8;
794 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
797 case MCD::OPC_Decode: {
799 // Extract the ULEB128 encoded Opcode to a buffer.
800 uint8_t Buffer[8], *p = Buffer;
801 while ((*p++ = *I++) >= 128)
802 assert((p - Buffer) <= (ptrdiff_t)sizeof(Buffer)
803 && "ULEB128 value too large!");
804 // Decode the Opcode value.
805 unsigned Opc = decodeULEB128(Buffer);
806 OS.indent(Indentation) << "MCD::OPC_Decode, ";
807 for (p = Buffer; *p >= 128; ++p)
808 OS << utostr(*p) << ", ";
809 OS << utostr(*p) << ", ";
812 for (; *I >= 128; ++I)
813 OS << utostr(*I) << ", ";
814 OS << utostr(*I++) << ", ";
817 << NumberedInstructions->at(Opc)->TheDef->getName() << "\n";
820 case MCD::OPC_SoftFail: {
822 OS.indent(Indentation) << "MCD::OPC_SoftFail";
827 OS << ", " << utostr(*I);
828 Value += (*I & 0x7f) << Shift;
830 } while (*I++ >= 128);
832 OS << " /* 0x" << utohexstr(Value) << " */";
837 OS << ", " << utostr(*I);
838 Value += (*I & 0x7f) << Shift;
840 } while (*I++ >= 128);
842 OS << " /* 0x" << utohexstr(Value) << " */";
846 case MCD::OPC_Fail: {
848 OS.indent(Indentation) << "MCD::OPC_Fail,\n";
853 OS.indent(Indentation) << "0\n";
857 OS.indent(Indentation) << "};\n\n";
860 void FixedLenDecoderEmitter::
861 emitPredicateFunction(formatted_raw_ostream &OS, PredicateSet &Predicates,
862 unsigned Indentation) const {
863 // The predicate function is just a big switch statement based on the
864 // input predicate index.
865 OS.indent(Indentation) << "static bool checkDecoderPredicate(unsigned Idx, "
866 << "uint64_t Bits) {\n";
868 if (!Predicates.empty()) {
869 OS.indent(Indentation) << "switch (Idx) {\n";
870 OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
872 for (PredicateSet::const_iterator I = Predicates.begin(), E = Predicates.end();
873 I != E; ++I, ++Index) {
874 OS.indent(Indentation) << "case " << Index << ":\n";
875 OS.indent(Indentation+2) << "return (" << *I << ");\n";
877 OS.indent(Indentation) << "}\n";
879 // No case statement to emit
880 OS.indent(Indentation) << "llvm_unreachable(\"Invalid index!\");\n";
883 OS.indent(Indentation) << "}\n\n";
886 void FixedLenDecoderEmitter::
887 emitDecoderFunction(formatted_raw_ostream &OS, DecoderSet &Decoders,
888 unsigned Indentation) const {
889 // The decoder function is just a big switch statement based on the
890 // input decoder index.
891 OS.indent(Indentation) << "template<typename InsnType>\n";
892 OS.indent(Indentation) << "static DecodeStatus decodeToMCInst(DecodeStatus S,"
893 << " unsigned Idx, InsnType insn, MCInst &MI,\n";
894 OS.indent(Indentation) << " uint64_t "
895 << "Address, const void *Decoder) {\n";
897 OS.indent(Indentation) << "InsnType tmp;\n";
898 OS.indent(Indentation) << "switch (Idx) {\n";
899 OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
901 for (DecoderSet::const_iterator I = Decoders.begin(), E = Decoders.end();
902 I != E; ++I, ++Index) {
903 OS.indent(Indentation) << "case " << Index << ":\n";
905 OS.indent(Indentation+2) << "return S;\n";
907 OS.indent(Indentation) << "}\n";
909 OS.indent(Indentation) << "}\n\n";
912 // Populates the field of the insn given the start position and the number of
913 // consecutive bits to scan for.
915 // Returns false if and on the first uninitialized bit value encountered.
916 // Returns true, otherwise.
917 bool FilterChooser::fieldFromInsn(uint64_t &Field, insn_t &Insn,
918 unsigned StartBit, unsigned NumBits) const {
921 for (unsigned i = 0; i < NumBits; ++i) {
922 if (Insn[StartBit + i] == BIT_UNSET)
925 if (Insn[StartBit + i] == BIT_TRUE)
926 Field = Field | (1ULL << i);
932 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
933 /// filter array as a series of chars.
934 void FilterChooser::dumpFilterArray(raw_ostream &o,
935 const std::vector<bit_value_t> &filter) const {
936 for (unsigned bitIndex = BitWidth; bitIndex > 0; bitIndex--) {
937 switch (filter[bitIndex - 1]) {
954 /// dumpStack - dumpStack traverses the filter chooser chain and calls
955 /// dumpFilterArray on each filter chooser up to the top level one.
956 void FilterChooser::dumpStack(raw_ostream &o, const char *prefix) const {
957 const FilterChooser *current = this;
961 dumpFilterArray(o, current->FilterBitValues);
963 current = current->Parent;
967 // Called from Filter::recurse() when singleton exists. For debug purpose.
968 void FilterChooser::SingletonExists(unsigned Opc) const {
970 insnWithID(Insn0, Opc);
972 errs() << "Singleton exists: " << nameWithID(Opc)
973 << " with its decoding dominating ";
974 for (unsigned i = 0; i < Opcodes.size(); ++i) {
975 if (Opcodes[i] == Opc) continue;
976 errs() << nameWithID(Opcodes[i]) << ' ';
980 dumpStack(errs(), "\t\t");
981 for (unsigned i = 0; i < Opcodes.size(); ++i) {
982 const std::string &Name = nameWithID(Opcodes[i]);
984 errs() << '\t' << Name << " ";
986 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
991 // Calculates the island(s) needed to decode the instruction.
992 // This returns a list of undecoded bits of an instructions, for example,
993 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
994 // decoded bits in order to verify that the instruction matches the Opcode.
995 unsigned FilterChooser::getIslands(std::vector<unsigned> &StartBits,
996 std::vector<unsigned> &EndBits,
997 std::vector<uint64_t> &FieldVals,
998 const insn_t &Insn) const {
1002 uint64_t FieldVal = 0;
1005 // 1: Water (the bit value does not affect decoding)
1006 // 2: Island (well-known bit value needed for decoding)
1010 for (unsigned i = 0; i < BitWidth; ++i) {
1011 Val = Value(Insn[i]);
1012 bool Filtered = PositionFiltered(i);
1014 default: llvm_unreachable("Unreachable code!");
1017 if (Filtered || Val == -1)
1018 State = 1; // Still in Water
1020 State = 2; // Into the Island
1022 StartBits.push_back(i);
1027 if (Filtered || Val == -1) {
1028 State = 1; // Into the Water
1029 EndBits.push_back(i - 1);
1030 FieldVals.push_back(FieldVal);
1033 State = 2; // Still in Island
1035 FieldVal = FieldVal | Val << BitNo;
1040 // If we are still in Island after the loop, do some housekeeping.
1042 EndBits.push_back(BitWidth - 1);
1043 FieldVals.push_back(FieldVal);
1047 assert(StartBits.size() == Num && EndBits.size() == Num &&
1048 FieldVals.size() == Num);
1052 void FilterChooser::emitBinaryParser(raw_ostream &o, unsigned &Indentation,
1053 const OperandInfo &OpInfo) const {
1054 const std::string &Decoder = OpInfo.Decoder;
1056 if (OpInfo.numFields() == 1) {
1057 OperandInfo::const_iterator OI = OpInfo.begin();
1058 o.indent(Indentation) << "tmp = fieldFromInstruction"
1059 << "(insn, " << OI->Base << ", " << OI->Width
1062 o.indent(Indentation) << "tmp = 0;\n";
1063 for (OperandInfo::const_iterator OI = OpInfo.begin(), OE = OpInfo.end();
1065 o.indent(Indentation) << "tmp |= (fieldFromInstruction"
1066 << "(insn, " << OI->Base << ", " << OI->Width
1067 << ") << " << OI->Offset << ");\n";
1072 o.indent(Indentation) << Emitter->GuardPrefix << Decoder
1073 << "(MI, tmp, Address, Decoder)"
1074 << Emitter->GuardPostfix << "\n";
1076 o.indent(Indentation) << "MI.addOperand(MCOperand::CreateImm(tmp));\n";
1080 void FilterChooser::emitDecoder(raw_ostream &OS, unsigned Indentation,
1081 unsigned Opc) const {
1082 std::map<unsigned, std::vector<OperandInfo> >::const_iterator OpIter =
1084 const std::vector<OperandInfo>& InsnOperands = OpIter->second;
1085 for (std::vector<OperandInfo>::const_iterator
1086 I = InsnOperands.begin(), E = InsnOperands.end(); I != E; ++I) {
1087 // If a custom instruction decoder was specified, use that.
1088 if (I->numFields() == 0 && I->Decoder.size()) {
1089 OS.indent(Indentation) << Emitter->GuardPrefix << I->Decoder
1090 << "(MI, insn, Address, Decoder)"
1091 << Emitter->GuardPostfix << "\n";
1095 emitBinaryParser(OS, Indentation, *I);
1099 unsigned FilterChooser::getDecoderIndex(DecoderSet &Decoders,
1100 unsigned Opc) const {
1101 // Build up the predicate string.
1102 SmallString<256> Decoder;
1103 // FIXME: emitDecoder() function can take a buffer directly rather than
1105 raw_svector_ostream S(Decoder);
1107 emitDecoder(S, I, Opc);
1110 // Using the full decoder string as the key value here is a bit
1111 // heavyweight, but is effective. If the string comparisons become a
1112 // performance concern, we can implement a mangling of the predicate
1113 // data easilly enough with a map back to the actual string. That's
1114 // overkill for now, though.
1116 // Make sure the predicate is in the table.
1117 Decoders.insert(Decoder.str());
1118 // Now figure out the index for when we write out the table.
1119 DecoderSet::const_iterator P = std::find(Decoders.begin(),
1122 return (unsigned)(P - Decoders.begin());
1125 static void emitSinglePredicateMatch(raw_ostream &o, StringRef str,
1126 const std::string &PredicateNamespace) {
1128 o << "!(Bits & " << PredicateNamespace << "::"
1129 << str.slice(1,str.size()) << ")";
1131 o << "(Bits & " << PredicateNamespace << "::" << str << ")";
1134 bool FilterChooser::emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
1135 unsigned Opc) const {
1136 ListInit *Predicates =
1137 AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
1138 for (unsigned i = 0; i < Predicates->getSize(); ++i) {
1139 Record *Pred = Predicates->getElementAsRecord(i);
1140 if (!Pred->getValue("AssemblerMatcherPredicate"))
1143 std::string P = Pred->getValueAsString("AssemblerCondString");
1152 std::pair<StringRef, StringRef> pairs = SR.split(',');
1153 while (pairs.second.size()) {
1154 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
1156 pairs = pairs.second.split(',');
1158 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
1160 return Predicates->getSize() > 0;
1163 bool FilterChooser::doesOpcodeNeedPredicate(unsigned Opc) const {
1164 ListInit *Predicates =
1165 AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
1166 for (unsigned i = 0; i < Predicates->getSize(); ++i) {
1167 Record *Pred = Predicates->getElementAsRecord(i);
1168 if (!Pred->getValue("AssemblerMatcherPredicate"))
1171 std::string P = Pred->getValueAsString("AssemblerCondString");
1181 unsigned FilterChooser::getPredicateIndex(DecoderTableInfo &TableInfo,
1182 StringRef Predicate) const {
1183 // Using the full predicate string as the key value here is a bit
1184 // heavyweight, but is effective. If the string comparisons become a
1185 // performance concern, we can implement a mangling of the predicate
1186 // data easilly enough with a map back to the actual string. That's
1187 // overkill for now, though.
1189 // Make sure the predicate is in the table.
1190 TableInfo.Predicates.insert(Predicate.str());
1191 // Now figure out the index for when we write out the table.
1192 PredicateSet::const_iterator P = std::find(TableInfo.Predicates.begin(),
1193 TableInfo.Predicates.end(),
1195 return (unsigned)(P - TableInfo.Predicates.begin());
1198 void FilterChooser::emitPredicateTableEntry(DecoderTableInfo &TableInfo,
1199 unsigned Opc) const {
1200 if (!doesOpcodeNeedPredicate(Opc))
1203 // Build up the predicate string.
1204 SmallString<256> Predicate;
1205 // FIXME: emitPredicateMatch() functions can take a buffer directly rather
1207 raw_svector_ostream PS(Predicate);
1209 emitPredicateMatch(PS, I, Opc);
1211 // Figure out the index into the predicate table for the predicate just
1213 unsigned PIdx = getPredicateIndex(TableInfo, PS.str());
1214 SmallString<16> PBytes;
1215 raw_svector_ostream S(PBytes);
1216 encodeULEB128(PIdx, S);
1219 TableInfo.Table.push_back(MCD::OPC_CheckPredicate);
1221 for (unsigned i = 0, e = PBytes.size(); i != e; ++i)
1222 TableInfo.Table.push_back(PBytes[i]);
1223 // Push location for NumToSkip backpatching.
1224 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1225 TableInfo.Table.push_back(0);
1226 TableInfo.Table.push_back(0);
1229 void FilterChooser::emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
1230 unsigned Opc) const {
1232 AllInstructions[Opc]->TheDef->getValueAsBitsInit("SoftFail");
1233 if (!SFBits) return;
1234 BitsInit *InstBits = AllInstructions[Opc]->TheDef->getValueAsBitsInit("Inst");
1236 APInt PositiveMask(BitWidth, 0ULL);
1237 APInt NegativeMask(BitWidth, 0ULL);
1238 for (unsigned i = 0; i < BitWidth; ++i) {
1239 bit_value_t B = bitFromBits(*SFBits, i);
1240 bit_value_t IB = bitFromBits(*InstBits, i);
1242 if (B != BIT_TRUE) continue;
1246 // The bit is meant to be false, so emit a check to see if it is true.
1247 PositiveMask.setBit(i);
1250 // The bit is meant to be true, so emit a check to see if it is false.
1251 NegativeMask.setBit(i);
1254 // The bit is not set; this must be an error!
1255 StringRef Name = AllInstructions[Opc]->TheDef->getName();
1256 errs() << "SoftFail Conflict: bit SoftFail{" << i << "} in " << Name
1257 << " is set but Inst{" << i << "} is unset!\n"
1258 << " - You can only mark a bit as SoftFail if it is fully defined"
1259 << " (1/0 - not '?') in Inst\n";
1264 bool NeedPositiveMask = PositiveMask.getBoolValue();
1265 bool NeedNegativeMask = NegativeMask.getBoolValue();
1267 if (!NeedPositiveMask && !NeedNegativeMask)
1270 TableInfo.Table.push_back(MCD::OPC_SoftFail);
1272 SmallString<16> MaskBytes;
1273 raw_svector_ostream S(MaskBytes);
1274 if (NeedPositiveMask) {
1275 encodeULEB128(PositiveMask.getZExtValue(), S);
1277 for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
1278 TableInfo.Table.push_back(MaskBytes[i]);
1280 TableInfo.Table.push_back(0);
1281 if (NeedNegativeMask) {
1284 encodeULEB128(NegativeMask.getZExtValue(), S);
1286 for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
1287 TableInfo.Table.push_back(MaskBytes[i]);
1289 TableInfo.Table.push_back(0);
1292 // Emits table entries to decode the singleton.
1293 void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1294 unsigned Opc) const {
1295 std::vector<unsigned> StartBits;
1296 std::vector<unsigned> EndBits;
1297 std::vector<uint64_t> FieldVals;
1299 insnWithID(Insn, Opc);
1301 // Look for islands of undecoded bits of the singleton.
1302 getIslands(StartBits, EndBits, FieldVals, Insn);
1304 unsigned Size = StartBits.size();
1306 // Emit the predicate table entry if one is needed.
1307 emitPredicateTableEntry(TableInfo, Opc);
1309 // Check any additional encoding fields needed.
1310 for (unsigned I = Size; I != 0; --I) {
1311 unsigned NumBits = EndBits[I-1] - StartBits[I-1] + 1;
1312 TableInfo.Table.push_back(MCD::OPC_CheckField);
1313 TableInfo.Table.push_back(StartBits[I-1]);
1314 TableInfo.Table.push_back(NumBits);
1315 uint8_t Buffer[8], *p;
1316 encodeULEB128(FieldVals[I-1], Buffer);
1317 for (p = Buffer; *p >= 128 ; ++p)
1318 TableInfo.Table.push_back(*p);
1319 TableInfo.Table.push_back(*p);
1320 // Push location for NumToSkip backpatching.
1321 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1322 // The fixup is always 16-bits, so go ahead and allocate the space
1323 // in the table so all our relative position calculations work OK even
1324 // before we fully resolve the real value here.
1325 TableInfo.Table.push_back(0);
1326 TableInfo.Table.push_back(0);
1329 // Check for soft failure of the match.
1330 emitSoftFailTableEntry(TableInfo, Opc);
1332 TableInfo.Table.push_back(MCD::OPC_Decode);
1333 uint8_t Buffer[8], *p;
1334 encodeULEB128(Opc, Buffer);
1335 for (p = Buffer; *p >= 128 ; ++p)
1336 TableInfo.Table.push_back(*p);
1337 TableInfo.Table.push_back(*p);
1339 unsigned DIdx = getDecoderIndex(TableInfo.Decoders, Opc);
1340 SmallString<16> Bytes;
1341 raw_svector_ostream S(Bytes);
1342 encodeULEB128(DIdx, S);
1346 for (unsigned i = 0, e = Bytes.size(); i != e; ++i)
1347 TableInfo.Table.push_back(Bytes[i]);
1350 // Emits table entries to decode the singleton, and then to decode the rest.
1351 void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1352 const Filter &Best) const {
1353 unsigned Opc = Best.getSingletonOpc();
1355 // complex singletons need predicate checks from the first singleton
1356 // to refer forward to the variable filterchooser that follows.
1357 TableInfo.FixupStack.push_back(FixupList());
1359 emitSingletonTableEntry(TableInfo, Opc);
1361 resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
1362 TableInfo.Table.size());
1363 TableInfo.FixupStack.pop_back();
1365 Best.getVariableFC().emitTableEntries(TableInfo);
1369 // Assign a single filter and run with it. Top level API client can initialize
1370 // with a single filter to start the filtering process.
1371 void FilterChooser::runSingleFilter(unsigned startBit, unsigned numBit,
1374 Filters.push_back(Filter(*this, startBit, numBit, true));
1375 BestIndex = 0; // Sole Filter instance to choose from.
1376 bestFilter().recurse();
1379 // reportRegion is a helper function for filterProcessor to mark a region as
1380 // eligible for use as a filter region.
1381 void FilterChooser::reportRegion(bitAttr_t RA, unsigned StartBit,
1382 unsigned BitIndex, bool AllowMixed) {
1383 if (RA == ATTR_MIXED && AllowMixed)
1384 Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, true));
1385 else if (RA == ATTR_ALL_SET && !AllowMixed)
1386 Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, false));
1389 // FilterProcessor scans the well-known encoding bits of the instructions and
1390 // builds up a list of candidate filters. It chooses the best filter and
1391 // recursively descends down the decoding tree.
1392 bool FilterChooser::filterProcessor(bool AllowMixed, bool Greedy) {
1395 unsigned numInstructions = Opcodes.size();
1397 assert(numInstructions && "Filter created with no instructions");
1399 // No further filtering is necessary.
1400 if (numInstructions == 1)
1403 // Heuristics. See also doFilter()'s "Heuristics" comment when num of
1404 // instructions is 3.
1405 if (AllowMixed && !Greedy) {
1406 assert(numInstructions == 3);
1408 for (unsigned i = 0; i < Opcodes.size(); ++i) {
1409 std::vector<unsigned> StartBits;
1410 std::vector<unsigned> EndBits;
1411 std::vector<uint64_t> FieldVals;
1414 insnWithID(Insn, Opcodes[i]);
1416 // Look for islands of undecoded bits of any instruction.
1417 if (getIslands(StartBits, EndBits, FieldVals, Insn) > 0) {
1418 // Found an instruction with island(s). Now just assign a filter.
1419 runSingleFilter(StartBits[0], EndBits[0] - StartBits[0] + 1, true);
1427 // We maintain BIT_WIDTH copies of the bitAttrs automaton.
1428 // The automaton consumes the corresponding bit from each
1431 // Input symbols: 0, 1, and _ (unset).
1432 // States: NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED.
1433 // Initial state: NONE.
1435 // (NONE) ------- [01] -> (ALL_SET)
1436 // (NONE) ------- _ ----> (ALL_UNSET)
1437 // (ALL_SET) ---- [01] -> (ALL_SET)
1438 // (ALL_SET) ---- _ ----> (MIXED)
1439 // (ALL_UNSET) -- [01] -> (MIXED)
1440 // (ALL_UNSET) -- _ ----> (ALL_UNSET)
1441 // (MIXED) ------ . ----> (MIXED)
1442 // (FILTERED)---- . ----> (FILTERED)
1444 std::vector<bitAttr_t> bitAttrs;
1446 // FILTERED bit positions provide no entropy and are not worthy of pursuing.
1447 // Filter::recurse() set either BIT_TRUE or BIT_FALSE for each position.
1448 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex)
1449 if (FilterBitValues[BitIndex] == BIT_TRUE ||
1450 FilterBitValues[BitIndex] == BIT_FALSE)
1451 bitAttrs.push_back(ATTR_FILTERED);
1453 bitAttrs.push_back(ATTR_NONE);
1455 for (unsigned InsnIndex = 0; InsnIndex < numInstructions; ++InsnIndex) {
1458 insnWithID(insn, Opcodes[InsnIndex]);
1460 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
1461 switch (bitAttrs[BitIndex]) {
1463 if (insn[BitIndex] == BIT_UNSET)
1464 bitAttrs[BitIndex] = ATTR_ALL_UNSET;
1466 bitAttrs[BitIndex] = ATTR_ALL_SET;
1469 if (insn[BitIndex] == BIT_UNSET)
1470 bitAttrs[BitIndex] = ATTR_MIXED;
1472 case ATTR_ALL_UNSET:
1473 if (insn[BitIndex] != BIT_UNSET)
1474 bitAttrs[BitIndex] = ATTR_MIXED;
1483 // The regionAttr automaton consumes the bitAttrs automatons' state,
1484 // lowest-to-highest.
1486 // Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed)
1487 // States: NONE, ALL_SET, MIXED
1488 // Initial state: NONE
1490 // (NONE) ----- F --> (NONE)
1491 // (NONE) ----- S --> (ALL_SET) ; and set region start
1492 // (NONE) ----- U --> (NONE)
1493 // (NONE) ----- M --> (MIXED) ; and set region start
1494 // (ALL_SET) -- F --> (NONE) ; and report an ALL_SET region
1495 // (ALL_SET) -- S --> (ALL_SET)
1496 // (ALL_SET) -- U --> (NONE) ; and report an ALL_SET region
1497 // (ALL_SET) -- M --> (MIXED) ; and report an ALL_SET region
1498 // (MIXED) ---- F --> (NONE) ; and report a MIXED region
1499 // (MIXED) ---- S --> (ALL_SET) ; and report a MIXED region
1500 // (MIXED) ---- U --> (NONE) ; and report a MIXED region
1501 // (MIXED) ---- M --> (MIXED)
1503 bitAttr_t RA = ATTR_NONE;
1504 unsigned StartBit = 0;
1506 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
1507 bitAttr_t bitAttr = bitAttrs[BitIndex];
1509 assert(bitAttr != ATTR_NONE && "Bit without attributes");
1517 StartBit = BitIndex;
1520 case ATTR_ALL_UNSET:
1523 StartBit = BitIndex;
1527 llvm_unreachable("Unexpected bitAttr!");
1533 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1538 case ATTR_ALL_UNSET:
1539 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1543 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1544 StartBit = BitIndex;
1548 llvm_unreachable("Unexpected bitAttr!");
1554 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1555 StartBit = BitIndex;
1559 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1560 StartBit = BitIndex;
1563 case ATTR_ALL_UNSET:
1564 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1570 llvm_unreachable("Unexpected bitAttr!");
1573 case ATTR_ALL_UNSET:
1574 llvm_unreachable("regionAttr state machine has no ATTR_UNSET state");
1576 llvm_unreachable("regionAttr state machine has no ATTR_FILTERED state");
1580 // At the end, if we're still in ALL_SET or MIXED states, report a region
1587 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1589 case ATTR_ALL_UNSET:
1592 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1596 // We have finished with the filter processings. Now it's time to choose
1597 // the best performing filter.
1599 bool AllUseless = true;
1600 unsigned BestScore = 0;
1602 for (unsigned i = 0, e = Filters.size(); i != e; ++i) {
1603 unsigned Usefulness = Filters[i].usefulness();
1608 if (Usefulness > BestScore) {
1610 BestScore = Usefulness;
1615 bestFilter().recurse();
1618 } // end of FilterChooser::filterProcessor(bool)
1620 // Decides on the best configuration of filter(s) to use in order to decode
1621 // the instructions. A conflict of instructions may occur, in which case we
1622 // dump the conflict set to the standard error.
1623 void FilterChooser::doFilter() {
1624 unsigned Num = Opcodes.size();
1625 assert(Num && "FilterChooser created with no instructions");
1627 // Try regions of consecutive known bit values first.
1628 if (filterProcessor(false))
1631 // Then regions of mixed bits (both known and unitialized bit values allowed).
1632 if (filterProcessor(true))
1635 // Heuristics to cope with conflict set {t2CMPrs, t2SUBSrr, t2SUBSrs} where
1636 // no single instruction for the maximum ATTR_MIXED region Inst{14-4} has a
1637 // well-known encoding pattern. In such case, we backtrack and scan for the
1638 // the very first consecutive ATTR_ALL_SET region and assign a filter to it.
1639 if (Num == 3 && filterProcessor(true, false))
1642 // If we come to here, the instruction decoding has failed.
1643 // Set the BestIndex to -1 to indicate so.
1647 // emitTableEntries - Emit state machine entries to decode our share of
1649 void FilterChooser::emitTableEntries(DecoderTableInfo &TableInfo) const {
1650 if (Opcodes.size() == 1) {
1651 // There is only one instruction in the set, which is great!
1652 // Call emitSingletonDecoder() to see whether there are any remaining
1654 emitSingletonTableEntry(TableInfo, Opcodes[0]);
1658 // Choose the best filter to do the decodings!
1659 if (BestIndex != -1) {
1660 const Filter &Best = Filters[BestIndex];
1661 if (Best.getNumFiltered() == 1)
1662 emitSingletonTableEntry(TableInfo, Best);
1664 Best.emitTableEntry(TableInfo);
1668 // We don't know how to decode these instructions! Dump the
1669 // conflict set and bail.
1671 // Print out useful conflict information for postmortem analysis.
1672 errs() << "Decoding Conflict:\n";
1674 dumpStack(errs(), "\t\t");
1676 for (unsigned i = 0; i < Opcodes.size(); ++i) {
1677 const std::string &Name = nameWithID(Opcodes[i]);
1679 errs() << '\t' << Name << " ";
1681 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
1686 static bool populateInstruction(CodeGenTarget &Target,
1687 const CodeGenInstruction &CGI, unsigned Opc,
1688 std::map<unsigned, std::vector<OperandInfo> > &Operands){
1689 const Record &Def = *CGI.TheDef;
1690 // If all the bit positions are not specified; do not decode this instruction.
1691 // We are bound to fail! For proper disassembly, the well-known encoding bits
1692 // of the instruction must be fully specified.
1694 BitsInit &Bits = getBitsField(Def, "Inst");
1695 if (Bits.allInComplete()) return false;
1697 std::vector<OperandInfo> InsnOperands;
1699 // If the instruction has specified a custom decoding hook, use that instead
1700 // of trying to auto-generate the decoder.
1701 std::string InstDecoder = Def.getValueAsString("DecoderMethod");
1702 if (InstDecoder != "") {
1703 InsnOperands.push_back(OperandInfo(InstDecoder));
1704 Operands[Opc] = InsnOperands;
1708 // Generate a description of the operand of the instruction that we know
1709 // how to decode automatically.
1710 // FIXME: We'll need to have a way to manually override this as needed.
1712 // Gather the outputs/inputs of the instruction, so we can find their
1713 // positions in the encoding. This assumes for now that they appear in the
1714 // MCInst in the order that they're listed.
1715 std::vector<std::pair<Init*, std::string> > InOutOperands;
1716 DagInit *Out = Def.getValueAsDag("OutOperandList");
1717 DagInit *In = Def.getValueAsDag("InOperandList");
1718 for (unsigned i = 0; i < Out->getNumArgs(); ++i)
1719 InOutOperands.push_back(std::make_pair(Out->getArg(i), Out->getArgName(i)));
1720 for (unsigned i = 0; i < In->getNumArgs(); ++i)
1721 InOutOperands.push_back(std::make_pair(In->getArg(i), In->getArgName(i)));
1723 // Search for tied operands, so that we can correctly instantiate
1724 // operands that are not explicitly represented in the encoding.
1725 std::map<std::string, std::string> TiedNames;
1726 for (unsigned i = 0; i < CGI.Operands.size(); ++i) {
1727 int tiedTo = CGI.Operands[i].getTiedRegister();
1729 std::pair<unsigned, unsigned> SO =
1730 CGI.Operands.getSubOperandNumber(tiedTo);
1731 TiedNames[InOutOperands[i].second] = InOutOperands[SO.first].second;
1732 TiedNames[InOutOperands[SO.first].second] = InOutOperands[i].second;
1736 std::map<std::string, std::vector<OperandInfo> > NumberedInsnOperands;
1737 std::set<std::string> NumberedInsnOperandsNoTie;
1738 if (Target.getInstructionSet()->
1739 getValueAsBit("decodePositionallyEncodedOperands")) {
1740 const std::vector<RecordVal> &Vals = Def.getValues();
1741 unsigned NumberedOp = 0;
1743 std::set<unsigned> NamedOpIndices;
1744 if (Target.getInstructionSet()->
1745 getValueAsBit("noNamedPositionallyEncodedOperands"))
1746 // Collect the set of operand indices that might correspond to named
1747 // operand, and skip these when assigning operands based on position.
1748 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1750 if (!CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
1753 NamedOpIndices.insert(OpIdx);
1756 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1757 // Ignore fixed fields in the record, we're looking for values like:
1758 // bits<5> RST = { ?, ?, ?, ?, ? };
1759 if (Vals[i].getPrefix() || Vals[i].getValue()->isComplete())
1762 // Determine if Vals[i] actually contributes to the Inst encoding.
1764 for (; bi < Bits.getNumBits(); ++bi) {
1765 VarInit *Var = nullptr;
1766 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1768 Var = dyn_cast<VarInit>(BI->getBitVar());
1770 Var = dyn_cast<VarInit>(Bits.getBit(bi));
1772 if (Var && Var->getName() == Vals[i].getName())
1776 if (bi == Bits.getNumBits())
1779 // Skip variables that correspond to explicitly-named operands.
1781 if (CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
1784 // Get the bit range for this operand:
1785 unsigned bitStart = bi++, bitWidth = 1;
1786 for (; bi < Bits.getNumBits(); ++bi) {
1787 VarInit *Var = nullptr;
1788 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1790 Var = dyn_cast<VarInit>(BI->getBitVar());
1792 Var = dyn_cast<VarInit>(Bits.getBit(bi));
1797 if (Var->getName() != Vals[i].getName())
1803 unsigned NumberOps = CGI.Operands.size();
1804 while (NumberedOp < NumberOps &&
1805 (CGI.Operands.isFlatOperandNotEmitted(NumberedOp) ||
1806 (NamedOpIndices.size() && NamedOpIndices.count(
1807 CGI.Operands.getSubOperandNumber(NumberedOp).first))))
1810 OpIdx = NumberedOp++;
1812 // OpIdx now holds the ordered operand number of Vals[i].
1813 std::pair<unsigned, unsigned> SO =
1814 CGI.Operands.getSubOperandNumber(OpIdx);
1815 const std::string &Name = CGI.Operands[SO.first].Name;
1817 DEBUG(dbgs() << "Numbered operand mapping for " << Def.getName() << ": " <<
1818 Name << "(" << SO.first << ", " << SO.second << ") => " <<
1819 Vals[i].getName() << "\n");
1821 std::string Decoder = "";
1822 Record *TypeRecord = CGI.Operands[SO.first].Rec;
1824 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
1825 StringInit *String = DecoderString ?
1826 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
1827 if (String && String->getValue() != "")
1828 Decoder = String->getValue();
1830 if (Decoder == "" &&
1831 CGI.Operands[SO.first].MIOperandInfo &&
1832 CGI.Operands[SO.first].MIOperandInfo->getNumArgs()) {
1833 Init *Arg = CGI.Operands[SO.first].MIOperandInfo->
1835 if (TypedInit *TI = cast<TypedInit>(Arg)) {
1836 RecordRecTy *Type = cast<RecordRecTy>(TI->getType());
1837 TypeRecord = Type->getRecord();
1842 if (TypeRecord->isSubClassOf("RegisterOperand"))
1843 TypeRecord = TypeRecord->getValueAsDef("RegClass");
1844 if (TypeRecord->isSubClassOf("RegisterClass")) {
1845 Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
1847 } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) {
1848 Decoder = "DecodePointerLikeRegClass" +
1849 utostr(TypeRecord->getValueAsInt("RegClassKind"));
1853 DecoderString = TypeRecord->getValue("DecoderMethod");
1854 String = DecoderString ?
1855 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
1856 if (!isReg && String && String->getValue() != "")
1857 Decoder = String->getValue();
1859 OperandInfo OpInfo(Decoder);
1860 OpInfo.addField(bitStart, bitWidth, 0);
1862 NumberedInsnOperands[Name].push_back(OpInfo);
1864 // FIXME: For complex operands with custom decoders we can't handle tied
1865 // sub-operands automatically. Skip those here and assume that this is
1866 // fixed up elsewhere.
1867 if (CGI.Operands[SO.first].MIOperandInfo &&
1868 CGI.Operands[SO.first].MIOperandInfo->getNumArgs() > 1 &&
1869 String && String->getValue() != "")
1870 NumberedInsnOperandsNoTie.insert(Name);
1874 // For each operand, see if we can figure out where it is encoded.
1875 for (std::vector<std::pair<Init*, std::string> >::const_iterator
1876 NI = InOutOperands.begin(), NE = InOutOperands.end(); NI != NE; ++NI) {
1877 if (!NumberedInsnOperands[NI->second].empty()) {
1878 InsnOperands.insert(InsnOperands.end(),
1879 NumberedInsnOperands[NI->second].begin(),
1880 NumberedInsnOperands[NI->second].end());
1882 } else if (!NumberedInsnOperands[TiedNames[NI->second]].empty()) {
1883 if (!NumberedInsnOperandsNoTie.count(TiedNames[NI->second])) {
1884 // Figure out to which (sub)operand we're tied.
1885 unsigned i = CGI.Operands.getOperandNamed(TiedNames[NI->second]);
1886 int tiedTo = CGI.Operands[i].getTiedRegister();
1888 i = CGI.Operands.getOperandNamed(NI->second);
1889 tiedTo = CGI.Operands[i].getTiedRegister();
1893 std::pair<unsigned, unsigned> SO =
1894 CGI.Operands.getSubOperandNumber(tiedTo);
1896 InsnOperands.push_back(NumberedInsnOperands[TiedNames[NI->second]]
1903 std::string Decoder = "";
1905 // At this point, we can locate the field, but we need to know how to
1906 // interpret it. As a first step, require the target to provide callbacks
1907 // for decoding register classes.
1908 // FIXME: This need to be extended to handle instructions with custom
1909 // decoder methods, and operands with (simple) MIOperandInfo's.
1910 TypedInit *TI = cast<TypedInit>(NI->first);
1911 RecordRecTy *Type = cast<RecordRecTy>(TI->getType());
1912 Record *TypeRecord = Type->getRecord();
1914 if (TypeRecord->isSubClassOf("RegisterOperand"))
1915 TypeRecord = TypeRecord->getValueAsDef("RegClass");
1916 if (TypeRecord->isSubClassOf("RegisterClass")) {
1917 Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
1919 } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) {
1920 Decoder = "DecodePointerLikeRegClass" +
1921 utostr(TypeRecord->getValueAsInt("RegClassKind"));
1925 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
1926 StringInit *String = DecoderString ?
1927 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
1928 if (!isReg && String && String->getValue() != "")
1929 Decoder = String->getValue();
1931 OperandInfo OpInfo(Decoder);
1932 unsigned Base = ~0U;
1934 unsigned Offset = 0;
1936 for (unsigned bi = 0; bi < Bits.getNumBits(); ++bi) {
1937 VarInit *Var = nullptr;
1938 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1940 Var = dyn_cast<VarInit>(BI->getBitVar());
1942 Var = dyn_cast<VarInit>(Bits.getBit(bi));
1946 OpInfo.addField(Base, Width, Offset);
1954 if (Var->getName() != NI->second &&
1955 Var->getName() != TiedNames[NI->second]) {
1957 OpInfo.addField(Base, Width, Offset);
1968 Offset = BI ? BI->getBitNum() : 0;
1969 } else if (BI && BI->getBitNum() != Offset + Width) {
1970 OpInfo.addField(Base, Width, Offset);
1973 Offset = BI->getBitNum();
1980 OpInfo.addField(Base, Width, Offset);
1982 if (OpInfo.numFields() > 0)
1983 InsnOperands.push_back(OpInfo);
1986 Operands[Opc] = InsnOperands;
1991 // Dumps the instruction encoding bits.
1992 dumpBits(errs(), Bits);
1996 // Dumps the list of operand info.
1997 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
1998 const CGIOperandList::OperandInfo &Info = CGI.Operands[i];
1999 const std::string &OperandName = Info.Name;
2000 const Record &OperandDef = *Info.Rec;
2002 errs() << "\t" << OperandName << " (" << OperandDef.getName() << ")\n";
2010 // emitFieldFromInstruction - Emit the templated helper function
2011 // fieldFromInstruction().
2012 static void emitFieldFromInstruction(formatted_raw_ostream &OS) {
2013 OS << "// Helper function for extracting fields from encoded instructions.\n"
2014 << "template<typename InsnType>\n"
2015 << "static InsnType fieldFromInstruction(InsnType insn, unsigned startBit,\n"
2016 << " unsigned numBits) {\n"
2017 << " assert(startBit + numBits <= (sizeof(InsnType)*8) &&\n"
2018 << " \"Instruction field out of bounds!\");\n"
2019 << " InsnType fieldMask;\n"
2020 << " if (numBits == sizeof(InsnType)*8)\n"
2021 << " fieldMask = (InsnType)(-1LL);\n"
2023 << " fieldMask = (((InsnType)1 << numBits) - 1) << startBit;\n"
2024 << " return (insn & fieldMask) >> startBit;\n"
2028 // emitDecodeInstruction - Emit the templated helper function
2029 // decodeInstruction().
2030 static void emitDecodeInstruction(formatted_raw_ostream &OS) {
2031 OS << "template<typename InsnType>\n"
2032 << "static DecodeStatus decodeInstruction(const uint8_t DecodeTable[], MCInst &MI,\n"
2033 << " InsnType insn, uint64_t Address,\n"
2034 << " const void *DisAsm,\n"
2035 << " const MCSubtargetInfo &STI) {\n"
2036 << " uint64_t Bits = STI.getFeatureBits();\n"
2038 << " const uint8_t *Ptr = DecodeTable;\n"
2039 << " uint32_t CurFieldValue = 0;\n"
2040 << " DecodeStatus S = MCDisassembler::Success;\n"
2042 << " ptrdiff_t Loc = Ptr - DecodeTable;\n"
2043 << " switch (*Ptr) {\n"
2045 << " errs() << Loc << \": Unexpected decode table opcode!\\n\";\n"
2046 << " return MCDisassembler::Fail;\n"
2047 << " case MCD::OPC_ExtractField: {\n"
2048 << " unsigned Start = *++Ptr;\n"
2049 << " unsigned Len = *++Ptr;\n"
2051 << " CurFieldValue = fieldFromInstruction(insn, Start, Len);\n"
2052 << " DEBUG(dbgs() << Loc << \": OPC_ExtractField(\" << Start << \", \"\n"
2053 << " << Len << \"): \" << CurFieldValue << \"\\n\");\n"
2056 << " case MCD::OPC_FilterValue: {\n"
2057 << " // Decode the field value.\n"
2058 << " unsigned Len;\n"
2059 << " InsnType Val = decodeULEB128(++Ptr, &Len);\n"
2061 << " // NumToSkip is a plain 16-bit integer.\n"
2062 << " unsigned NumToSkip = *Ptr++;\n"
2063 << " NumToSkip |= (*Ptr++) << 8;\n"
2065 << " // Perform the filter operation.\n"
2066 << " if (Val != CurFieldValue)\n"
2067 << " Ptr += NumToSkip;\n"
2068 << " DEBUG(dbgs() << Loc << \": OPC_FilterValue(\" << Val << \", \" << NumToSkip\n"
2069 << " << \"): \" << ((Val != CurFieldValue) ? \"FAIL:\" : \"PASS:\")\n"
2070 << " << \" continuing at \" << (Ptr - DecodeTable) << \"\\n\");\n"
2074 << " case MCD::OPC_CheckField: {\n"
2075 << " unsigned Start = *++Ptr;\n"
2076 << " unsigned Len = *++Ptr;\n"
2077 << " InsnType FieldValue = fieldFromInstruction(insn, Start, Len);\n"
2078 << " // Decode the field value.\n"
2079 << " uint32_t ExpectedValue = decodeULEB128(++Ptr, &Len);\n"
2081 << " // NumToSkip is a plain 16-bit integer.\n"
2082 << " unsigned NumToSkip = *Ptr++;\n"
2083 << " NumToSkip |= (*Ptr++) << 8;\n"
2085 << " // If the actual and expected values don't match, skip.\n"
2086 << " if (ExpectedValue != FieldValue)\n"
2087 << " Ptr += NumToSkip;\n"
2088 << " DEBUG(dbgs() << Loc << \": OPC_CheckField(\" << Start << \", \"\n"
2089 << " << Len << \", \" << ExpectedValue << \", \" << NumToSkip\n"
2090 << " << \"): FieldValue = \" << FieldValue << \", ExpectedValue = \"\n"
2091 << " << ExpectedValue << \": \"\n"
2092 << " << ((ExpectedValue == FieldValue) ? \"PASS\\n\" : \"FAIL\\n\"));\n"
2095 << " case MCD::OPC_CheckPredicate: {\n"
2096 << " unsigned Len;\n"
2097 << " // Decode the Predicate Index value.\n"
2098 << " unsigned PIdx = decodeULEB128(++Ptr, &Len);\n"
2100 << " // NumToSkip is a plain 16-bit integer.\n"
2101 << " unsigned NumToSkip = *Ptr++;\n"
2102 << " NumToSkip |= (*Ptr++) << 8;\n"
2103 << " // Check the predicate.\n"
2105 << " if (!(Pred = checkDecoderPredicate(PIdx, Bits)))\n"
2106 << " Ptr += NumToSkip;\n"
2108 << " DEBUG(dbgs() << Loc << \": OPC_CheckPredicate(\" << PIdx << \"): \"\n"
2109 << " << (Pred ? \"PASS\\n\" : \"FAIL\\n\"));\n"
2113 << " case MCD::OPC_Decode: {\n"
2114 << " unsigned Len;\n"
2115 << " // Decode the Opcode value.\n"
2116 << " unsigned Opc = decodeULEB128(++Ptr, &Len);\n"
2118 << " unsigned DecodeIdx = decodeULEB128(Ptr, &Len);\n"
2120 << " DEBUG(dbgs() << Loc << \": OPC_Decode: opcode \" << Opc\n"
2121 << " << \", using decoder \" << DecodeIdx << \"\\n\" );\n"
2122 << " DEBUG(dbgs() << \"----- DECODE SUCCESSFUL -----\\n\");\n"
2124 << " MI.setOpcode(Opc);\n"
2125 << " return decodeToMCInst(S, DecodeIdx, insn, MI, Address, DisAsm);\n"
2127 << " case MCD::OPC_SoftFail: {\n"
2128 << " // Decode the mask values.\n"
2129 << " unsigned Len;\n"
2130 << " InsnType PositiveMask = decodeULEB128(++Ptr, &Len);\n"
2132 << " InsnType NegativeMask = decodeULEB128(Ptr, &Len);\n"
2134 << " bool Fail = (insn & PositiveMask) || (~insn & NegativeMask);\n"
2136 << " S = MCDisassembler::SoftFail;\n"
2137 << " DEBUG(dbgs() << Loc << \": OPC_SoftFail: \" << (Fail ? \"FAIL\\n\":\"PASS\\n\"));\n"
2140 << " case MCD::OPC_Fail: {\n"
2141 << " DEBUG(dbgs() << Loc << \": OPC_Fail\\n\");\n"
2142 << " return MCDisassembler::Fail;\n"
2146 << " llvm_unreachable(\"bogosity detected in disassembler state machine!\");\n"
2150 // Emits disassembler code for instruction decoding.
2151 void FixedLenDecoderEmitter::run(raw_ostream &o) {
2152 formatted_raw_ostream OS(o);
2153 OS << "#include \"llvm/MC/MCInst.h\"\n";
2154 OS << "#include \"llvm/Support/Debug.h\"\n";
2155 OS << "#include \"llvm/Support/DataTypes.h\"\n";
2156 OS << "#include \"llvm/Support/LEB128.h\"\n";
2157 OS << "#include \"llvm/Support/raw_ostream.h\"\n";
2158 OS << "#include <assert.h>\n";
2160 OS << "namespace llvm {\n\n";
2162 emitFieldFromInstruction(OS);
2164 Target.reverseBitsForLittleEndianEncoding();
2166 // Parameterize the decoders based on namespace and instruction width.
2167 NumberedInstructions = &Target.getInstructionsByEnumValue();
2168 std::map<std::pair<std::string, unsigned>,
2169 std::vector<unsigned> > OpcMap;
2170 std::map<unsigned, std::vector<OperandInfo> > Operands;
2172 for (unsigned i = 0; i < NumberedInstructions->size(); ++i) {
2173 const CodeGenInstruction *Inst = NumberedInstructions->at(i);
2174 const Record *Def = Inst->TheDef;
2175 unsigned Size = Def->getValueAsInt("Size");
2176 if (Def->getValueAsString("Namespace") == "TargetOpcode" ||
2177 Def->getValueAsBit("isPseudo") ||
2178 Def->getValueAsBit("isAsmParserOnly") ||
2179 Def->getValueAsBit("isCodeGenOnly"))
2182 std::string DecoderNamespace = Def->getValueAsString("DecoderNamespace");
2185 if (populateInstruction(Target, *Inst, i, Operands)) {
2186 OpcMap[std::make_pair(DecoderNamespace, Size)].push_back(i);
2191 DecoderTableInfo TableInfo;
2192 for (std::map<std::pair<std::string, unsigned>,
2193 std::vector<unsigned> >::const_iterator
2194 I = OpcMap.begin(), E = OpcMap.end(); I != E; ++I) {
2195 // Emit the decoder for this namespace+width combination.
2196 FilterChooser FC(*NumberedInstructions, I->second, Operands,
2197 8*I->first.second, this);
2199 // The decode table is cleared for each top level decoder function. The
2200 // predicates and decoders themselves, however, are shared across all
2201 // decoders to give more opportunities for uniqueing.
2202 TableInfo.Table.clear();
2203 TableInfo.FixupStack.clear();
2204 TableInfo.Table.reserve(16384);
2205 TableInfo.FixupStack.push_back(FixupList());
2206 FC.emitTableEntries(TableInfo);
2207 // Any NumToSkip fixups in the top level scope can resolve to the
2208 // OPC_Fail at the end of the table.
2209 assert(TableInfo.FixupStack.size() == 1 && "fixup stack phasing error!");
2210 // Resolve any NumToSkip fixups in the current scope.
2211 resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
2212 TableInfo.Table.size());
2213 TableInfo.FixupStack.clear();
2215 TableInfo.Table.push_back(MCD::OPC_Fail);
2217 // Print the table to the output stream.
2218 emitTable(OS, TableInfo.Table, 0, FC.getBitWidth(), I->first.first);
2222 // Emit the predicate function.
2223 emitPredicateFunction(OS, TableInfo.Predicates, 0);
2225 // Emit the decoder function.
2226 emitDecoderFunction(OS, TableInfo.Decoders, 0);
2228 // Emit the main entry point for the decoder, decodeInstruction().
2229 emitDecodeInstruction(OS);
2231 OS << "\n} // End llvm namespace\n";
2236 void EmitFixedLenDecoder(RecordKeeper &RK, raw_ostream &OS,
2237 std::string PredicateNamespace,
2238 std::string GPrefix,
2239 std::string GPostfix,
2243 FixedLenDecoderEmitter(RK, PredicateNamespace, GPrefix, GPostfix,
2244 ROK, RFail, L).run(OS);
2247 } // End llvm namespace