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;
47 bool HasCompleteDecoder;
49 OperandInfo(std::string D, bool HCD)
50 : Decoder(D), HasCompleteDecoder(HCD) { }
52 void addField(unsigned Base, unsigned Width, unsigned Offset) {
53 Fields.push_back(EncodingField(Base, Width, Offset));
56 unsigned numFields() const { return Fields.size(); }
58 typedef std::vector<EncodingField>::const_iterator const_iterator;
60 const_iterator begin() const { return Fields.begin(); }
61 const_iterator end() const { return Fields.end(); }
64 typedef std::vector<uint8_t> DecoderTable;
65 typedef uint32_t DecoderFixup;
66 typedef std::vector<DecoderFixup> FixupList;
67 typedef std::vector<FixupList> FixupScopeList;
68 typedef SetVector<std::string> PredicateSet;
69 typedef SetVector<std::string> DecoderSet;
70 struct DecoderTableInfo {
72 FixupScopeList FixupStack;
73 PredicateSet Predicates;
77 } // End anonymous namespace
80 class FixedLenDecoderEmitter {
81 const std::vector<const CodeGenInstruction*> *NumberedInstructions;
84 // Defaults preserved here for documentation, even though they aren't
85 // strictly necessary given the way that this is currently being called.
86 FixedLenDecoderEmitter(RecordKeeper &R,
87 std::string PredicateNamespace,
88 std::string GPrefix = "if (",
89 std::string GPostfix = " == 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 registers.
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 &) = delete;
337 void operator=(const FilterChooser &) = delete;
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 FilterBitValues(BW, BIT_UNFILTERED), Parent(nullptr), BestIndex(-1),
347 BitWidth(BW), Emitter(E) {
351 FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
352 const std::vector<unsigned> &IDs,
353 const std::map<unsigned, std::vector<OperandInfo> > &Ops,
354 const std::vector<bit_value_t> &ParentFilterBitValues,
355 const FilterChooser &parent)
356 : AllInstructions(Insts), Opcodes(IDs), Operands(Ops),
357 Filters(), FilterBitValues(ParentFilterBitValues),
358 Parent(&parent), BestIndex(-1), BitWidth(parent.BitWidth),
359 Emitter(parent.Emitter) {
363 unsigned getBitWidth() const { return BitWidth; }
366 // Populates the insn given the uid.
367 void insnWithID(insn_t &Insn, unsigned Opcode) const {
368 BitsInit &Bits = getBitsField(*AllInstructions[Opcode]->TheDef, "Inst");
370 // We may have a SoftFail bitmask, which specifies a mask where an encoding
371 // may differ from the value in "Inst" and yet still be valid, but the
372 // disassembler should return SoftFail instead of Success.
374 // This is used for marking UNPREDICTABLE instructions in the ARM world.
376 AllInstructions[Opcode]->TheDef->getValueAsBitsInit("SoftFail");
378 for (unsigned i = 0; i < BitWidth; ++i) {
379 if (SFBits && bitFromBits(*SFBits, i) == BIT_TRUE)
380 Insn.push_back(BIT_UNSET);
382 Insn.push_back(bitFromBits(Bits, i));
386 // Returns the record name.
387 const std::string &nameWithID(unsigned Opcode) const {
388 return AllInstructions[Opcode]->TheDef->getName();
391 // Populates the field of the insn given the start position and the number of
392 // consecutive bits to scan for.
394 // Returns false if there exists any uninitialized bit value in the range.
395 // Returns true, otherwise.
396 bool fieldFromInsn(uint64_t &Field, insn_t &Insn, unsigned StartBit,
397 unsigned NumBits) const;
399 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
400 /// filter array as a series of chars.
401 void dumpFilterArray(raw_ostream &o,
402 const std::vector<bit_value_t> & filter) const;
404 /// dumpStack - dumpStack traverses the filter chooser chain and calls
405 /// dumpFilterArray on each filter chooser up to the top level one.
406 void dumpStack(raw_ostream &o, const char *prefix) const;
408 Filter &bestFilter() {
409 assert(BestIndex != -1 && "BestIndex not set");
410 return Filters[BestIndex];
413 // Called from Filter::recurse() when singleton exists. For debug purpose.
414 void SingletonExists(unsigned Opc) const;
416 bool PositionFiltered(unsigned i) const {
417 return ValueSet(FilterBitValues[i]);
420 // Calculates the island(s) needed to decode the instruction.
421 // This returns a lit of undecoded bits of an instructions, for example,
422 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
423 // decoded bits in order to verify that the instruction matches the Opcode.
424 unsigned getIslands(std::vector<unsigned> &StartBits,
425 std::vector<unsigned> &EndBits,
426 std::vector<uint64_t> &FieldVals,
427 const insn_t &Insn) const;
429 // Emits code to check the Predicates member of an instruction are true.
430 // Returns true if predicate matches were emitted, false otherwise.
431 bool emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
434 bool doesOpcodeNeedPredicate(unsigned Opc) const;
435 unsigned getPredicateIndex(DecoderTableInfo &TableInfo, StringRef P) const;
436 void emitPredicateTableEntry(DecoderTableInfo &TableInfo,
439 void emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
442 // Emits table entries to decode the singleton.
443 void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
446 // Emits code to decode the singleton, and then to decode the rest.
447 void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
448 const Filter &Best) const;
450 void emitBinaryParser(raw_ostream &o, unsigned &Indentation,
451 const OperandInfo &OpInfo,
452 bool &OpHasCompleteDecoder) const;
454 void emitDecoder(raw_ostream &OS, unsigned Indentation, unsigned Opc,
455 bool &HasCompleteDecoder) const;
456 unsigned getDecoderIndex(DecoderSet &Decoders, unsigned Opc,
457 bool &HasCompleteDecoder) const;
459 // Assign a single filter and run with it.
460 void runSingleFilter(unsigned startBit, unsigned numBit, bool mixed);
462 // reportRegion is a helper function for filterProcessor to mark a region as
463 // eligible for use as a filter region.
464 void reportRegion(bitAttr_t RA, unsigned StartBit, unsigned BitIndex,
467 // FilterProcessor scans the well-known encoding bits of the instructions and
468 // builds up a list of candidate filters. It chooses the best filter and
469 // recursively descends down the decoding tree.
470 bool filterProcessor(bool AllowMixed, bool Greedy = true);
472 // Decides on the best configuration of filter(s) to use in order to decode
473 // the instructions. A conflict of instructions may occur, in which case we
474 // dump the conflict set to the standard error.
478 // emitTableEntries - Emit state machine entries to decode our share of
480 void emitTableEntries(DecoderTableInfo &TableInfo) const;
482 } // End anonymous namespace
484 ///////////////////////////
486 // Filter Implementation //
488 ///////////////////////////
490 Filter::Filter(Filter &&f)
491 : Owner(f.Owner), StartBit(f.StartBit), NumBits(f.NumBits), Mixed(f.Mixed),
492 FilteredInstructions(std::move(f.FilteredInstructions)),
493 VariableInstructions(std::move(f.VariableInstructions)),
494 FilterChooserMap(std::move(f.FilterChooserMap)), NumFiltered(f.NumFiltered),
495 LastOpcFiltered(f.LastOpcFiltered) {
498 Filter::Filter(FilterChooser &owner, unsigned startBit, unsigned numBits,
500 : Owner(&owner), StartBit(startBit), NumBits(numBits), Mixed(mixed) {
501 assert(StartBit + NumBits - 1 < Owner->BitWidth);
506 for (unsigned i = 0, e = Owner->Opcodes.size(); i != e; ++i) {
509 // Populates the insn given the uid.
510 Owner->insnWithID(Insn, Owner->Opcodes[i]);
513 // Scans the segment for possibly well-specified encoding bits.
514 bool ok = Owner->fieldFromInsn(Field, Insn, StartBit, NumBits);
517 // The encoding bits are well-known. Lets add the uid of the
518 // instruction into the bucket keyed off the constant field value.
519 LastOpcFiltered = Owner->Opcodes[i];
520 FilteredInstructions[Field].push_back(LastOpcFiltered);
523 // Some of the encoding bit(s) are unspecified. This contributes to
524 // one additional member of "Variable" instructions.
525 VariableInstructions.push_back(Owner->Opcodes[i]);
529 assert((FilteredInstructions.size() + VariableInstructions.size() > 0)
530 && "Filter returns no instruction categories");
536 // Divides the decoding task into sub tasks and delegates them to the
537 // inferior FilterChooser's.
539 // A special case arises when there's only one entry in the filtered
540 // instructions. In order to unambiguously decode the singleton, we need to
541 // match the remaining undecoded encoding bits against the singleton.
542 void Filter::recurse() {
543 // Starts by inheriting our parent filter chooser's filter bit values.
544 std::vector<bit_value_t> BitValueArray(Owner->FilterBitValues);
546 if (!VariableInstructions.empty()) {
547 // Conservatively marks each segment position as BIT_UNSET.
548 for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex)
549 BitValueArray[StartBit + bitIndex] = BIT_UNSET;
551 // Delegates to an inferior filter chooser for further processing on this
552 // group of instructions whose segment values are variable.
553 FilterChooserMap.insert(
554 std::make_pair(-1U, llvm::make_unique<FilterChooser>(
555 Owner->AllInstructions, VariableInstructions,
556 Owner->Operands, BitValueArray, *Owner)));
559 // No need to recurse for a singleton filtered instruction.
560 // See also Filter::emit*().
561 if (getNumFiltered() == 1) {
562 //Owner->SingletonExists(LastOpcFiltered);
563 assert(FilterChooserMap.size() == 1);
567 // Otherwise, create sub choosers.
568 for (const auto &Inst : FilteredInstructions) {
570 // Marks all the segment positions with either BIT_TRUE or BIT_FALSE.
571 for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex) {
572 if (Inst.first & (1ULL << bitIndex))
573 BitValueArray[StartBit + bitIndex] = BIT_TRUE;
575 BitValueArray[StartBit + bitIndex] = BIT_FALSE;
578 // Delegates to an inferior filter chooser for further processing on this
579 // category of instructions.
580 FilterChooserMap.insert(std::make_pair(
581 Inst.first, llvm::make_unique<FilterChooser>(
582 Owner->AllInstructions, Inst.second,
583 Owner->Operands, BitValueArray, *Owner)));
587 static void resolveTableFixups(DecoderTable &Table, const FixupList &Fixups,
589 // Any NumToSkip fixups in the current scope can resolve to the
591 for (FixupList::const_reverse_iterator I = Fixups.rbegin(),
594 // Calculate the distance from the byte following the fixup entry byte
595 // to the destination. The Target is calculated from after the 16-bit
596 // NumToSkip entry itself, so subtract two from the displacement here
597 // to account for that.
598 uint32_t FixupIdx = *I;
599 uint32_t Delta = DestIdx - FixupIdx - 2;
600 // Our NumToSkip entries are 16-bits. Make sure our table isn't too
602 assert(Delta < 65536U && "disassembler decoding table too large!");
603 Table[FixupIdx] = (uint8_t)Delta;
604 Table[FixupIdx + 1] = (uint8_t)(Delta >> 8);
608 // Emit table entries to decode instructions given a segment or segments
610 void Filter::emitTableEntry(DecoderTableInfo &TableInfo) const {
611 TableInfo.Table.push_back(MCD::OPC_ExtractField);
612 TableInfo.Table.push_back(StartBit);
613 TableInfo.Table.push_back(NumBits);
615 // A new filter entry begins a new scope for fixup resolution.
616 TableInfo.FixupStack.emplace_back();
618 DecoderTable &Table = TableInfo.Table;
620 size_t PrevFilter = 0;
621 bool HasFallthrough = false;
622 for (auto &Filter : FilterChooserMap) {
623 // Field value -1 implies a non-empty set of variable instructions.
624 // See also recurse().
625 if (Filter.first == (unsigned)-1) {
626 HasFallthrough = true;
628 // Each scope should always have at least one filter value to check
630 assert(PrevFilter != 0 && "empty filter set!");
631 FixupList &CurScope = TableInfo.FixupStack.back();
632 // Resolve any NumToSkip fixups in the current scope.
633 resolveTableFixups(Table, CurScope, Table.size());
635 PrevFilter = 0; // Don't re-process the filter's fallthrough.
637 Table.push_back(MCD::OPC_FilterValue);
638 // Encode and emit the value to filter against.
640 unsigned Len = encodeULEB128(Filter.first, Buffer);
641 Table.insert(Table.end(), Buffer, Buffer + Len);
642 // Reserve space for the NumToSkip entry. We'll backpatch the value
644 PrevFilter = Table.size();
649 // We arrive at a category of instructions with the same segment value.
650 // Now delegate to the sub filter chooser for further decodings.
651 // The case may fallthrough, which happens if the remaining well-known
652 // encoding bits do not match exactly.
653 Filter.second->emitTableEntries(TableInfo);
655 // Now that we've emitted the body of the handler, update the NumToSkip
656 // of the filter itself to be able to skip forward when false. Subtract
657 // two as to account for the width of the NumToSkip field itself.
659 uint32_t NumToSkip = Table.size() - PrevFilter - 2;
660 assert(NumToSkip < 65536U && "disassembler decoding table too large!");
661 Table[PrevFilter] = (uint8_t)NumToSkip;
662 Table[PrevFilter + 1] = (uint8_t)(NumToSkip >> 8);
666 // Any remaining unresolved fixups bubble up to the parent fixup scope.
667 assert(TableInfo.FixupStack.size() > 1 && "fixup stack underflow!");
668 FixupScopeList::iterator Source = TableInfo.FixupStack.end() - 1;
669 FixupScopeList::iterator Dest = Source - 1;
670 Dest->insert(Dest->end(), Source->begin(), Source->end());
671 TableInfo.FixupStack.pop_back();
673 // If there is no fallthrough, then the final filter should get fixed
674 // up according to the enclosing scope rather than the current position.
676 TableInfo.FixupStack.back().push_back(PrevFilter);
679 // Returns the number of fanout produced by the filter. More fanout implies
680 // the filter distinguishes more categories of instructions.
681 unsigned Filter::usefulness() const {
682 if (!VariableInstructions.empty())
683 return FilteredInstructions.size();
685 return FilteredInstructions.size() + 1;
688 //////////////////////////////////
690 // Filterchooser Implementation //
692 //////////////////////////////////
694 // Emit the decoder state machine table.
695 void FixedLenDecoderEmitter::emitTable(formatted_raw_ostream &OS,
697 unsigned Indentation,
699 StringRef Namespace) const {
700 OS.indent(Indentation) << "static const uint8_t DecoderTable" << Namespace
701 << BitWidth << "[] = {\n";
705 // FIXME: We may be able to use the NumToSkip values to recover
706 // appropriate indentation levels.
707 DecoderTable::const_iterator I = Table.begin();
708 DecoderTable::const_iterator E = Table.end();
710 assert (I < E && "incomplete decode table entry!");
712 uint64_t Pos = I - Table.begin();
713 OS << "/* " << Pos << " */";
718 PrintFatalError("invalid decode table opcode");
719 case MCD::OPC_ExtractField: {
721 unsigned Start = *I++;
723 OS.indent(Indentation) << "MCD::OPC_ExtractField, " << Start << ", "
724 << Len << ", // Inst{";
726 OS << (Start + Len - 1) << "-";
727 OS << Start << "} ...\n";
730 case MCD::OPC_FilterValue: {
732 OS.indent(Indentation) << "MCD::OPC_FilterValue, ";
733 // The filter value is ULEB128 encoded.
735 OS << utostr(*I++) << ", ";
736 OS << utostr(*I++) << ", ";
738 // 16-bit numtoskip value.
740 uint32_t NumToSkip = Byte;
741 OS << utostr(Byte) << ", ";
743 OS << utostr(Byte) << ", ";
744 NumToSkip |= Byte << 8;
745 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
748 case MCD::OPC_CheckField: {
750 unsigned Start = *I++;
752 OS.indent(Indentation) << "MCD::OPC_CheckField, " << Start << ", "
753 << Len << ", ";// << Val << ", " << NumToSkip << ",\n";
754 // ULEB128 encoded field value.
755 for (; *I >= 128; ++I)
756 OS << utostr(*I) << ", ";
757 OS << utostr(*I++) << ", ";
758 // 16-bit numtoskip value.
760 uint32_t NumToSkip = Byte;
761 OS << utostr(Byte) << ", ";
763 OS << utostr(Byte) << ", ";
764 NumToSkip |= Byte << 8;
765 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
768 case MCD::OPC_CheckPredicate: {
770 OS.indent(Indentation) << "MCD::OPC_CheckPredicate, ";
771 for (; *I >= 128; ++I)
772 OS << utostr(*I) << ", ";
773 OS << utostr(*I++) << ", ";
775 // 16-bit numtoskip value.
777 uint32_t NumToSkip = Byte;
778 OS << utostr(Byte) << ", ";
780 OS << utostr(Byte) << ", ";
781 NumToSkip |= Byte << 8;
782 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
785 case MCD::OPC_Decode:
786 case MCD::OPC_TryDecode: {
787 bool IsTry = *I == MCD::OPC_TryDecode;
789 // Extract the ULEB128 encoded Opcode to a buffer.
790 uint8_t Buffer[8], *p = Buffer;
791 while ((*p++ = *I++) >= 128)
792 assert((p - Buffer) <= (ptrdiff_t)sizeof(Buffer)
793 && "ULEB128 value too large!");
794 // Decode the Opcode value.
795 unsigned Opc = decodeULEB128(Buffer);
796 OS.indent(Indentation) << "MCD::OPC_" << (IsTry ? "Try" : "")
798 for (p = Buffer; *p >= 128; ++p)
799 OS << utostr(*p) << ", ";
800 OS << utostr(*p) << ", ";
803 for (; *I >= 128; ++I)
804 OS << utostr(*I) << ", ";
805 OS << utostr(*I++) << ", ";
809 << NumberedInstructions->at(Opc)->TheDef->getName() << "\n";
813 // Fallthrough for OPC_TryDecode.
815 // 16-bit numtoskip value.
817 uint32_t NumToSkip = Byte;
818 OS << utostr(Byte) << ", ";
820 OS << utostr(Byte) << ", ";
821 NumToSkip |= Byte << 8;
824 << NumberedInstructions->at(Opc)->TheDef->getName()
825 << ", skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
828 case MCD::OPC_SoftFail: {
830 OS.indent(Indentation) << "MCD::OPC_SoftFail";
835 OS << ", " << utostr(*I);
836 Value += (*I & 0x7f) << Shift;
838 } while (*I++ >= 128);
840 OS << " /* 0x" << utohexstr(Value) << " */";
845 OS << ", " << utostr(*I);
846 Value += (*I & 0x7f) << Shift;
848 } while (*I++ >= 128);
850 OS << " /* 0x" << utohexstr(Value) << " */";
854 case MCD::OPC_Fail: {
856 OS.indent(Indentation) << "MCD::OPC_Fail,\n";
861 OS.indent(Indentation) << "0\n";
865 OS.indent(Indentation) << "};\n\n";
868 void FixedLenDecoderEmitter::
869 emitPredicateFunction(formatted_raw_ostream &OS, PredicateSet &Predicates,
870 unsigned Indentation) const {
871 // The predicate function is just a big switch statement based on the
872 // input predicate index.
873 OS.indent(Indentation) << "static bool checkDecoderPredicate(unsigned Idx, "
874 << "const FeatureBitset& Bits) {\n";
876 if (!Predicates.empty()) {
877 OS.indent(Indentation) << "switch (Idx) {\n";
878 OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
880 for (const auto &Predicate : Predicates) {
881 OS.indent(Indentation) << "case " << Index++ << ":\n";
882 OS.indent(Indentation+2) << "return (" << Predicate << ");\n";
884 OS.indent(Indentation) << "}\n";
886 // No case statement to emit
887 OS.indent(Indentation) << "llvm_unreachable(\"Invalid index!\");\n";
890 OS.indent(Indentation) << "}\n\n";
893 void FixedLenDecoderEmitter::
894 emitDecoderFunction(formatted_raw_ostream &OS, DecoderSet &Decoders,
895 unsigned Indentation) const {
896 // The decoder function is just a big switch statement based on the
897 // input decoder index.
898 OS.indent(Indentation) << "template<typename InsnType>\n";
899 OS.indent(Indentation) << "static DecodeStatus decodeToMCInst(DecodeStatus S,"
900 << " unsigned Idx, InsnType insn, MCInst &MI,\n";
901 OS.indent(Indentation) << " uint64_t "
902 << "Address, const void *Decoder, bool &DecodeComplete) {\n";
904 OS.indent(Indentation) << "DecodeComplete = true;\n";
905 OS.indent(Indentation) << "InsnType tmp;\n";
906 OS.indent(Indentation) << "switch (Idx) {\n";
907 OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
909 for (const auto &Decoder : Decoders) {
910 OS.indent(Indentation) << "case " << Index++ << ":\n";
912 OS.indent(Indentation+2) << "return S;\n";
914 OS.indent(Indentation) << "}\n";
916 OS.indent(Indentation) << "}\n\n";
919 // Populates the field of the insn given the start position and the number of
920 // consecutive bits to scan for.
922 // Returns false if and on the first uninitialized bit value encountered.
923 // Returns true, otherwise.
924 bool FilterChooser::fieldFromInsn(uint64_t &Field, insn_t &Insn,
925 unsigned StartBit, unsigned NumBits) const {
928 for (unsigned i = 0; i < NumBits; ++i) {
929 if (Insn[StartBit + i] == BIT_UNSET)
932 if (Insn[StartBit + i] == BIT_TRUE)
933 Field = Field | (1ULL << i);
939 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
940 /// filter array as a series of chars.
941 void FilterChooser::dumpFilterArray(raw_ostream &o,
942 const std::vector<bit_value_t> &filter) const {
943 for (unsigned bitIndex = BitWidth; bitIndex > 0; bitIndex--) {
944 switch (filter[bitIndex - 1]) {
961 /// dumpStack - dumpStack traverses the filter chooser chain and calls
962 /// dumpFilterArray on each filter chooser up to the top level one.
963 void FilterChooser::dumpStack(raw_ostream &o, const char *prefix) const {
964 const FilterChooser *current = this;
968 dumpFilterArray(o, current->FilterBitValues);
970 current = current->Parent;
974 // Called from Filter::recurse() when singleton exists. For debug purpose.
975 void FilterChooser::SingletonExists(unsigned Opc) const {
977 insnWithID(Insn0, Opc);
979 errs() << "Singleton exists: " << nameWithID(Opc)
980 << " with its decoding dominating ";
981 for (unsigned i = 0; i < Opcodes.size(); ++i) {
982 if (Opcodes[i] == Opc) continue;
983 errs() << nameWithID(Opcodes[i]) << ' ';
987 dumpStack(errs(), "\t\t");
988 for (unsigned i = 0; i < Opcodes.size(); ++i) {
989 const std::string &Name = nameWithID(Opcodes[i]);
991 errs() << '\t' << Name << " ";
993 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
998 // Calculates the island(s) needed to decode the instruction.
999 // This returns a list of undecoded bits of an instructions, for example,
1000 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
1001 // decoded bits in order to verify that the instruction matches the Opcode.
1002 unsigned FilterChooser::getIslands(std::vector<unsigned> &StartBits,
1003 std::vector<unsigned> &EndBits,
1004 std::vector<uint64_t> &FieldVals,
1005 const insn_t &Insn) const {
1006 unsigned Num, BitNo;
1009 uint64_t FieldVal = 0;
1012 // 1: Water (the bit value does not affect decoding)
1013 // 2: Island (well-known bit value needed for decoding)
1017 for (unsigned i = 0; i < BitWidth; ++i) {
1018 Val = Value(Insn[i]);
1019 bool Filtered = PositionFiltered(i);
1021 default: llvm_unreachable("Unreachable code!");
1024 if (Filtered || Val == -1)
1025 State = 1; // Still in Water
1027 State = 2; // Into the Island
1029 StartBits.push_back(i);
1034 if (Filtered || Val == -1) {
1035 State = 1; // Into the Water
1036 EndBits.push_back(i - 1);
1037 FieldVals.push_back(FieldVal);
1040 State = 2; // Still in Island
1042 FieldVal = FieldVal | Val << BitNo;
1047 // If we are still in Island after the loop, do some housekeeping.
1049 EndBits.push_back(BitWidth - 1);
1050 FieldVals.push_back(FieldVal);
1054 assert(StartBits.size() == Num && EndBits.size() == Num &&
1055 FieldVals.size() == Num);
1059 void FilterChooser::emitBinaryParser(raw_ostream &o, unsigned &Indentation,
1060 const OperandInfo &OpInfo,
1061 bool &OpHasCompleteDecoder) const {
1062 const std::string &Decoder = OpInfo.Decoder;
1064 if (OpInfo.numFields() != 1)
1065 o.indent(Indentation) << "tmp = 0;\n";
1067 for (const EncodingField &EF : OpInfo) {
1068 o.indent(Indentation) << "tmp ";
1069 if (OpInfo.numFields() != 1) o << '|';
1070 o << "= fieldFromInstruction"
1071 << "(insn, " << EF.Base << ", " << EF.Width << ')';
1072 if (OpInfo.numFields() != 1 || EF.Offset != 0)
1073 o << " << " << EF.Offset;
1077 if (Decoder != "") {
1078 OpHasCompleteDecoder = OpInfo.HasCompleteDecoder;
1079 o.indent(Indentation) << Emitter->GuardPrefix << Decoder
1080 << "(MI, tmp, Address, Decoder)"
1081 << Emitter->GuardPostfix
1082 << " { " << (OpHasCompleteDecoder ? "" : "DecodeComplete = false; ")
1083 << "return MCDisassembler::Fail; }\n";
1085 OpHasCompleteDecoder = true;
1086 o.indent(Indentation) << "MI.addOperand(MCOperand::createImm(tmp));\n";
1090 void FilterChooser::emitDecoder(raw_ostream &OS, unsigned Indentation,
1091 unsigned Opc, bool &HasCompleteDecoder) const {
1092 HasCompleteDecoder = true;
1094 for (const auto &Op : Operands.find(Opc)->second) {
1095 // If a custom instruction decoder was specified, use that.
1096 if (Op.numFields() == 0 && Op.Decoder.size()) {
1097 HasCompleteDecoder = Op.HasCompleteDecoder;
1098 OS.indent(Indentation) << Emitter->GuardPrefix << Op.Decoder
1099 << "(MI, insn, Address, Decoder)"
1100 << Emitter->GuardPostfix
1101 << " { " << (HasCompleteDecoder ? "" : "DecodeComplete = false; ")
1102 << "return MCDisassembler::Fail; }\n";
1106 bool OpHasCompleteDecoder;
1107 emitBinaryParser(OS, Indentation, Op, OpHasCompleteDecoder);
1108 if (!OpHasCompleteDecoder)
1109 HasCompleteDecoder = false;
1113 unsigned FilterChooser::getDecoderIndex(DecoderSet &Decoders,
1115 bool &HasCompleteDecoder) const {
1116 // Build up the predicate string.
1117 SmallString<256> Decoder;
1118 // FIXME: emitDecoder() function can take a buffer directly rather than
1120 raw_svector_ostream S(Decoder);
1122 emitDecoder(S, I, Opc, HasCompleteDecoder);
1125 // Using the full decoder string as the key value here is a bit
1126 // heavyweight, but is effective. If the string comparisons become a
1127 // performance concern, we can implement a mangling of the predicate
1128 // data easilly enough with a map back to the actual string. That's
1129 // overkill for now, though.
1131 // Make sure the predicate is in the table.
1132 Decoders.insert(StringRef(Decoder));
1133 // Now figure out the index for when we write out the table.
1134 DecoderSet::const_iterator P = std::find(Decoders.begin(),
1137 return (unsigned)(P - Decoders.begin());
1140 static void emitSinglePredicateMatch(raw_ostream &o, StringRef str,
1141 const std::string &PredicateNamespace) {
1143 o << "!Bits[" << PredicateNamespace << "::"
1144 << str.slice(1,str.size()) << "]";
1146 o << "Bits[" << PredicateNamespace << "::" << str << "]";
1149 bool FilterChooser::emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
1150 unsigned Opc) const {
1151 ListInit *Predicates =
1152 AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
1153 bool IsFirstEmission = true;
1154 for (unsigned i = 0; i < Predicates->size(); ++i) {
1155 Record *Pred = Predicates->getElementAsRecord(i);
1156 if (!Pred->getValue("AssemblerMatcherPredicate"))
1159 std::string P = Pred->getValueAsString("AssemblerCondString");
1164 if (!IsFirstEmission)
1168 std::pair<StringRef, StringRef> pairs = SR.split(',');
1169 while (pairs.second.size()) {
1170 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
1172 pairs = pairs.second.split(',');
1174 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
1175 IsFirstEmission = false;
1177 return !Predicates->empty();
1180 bool FilterChooser::doesOpcodeNeedPredicate(unsigned Opc) const {
1181 ListInit *Predicates =
1182 AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
1183 for (unsigned i = 0; i < Predicates->size(); ++i) {
1184 Record *Pred = Predicates->getElementAsRecord(i);
1185 if (!Pred->getValue("AssemblerMatcherPredicate"))
1188 std::string P = Pred->getValueAsString("AssemblerCondString");
1198 unsigned FilterChooser::getPredicateIndex(DecoderTableInfo &TableInfo,
1199 StringRef Predicate) const {
1200 // Using the full predicate string as the key value here is a bit
1201 // heavyweight, but is effective. If the string comparisons become a
1202 // performance concern, we can implement a mangling of the predicate
1203 // data easilly enough with a map back to the actual string. That's
1204 // overkill for now, though.
1206 // Make sure the predicate is in the table.
1207 TableInfo.Predicates.insert(Predicate.str());
1208 // Now figure out the index for when we write out the table.
1209 PredicateSet::const_iterator P = std::find(TableInfo.Predicates.begin(),
1210 TableInfo.Predicates.end(),
1212 return (unsigned)(P - TableInfo.Predicates.begin());
1215 void FilterChooser::emitPredicateTableEntry(DecoderTableInfo &TableInfo,
1216 unsigned Opc) const {
1217 if (!doesOpcodeNeedPredicate(Opc))
1220 // Build up the predicate string.
1221 SmallString<256> Predicate;
1222 // FIXME: emitPredicateMatch() functions can take a buffer directly rather
1224 raw_svector_ostream PS(Predicate);
1226 emitPredicateMatch(PS, I, Opc);
1228 // Figure out the index into the predicate table for the predicate just
1230 unsigned PIdx = getPredicateIndex(TableInfo, PS.str());
1231 SmallString<16> PBytes;
1232 raw_svector_ostream S(PBytes);
1233 encodeULEB128(PIdx, S);
1236 TableInfo.Table.push_back(MCD::OPC_CheckPredicate);
1238 for (unsigned i = 0, e = PBytes.size(); i != e; ++i)
1239 TableInfo.Table.push_back(PBytes[i]);
1240 // Push location for NumToSkip backpatching.
1241 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1242 TableInfo.Table.push_back(0);
1243 TableInfo.Table.push_back(0);
1246 void FilterChooser::emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
1247 unsigned Opc) const {
1249 AllInstructions[Opc]->TheDef->getValueAsBitsInit("SoftFail");
1250 if (!SFBits) return;
1251 BitsInit *InstBits = AllInstructions[Opc]->TheDef->getValueAsBitsInit("Inst");
1253 APInt PositiveMask(BitWidth, 0ULL);
1254 APInt NegativeMask(BitWidth, 0ULL);
1255 for (unsigned i = 0; i < BitWidth; ++i) {
1256 bit_value_t B = bitFromBits(*SFBits, i);
1257 bit_value_t IB = bitFromBits(*InstBits, i);
1259 if (B != BIT_TRUE) continue;
1263 // The bit is meant to be false, so emit a check to see if it is true.
1264 PositiveMask.setBit(i);
1267 // The bit is meant to be true, so emit a check to see if it is false.
1268 NegativeMask.setBit(i);
1271 // The bit is not set; this must be an error!
1272 StringRef Name = AllInstructions[Opc]->TheDef->getName();
1273 errs() << "SoftFail Conflict: bit SoftFail{" << i << "} in " << Name
1274 << " is set but Inst{" << i << "} is unset!\n"
1275 << " - You can only mark a bit as SoftFail if it is fully defined"
1276 << " (1/0 - not '?') in Inst\n";
1281 bool NeedPositiveMask = PositiveMask.getBoolValue();
1282 bool NeedNegativeMask = NegativeMask.getBoolValue();
1284 if (!NeedPositiveMask && !NeedNegativeMask)
1287 TableInfo.Table.push_back(MCD::OPC_SoftFail);
1289 SmallString<16> MaskBytes;
1290 raw_svector_ostream S(MaskBytes);
1291 if (NeedPositiveMask) {
1292 encodeULEB128(PositiveMask.getZExtValue(), S);
1294 for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
1295 TableInfo.Table.push_back(MaskBytes[i]);
1297 TableInfo.Table.push_back(0);
1298 if (NeedNegativeMask) {
1301 encodeULEB128(NegativeMask.getZExtValue(), S);
1303 for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
1304 TableInfo.Table.push_back(MaskBytes[i]);
1306 TableInfo.Table.push_back(0);
1309 // Emits table entries to decode the singleton.
1310 void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1311 unsigned Opc) const {
1312 std::vector<unsigned> StartBits;
1313 std::vector<unsigned> EndBits;
1314 std::vector<uint64_t> FieldVals;
1316 insnWithID(Insn, Opc);
1318 // Look for islands of undecoded bits of the singleton.
1319 getIslands(StartBits, EndBits, FieldVals, Insn);
1321 unsigned Size = StartBits.size();
1323 // Emit the predicate table entry if one is needed.
1324 emitPredicateTableEntry(TableInfo, Opc);
1326 // Check any additional encoding fields needed.
1327 for (unsigned I = Size; I != 0; --I) {
1328 unsigned NumBits = EndBits[I-1] - StartBits[I-1] + 1;
1329 TableInfo.Table.push_back(MCD::OPC_CheckField);
1330 TableInfo.Table.push_back(StartBits[I-1]);
1331 TableInfo.Table.push_back(NumBits);
1332 uint8_t Buffer[8], *p;
1333 encodeULEB128(FieldVals[I-1], Buffer);
1334 for (p = Buffer; *p >= 128 ; ++p)
1335 TableInfo.Table.push_back(*p);
1336 TableInfo.Table.push_back(*p);
1337 // Push location for NumToSkip backpatching.
1338 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1339 // The fixup is always 16-bits, so go ahead and allocate the space
1340 // in the table so all our relative position calculations work OK even
1341 // before we fully resolve the real value here.
1342 TableInfo.Table.push_back(0);
1343 TableInfo.Table.push_back(0);
1346 // Check for soft failure of the match.
1347 emitSoftFailTableEntry(TableInfo, Opc);
1349 bool HasCompleteDecoder;
1350 unsigned DIdx = getDecoderIndex(TableInfo.Decoders, Opc, HasCompleteDecoder);
1352 // Produce OPC_Decode or OPC_TryDecode opcode based on the information
1353 // whether the instruction decoder is complete or not. If it is complete
1354 // then it handles all possible values of remaining variable/unfiltered bits
1355 // and for any value can determine if the bitpattern is a valid instruction
1356 // or not. This means OPC_Decode will be the final step in the decoding
1357 // process. If it is not complete, then the Fail return code from the
1358 // decoder method indicates that additional processing should be done to see
1359 // if there is any other instruction that also matches the bitpattern and
1361 TableInfo.Table.push_back(HasCompleteDecoder ? MCD::OPC_Decode :
1362 MCD::OPC_TryDecode);
1363 uint8_t Buffer[8], *p;
1364 encodeULEB128(Opc, Buffer);
1365 for (p = Buffer; *p >= 128 ; ++p)
1366 TableInfo.Table.push_back(*p);
1367 TableInfo.Table.push_back(*p);
1369 SmallString<16> Bytes;
1370 raw_svector_ostream S(Bytes);
1371 encodeULEB128(DIdx, S);
1375 for (unsigned i = 0, e = Bytes.size(); i != e; ++i)
1376 TableInfo.Table.push_back(Bytes[i]);
1378 if (!HasCompleteDecoder) {
1379 // Push location for NumToSkip backpatching.
1380 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1381 // Allocate the space for the fixup.
1382 TableInfo.Table.push_back(0);
1383 TableInfo.Table.push_back(0);
1387 // Emits table entries to decode the singleton, and then to decode the rest.
1388 void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1389 const Filter &Best) const {
1390 unsigned Opc = Best.getSingletonOpc();
1392 // complex singletons need predicate checks from the first singleton
1393 // to refer forward to the variable filterchooser that follows.
1394 TableInfo.FixupStack.emplace_back();
1396 emitSingletonTableEntry(TableInfo, Opc);
1398 resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
1399 TableInfo.Table.size());
1400 TableInfo.FixupStack.pop_back();
1402 Best.getVariableFC().emitTableEntries(TableInfo);
1406 // Assign a single filter and run with it. Top level API client can initialize
1407 // with a single filter to start the filtering process.
1408 void FilterChooser::runSingleFilter(unsigned startBit, unsigned numBit,
1411 Filters.emplace_back(*this, startBit, numBit, true);
1412 BestIndex = 0; // Sole Filter instance to choose from.
1413 bestFilter().recurse();
1416 // reportRegion is a helper function for filterProcessor to mark a region as
1417 // eligible for use as a filter region.
1418 void FilterChooser::reportRegion(bitAttr_t RA, unsigned StartBit,
1419 unsigned BitIndex, bool AllowMixed) {
1420 if (RA == ATTR_MIXED && AllowMixed)
1421 Filters.emplace_back(*this, StartBit, BitIndex - StartBit, true);
1422 else if (RA == ATTR_ALL_SET && !AllowMixed)
1423 Filters.emplace_back(*this, StartBit, BitIndex - StartBit, false);
1426 // FilterProcessor scans the well-known encoding bits of the instructions and
1427 // builds up a list of candidate filters. It chooses the best filter and
1428 // recursively descends down the decoding tree.
1429 bool FilterChooser::filterProcessor(bool AllowMixed, bool Greedy) {
1432 unsigned numInstructions = Opcodes.size();
1434 assert(numInstructions && "Filter created with no instructions");
1436 // No further filtering is necessary.
1437 if (numInstructions == 1)
1440 // Heuristics. See also doFilter()'s "Heuristics" comment when num of
1441 // instructions is 3.
1442 if (AllowMixed && !Greedy) {
1443 assert(numInstructions == 3);
1445 for (unsigned i = 0; i < Opcodes.size(); ++i) {
1446 std::vector<unsigned> StartBits;
1447 std::vector<unsigned> EndBits;
1448 std::vector<uint64_t> FieldVals;
1451 insnWithID(Insn, Opcodes[i]);
1453 // Look for islands of undecoded bits of any instruction.
1454 if (getIslands(StartBits, EndBits, FieldVals, Insn) > 0) {
1455 // Found an instruction with island(s). Now just assign a filter.
1456 runSingleFilter(StartBits[0], EndBits[0] - StartBits[0] + 1, true);
1464 // We maintain BIT_WIDTH copies of the bitAttrs automaton.
1465 // The automaton consumes the corresponding bit from each
1468 // Input symbols: 0, 1, and _ (unset).
1469 // States: NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED.
1470 // Initial state: NONE.
1472 // (NONE) ------- [01] -> (ALL_SET)
1473 // (NONE) ------- _ ----> (ALL_UNSET)
1474 // (ALL_SET) ---- [01] -> (ALL_SET)
1475 // (ALL_SET) ---- _ ----> (MIXED)
1476 // (ALL_UNSET) -- [01] -> (MIXED)
1477 // (ALL_UNSET) -- _ ----> (ALL_UNSET)
1478 // (MIXED) ------ . ----> (MIXED)
1479 // (FILTERED)---- . ----> (FILTERED)
1481 std::vector<bitAttr_t> bitAttrs;
1483 // FILTERED bit positions provide no entropy and are not worthy of pursuing.
1484 // Filter::recurse() set either BIT_TRUE or BIT_FALSE for each position.
1485 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex)
1486 if (FilterBitValues[BitIndex] == BIT_TRUE ||
1487 FilterBitValues[BitIndex] == BIT_FALSE)
1488 bitAttrs.push_back(ATTR_FILTERED);
1490 bitAttrs.push_back(ATTR_NONE);
1492 for (unsigned InsnIndex = 0; InsnIndex < numInstructions; ++InsnIndex) {
1495 insnWithID(insn, Opcodes[InsnIndex]);
1497 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
1498 switch (bitAttrs[BitIndex]) {
1500 if (insn[BitIndex] == BIT_UNSET)
1501 bitAttrs[BitIndex] = ATTR_ALL_UNSET;
1503 bitAttrs[BitIndex] = ATTR_ALL_SET;
1506 if (insn[BitIndex] == BIT_UNSET)
1507 bitAttrs[BitIndex] = ATTR_MIXED;
1509 case ATTR_ALL_UNSET:
1510 if (insn[BitIndex] != BIT_UNSET)
1511 bitAttrs[BitIndex] = ATTR_MIXED;
1520 // The regionAttr automaton consumes the bitAttrs automatons' state,
1521 // lowest-to-highest.
1523 // Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed)
1524 // States: NONE, ALL_SET, MIXED
1525 // Initial state: NONE
1527 // (NONE) ----- F --> (NONE)
1528 // (NONE) ----- S --> (ALL_SET) ; and set region start
1529 // (NONE) ----- U --> (NONE)
1530 // (NONE) ----- M --> (MIXED) ; and set region start
1531 // (ALL_SET) -- F --> (NONE) ; and report an ALL_SET region
1532 // (ALL_SET) -- S --> (ALL_SET)
1533 // (ALL_SET) -- U --> (NONE) ; and report an ALL_SET region
1534 // (ALL_SET) -- M --> (MIXED) ; and report an ALL_SET region
1535 // (MIXED) ---- F --> (NONE) ; and report a MIXED region
1536 // (MIXED) ---- S --> (ALL_SET) ; and report a MIXED region
1537 // (MIXED) ---- U --> (NONE) ; and report a MIXED region
1538 // (MIXED) ---- M --> (MIXED)
1540 bitAttr_t RA = ATTR_NONE;
1541 unsigned StartBit = 0;
1543 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
1544 bitAttr_t bitAttr = bitAttrs[BitIndex];
1546 assert(bitAttr != ATTR_NONE && "Bit without attributes");
1554 StartBit = BitIndex;
1557 case ATTR_ALL_UNSET:
1560 StartBit = BitIndex;
1564 llvm_unreachable("Unexpected bitAttr!");
1570 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1575 case ATTR_ALL_UNSET:
1576 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1580 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1581 StartBit = BitIndex;
1585 llvm_unreachable("Unexpected bitAttr!");
1591 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1592 StartBit = BitIndex;
1596 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1597 StartBit = BitIndex;
1600 case ATTR_ALL_UNSET:
1601 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1607 llvm_unreachable("Unexpected bitAttr!");
1610 case ATTR_ALL_UNSET:
1611 llvm_unreachable("regionAttr state machine has no ATTR_UNSET state");
1613 llvm_unreachable("regionAttr state machine has no ATTR_FILTERED state");
1617 // At the end, if we're still in ALL_SET or MIXED states, report a region
1624 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1626 case ATTR_ALL_UNSET:
1629 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1633 // We have finished with the filter processings. Now it's time to choose
1634 // the best performing filter.
1636 bool AllUseless = true;
1637 unsigned BestScore = 0;
1639 for (unsigned i = 0, e = Filters.size(); i != e; ++i) {
1640 unsigned Usefulness = Filters[i].usefulness();
1645 if (Usefulness > BestScore) {
1647 BestScore = Usefulness;
1652 bestFilter().recurse();
1655 } // end of FilterChooser::filterProcessor(bool)
1657 // Decides on the best configuration of filter(s) to use in order to decode
1658 // the instructions. A conflict of instructions may occur, in which case we
1659 // dump the conflict set to the standard error.
1660 void FilterChooser::doFilter() {
1661 unsigned Num = Opcodes.size();
1662 assert(Num && "FilterChooser created with no instructions");
1664 // Try regions of consecutive known bit values first.
1665 if (filterProcessor(false))
1668 // Then regions of mixed bits (both known and unitialized bit values allowed).
1669 if (filterProcessor(true))
1672 // Heuristics to cope with conflict set {t2CMPrs, t2SUBSrr, t2SUBSrs} where
1673 // no single instruction for the maximum ATTR_MIXED region Inst{14-4} has a
1674 // well-known encoding pattern. In such case, we backtrack and scan for the
1675 // the very first consecutive ATTR_ALL_SET region and assign a filter to it.
1676 if (Num == 3 && filterProcessor(true, false))
1679 // If we come to here, the instruction decoding has failed.
1680 // Set the BestIndex to -1 to indicate so.
1684 // emitTableEntries - Emit state machine entries to decode our share of
1686 void FilterChooser::emitTableEntries(DecoderTableInfo &TableInfo) const {
1687 if (Opcodes.size() == 1) {
1688 // There is only one instruction in the set, which is great!
1689 // Call emitSingletonDecoder() to see whether there are any remaining
1691 emitSingletonTableEntry(TableInfo, Opcodes[0]);
1695 // Choose the best filter to do the decodings!
1696 if (BestIndex != -1) {
1697 const Filter &Best = Filters[BestIndex];
1698 if (Best.getNumFiltered() == 1)
1699 emitSingletonTableEntry(TableInfo, Best);
1701 Best.emitTableEntry(TableInfo);
1705 // We don't know how to decode these instructions! Dump the
1706 // conflict set and bail.
1708 // Print out useful conflict information for postmortem analysis.
1709 errs() << "Decoding Conflict:\n";
1711 dumpStack(errs(), "\t\t");
1713 for (unsigned i = 0; i < Opcodes.size(); ++i) {
1714 const std::string &Name = nameWithID(Opcodes[i]);
1716 errs() << '\t' << Name << " ";
1718 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
1723 static bool populateInstruction(CodeGenTarget &Target,
1724 const CodeGenInstruction &CGI, unsigned Opc,
1725 std::map<unsigned, std::vector<OperandInfo> > &Operands){
1726 const Record &Def = *CGI.TheDef;
1727 // If all the bit positions are not specified; do not decode this instruction.
1728 // We are bound to fail! For proper disassembly, the well-known encoding bits
1729 // of the instruction must be fully specified.
1731 BitsInit &Bits = getBitsField(Def, "Inst");
1732 if (Bits.allInComplete()) return false;
1734 std::vector<OperandInfo> InsnOperands;
1736 // If the instruction has specified a custom decoding hook, use that instead
1737 // of trying to auto-generate the decoder.
1738 std::string InstDecoder = Def.getValueAsString("DecoderMethod");
1739 if (InstDecoder != "") {
1740 bool HasCompleteInstDecoder = Def.getValueAsBit("hasCompleteDecoder");
1741 InsnOperands.push_back(OperandInfo(InstDecoder, HasCompleteInstDecoder));
1742 Operands[Opc] = InsnOperands;
1746 // Generate a description of the operand of the instruction that we know
1747 // how to decode automatically.
1748 // FIXME: We'll need to have a way to manually override this as needed.
1750 // Gather the outputs/inputs of the instruction, so we can find their
1751 // positions in the encoding. This assumes for now that they appear in the
1752 // MCInst in the order that they're listed.
1753 std::vector<std::pair<Init*, std::string> > InOutOperands;
1754 DagInit *Out = Def.getValueAsDag("OutOperandList");
1755 DagInit *In = Def.getValueAsDag("InOperandList");
1756 for (unsigned i = 0; i < Out->getNumArgs(); ++i)
1757 InOutOperands.push_back(std::make_pair(Out->getArg(i), Out->getArgName(i)));
1758 for (unsigned i = 0; i < In->getNumArgs(); ++i)
1759 InOutOperands.push_back(std::make_pair(In->getArg(i), In->getArgName(i)));
1761 // Search for tied operands, so that we can correctly instantiate
1762 // operands that are not explicitly represented in the encoding.
1763 std::map<std::string, std::string> TiedNames;
1764 for (unsigned i = 0; i < CGI.Operands.size(); ++i) {
1765 int tiedTo = CGI.Operands[i].getTiedRegister();
1767 std::pair<unsigned, unsigned> SO =
1768 CGI.Operands.getSubOperandNumber(tiedTo);
1769 TiedNames[InOutOperands[i].second] = InOutOperands[SO.first].second;
1770 TiedNames[InOutOperands[SO.first].second] = InOutOperands[i].second;
1774 std::map<std::string, std::vector<OperandInfo> > NumberedInsnOperands;
1775 std::set<std::string> NumberedInsnOperandsNoTie;
1776 if (Target.getInstructionSet()->
1777 getValueAsBit("decodePositionallyEncodedOperands")) {
1778 const std::vector<RecordVal> &Vals = Def.getValues();
1779 unsigned NumberedOp = 0;
1781 std::set<unsigned> NamedOpIndices;
1782 if (Target.getInstructionSet()->
1783 getValueAsBit("noNamedPositionallyEncodedOperands"))
1784 // Collect the set of operand indices that might correspond to named
1785 // operand, and skip these when assigning operands based on position.
1786 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1788 if (!CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
1791 NamedOpIndices.insert(OpIdx);
1794 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1795 // Ignore fixed fields in the record, we're looking for values like:
1796 // bits<5> RST = { ?, ?, ?, ?, ? };
1797 if (Vals[i].getPrefix() || Vals[i].getValue()->isComplete())
1800 // Determine if Vals[i] actually contributes to the Inst encoding.
1802 for (; bi < Bits.getNumBits(); ++bi) {
1803 VarInit *Var = nullptr;
1804 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1806 Var = dyn_cast<VarInit>(BI->getBitVar());
1808 Var = dyn_cast<VarInit>(Bits.getBit(bi));
1810 if (Var && Var->getName() == Vals[i].getName())
1814 if (bi == Bits.getNumBits())
1817 // Skip variables that correspond to explicitly-named operands.
1819 if (CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
1822 // Get the bit range for this operand:
1823 unsigned bitStart = bi++, bitWidth = 1;
1824 for (; bi < Bits.getNumBits(); ++bi) {
1825 VarInit *Var = nullptr;
1826 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1828 Var = dyn_cast<VarInit>(BI->getBitVar());
1830 Var = dyn_cast<VarInit>(Bits.getBit(bi));
1835 if (Var->getName() != Vals[i].getName())
1841 unsigned NumberOps = CGI.Operands.size();
1842 while (NumberedOp < NumberOps &&
1843 (CGI.Operands.isFlatOperandNotEmitted(NumberedOp) ||
1844 (!NamedOpIndices.empty() && NamedOpIndices.count(
1845 CGI.Operands.getSubOperandNumber(NumberedOp).first))))
1848 OpIdx = NumberedOp++;
1850 // OpIdx now holds the ordered operand number of Vals[i].
1851 std::pair<unsigned, unsigned> SO =
1852 CGI.Operands.getSubOperandNumber(OpIdx);
1853 const std::string &Name = CGI.Operands[SO.first].Name;
1855 DEBUG(dbgs() << "Numbered operand mapping for " << Def.getName() << ": " <<
1856 Name << "(" << SO.first << ", " << SO.second << ") => " <<
1857 Vals[i].getName() << "\n");
1859 std::string Decoder = "";
1860 Record *TypeRecord = CGI.Operands[SO.first].Rec;
1862 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
1863 StringInit *String = DecoderString ?
1864 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
1865 if (String && String->getValue() != "")
1866 Decoder = String->getValue();
1868 if (Decoder == "" &&
1869 CGI.Operands[SO.first].MIOperandInfo &&
1870 CGI.Operands[SO.first].MIOperandInfo->getNumArgs()) {
1871 Init *Arg = CGI.Operands[SO.first].MIOperandInfo->
1873 if (TypedInit *TI = cast<TypedInit>(Arg)) {
1874 RecordRecTy *Type = cast<RecordRecTy>(TI->getType());
1875 TypeRecord = Type->getRecord();
1880 if (TypeRecord->isSubClassOf("RegisterOperand"))
1881 TypeRecord = TypeRecord->getValueAsDef("RegClass");
1882 if (TypeRecord->isSubClassOf("RegisterClass")) {
1883 Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
1885 } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) {
1886 Decoder = "DecodePointerLikeRegClass" +
1887 utostr(TypeRecord->getValueAsInt("RegClassKind"));
1891 DecoderString = TypeRecord->getValue("DecoderMethod");
1892 String = DecoderString ?
1893 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
1894 if (!isReg && String && String->getValue() != "")
1895 Decoder = String->getValue();
1897 RecordVal *HasCompleteDecoderVal =
1898 TypeRecord->getValue("hasCompleteDecoder");
1899 BitInit *HasCompleteDecoderBit = HasCompleteDecoderVal ?
1900 dyn_cast<BitInit>(HasCompleteDecoderVal->getValue()) : nullptr;
1901 bool HasCompleteDecoder = HasCompleteDecoderBit ?
1902 HasCompleteDecoderBit->getValue() : true;
1904 OperandInfo OpInfo(Decoder, HasCompleteDecoder);
1905 OpInfo.addField(bitStart, bitWidth, 0);
1907 NumberedInsnOperands[Name].push_back(OpInfo);
1909 // FIXME: For complex operands with custom decoders we can't handle tied
1910 // sub-operands automatically. Skip those here and assume that this is
1911 // fixed up elsewhere.
1912 if (CGI.Operands[SO.first].MIOperandInfo &&
1913 CGI.Operands[SO.first].MIOperandInfo->getNumArgs() > 1 &&
1914 String && String->getValue() != "")
1915 NumberedInsnOperandsNoTie.insert(Name);
1919 // For each operand, see if we can figure out where it is encoded.
1920 for (const auto &Op : InOutOperands) {
1921 if (!NumberedInsnOperands[Op.second].empty()) {
1922 InsnOperands.insert(InsnOperands.end(),
1923 NumberedInsnOperands[Op.second].begin(),
1924 NumberedInsnOperands[Op.second].end());
1927 if (!NumberedInsnOperands[TiedNames[Op.second]].empty()) {
1928 if (!NumberedInsnOperandsNoTie.count(TiedNames[Op.second])) {
1929 // Figure out to which (sub)operand we're tied.
1930 unsigned i = CGI.Operands.getOperandNamed(TiedNames[Op.second]);
1931 int tiedTo = CGI.Operands[i].getTiedRegister();
1933 i = CGI.Operands.getOperandNamed(Op.second);
1934 tiedTo = CGI.Operands[i].getTiedRegister();
1938 std::pair<unsigned, unsigned> SO =
1939 CGI.Operands.getSubOperandNumber(tiedTo);
1941 InsnOperands.push_back(NumberedInsnOperands[TiedNames[Op.second]]
1948 std::string Decoder = "";
1950 // At this point, we can locate the field, but we need to know how to
1951 // interpret it. As a first step, require the target to provide callbacks
1952 // for decoding register classes.
1953 // FIXME: This need to be extended to handle instructions with custom
1954 // decoder methods, and operands with (simple) MIOperandInfo's.
1955 TypedInit *TI = cast<TypedInit>(Op.first);
1956 RecordRecTy *Type = cast<RecordRecTy>(TI->getType());
1957 Record *TypeRecord = Type->getRecord();
1959 if (TypeRecord->isSubClassOf("RegisterOperand"))
1960 TypeRecord = TypeRecord->getValueAsDef("RegClass");
1961 if (TypeRecord->isSubClassOf("RegisterClass")) {
1962 Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
1964 } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) {
1965 Decoder = "DecodePointerLikeRegClass" +
1966 utostr(TypeRecord->getValueAsInt("RegClassKind"));
1970 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
1971 StringInit *String = DecoderString ?
1972 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
1973 if (!isReg && String && String->getValue() != "")
1974 Decoder = String->getValue();
1976 RecordVal *HasCompleteDecoderVal =
1977 TypeRecord->getValue("hasCompleteDecoder");
1978 BitInit *HasCompleteDecoderBit = HasCompleteDecoderVal ?
1979 dyn_cast<BitInit>(HasCompleteDecoderVal->getValue()) : nullptr;
1980 bool HasCompleteDecoder = HasCompleteDecoderBit ?
1981 HasCompleteDecoderBit->getValue() : true;
1983 OperandInfo OpInfo(Decoder, HasCompleteDecoder);
1984 unsigned Base = ~0U;
1986 unsigned Offset = 0;
1988 for (unsigned bi = 0; bi < Bits.getNumBits(); ++bi) {
1989 VarInit *Var = nullptr;
1990 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1992 Var = dyn_cast<VarInit>(BI->getBitVar());
1994 Var = dyn_cast<VarInit>(Bits.getBit(bi));
1998 OpInfo.addField(Base, Width, Offset);
2006 if (Var->getName() != Op.second &&
2007 Var->getName() != TiedNames[Op.second]) {
2009 OpInfo.addField(Base, Width, Offset);
2020 Offset = BI ? BI->getBitNum() : 0;
2021 } else if (BI && BI->getBitNum() != Offset + Width) {
2022 OpInfo.addField(Base, Width, Offset);
2025 Offset = BI->getBitNum();
2032 OpInfo.addField(Base, Width, Offset);
2034 if (OpInfo.numFields() > 0)
2035 InsnOperands.push_back(OpInfo);
2038 Operands[Opc] = InsnOperands;
2043 // Dumps the instruction encoding bits.
2044 dumpBits(errs(), Bits);
2048 // Dumps the list of operand info.
2049 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
2050 const CGIOperandList::OperandInfo &Info = CGI.Operands[i];
2051 const std::string &OperandName = Info.Name;
2052 const Record &OperandDef = *Info.Rec;
2054 errs() << "\t" << OperandName << " (" << OperandDef.getName() << ")\n";
2062 // emitFieldFromInstruction - Emit the templated helper function
2063 // fieldFromInstruction().
2064 static void emitFieldFromInstruction(formatted_raw_ostream &OS) {
2065 OS << "// Helper function for extracting fields from encoded instructions.\n"
2066 << "template<typename InsnType>\n"
2067 << "static InsnType fieldFromInstruction(InsnType insn, unsigned startBit,\n"
2068 << " unsigned numBits) {\n"
2069 << " assert(startBit + numBits <= (sizeof(InsnType)*8) &&\n"
2070 << " \"Instruction field out of bounds!\");\n"
2071 << " InsnType fieldMask;\n"
2072 << " if (numBits == sizeof(InsnType)*8)\n"
2073 << " fieldMask = (InsnType)(-1LL);\n"
2075 << " fieldMask = (((InsnType)1 << numBits) - 1) << startBit;\n"
2076 << " return (insn & fieldMask) >> startBit;\n"
2080 // emitDecodeInstruction - Emit the templated helper function
2081 // decodeInstruction().
2082 static void emitDecodeInstruction(formatted_raw_ostream &OS) {
2083 OS << "template<typename InsnType>\n"
2084 << "static DecodeStatus decodeInstruction(const uint8_t DecodeTable[], MCInst &MI,\n"
2085 << " InsnType insn, uint64_t Address,\n"
2086 << " const void *DisAsm,\n"
2087 << " const MCSubtargetInfo &STI) {\n"
2088 << " const FeatureBitset& Bits = STI.getFeatureBits();\n"
2090 << " const uint8_t *Ptr = DecodeTable;\n"
2091 << " uint32_t CurFieldValue = 0;\n"
2092 << " DecodeStatus S = MCDisassembler::Success;\n"
2094 << " ptrdiff_t Loc = Ptr - DecodeTable;\n"
2095 << " switch (*Ptr) {\n"
2097 << " errs() << Loc << \": Unexpected decode table opcode!\\n\";\n"
2098 << " return MCDisassembler::Fail;\n"
2099 << " case MCD::OPC_ExtractField: {\n"
2100 << " unsigned Start = *++Ptr;\n"
2101 << " unsigned Len = *++Ptr;\n"
2103 << " CurFieldValue = fieldFromInstruction(insn, Start, Len);\n"
2104 << " DEBUG(dbgs() << Loc << \": OPC_ExtractField(\" << Start << \", \"\n"
2105 << " << Len << \"): \" << CurFieldValue << \"\\n\");\n"
2108 << " case MCD::OPC_FilterValue: {\n"
2109 << " // Decode the field value.\n"
2110 << " unsigned Len;\n"
2111 << " InsnType Val = decodeULEB128(++Ptr, &Len);\n"
2113 << " // NumToSkip is a plain 16-bit integer.\n"
2114 << " unsigned NumToSkip = *Ptr++;\n"
2115 << " NumToSkip |= (*Ptr++) << 8;\n"
2117 << " // Perform the filter operation.\n"
2118 << " if (Val != CurFieldValue)\n"
2119 << " Ptr += NumToSkip;\n"
2120 << " DEBUG(dbgs() << Loc << \": OPC_FilterValue(\" << Val << \", \" << NumToSkip\n"
2121 << " << \"): \" << ((Val != CurFieldValue) ? \"FAIL:\" : \"PASS:\")\n"
2122 << " << \" continuing at \" << (Ptr - DecodeTable) << \"\\n\");\n"
2126 << " case MCD::OPC_CheckField: {\n"
2127 << " unsigned Start = *++Ptr;\n"
2128 << " unsigned Len = *++Ptr;\n"
2129 << " InsnType FieldValue = fieldFromInstruction(insn, Start, Len);\n"
2130 << " // Decode the field value.\n"
2131 << " uint32_t ExpectedValue = decodeULEB128(++Ptr, &Len);\n"
2133 << " // NumToSkip is a plain 16-bit integer.\n"
2134 << " unsigned NumToSkip = *Ptr++;\n"
2135 << " NumToSkip |= (*Ptr++) << 8;\n"
2137 << " // If the actual and expected values don't match, skip.\n"
2138 << " if (ExpectedValue != FieldValue)\n"
2139 << " Ptr += NumToSkip;\n"
2140 << " DEBUG(dbgs() << Loc << \": OPC_CheckField(\" << Start << \", \"\n"
2141 << " << Len << \", \" << ExpectedValue << \", \" << NumToSkip\n"
2142 << " << \"): FieldValue = \" << FieldValue << \", ExpectedValue = \"\n"
2143 << " << ExpectedValue << \": \"\n"
2144 << " << ((ExpectedValue == FieldValue) ? \"PASS\\n\" : \"FAIL\\n\"));\n"
2147 << " case MCD::OPC_CheckPredicate: {\n"
2148 << " unsigned Len;\n"
2149 << " // Decode the Predicate Index value.\n"
2150 << " unsigned PIdx = decodeULEB128(++Ptr, &Len);\n"
2152 << " // NumToSkip is a plain 16-bit integer.\n"
2153 << " unsigned NumToSkip = *Ptr++;\n"
2154 << " NumToSkip |= (*Ptr++) << 8;\n"
2155 << " // Check the predicate.\n"
2157 << " if (!(Pred = checkDecoderPredicate(PIdx, Bits)))\n"
2158 << " Ptr += NumToSkip;\n"
2160 << " DEBUG(dbgs() << Loc << \": OPC_CheckPredicate(\" << PIdx << \"): \"\n"
2161 << " << (Pred ? \"PASS\\n\" : \"FAIL\\n\"));\n"
2165 << " case MCD::OPC_Decode: {\n"
2166 << " unsigned Len;\n"
2167 << " // Decode the Opcode value.\n"
2168 << " unsigned Opc = decodeULEB128(++Ptr, &Len);\n"
2170 << " unsigned DecodeIdx = decodeULEB128(Ptr, &Len);\n"
2173 << " MI.setOpcode(Opc);\n"
2174 << " bool DecodeComplete;\n"
2175 << " S = decodeToMCInst(S, DecodeIdx, insn, MI, Address, DisAsm, DecodeComplete);\n"
2176 << " assert(DecodeComplete);\n"
2178 << " DEBUG(dbgs() << Loc << \": OPC_Decode: opcode \" << Opc\n"
2179 << " << \", using decoder \" << DecodeIdx << \": \"\n"
2180 << " << (S != MCDisassembler::Fail ? \"PASS\" : \"FAIL\") << \"\\n\");\n"
2183 << " case MCD::OPC_TryDecode: {\n"
2184 << " unsigned Len;\n"
2185 << " // Decode the Opcode value.\n"
2186 << " unsigned Opc = decodeULEB128(++Ptr, &Len);\n"
2188 << " unsigned DecodeIdx = decodeULEB128(Ptr, &Len);\n"
2190 << " // NumToSkip is a plain 16-bit integer.\n"
2191 << " unsigned NumToSkip = *Ptr++;\n"
2192 << " NumToSkip |= (*Ptr++) << 8;\n"
2194 << " // Perform the decode operation.\n"
2195 << " MCInst TmpMI;\n"
2196 << " TmpMI.setOpcode(Opc);\n"
2197 << " bool DecodeComplete;\n"
2198 << " S = decodeToMCInst(S, DecodeIdx, insn, TmpMI, Address, DisAsm, DecodeComplete);\n"
2199 << " DEBUG(dbgs() << Loc << \": OPC_TryDecode: opcode \" << Opc\n"
2200 << " << \", using decoder \" << DecodeIdx << \": \");\n"
2202 << " if (DecodeComplete) {\n"
2203 << " // Decoding complete.\n"
2204 << " DEBUG(dbgs() << (S != MCDisassembler::Fail ? \"PASS\" : \"FAIL\") << \"\\n\");\n"
2208 << " assert(S == MCDisassembler::Fail);\n"
2209 << " // If the decoding was incomplete, skip.\n"
2210 << " Ptr += NumToSkip;\n"
2211 << " DEBUG(dbgs() << \"FAIL: continuing at \" << (Ptr - DecodeTable) << \"\\n\");\n"
2212 << " // Reset decode status. This also drops a SoftFail status that could be\n"
2213 << " // set before the decode attempt.\n"
2214 << " S = MCDisassembler::Success;\n"
2218 << " case MCD::OPC_SoftFail: {\n"
2219 << " // Decode the mask values.\n"
2220 << " unsigned Len;\n"
2221 << " InsnType PositiveMask = decodeULEB128(++Ptr, &Len);\n"
2223 << " InsnType NegativeMask = decodeULEB128(Ptr, &Len);\n"
2225 << " bool Fail = (insn & PositiveMask) || (~insn & NegativeMask);\n"
2227 << " S = MCDisassembler::SoftFail;\n"
2228 << " DEBUG(dbgs() << Loc << \": OPC_SoftFail: \" << (Fail ? \"FAIL\\n\":\"PASS\\n\"));\n"
2231 << " case MCD::OPC_Fail: {\n"
2232 << " DEBUG(dbgs() << Loc << \": OPC_Fail\\n\");\n"
2233 << " return MCDisassembler::Fail;\n"
2237 << " llvm_unreachable(\"bogosity detected in disassembler state machine!\");\n"
2241 // Emits disassembler code for instruction decoding.
2242 void FixedLenDecoderEmitter::run(raw_ostream &o) {
2243 formatted_raw_ostream OS(o);
2244 OS << "#include \"llvm/MC/MCInst.h\"\n";
2245 OS << "#include \"llvm/Support/Debug.h\"\n";
2246 OS << "#include \"llvm/Support/DataTypes.h\"\n";
2247 OS << "#include \"llvm/Support/LEB128.h\"\n";
2248 OS << "#include \"llvm/Support/raw_ostream.h\"\n";
2249 OS << "#include <assert.h>\n";
2251 OS << "namespace llvm {\n\n";
2253 emitFieldFromInstruction(OS);
2255 Target.reverseBitsForLittleEndianEncoding();
2257 // Parameterize the decoders based on namespace and instruction width.
2258 NumberedInstructions = &Target.getInstructionsByEnumValue();
2259 std::map<std::pair<std::string, unsigned>,
2260 std::vector<unsigned> > OpcMap;
2261 std::map<unsigned, std::vector<OperandInfo> > Operands;
2263 for (unsigned i = 0; i < NumberedInstructions->size(); ++i) {
2264 const CodeGenInstruction *Inst = NumberedInstructions->at(i);
2265 const Record *Def = Inst->TheDef;
2266 unsigned Size = Def->getValueAsInt("Size");
2267 if (Def->getValueAsString("Namespace") == "TargetOpcode" ||
2268 Def->getValueAsBit("isPseudo") ||
2269 Def->getValueAsBit("isAsmParserOnly") ||
2270 Def->getValueAsBit("isCodeGenOnly"))
2273 std::string DecoderNamespace = Def->getValueAsString("DecoderNamespace");
2276 if (populateInstruction(Target, *Inst, i, Operands)) {
2277 OpcMap[std::make_pair(DecoderNamespace, Size)].push_back(i);
2282 DecoderTableInfo TableInfo;
2283 for (const auto &Opc : OpcMap) {
2284 // Emit the decoder for this namespace+width combination.
2285 FilterChooser FC(*NumberedInstructions, Opc.second, Operands,
2286 8*Opc.first.second, this);
2288 // The decode table is cleared for each top level decoder function. The
2289 // predicates and decoders themselves, however, are shared across all
2290 // decoders to give more opportunities for uniqueing.
2291 TableInfo.Table.clear();
2292 TableInfo.FixupStack.clear();
2293 TableInfo.Table.reserve(16384);
2294 TableInfo.FixupStack.emplace_back();
2295 FC.emitTableEntries(TableInfo);
2296 // Any NumToSkip fixups in the top level scope can resolve to the
2297 // OPC_Fail at the end of the table.
2298 assert(TableInfo.FixupStack.size() == 1 && "fixup stack phasing error!");
2299 // Resolve any NumToSkip fixups in the current scope.
2300 resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
2301 TableInfo.Table.size());
2302 TableInfo.FixupStack.clear();
2304 TableInfo.Table.push_back(MCD::OPC_Fail);
2306 // Print the table to the output stream.
2307 emitTable(OS, TableInfo.Table, 0, FC.getBitWidth(), Opc.first.first);
2311 // Emit the predicate function.
2312 emitPredicateFunction(OS, TableInfo.Predicates, 0);
2314 // Emit the decoder function.
2315 emitDecoderFunction(OS, TableInfo.Decoders, 0);
2317 // Emit the main entry point for the decoder, decodeInstruction().
2318 emitDecodeInstruction(OS);
2320 OS << "\n} // End llvm namespace\n";
2325 void EmitFixedLenDecoder(RecordKeeper &RK, raw_ostream &OS,
2326 std::string PredicateNamespace,
2327 std::string GPrefix,
2328 std::string GPostfix,
2332 FixedLenDecoderEmitter(RK, PredicateNamespace, GPrefix, GPostfix,
2333 ROK, RFail, L).run(OS);
2336 } // End llvm namespace