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);
1293 for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
1294 TableInfo.Table.push_back(MaskBytes[i]);
1296 TableInfo.Table.push_back(0);
1297 if (NeedNegativeMask) {
1299 encodeULEB128(NegativeMask.getZExtValue(), S);
1301 for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
1302 TableInfo.Table.push_back(MaskBytes[i]);
1304 TableInfo.Table.push_back(0);
1307 // Emits table entries to decode the singleton.
1308 void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1309 unsigned Opc) const {
1310 std::vector<unsigned> StartBits;
1311 std::vector<unsigned> EndBits;
1312 std::vector<uint64_t> FieldVals;
1314 insnWithID(Insn, Opc);
1316 // Look for islands of undecoded bits of the singleton.
1317 getIslands(StartBits, EndBits, FieldVals, Insn);
1319 unsigned Size = StartBits.size();
1321 // Emit the predicate table entry if one is needed.
1322 emitPredicateTableEntry(TableInfo, Opc);
1324 // Check any additional encoding fields needed.
1325 for (unsigned I = Size; I != 0; --I) {
1326 unsigned NumBits = EndBits[I-1] - StartBits[I-1] + 1;
1327 TableInfo.Table.push_back(MCD::OPC_CheckField);
1328 TableInfo.Table.push_back(StartBits[I-1]);
1329 TableInfo.Table.push_back(NumBits);
1330 uint8_t Buffer[8], *p;
1331 encodeULEB128(FieldVals[I-1], Buffer);
1332 for (p = Buffer; *p >= 128 ; ++p)
1333 TableInfo.Table.push_back(*p);
1334 TableInfo.Table.push_back(*p);
1335 // Push location for NumToSkip backpatching.
1336 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1337 // The fixup is always 16-bits, so go ahead and allocate the space
1338 // in the table so all our relative position calculations work OK even
1339 // before we fully resolve the real value here.
1340 TableInfo.Table.push_back(0);
1341 TableInfo.Table.push_back(0);
1344 // Check for soft failure of the match.
1345 emitSoftFailTableEntry(TableInfo, Opc);
1347 bool HasCompleteDecoder;
1348 unsigned DIdx = getDecoderIndex(TableInfo.Decoders, Opc, HasCompleteDecoder);
1350 // Produce OPC_Decode or OPC_TryDecode opcode based on the information
1351 // whether the instruction decoder is complete or not. If it is complete
1352 // then it handles all possible values of remaining variable/unfiltered bits
1353 // and for any value can determine if the bitpattern is a valid instruction
1354 // or not. This means OPC_Decode will be the final step in the decoding
1355 // process. If it is not complete, then the Fail return code from the
1356 // decoder method indicates that additional processing should be done to see
1357 // if there is any other instruction that also matches the bitpattern and
1359 TableInfo.Table.push_back(HasCompleteDecoder ? MCD::OPC_Decode :
1360 MCD::OPC_TryDecode);
1361 uint8_t Buffer[8], *p;
1362 encodeULEB128(Opc, Buffer);
1363 for (p = Buffer; *p >= 128 ; ++p)
1364 TableInfo.Table.push_back(*p);
1365 TableInfo.Table.push_back(*p);
1367 SmallString<16> Bytes;
1368 raw_svector_ostream S(Bytes);
1369 encodeULEB128(DIdx, S);
1373 for (unsigned i = 0, e = Bytes.size(); i != e; ++i)
1374 TableInfo.Table.push_back(Bytes[i]);
1376 if (!HasCompleteDecoder) {
1377 // Push location for NumToSkip backpatching.
1378 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1379 // Allocate the space for the fixup.
1380 TableInfo.Table.push_back(0);
1381 TableInfo.Table.push_back(0);
1385 // Emits table entries to decode the singleton, and then to decode the rest.
1386 void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1387 const Filter &Best) const {
1388 unsigned Opc = Best.getSingletonOpc();
1390 // complex singletons need predicate checks from the first singleton
1391 // to refer forward to the variable filterchooser that follows.
1392 TableInfo.FixupStack.emplace_back();
1394 emitSingletonTableEntry(TableInfo, Opc);
1396 resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
1397 TableInfo.Table.size());
1398 TableInfo.FixupStack.pop_back();
1400 Best.getVariableFC().emitTableEntries(TableInfo);
1404 // Assign a single filter and run with it. Top level API client can initialize
1405 // with a single filter to start the filtering process.
1406 void FilterChooser::runSingleFilter(unsigned startBit, unsigned numBit,
1409 Filters.emplace_back(*this, startBit, numBit, true);
1410 BestIndex = 0; // Sole Filter instance to choose from.
1411 bestFilter().recurse();
1414 // reportRegion is a helper function for filterProcessor to mark a region as
1415 // eligible for use as a filter region.
1416 void FilterChooser::reportRegion(bitAttr_t RA, unsigned StartBit,
1417 unsigned BitIndex, bool AllowMixed) {
1418 if (RA == ATTR_MIXED && AllowMixed)
1419 Filters.emplace_back(*this, StartBit, BitIndex - StartBit, true);
1420 else if (RA == ATTR_ALL_SET && !AllowMixed)
1421 Filters.emplace_back(*this, StartBit, BitIndex - StartBit, false);
1424 // FilterProcessor scans the well-known encoding bits of the instructions and
1425 // builds up a list of candidate filters. It chooses the best filter and
1426 // recursively descends down the decoding tree.
1427 bool FilterChooser::filterProcessor(bool AllowMixed, bool Greedy) {
1430 unsigned numInstructions = Opcodes.size();
1432 assert(numInstructions && "Filter created with no instructions");
1434 // No further filtering is necessary.
1435 if (numInstructions == 1)
1438 // Heuristics. See also doFilter()'s "Heuristics" comment when num of
1439 // instructions is 3.
1440 if (AllowMixed && !Greedy) {
1441 assert(numInstructions == 3);
1443 for (unsigned i = 0; i < Opcodes.size(); ++i) {
1444 std::vector<unsigned> StartBits;
1445 std::vector<unsigned> EndBits;
1446 std::vector<uint64_t> FieldVals;
1449 insnWithID(Insn, Opcodes[i]);
1451 // Look for islands of undecoded bits of any instruction.
1452 if (getIslands(StartBits, EndBits, FieldVals, Insn) > 0) {
1453 // Found an instruction with island(s). Now just assign a filter.
1454 runSingleFilter(StartBits[0], EndBits[0] - StartBits[0] + 1, true);
1462 // We maintain BIT_WIDTH copies of the bitAttrs automaton.
1463 // The automaton consumes the corresponding bit from each
1466 // Input symbols: 0, 1, and _ (unset).
1467 // States: NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED.
1468 // Initial state: NONE.
1470 // (NONE) ------- [01] -> (ALL_SET)
1471 // (NONE) ------- _ ----> (ALL_UNSET)
1472 // (ALL_SET) ---- [01] -> (ALL_SET)
1473 // (ALL_SET) ---- _ ----> (MIXED)
1474 // (ALL_UNSET) -- [01] -> (MIXED)
1475 // (ALL_UNSET) -- _ ----> (ALL_UNSET)
1476 // (MIXED) ------ . ----> (MIXED)
1477 // (FILTERED)---- . ----> (FILTERED)
1479 std::vector<bitAttr_t> bitAttrs;
1481 // FILTERED bit positions provide no entropy and are not worthy of pursuing.
1482 // Filter::recurse() set either BIT_TRUE or BIT_FALSE for each position.
1483 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex)
1484 if (FilterBitValues[BitIndex] == BIT_TRUE ||
1485 FilterBitValues[BitIndex] == BIT_FALSE)
1486 bitAttrs.push_back(ATTR_FILTERED);
1488 bitAttrs.push_back(ATTR_NONE);
1490 for (unsigned InsnIndex = 0; InsnIndex < numInstructions; ++InsnIndex) {
1493 insnWithID(insn, Opcodes[InsnIndex]);
1495 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
1496 switch (bitAttrs[BitIndex]) {
1498 if (insn[BitIndex] == BIT_UNSET)
1499 bitAttrs[BitIndex] = ATTR_ALL_UNSET;
1501 bitAttrs[BitIndex] = ATTR_ALL_SET;
1504 if (insn[BitIndex] == BIT_UNSET)
1505 bitAttrs[BitIndex] = ATTR_MIXED;
1507 case ATTR_ALL_UNSET:
1508 if (insn[BitIndex] != BIT_UNSET)
1509 bitAttrs[BitIndex] = ATTR_MIXED;
1518 // The regionAttr automaton consumes the bitAttrs automatons' state,
1519 // lowest-to-highest.
1521 // Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed)
1522 // States: NONE, ALL_SET, MIXED
1523 // Initial state: NONE
1525 // (NONE) ----- F --> (NONE)
1526 // (NONE) ----- S --> (ALL_SET) ; and set region start
1527 // (NONE) ----- U --> (NONE)
1528 // (NONE) ----- M --> (MIXED) ; and set region start
1529 // (ALL_SET) -- F --> (NONE) ; and report an ALL_SET region
1530 // (ALL_SET) -- S --> (ALL_SET)
1531 // (ALL_SET) -- U --> (NONE) ; and report an ALL_SET region
1532 // (ALL_SET) -- M --> (MIXED) ; and report an ALL_SET region
1533 // (MIXED) ---- F --> (NONE) ; and report a MIXED region
1534 // (MIXED) ---- S --> (ALL_SET) ; and report a MIXED region
1535 // (MIXED) ---- U --> (NONE) ; and report a MIXED region
1536 // (MIXED) ---- M --> (MIXED)
1538 bitAttr_t RA = ATTR_NONE;
1539 unsigned StartBit = 0;
1541 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
1542 bitAttr_t bitAttr = bitAttrs[BitIndex];
1544 assert(bitAttr != ATTR_NONE && "Bit without attributes");
1552 StartBit = BitIndex;
1555 case ATTR_ALL_UNSET:
1558 StartBit = BitIndex;
1562 llvm_unreachable("Unexpected bitAttr!");
1568 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1573 case ATTR_ALL_UNSET:
1574 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1578 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1579 StartBit = BitIndex;
1583 llvm_unreachable("Unexpected bitAttr!");
1589 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1590 StartBit = BitIndex;
1594 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1595 StartBit = BitIndex;
1598 case ATTR_ALL_UNSET:
1599 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1605 llvm_unreachable("Unexpected bitAttr!");
1608 case ATTR_ALL_UNSET:
1609 llvm_unreachable("regionAttr state machine has no ATTR_UNSET state");
1611 llvm_unreachable("regionAttr state machine has no ATTR_FILTERED state");
1615 // At the end, if we're still in ALL_SET or MIXED states, report a region
1622 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1624 case ATTR_ALL_UNSET:
1627 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1631 // We have finished with the filter processings. Now it's time to choose
1632 // the best performing filter.
1634 bool AllUseless = true;
1635 unsigned BestScore = 0;
1637 for (unsigned i = 0, e = Filters.size(); i != e; ++i) {
1638 unsigned Usefulness = Filters[i].usefulness();
1643 if (Usefulness > BestScore) {
1645 BestScore = Usefulness;
1650 bestFilter().recurse();
1653 } // end of FilterChooser::filterProcessor(bool)
1655 // Decides on the best configuration of filter(s) to use in order to decode
1656 // the instructions. A conflict of instructions may occur, in which case we
1657 // dump the conflict set to the standard error.
1658 void FilterChooser::doFilter() {
1659 unsigned Num = Opcodes.size();
1660 assert(Num && "FilterChooser created with no instructions");
1662 // Try regions of consecutive known bit values first.
1663 if (filterProcessor(false))
1666 // Then regions of mixed bits (both known and unitialized bit values allowed).
1667 if (filterProcessor(true))
1670 // Heuristics to cope with conflict set {t2CMPrs, t2SUBSrr, t2SUBSrs} where
1671 // no single instruction for the maximum ATTR_MIXED region Inst{14-4} has a
1672 // well-known encoding pattern. In such case, we backtrack and scan for the
1673 // the very first consecutive ATTR_ALL_SET region and assign a filter to it.
1674 if (Num == 3 && filterProcessor(true, false))
1677 // If we come to here, the instruction decoding has failed.
1678 // Set the BestIndex to -1 to indicate so.
1682 // emitTableEntries - Emit state machine entries to decode our share of
1684 void FilterChooser::emitTableEntries(DecoderTableInfo &TableInfo) const {
1685 if (Opcodes.size() == 1) {
1686 // There is only one instruction in the set, which is great!
1687 // Call emitSingletonDecoder() to see whether there are any remaining
1689 emitSingletonTableEntry(TableInfo, Opcodes[0]);
1693 // Choose the best filter to do the decodings!
1694 if (BestIndex != -1) {
1695 const Filter &Best = Filters[BestIndex];
1696 if (Best.getNumFiltered() == 1)
1697 emitSingletonTableEntry(TableInfo, Best);
1699 Best.emitTableEntry(TableInfo);
1703 // We don't know how to decode these instructions! Dump the
1704 // conflict set and bail.
1706 // Print out useful conflict information for postmortem analysis.
1707 errs() << "Decoding Conflict:\n";
1709 dumpStack(errs(), "\t\t");
1711 for (unsigned i = 0; i < Opcodes.size(); ++i) {
1712 const std::string &Name = nameWithID(Opcodes[i]);
1714 errs() << '\t' << Name << " ";
1716 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
1721 static bool populateInstruction(CodeGenTarget &Target,
1722 const CodeGenInstruction &CGI, unsigned Opc,
1723 std::map<unsigned, std::vector<OperandInfo> > &Operands){
1724 const Record &Def = *CGI.TheDef;
1725 // If all the bit positions are not specified; do not decode this instruction.
1726 // We are bound to fail! For proper disassembly, the well-known encoding bits
1727 // of the instruction must be fully specified.
1729 BitsInit &Bits = getBitsField(Def, "Inst");
1730 if (Bits.allInComplete()) return false;
1732 std::vector<OperandInfo> InsnOperands;
1734 // If the instruction has specified a custom decoding hook, use that instead
1735 // of trying to auto-generate the decoder.
1736 std::string InstDecoder = Def.getValueAsString("DecoderMethod");
1737 if (InstDecoder != "") {
1738 bool HasCompleteInstDecoder = Def.getValueAsBit("hasCompleteDecoder");
1739 InsnOperands.push_back(OperandInfo(InstDecoder, HasCompleteInstDecoder));
1740 Operands[Opc] = InsnOperands;
1744 // Generate a description of the operand of the instruction that we know
1745 // how to decode automatically.
1746 // FIXME: We'll need to have a way to manually override this as needed.
1748 // Gather the outputs/inputs of the instruction, so we can find their
1749 // positions in the encoding. This assumes for now that they appear in the
1750 // MCInst in the order that they're listed.
1751 std::vector<std::pair<Init*, std::string> > InOutOperands;
1752 DagInit *Out = Def.getValueAsDag("OutOperandList");
1753 DagInit *In = Def.getValueAsDag("InOperandList");
1754 for (unsigned i = 0; i < Out->getNumArgs(); ++i)
1755 InOutOperands.push_back(std::make_pair(Out->getArg(i), Out->getArgName(i)));
1756 for (unsigned i = 0; i < In->getNumArgs(); ++i)
1757 InOutOperands.push_back(std::make_pair(In->getArg(i), In->getArgName(i)));
1759 // Search for tied operands, so that we can correctly instantiate
1760 // operands that are not explicitly represented in the encoding.
1761 std::map<std::string, std::string> TiedNames;
1762 for (unsigned i = 0; i < CGI.Operands.size(); ++i) {
1763 int tiedTo = CGI.Operands[i].getTiedRegister();
1765 std::pair<unsigned, unsigned> SO =
1766 CGI.Operands.getSubOperandNumber(tiedTo);
1767 TiedNames[InOutOperands[i].second] = InOutOperands[SO.first].second;
1768 TiedNames[InOutOperands[SO.first].second] = InOutOperands[i].second;
1772 std::map<std::string, std::vector<OperandInfo> > NumberedInsnOperands;
1773 std::set<std::string> NumberedInsnOperandsNoTie;
1774 if (Target.getInstructionSet()->
1775 getValueAsBit("decodePositionallyEncodedOperands")) {
1776 const std::vector<RecordVal> &Vals = Def.getValues();
1777 unsigned NumberedOp = 0;
1779 std::set<unsigned> NamedOpIndices;
1780 if (Target.getInstructionSet()->
1781 getValueAsBit("noNamedPositionallyEncodedOperands"))
1782 // Collect the set of operand indices that might correspond to named
1783 // operand, and skip these when assigning operands based on position.
1784 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1786 if (!CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
1789 NamedOpIndices.insert(OpIdx);
1792 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1793 // Ignore fixed fields in the record, we're looking for values like:
1794 // bits<5> RST = { ?, ?, ?, ?, ? };
1795 if (Vals[i].getPrefix() || Vals[i].getValue()->isComplete())
1798 // Determine if Vals[i] actually contributes to the Inst encoding.
1800 for (; bi < Bits.getNumBits(); ++bi) {
1801 VarInit *Var = nullptr;
1802 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1804 Var = dyn_cast<VarInit>(BI->getBitVar());
1806 Var = dyn_cast<VarInit>(Bits.getBit(bi));
1808 if (Var && Var->getName() == Vals[i].getName())
1812 if (bi == Bits.getNumBits())
1815 // Skip variables that correspond to explicitly-named operands.
1817 if (CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
1820 // Get the bit range for this operand:
1821 unsigned bitStart = bi++, bitWidth = 1;
1822 for (; bi < Bits.getNumBits(); ++bi) {
1823 VarInit *Var = nullptr;
1824 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1826 Var = dyn_cast<VarInit>(BI->getBitVar());
1828 Var = dyn_cast<VarInit>(Bits.getBit(bi));
1833 if (Var->getName() != Vals[i].getName())
1839 unsigned NumberOps = CGI.Operands.size();
1840 while (NumberedOp < NumberOps &&
1841 (CGI.Operands.isFlatOperandNotEmitted(NumberedOp) ||
1842 (!NamedOpIndices.empty() && NamedOpIndices.count(
1843 CGI.Operands.getSubOperandNumber(NumberedOp).first))))
1846 OpIdx = NumberedOp++;
1848 // OpIdx now holds the ordered operand number of Vals[i].
1849 std::pair<unsigned, unsigned> SO =
1850 CGI.Operands.getSubOperandNumber(OpIdx);
1851 const std::string &Name = CGI.Operands[SO.first].Name;
1853 DEBUG(dbgs() << "Numbered operand mapping for " << Def.getName() << ": " <<
1854 Name << "(" << SO.first << ", " << SO.second << ") => " <<
1855 Vals[i].getName() << "\n");
1857 std::string Decoder = "";
1858 Record *TypeRecord = CGI.Operands[SO.first].Rec;
1860 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
1861 StringInit *String = DecoderString ?
1862 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
1863 if (String && String->getValue() != "")
1864 Decoder = String->getValue();
1866 if (Decoder == "" &&
1867 CGI.Operands[SO.first].MIOperandInfo &&
1868 CGI.Operands[SO.first].MIOperandInfo->getNumArgs()) {
1869 Init *Arg = CGI.Operands[SO.first].MIOperandInfo->
1871 if (TypedInit *TI = cast<TypedInit>(Arg)) {
1872 RecordRecTy *Type = cast<RecordRecTy>(TI->getType());
1873 TypeRecord = Type->getRecord();
1878 if (TypeRecord->isSubClassOf("RegisterOperand"))
1879 TypeRecord = TypeRecord->getValueAsDef("RegClass");
1880 if (TypeRecord->isSubClassOf("RegisterClass")) {
1881 Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
1883 } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) {
1884 Decoder = "DecodePointerLikeRegClass" +
1885 utostr(TypeRecord->getValueAsInt("RegClassKind"));
1889 DecoderString = TypeRecord->getValue("DecoderMethod");
1890 String = DecoderString ?
1891 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
1892 if (!isReg && String && String->getValue() != "")
1893 Decoder = String->getValue();
1895 RecordVal *HasCompleteDecoderVal =
1896 TypeRecord->getValue("hasCompleteDecoder");
1897 BitInit *HasCompleteDecoderBit = HasCompleteDecoderVal ?
1898 dyn_cast<BitInit>(HasCompleteDecoderVal->getValue()) : nullptr;
1899 bool HasCompleteDecoder = HasCompleteDecoderBit ?
1900 HasCompleteDecoderBit->getValue() : true;
1902 OperandInfo OpInfo(Decoder, HasCompleteDecoder);
1903 OpInfo.addField(bitStart, bitWidth, 0);
1905 NumberedInsnOperands[Name].push_back(OpInfo);
1907 // FIXME: For complex operands with custom decoders we can't handle tied
1908 // sub-operands automatically. Skip those here and assume that this is
1909 // fixed up elsewhere.
1910 if (CGI.Operands[SO.first].MIOperandInfo &&
1911 CGI.Operands[SO.first].MIOperandInfo->getNumArgs() > 1 &&
1912 String && String->getValue() != "")
1913 NumberedInsnOperandsNoTie.insert(Name);
1917 // For each operand, see if we can figure out where it is encoded.
1918 for (const auto &Op : InOutOperands) {
1919 if (!NumberedInsnOperands[Op.second].empty()) {
1920 InsnOperands.insert(InsnOperands.end(),
1921 NumberedInsnOperands[Op.second].begin(),
1922 NumberedInsnOperands[Op.second].end());
1925 if (!NumberedInsnOperands[TiedNames[Op.second]].empty()) {
1926 if (!NumberedInsnOperandsNoTie.count(TiedNames[Op.second])) {
1927 // Figure out to which (sub)operand we're tied.
1928 unsigned i = CGI.Operands.getOperandNamed(TiedNames[Op.second]);
1929 int tiedTo = CGI.Operands[i].getTiedRegister();
1931 i = CGI.Operands.getOperandNamed(Op.second);
1932 tiedTo = CGI.Operands[i].getTiedRegister();
1936 std::pair<unsigned, unsigned> SO =
1937 CGI.Operands.getSubOperandNumber(tiedTo);
1939 InsnOperands.push_back(NumberedInsnOperands[TiedNames[Op.second]]
1946 std::string Decoder = "";
1948 // At this point, we can locate the field, but we need to know how to
1949 // interpret it. As a first step, require the target to provide callbacks
1950 // for decoding register classes.
1951 // FIXME: This need to be extended to handle instructions with custom
1952 // decoder methods, and operands with (simple) MIOperandInfo's.
1953 TypedInit *TI = cast<TypedInit>(Op.first);
1954 RecordRecTy *Type = cast<RecordRecTy>(TI->getType());
1955 Record *TypeRecord = Type->getRecord();
1957 if (TypeRecord->isSubClassOf("RegisterOperand"))
1958 TypeRecord = TypeRecord->getValueAsDef("RegClass");
1959 if (TypeRecord->isSubClassOf("RegisterClass")) {
1960 Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
1962 } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) {
1963 Decoder = "DecodePointerLikeRegClass" +
1964 utostr(TypeRecord->getValueAsInt("RegClassKind"));
1968 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
1969 StringInit *String = DecoderString ?
1970 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
1971 if (!isReg && String && String->getValue() != "")
1972 Decoder = String->getValue();
1974 RecordVal *HasCompleteDecoderVal =
1975 TypeRecord->getValue("hasCompleteDecoder");
1976 BitInit *HasCompleteDecoderBit = HasCompleteDecoderVal ?
1977 dyn_cast<BitInit>(HasCompleteDecoderVal->getValue()) : nullptr;
1978 bool HasCompleteDecoder = HasCompleteDecoderBit ?
1979 HasCompleteDecoderBit->getValue() : true;
1981 OperandInfo OpInfo(Decoder, HasCompleteDecoder);
1982 unsigned Base = ~0U;
1984 unsigned Offset = 0;
1986 for (unsigned bi = 0; bi < Bits.getNumBits(); ++bi) {
1987 VarInit *Var = nullptr;
1988 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1990 Var = dyn_cast<VarInit>(BI->getBitVar());
1992 Var = dyn_cast<VarInit>(Bits.getBit(bi));
1996 OpInfo.addField(Base, Width, Offset);
2004 if (Var->getName() != Op.second &&
2005 Var->getName() != TiedNames[Op.second]) {
2007 OpInfo.addField(Base, Width, Offset);
2018 Offset = BI ? BI->getBitNum() : 0;
2019 } else if (BI && BI->getBitNum() != Offset + Width) {
2020 OpInfo.addField(Base, Width, Offset);
2023 Offset = BI->getBitNum();
2030 OpInfo.addField(Base, Width, Offset);
2032 if (OpInfo.numFields() > 0)
2033 InsnOperands.push_back(OpInfo);
2036 Operands[Opc] = InsnOperands;
2041 // Dumps the instruction encoding bits.
2042 dumpBits(errs(), Bits);
2046 // Dumps the list of operand info.
2047 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
2048 const CGIOperandList::OperandInfo &Info = CGI.Operands[i];
2049 const std::string &OperandName = Info.Name;
2050 const Record &OperandDef = *Info.Rec;
2052 errs() << "\t" << OperandName << " (" << OperandDef.getName() << ")\n";
2060 // emitFieldFromInstruction - Emit the templated helper function
2061 // fieldFromInstruction().
2062 static void emitFieldFromInstruction(formatted_raw_ostream &OS) {
2063 OS << "// Helper function for extracting fields from encoded instructions.\n"
2064 << "template<typename InsnType>\n"
2065 << "static InsnType fieldFromInstruction(InsnType insn, unsigned startBit,\n"
2066 << " unsigned numBits) {\n"
2067 << " assert(startBit + numBits <= (sizeof(InsnType)*8) &&\n"
2068 << " \"Instruction field out of bounds!\");\n"
2069 << " InsnType fieldMask;\n"
2070 << " if (numBits == sizeof(InsnType)*8)\n"
2071 << " fieldMask = (InsnType)(-1LL);\n"
2073 << " fieldMask = (((InsnType)1 << numBits) - 1) << startBit;\n"
2074 << " return (insn & fieldMask) >> startBit;\n"
2078 // emitDecodeInstruction - Emit the templated helper function
2079 // decodeInstruction().
2080 static void emitDecodeInstruction(formatted_raw_ostream &OS) {
2081 OS << "template<typename InsnType>\n"
2082 << "static DecodeStatus decodeInstruction(const uint8_t DecodeTable[], MCInst &MI,\n"
2083 << " InsnType insn, uint64_t Address,\n"
2084 << " const void *DisAsm,\n"
2085 << " const MCSubtargetInfo &STI) {\n"
2086 << " const FeatureBitset& Bits = STI.getFeatureBits();\n"
2088 << " const uint8_t *Ptr = DecodeTable;\n"
2089 << " uint32_t CurFieldValue = 0;\n"
2090 << " DecodeStatus S = MCDisassembler::Success;\n"
2092 << " ptrdiff_t Loc = Ptr - DecodeTable;\n"
2093 << " switch (*Ptr) {\n"
2095 << " errs() << Loc << \": Unexpected decode table opcode!\\n\";\n"
2096 << " return MCDisassembler::Fail;\n"
2097 << " case MCD::OPC_ExtractField: {\n"
2098 << " unsigned Start = *++Ptr;\n"
2099 << " unsigned Len = *++Ptr;\n"
2101 << " CurFieldValue = fieldFromInstruction(insn, Start, Len);\n"
2102 << " DEBUG(dbgs() << Loc << \": OPC_ExtractField(\" << Start << \", \"\n"
2103 << " << Len << \"): \" << CurFieldValue << \"\\n\");\n"
2106 << " case MCD::OPC_FilterValue: {\n"
2107 << " // Decode the field value.\n"
2108 << " unsigned Len;\n"
2109 << " InsnType Val = decodeULEB128(++Ptr, &Len);\n"
2111 << " // NumToSkip is a plain 16-bit integer.\n"
2112 << " unsigned NumToSkip = *Ptr++;\n"
2113 << " NumToSkip |= (*Ptr++) << 8;\n"
2115 << " // Perform the filter operation.\n"
2116 << " if (Val != CurFieldValue)\n"
2117 << " Ptr += NumToSkip;\n"
2118 << " DEBUG(dbgs() << Loc << \": OPC_FilterValue(\" << Val << \", \" << NumToSkip\n"
2119 << " << \"): \" << ((Val != CurFieldValue) ? \"FAIL:\" : \"PASS:\")\n"
2120 << " << \" continuing at \" << (Ptr - DecodeTable) << \"\\n\");\n"
2124 << " case MCD::OPC_CheckField: {\n"
2125 << " unsigned Start = *++Ptr;\n"
2126 << " unsigned Len = *++Ptr;\n"
2127 << " InsnType FieldValue = fieldFromInstruction(insn, Start, Len);\n"
2128 << " // Decode the field value.\n"
2129 << " uint32_t ExpectedValue = decodeULEB128(++Ptr, &Len);\n"
2131 << " // NumToSkip is a plain 16-bit integer.\n"
2132 << " unsigned NumToSkip = *Ptr++;\n"
2133 << " NumToSkip |= (*Ptr++) << 8;\n"
2135 << " // If the actual and expected values don't match, skip.\n"
2136 << " if (ExpectedValue != FieldValue)\n"
2137 << " Ptr += NumToSkip;\n"
2138 << " DEBUG(dbgs() << Loc << \": OPC_CheckField(\" << Start << \", \"\n"
2139 << " << Len << \", \" << ExpectedValue << \", \" << NumToSkip\n"
2140 << " << \"): FieldValue = \" << FieldValue << \", ExpectedValue = \"\n"
2141 << " << ExpectedValue << \": \"\n"
2142 << " << ((ExpectedValue == FieldValue) ? \"PASS\\n\" : \"FAIL\\n\"));\n"
2145 << " case MCD::OPC_CheckPredicate: {\n"
2146 << " unsigned Len;\n"
2147 << " // Decode the Predicate Index value.\n"
2148 << " unsigned PIdx = decodeULEB128(++Ptr, &Len);\n"
2150 << " // NumToSkip is a plain 16-bit integer.\n"
2151 << " unsigned NumToSkip = *Ptr++;\n"
2152 << " NumToSkip |= (*Ptr++) << 8;\n"
2153 << " // Check the predicate.\n"
2155 << " if (!(Pred = checkDecoderPredicate(PIdx, Bits)))\n"
2156 << " Ptr += NumToSkip;\n"
2158 << " DEBUG(dbgs() << Loc << \": OPC_CheckPredicate(\" << PIdx << \"): \"\n"
2159 << " << (Pred ? \"PASS\\n\" : \"FAIL\\n\"));\n"
2163 << " case MCD::OPC_Decode: {\n"
2164 << " unsigned Len;\n"
2165 << " // Decode the Opcode value.\n"
2166 << " unsigned Opc = decodeULEB128(++Ptr, &Len);\n"
2168 << " unsigned DecodeIdx = decodeULEB128(Ptr, &Len);\n"
2172 << " MI.setOpcode(Opc);\n"
2173 << " bool DecodeComplete;\n"
2174 << " S = decodeToMCInst(S, DecodeIdx, insn, MI, Address, DisAsm, DecodeComplete);\n"
2175 << " assert(DecodeComplete);\n"
2177 << " DEBUG(dbgs() << Loc << \": OPC_Decode: opcode \" << Opc\n"
2178 << " << \", using decoder \" << DecodeIdx << \": \"\n"
2179 << " << (S != MCDisassembler::Fail ? \"PASS\" : \"FAIL\") << \"\\n\");\n"
2182 << " case MCD::OPC_TryDecode: {\n"
2183 << " unsigned Len;\n"
2184 << " // Decode the Opcode value.\n"
2185 << " unsigned Opc = decodeULEB128(++Ptr, &Len);\n"
2187 << " unsigned DecodeIdx = decodeULEB128(Ptr, &Len);\n"
2189 << " // NumToSkip is a plain 16-bit integer.\n"
2190 << " unsigned NumToSkip = *Ptr++;\n"
2191 << " NumToSkip |= (*Ptr++) << 8;\n"
2193 << " // Perform the decode operation.\n"
2194 << " MCInst TmpMI;\n"
2195 << " TmpMI.setOpcode(Opc);\n"
2196 << " bool DecodeComplete;\n"
2197 << " S = decodeToMCInst(S, DecodeIdx, insn, TmpMI, Address, DisAsm, DecodeComplete);\n"
2198 << " DEBUG(dbgs() << Loc << \": OPC_TryDecode: opcode \" << Opc\n"
2199 << " << \", using decoder \" << DecodeIdx << \": \");\n"
2201 << " if (DecodeComplete) {\n"
2202 << " // Decoding complete.\n"
2203 << " DEBUG(dbgs() << (S != MCDisassembler::Fail ? \"PASS\" : \"FAIL\") << \"\\n\");\n"
2207 << " assert(S == MCDisassembler::Fail);\n"
2208 << " // If the decoding was incomplete, skip.\n"
2209 << " Ptr += NumToSkip;\n"
2210 << " DEBUG(dbgs() << \"FAIL: continuing at \" << (Ptr - DecodeTable) << \"\\n\");\n"
2211 << " // Reset decode status. This also drops a SoftFail status that could be\n"
2212 << " // set before the decode attempt.\n"
2213 << " S = MCDisassembler::Success;\n"
2217 << " case MCD::OPC_SoftFail: {\n"
2218 << " // Decode the mask values.\n"
2219 << " unsigned Len;\n"
2220 << " InsnType PositiveMask = decodeULEB128(++Ptr, &Len);\n"
2222 << " InsnType NegativeMask = decodeULEB128(Ptr, &Len);\n"
2224 << " bool Fail = (insn & PositiveMask) || (~insn & NegativeMask);\n"
2226 << " S = MCDisassembler::SoftFail;\n"
2227 << " DEBUG(dbgs() << Loc << \": OPC_SoftFail: \" << (Fail ? \"FAIL\\n\":\"PASS\\n\"));\n"
2230 << " case MCD::OPC_Fail: {\n"
2231 << " DEBUG(dbgs() << Loc << \": OPC_Fail\\n\");\n"
2232 << " return MCDisassembler::Fail;\n"
2236 << " llvm_unreachable(\"bogosity detected in disassembler state machine!\");\n"
2240 // Emits disassembler code for instruction decoding.
2241 void FixedLenDecoderEmitter::run(raw_ostream &o) {
2242 formatted_raw_ostream OS(o);
2243 OS << "#include \"llvm/MC/MCInst.h\"\n";
2244 OS << "#include \"llvm/Support/Debug.h\"\n";
2245 OS << "#include \"llvm/Support/DataTypes.h\"\n";
2246 OS << "#include \"llvm/Support/LEB128.h\"\n";
2247 OS << "#include \"llvm/Support/raw_ostream.h\"\n";
2248 OS << "#include <assert.h>\n";
2250 OS << "namespace llvm {\n\n";
2252 emitFieldFromInstruction(OS);
2254 Target.reverseBitsForLittleEndianEncoding();
2256 // Parameterize the decoders based on namespace and instruction width.
2257 NumberedInstructions = &Target.getInstructionsByEnumValue();
2258 std::map<std::pair<std::string, unsigned>,
2259 std::vector<unsigned> > OpcMap;
2260 std::map<unsigned, std::vector<OperandInfo> > Operands;
2262 for (unsigned i = 0; i < NumberedInstructions->size(); ++i) {
2263 const CodeGenInstruction *Inst = NumberedInstructions->at(i);
2264 const Record *Def = Inst->TheDef;
2265 unsigned Size = Def->getValueAsInt("Size");
2266 if (Def->getValueAsString("Namespace") == "TargetOpcode" ||
2267 Def->getValueAsBit("isPseudo") ||
2268 Def->getValueAsBit("isAsmParserOnly") ||
2269 Def->getValueAsBit("isCodeGenOnly"))
2272 std::string DecoderNamespace = Def->getValueAsString("DecoderNamespace");
2275 if (populateInstruction(Target, *Inst, i, Operands)) {
2276 OpcMap[std::make_pair(DecoderNamespace, Size)].push_back(i);
2281 DecoderTableInfo TableInfo;
2282 for (const auto &Opc : OpcMap) {
2283 // Emit the decoder for this namespace+width combination.
2284 FilterChooser FC(*NumberedInstructions, Opc.second, Operands,
2285 8*Opc.first.second, this);
2287 // The decode table is cleared for each top level decoder function. The
2288 // predicates and decoders themselves, however, are shared across all
2289 // decoders to give more opportunities for uniqueing.
2290 TableInfo.Table.clear();
2291 TableInfo.FixupStack.clear();
2292 TableInfo.Table.reserve(16384);
2293 TableInfo.FixupStack.emplace_back();
2294 FC.emitTableEntries(TableInfo);
2295 // Any NumToSkip fixups in the top level scope can resolve to the
2296 // OPC_Fail at the end of the table.
2297 assert(TableInfo.FixupStack.size() == 1 && "fixup stack phasing error!");
2298 // Resolve any NumToSkip fixups in the current scope.
2299 resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
2300 TableInfo.Table.size());
2301 TableInfo.FixupStack.clear();
2303 TableInfo.Table.push_back(MCD::OPC_Fail);
2305 // Print the table to the output stream.
2306 emitTable(OS, TableInfo.Table, 0, FC.getBitWidth(), Opc.first.first);
2310 // Emit the predicate function.
2311 emitPredicateFunction(OS, TableInfo.Predicates, 0);
2313 // Emit the decoder function.
2314 emitDecoderFunction(OS, TableInfo.Decoders, 0);
2316 // Emit the main entry point for the decoder, decodeInstruction().
2317 emitDecodeInstruction(OS);
2319 OS << "\n} // End llvm namespace\n";
2324 void EmitFixedLenDecoder(RecordKeeper &RK, raw_ostream &OS,
2325 std::string PredicateNamespace,
2326 std::string GPrefix,
2327 std::string GPostfix,
2331 FixedLenDecoderEmitter(RK, PredicateNamespace, GPrefix, GPostfix,
2332 ROK, RFail, L).run(OS);
2335 } // End llvm namespace