1 //===------------ FixedLenDecoderEmitter.cpp - Decoder Generator ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // It contains the tablegen backend that emits the decoder functions for
11 // targets with fixed length instruction set.
13 //===----------------------------------------------------------------------===//
15 #include "CodeGenTarget.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/MC/MCFixedLenDisassembler.h"
22 #include "llvm/Support/DataTypes.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/FormattedStream.h"
25 #include "llvm/Support/LEB128.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/TableGen/Error.h"
28 #include "llvm/TableGen/Record.h"
35 #define DEBUG_TYPE "decoder-emitter"
38 struct EncodingField {
39 unsigned Base, Width, Offset;
40 EncodingField(unsigned B, unsigned W, unsigned O)
41 : Base(B), Width(W), Offset(O) { }
45 std::vector<EncodingField> Fields;
48 OperandInfo(std::string D)
51 void addField(unsigned Base, unsigned Width, unsigned Offset) {
52 Fields.push_back(EncodingField(Base, Width, Offset));
55 unsigned numFields() const { return Fields.size(); }
57 typedef std::vector<EncodingField>::const_iterator const_iterator;
59 const_iterator begin() const { return Fields.begin(); }
60 const_iterator end() const { return Fields.end(); }
63 typedef std::vector<uint8_t> DecoderTable;
64 typedef uint32_t DecoderFixup;
65 typedef std::vector<DecoderFixup> FixupList;
66 typedef std::vector<FixupList> FixupScopeList;
67 typedef SetVector<std::string> PredicateSet;
68 typedef SetVector<std::string> DecoderSet;
69 struct DecoderTableInfo {
71 FixupScopeList FixupStack;
72 PredicateSet Predicates;
76 } // End anonymous namespace
79 class FixedLenDecoderEmitter {
80 const std::vector<const CodeGenInstruction*> *NumberedInstructions;
83 // Defaults preserved here for documentation, even though they aren't
84 // strictly necessary given the way that this is currently being called.
85 FixedLenDecoderEmitter(RecordKeeper &R,
86 std::string PredicateNamespace,
87 std::string GPrefix = "if (",
88 std::string GPostfix = " == MCDisassembler::Fail)"
89 " return MCDisassembler::Fail;",
90 std::string ROK = "MCDisassembler::Success",
91 std::string RFail = "MCDisassembler::Fail",
94 PredicateNamespace(PredicateNamespace),
95 GuardPrefix(GPrefix), GuardPostfix(GPostfix),
96 ReturnOK(ROK), ReturnFail(RFail), Locals(L) {}
98 // Emit the decoder state machine table.
99 void emitTable(formatted_raw_ostream &o, DecoderTable &Table,
100 unsigned Indentation, unsigned BitWidth,
101 StringRef Namespace) const;
102 void emitPredicateFunction(formatted_raw_ostream &OS,
103 PredicateSet &Predicates,
104 unsigned Indentation) const;
105 void emitDecoderFunction(formatted_raw_ostream &OS,
106 DecoderSet &Decoders,
107 unsigned Indentation) const;
109 // run - Output the code emitter
110 void run(raw_ostream &o);
113 CodeGenTarget Target;
115 std::string PredicateNamespace;
116 std::string GuardPrefix, GuardPostfix;
117 std::string ReturnOK, ReturnFail;
120 } // End anonymous namespace
122 // The set (BIT_TRUE, BIT_FALSE, BIT_UNSET) represents a ternary logic system
125 // BIT_UNFILTERED is used as the init value for a filter position. It is used
126 // only for filter processings.
131 BIT_UNFILTERED // unfiltered
134 static bool ValueSet(bit_value_t V) {
135 return (V == BIT_TRUE || V == BIT_FALSE);
137 static bool ValueNotSet(bit_value_t V) {
138 return (V == BIT_UNSET);
140 static int Value(bit_value_t V) {
141 return ValueNotSet(V) ? -1 : (V == BIT_FALSE ? 0 : 1);
143 static bit_value_t bitFromBits(const BitsInit &bits, unsigned index) {
144 if (BitInit *bit = dyn_cast<BitInit>(bits.getBit(index)))
145 return bit->getValue() ? BIT_TRUE : BIT_FALSE;
147 // The bit is uninitialized.
150 // Prints the bit value for each position.
151 static void dumpBits(raw_ostream &o, const BitsInit &bits) {
152 for (unsigned index = bits.getNumBits(); index > 0; --index) {
153 switch (bitFromBits(bits, index - 1)) {
164 llvm_unreachable("unexpected return value from bitFromBits");
169 static BitsInit &getBitsField(const Record &def, const char *str) {
170 BitsInit *bits = def.getValueAsBitsInit(str);
174 // Forward declaration.
177 } // End anonymous namespace
179 // Representation of the instruction to work on.
180 typedef std::vector<bit_value_t> insn_t;
182 /// Filter - Filter works with FilterChooser to produce the decoding tree for
185 /// It is useful to think of a Filter as governing the switch stmts of the
186 /// decoding tree in a certain level. Each case stmt delegates to an inferior
187 /// FilterChooser to decide what further decoding logic to employ, or in another
188 /// words, what other remaining bits to look at. The FilterChooser eventually
189 /// chooses a best Filter to do its job.
191 /// This recursive scheme ends when the number of Opcodes assigned to the
192 /// FilterChooser becomes 1 or if there is a conflict. A conflict happens when
193 /// the Filter/FilterChooser combo does not know how to distinguish among the
194 /// Opcodes assigned.
196 /// An example of a conflict is
199 /// 111101000.00........00010000....
200 /// 111101000.00........0001........
201 /// 1111010...00........0001........
202 /// 1111010...00....................
203 /// 1111010.........................
204 /// 1111............................
205 /// ................................
206 /// VST4q8a 111101000_00________00010000____
207 /// VST4q8b 111101000_00________00010000____
209 /// The Debug output shows the path that the decoding tree follows to reach the
210 /// the conclusion that there is a conflict. VST4q8a is a vst4 to double-spaced
211 /// even registers, while VST4q8b is a vst4 to double-spaced odd regsisters.
213 /// The encoding info in the .td files does not specify this meta information,
214 /// which could have been used by the decoder to resolve the conflict. The
215 /// decoder could try to decode the even/odd register numbering and assign to
216 /// VST4q8a or VST4q8b, but for the time being, the decoder chooses the "a"
217 /// version and return the Opcode since the two have the same Asm format string.
221 const FilterChooser *Owner;// points to the FilterChooser who owns this filter
222 unsigned StartBit; // the starting bit position
223 unsigned NumBits; // number of bits to filter
224 bool Mixed; // a mixed region contains both set and unset bits
226 // Map of well-known segment value to the set of uid's with that value.
227 std::map<uint64_t, std::vector<unsigned> > FilteredInstructions;
229 // Set of uid's with non-constant segment values.
230 std::vector<unsigned> VariableInstructions;
232 // Map of well-known segment value to its delegate.
233 std::map<unsigned, std::unique_ptr<const FilterChooser>> FilterChooserMap;
235 // Number of instructions which fall under FilteredInstructions category.
236 unsigned NumFiltered;
238 // Keeps track of the last opcode in the filtered bucket.
239 unsigned LastOpcFiltered;
242 unsigned getNumFiltered() const { return NumFiltered; }
243 unsigned getSingletonOpc() const {
244 assert(NumFiltered == 1);
245 return LastOpcFiltered;
247 // Return the filter chooser for the group of instructions without constant
249 const FilterChooser &getVariableFC() const {
250 assert(NumFiltered == 1);
251 assert(FilterChooserMap.size() == 1);
252 return *(FilterChooserMap.find((unsigned)-1)->second);
256 Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, bool mixed);
260 // Divides the decoding task into sub tasks and delegates them to the
261 // inferior FilterChooser's.
263 // A special case arises when there's only one entry in the filtered
264 // instructions. In order to unambiguously decode the singleton, we need to
265 // match the remaining undecoded encoding bits against the singleton.
268 // Emit table entries to decode instructions given a segment or segments of
270 void emitTableEntry(DecoderTableInfo &TableInfo) const;
272 // Returns the number of fanout produced by the filter. More fanout implies
273 // the filter distinguishes more categories of instructions.
274 unsigned usefulness() const;
275 }; // End of class Filter
276 } // End anonymous namespace
278 // These are states of our finite state machines used in FilterChooser's
279 // filterProcessor() which produces the filter candidates to use.
288 /// FilterChooser - FilterChooser chooses the best filter among a set of Filters
289 /// in order to perform the decoding of instructions at the current level.
291 /// Decoding proceeds from the top down. Based on the well-known encoding bits
292 /// of instructions available, FilterChooser builds up the possible Filters that
293 /// can further the task of decoding by distinguishing among the remaining
294 /// candidate instructions.
296 /// Once a filter has been chosen, it is called upon to divide the decoding task
297 /// into sub-tasks and delegates them to its inferior FilterChoosers for further
300 /// It is useful to think of a Filter as governing the switch stmts of the
301 /// decoding tree. And each case is delegated to an inferior FilterChooser to
302 /// decide what further remaining bits to look at.
304 class FilterChooser {
308 // Vector of codegen instructions to choose our filter.
309 const std::vector<const CodeGenInstruction*> &AllInstructions;
311 // Vector of uid's for this filter chooser to work on.
312 const std::vector<unsigned> &Opcodes;
314 // Lookup table for the operand decoding of instructions.
315 const std::map<unsigned, std::vector<OperandInfo> > &Operands;
317 // Vector of candidate filters.
318 std::vector<Filter> Filters;
320 // Array of bit values passed down from our parent.
321 // Set to all BIT_UNFILTERED's for Parent == NULL.
322 std::vector<bit_value_t> FilterBitValues;
324 // Links to the FilterChooser above us in the decoding tree.
325 const FilterChooser *Parent;
327 // Index of the best filter from Filters.
330 // Width of instructions
334 const FixedLenDecoderEmitter *Emitter;
336 FilterChooser(const FilterChooser &) LLVM_DELETED_FUNCTION;
337 void operator=(const FilterChooser &) LLVM_DELETED_FUNCTION;
340 FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
341 const std::vector<unsigned> &IDs,
342 const std::map<unsigned, std::vector<OperandInfo> > &Ops,
344 const FixedLenDecoderEmitter *E)
345 : AllInstructions(Insts), Opcodes(IDs), Operands(Ops), Filters(),
346 Parent(nullptr), BestIndex(-1), BitWidth(BW), Emitter(E) {
347 for (unsigned i = 0; i < BitWidth; ++i)
348 FilterBitValues.push_back(BIT_UNFILTERED);
353 FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
354 const std::vector<unsigned> &IDs,
355 const std::map<unsigned, std::vector<OperandInfo> > &Ops,
356 const std::vector<bit_value_t> &ParentFilterBitValues,
357 const FilterChooser &parent)
358 : AllInstructions(Insts), Opcodes(IDs), Operands(Ops),
359 Filters(), FilterBitValues(ParentFilterBitValues),
360 Parent(&parent), BestIndex(-1), BitWidth(parent.BitWidth),
361 Emitter(parent.Emitter) {
365 unsigned getBitWidth() const { return BitWidth; }
368 // Populates the insn given the uid.
369 void insnWithID(insn_t &Insn, unsigned Opcode) const {
370 BitsInit &Bits = getBitsField(*AllInstructions[Opcode]->TheDef, "Inst");
372 // We may have a SoftFail bitmask, which specifies a mask where an encoding
373 // may differ from the value in "Inst" and yet still be valid, but the
374 // disassembler should return SoftFail instead of Success.
376 // This is used for marking UNPREDICTABLE instructions in the ARM world.
378 AllInstructions[Opcode]->TheDef->getValueAsBitsInit("SoftFail");
380 for (unsigned i = 0; i < BitWidth; ++i) {
381 if (SFBits && bitFromBits(*SFBits, i) == BIT_TRUE)
382 Insn.push_back(BIT_UNSET);
384 Insn.push_back(bitFromBits(Bits, i));
388 // Returns the record name.
389 const std::string &nameWithID(unsigned Opcode) const {
390 return AllInstructions[Opcode]->TheDef->getName();
393 // Populates the field of the insn given the start position and the number of
394 // consecutive bits to scan for.
396 // Returns false if there exists any uninitialized bit value in the range.
397 // Returns true, otherwise.
398 bool fieldFromInsn(uint64_t &Field, insn_t &Insn, unsigned StartBit,
399 unsigned NumBits) const;
401 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
402 /// filter array as a series of chars.
403 void dumpFilterArray(raw_ostream &o,
404 const std::vector<bit_value_t> & filter) const;
406 /// dumpStack - dumpStack traverses the filter chooser chain and calls
407 /// dumpFilterArray on each filter chooser up to the top level one.
408 void dumpStack(raw_ostream &o, const char *prefix) const;
410 Filter &bestFilter() {
411 assert(BestIndex != -1 && "BestIndex not set");
412 return Filters[BestIndex];
415 // Called from Filter::recurse() when singleton exists. For debug purpose.
416 void SingletonExists(unsigned Opc) const;
418 bool PositionFiltered(unsigned i) const {
419 return ValueSet(FilterBitValues[i]);
422 // Calculates the island(s) needed to decode the instruction.
423 // This returns a lit of undecoded bits of an instructions, for example,
424 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
425 // decoded bits in order to verify that the instruction matches the Opcode.
426 unsigned getIslands(std::vector<unsigned> &StartBits,
427 std::vector<unsigned> &EndBits,
428 std::vector<uint64_t> &FieldVals,
429 const insn_t &Insn) const;
431 // Emits code to check the Predicates member of an instruction are true.
432 // Returns true if predicate matches were emitted, false otherwise.
433 bool emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
436 bool doesOpcodeNeedPredicate(unsigned Opc) const;
437 unsigned getPredicateIndex(DecoderTableInfo &TableInfo, StringRef P) const;
438 void emitPredicateTableEntry(DecoderTableInfo &TableInfo,
441 void emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
444 // Emits table entries to decode the singleton.
445 void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
448 // Emits code to decode the singleton, and then to decode the rest.
449 void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
450 const Filter &Best) const;
452 void emitBinaryParser(raw_ostream &o, unsigned &Indentation,
453 const OperandInfo &OpInfo) const;
455 void emitDecoder(raw_ostream &OS, unsigned Indentation, unsigned Opc) const;
456 unsigned getDecoderIndex(DecoderSet &Decoders, unsigned Opc) const;
458 // Assign a single filter and run with it.
459 void runSingleFilter(unsigned startBit, unsigned numBit, bool mixed);
461 // reportRegion is a helper function for filterProcessor to mark a region as
462 // eligible for use as a filter region.
463 void reportRegion(bitAttr_t RA, unsigned StartBit, unsigned BitIndex,
466 // FilterProcessor scans the well-known encoding bits of the instructions and
467 // builds up a list of candidate filters. It chooses the best filter and
468 // recursively descends down the decoding tree.
469 bool filterProcessor(bool AllowMixed, bool Greedy = true);
471 // Decides on the best configuration of filter(s) to use in order to decode
472 // the instructions. A conflict of instructions may occur, in which case we
473 // dump the conflict set to the standard error.
477 // emitTableEntries - Emit state machine entries to decode our share of
479 void emitTableEntries(DecoderTableInfo &TableInfo) const;
481 } // End anonymous namespace
483 ///////////////////////////
485 // Filter Implementation //
487 ///////////////////////////
489 Filter::Filter(Filter &&f)
490 : Owner(f.Owner), StartBit(f.StartBit), NumBits(f.NumBits), Mixed(f.Mixed),
491 FilteredInstructions(std::move(f.FilteredInstructions)),
492 VariableInstructions(std::move(f.VariableInstructions)),
493 FilterChooserMap(std::move(f.FilterChooserMap)), NumFiltered(f.NumFiltered),
494 LastOpcFiltered(f.LastOpcFiltered) {
497 Filter::Filter(FilterChooser &owner, unsigned startBit, unsigned numBits,
499 : Owner(&owner), StartBit(startBit), NumBits(numBits), Mixed(mixed) {
500 assert(StartBit + NumBits - 1 < Owner->BitWidth);
505 for (unsigned i = 0, e = Owner->Opcodes.size(); i != e; ++i) {
508 // Populates the insn given the uid.
509 Owner->insnWithID(Insn, Owner->Opcodes[i]);
512 // Scans the segment for possibly well-specified encoding bits.
513 bool ok = Owner->fieldFromInsn(Field, Insn, StartBit, NumBits);
516 // The encoding bits are well-known. Lets add the uid of the
517 // instruction into the bucket keyed off the constant field value.
518 LastOpcFiltered = Owner->Opcodes[i];
519 FilteredInstructions[Field].push_back(LastOpcFiltered);
522 // Some of the encoding bit(s) are unspecified. This contributes to
523 // one additional member of "Variable" instructions.
524 VariableInstructions.push_back(Owner->Opcodes[i]);
528 assert((FilteredInstructions.size() + VariableInstructions.size() > 0)
529 && "Filter returns no instruction categories");
535 // Divides the decoding task into sub tasks and delegates them to the
536 // inferior FilterChooser's.
538 // A special case arises when there's only one entry in the filtered
539 // instructions. In order to unambiguously decode the singleton, we need to
540 // match the remaining undecoded encoding bits against the singleton.
541 void Filter::recurse() {
542 std::map<uint64_t, std::vector<unsigned> >::const_iterator mapIterator;
544 // Starts by inheriting our parent filter chooser's filter bit values.
545 std::vector<bit_value_t> BitValueArray(Owner->FilterBitValues);
547 if (VariableInstructions.size()) {
548 // Conservatively marks each segment position as BIT_UNSET.
549 for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex)
550 BitValueArray[StartBit + bitIndex] = BIT_UNSET;
552 // Delegates to an inferior filter chooser for further processing on this
553 // group of instructions whose segment values are variable.
554 FilterChooserMap.insert(
555 std::make_pair(-1U, llvm::make_unique<FilterChooser>(
556 Owner->AllInstructions, VariableInstructions,
557 Owner->Operands, BitValueArray, *Owner)));
560 // No need to recurse for a singleton filtered instruction.
561 // See also Filter::emit*().
562 if (getNumFiltered() == 1) {
563 //Owner->SingletonExists(LastOpcFiltered);
564 assert(FilterChooserMap.size() == 1);
568 // Otherwise, create sub choosers.
569 for (mapIterator = FilteredInstructions.begin();
570 mapIterator != FilteredInstructions.end();
573 // Marks all the segment positions with either BIT_TRUE or BIT_FALSE.
574 for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex) {
575 if (mapIterator->first & (1ULL << bitIndex))
576 BitValueArray[StartBit + bitIndex] = BIT_TRUE;
578 BitValueArray[StartBit + bitIndex] = BIT_FALSE;
581 // Delegates to an inferior filter chooser for further processing on this
582 // category of instructions.
583 FilterChooserMap.insert(std::make_pair(
584 mapIterator->first, llvm::make_unique<FilterChooser>(
585 Owner->AllInstructions, mapIterator->second,
586 Owner->Operands, BitValueArray, *Owner)));
590 static void resolveTableFixups(DecoderTable &Table, const FixupList &Fixups,
592 // Any NumToSkip fixups in the current scope can resolve to the
594 for (FixupList::const_reverse_iterator I = Fixups.rbegin(),
597 // Calculate the distance from the byte following the fixup entry byte
598 // to the destination. The Target is calculated from after the 16-bit
599 // NumToSkip entry itself, so subtract two from the displacement here
600 // to account for that.
601 uint32_t FixupIdx = *I;
602 uint32_t Delta = DestIdx - FixupIdx - 2;
603 // Our NumToSkip entries are 16-bits. Make sure our table isn't too
605 assert(Delta < 65536U && "disassembler decoding table too large!");
606 Table[FixupIdx] = (uint8_t)Delta;
607 Table[FixupIdx + 1] = (uint8_t)(Delta >> 8);
611 // Emit table entries to decode instructions given a segment or segments
613 void Filter::emitTableEntry(DecoderTableInfo &TableInfo) const {
614 TableInfo.Table.push_back(MCD::OPC_ExtractField);
615 TableInfo.Table.push_back(StartBit);
616 TableInfo.Table.push_back(NumBits);
618 // A new filter entry begins a new scope for fixup resolution.
619 TableInfo.FixupStack.push_back(FixupList());
622 std::unique_ptr<const FilterChooser>>::const_iterator filterIterator;
624 DecoderTable &Table = TableInfo.Table;
626 size_t PrevFilter = 0;
627 bool HasFallthrough = false;
628 for (filterIterator = FilterChooserMap.begin();
629 filterIterator != FilterChooserMap.end();
631 // Field value -1 implies a non-empty set of variable instructions.
632 // See also recurse().
633 if (filterIterator->first == (unsigned)-1) {
634 HasFallthrough = true;
636 // Each scope should always have at least one filter value to check
638 assert(PrevFilter != 0 && "empty filter set!");
639 FixupList &CurScope = TableInfo.FixupStack.back();
640 // Resolve any NumToSkip fixups in the current scope.
641 resolveTableFixups(Table, CurScope, Table.size());
643 PrevFilter = 0; // Don't re-process the filter's fallthrough.
645 Table.push_back(MCD::OPC_FilterValue);
646 // Encode and emit the value to filter against.
648 unsigned Len = encodeULEB128(filterIterator->first, Buffer);
649 Table.insert(Table.end(), Buffer, Buffer + Len);
650 // Reserve space for the NumToSkip entry. We'll backpatch the value
652 PrevFilter = Table.size();
657 // We arrive at a category of instructions with the same segment value.
658 // Now delegate to the sub filter chooser for further decodings.
659 // The case may fallthrough, which happens if the remaining well-known
660 // encoding bits do not match exactly.
661 filterIterator->second->emitTableEntries(TableInfo);
663 // Now that we've emitted the body of the handler, update the NumToSkip
664 // of the filter itself to be able to skip forward when false. Subtract
665 // two as to account for the width of the NumToSkip field itself.
667 uint32_t NumToSkip = Table.size() - PrevFilter - 2;
668 assert(NumToSkip < 65536U && "disassembler decoding table too large!");
669 Table[PrevFilter] = (uint8_t)NumToSkip;
670 Table[PrevFilter + 1] = (uint8_t)(NumToSkip >> 8);
674 // Any remaining unresolved fixups bubble up to the parent fixup scope.
675 assert(TableInfo.FixupStack.size() > 1 && "fixup stack underflow!");
676 FixupScopeList::iterator Source = TableInfo.FixupStack.end() - 1;
677 FixupScopeList::iterator Dest = Source - 1;
678 Dest->insert(Dest->end(), Source->begin(), Source->end());
679 TableInfo.FixupStack.pop_back();
681 // If there is no fallthrough, then the final filter should get fixed
682 // up according to the enclosing scope rather than the current position.
684 TableInfo.FixupStack.back().push_back(PrevFilter);
687 // Returns the number of fanout produced by the filter. More fanout implies
688 // the filter distinguishes more categories of instructions.
689 unsigned Filter::usefulness() const {
690 if (VariableInstructions.size())
691 return FilteredInstructions.size();
693 return FilteredInstructions.size() + 1;
696 //////////////////////////////////
698 // Filterchooser Implementation //
700 //////////////////////////////////
702 // Emit the decoder state machine table.
703 void FixedLenDecoderEmitter::emitTable(formatted_raw_ostream &OS,
705 unsigned Indentation,
707 StringRef Namespace) const {
708 OS.indent(Indentation) << "static const uint8_t DecoderTable" << Namespace
709 << BitWidth << "[] = {\n";
713 // FIXME: We may be able to use the NumToSkip values to recover
714 // appropriate indentation levels.
715 DecoderTable::const_iterator I = Table.begin();
716 DecoderTable::const_iterator E = Table.end();
718 assert (I < E && "incomplete decode table entry!");
720 uint64_t Pos = I - Table.begin();
721 OS << "/* " << Pos << " */";
726 PrintFatalError("invalid decode table opcode");
727 case MCD::OPC_ExtractField: {
729 unsigned Start = *I++;
731 OS.indent(Indentation) << "MCD::OPC_ExtractField, " << Start << ", "
732 << Len << ", // Inst{";
734 OS << (Start + Len - 1) << "-";
735 OS << Start << "} ...\n";
738 case MCD::OPC_FilterValue: {
740 OS.indent(Indentation) << "MCD::OPC_FilterValue, ";
741 // The filter value is ULEB128 encoded.
743 OS << utostr(*I++) << ", ";
744 OS << utostr(*I++) << ", ";
746 // 16-bit numtoskip value.
748 uint32_t NumToSkip = Byte;
749 OS << utostr(Byte) << ", ";
751 OS << utostr(Byte) << ", ";
752 NumToSkip |= Byte << 8;
753 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
756 case MCD::OPC_CheckField: {
758 unsigned Start = *I++;
760 OS.indent(Indentation) << "MCD::OPC_CheckField, " << Start << ", "
761 << Len << ", ";// << Val << ", " << NumToSkip << ",\n";
762 // ULEB128 encoded field value.
763 for (; *I >= 128; ++I)
764 OS << utostr(*I) << ", ";
765 OS << utostr(*I++) << ", ";
766 // 16-bit numtoskip value.
768 uint32_t NumToSkip = Byte;
769 OS << utostr(Byte) << ", ";
771 OS << utostr(Byte) << ", ";
772 NumToSkip |= Byte << 8;
773 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
776 case MCD::OPC_CheckPredicate: {
778 OS.indent(Indentation) << "MCD::OPC_CheckPredicate, ";
779 for (; *I >= 128; ++I)
780 OS << utostr(*I) << ", ";
781 OS << utostr(*I++) << ", ";
783 // 16-bit numtoskip value.
785 uint32_t NumToSkip = Byte;
786 OS << utostr(Byte) << ", ";
788 OS << utostr(Byte) << ", ";
789 NumToSkip |= Byte << 8;
790 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
793 case MCD::OPC_Decode: {
795 // Extract the ULEB128 encoded Opcode to a buffer.
796 uint8_t Buffer[8], *p = Buffer;
797 while ((*p++ = *I++) >= 128)
798 assert((p - Buffer) <= (ptrdiff_t)sizeof(Buffer)
799 && "ULEB128 value too large!");
800 // Decode the Opcode value.
801 unsigned Opc = decodeULEB128(Buffer);
802 OS.indent(Indentation) << "MCD::OPC_Decode, ";
803 for (p = Buffer; *p >= 128; ++p)
804 OS << utostr(*p) << ", ";
805 OS << utostr(*p) << ", ";
808 for (; *I >= 128; ++I)
809 OS << utostr(*I) << ", ";
810 OS << utostr(*I++) << ", ";
813 << NumberedInstructions->at(Opc)->TheDef->getName() << "\n";
816 case MCD::OPC_SoftFail: {
818 OS.indent(Indentation) << "MCD::OPC_SoftFail";
823 OS << ", " << utostr(*I);
824 Value += (*I & 0x7f) << Shift;
826 } while (*I++ >= 128);
828 OS << " /* 0x" << utohexstr(Value) << " */";
833 OS << ", " << utostr(*I);
834 Value += (*I & 0x7f) << Shift;
836 } while (*I++ >= 128);
838 OS << " /* 0x" << utohexstr(Value) << " */";
842 case MCD::OPC_Fail: {
844 OS.indent(Indentation) << "MCD::OPC_Fail,\n";
849 OS.indent(Indentation) << "0\n";
853 OS.indent(Indentation) << "};\n\n";
856 void FixedLenDecoderEmitter::
857 emitPredicateFunction(formatted_raw_ostream &OS, PredicateSet &Predicates,
858 unsigned Indentation) const {
859 // The predicate function is just a big switch statement based on the
860 // input predicate index.
861 OS.indent(Indentation) << "static bool checkDecoderPredicate(unsigned Idx, "
862 << "uint64_t Bits) {\n";
864 if (!Predicates.empty()) {
865 OS.indent(Indentation) << "switch (Idx) {\n";
866 OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
868 for (PredicateSet::const_iterator I = Predicates.begin(), E = Predicates.end();
869 I != E; ++I, ++Index) {
870 OS.indent(Indentation) << "case " << Index << ":\n";
871 OS.indent(Indentation+2) << "return (" << *I << ");\n";
873 OS.indent(Indentation) << "}\n";
875 // No case statement to emit
876 OS.indent(Indentation) << "llvm_unreachable(\"Invalid index!\");\n";
879 OS.indent(Indentation) << "}\n\n";
882 void FixedLenDecoderEmitter::
883 emitDecoderFunction(formatted_raw_ostream &OS, DecoderSet &Decoders,
884 unsigned Indentation) const {
885 // The decoder function is just a big switch statement based on the
886 // input decoder index.
887 OS.indent(Indentation) << "template<typename InsnType>\n";
888 OS.indent(Indentation) << "static DecodeStatus decodeToMCInst(DecodeStatus S,"
889 << " unsigned Idx, InsnType insn, MCInst &MI,\n";
890 OS.indent(Indentation) << " uint64_t "
891 << "Address, const void *Decoder) {\n";
893 OS.indent(Indentation) << "InsnType tmp;\n";
894 OS.indent(Indentation) << "switch (Idx) {\n";
895 OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
897 for (DecoderSet::const_iterator I = Decoders.begin(), E = Decoders.end();
898 I != E; ++I, ++Index) {
899 OS.indent(Indentation) << "case " << Index << ":\n";
901 OS.indent(Indentation+2) << "return S;\n";
903 OS.indent(Indentation) << "}\n";
905 OS.indent(Indentation) << "}\n\n";
908 // Populates the field of the insn given the start position and the number of
909 // consecutive bits to scan for.
911 // Returns false if and on the first uninitialized bit value encountered.
912 // Returns true, otherwise.
913 bool FilterChooser::fieldFromInsn(uint64_t &Field, insn_t &Insn,
914 unsigned StartBit, unsigned NumBits) const {
917 for (unsigned i = 0; i < NumBits; ++i) {
918 if (Insn[StartBit + i] == BIT_UNSET)
921 if (Insn[StartBit + i] == BIT_TRUE)
922 Field = Field | (1ULL << i);
928 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
929 /// filter array as a series of chars.
930 void FilterChooser::dumpFilterArray(raw_ostream &o,
931 const std::vector<bit_value_t> &filter) const {
932 for (unsigned bitIndex = BitWidth; bitIndex > 0; bitIndex--) {
933 switch (filter[bitIndex - 1]) {
950 /// dumpStack - dumpStack traverses the filter chooser chain and calls
951 /// dumpFilterArray on each filter chooser up to the top level one.
952 void FilterChooser::dumpStack(raw_ostream &o, const char *prefix) const {
953 const FilterChooser *current = this;
957 dumpFilterArray(o, current->FilterBitValues);
959 current = current->Parent;
963 // Called from Filter::recurse() when singleton exists. For debug purpose.
964 void FilterChooser::SingletonExists(unsigned Opc) const {
966 insnWithID(Insn0, Opc);
968 errs() << "Singleton exists: " << nameWithID(Opc)
969 << " with its decoding dominating ";
970 for (unsigned i = 0; i < Opcodes.size(); ++i) {
971 if (Opcodes[i] == Opc) continue;
972 errs() << nameWithID(Opcodes[i]) << ' ';
976 dumpStack(errs(), "\t\t");
977 for (unsigned i = 0; i < Opcodes.size(); ++i) {
978 const std::string &Name = nameWithID(Opcodes[i]);
980 errs() << '\t' << Name << " ";
982 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
987 // Calculates the island(s) needed to decode the instruction.
988 // This returns a list of undecoded bits of an instructions, for example,
989 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
990 // decoded bits in order to verify that the instruction matches the Opcode.
991 unsigned FilterChooser::getIslands(std::vector<unsigned> &StartBits,
992 std::vector<unsigned> &EndBits,
993 std::vector<uint64_t> &FieldVals,
994 const insn_t &Insn) const {
998 uint64_t FieldVal = 0;
1001 // 1: Water (the bit value does not affect decoding)
1002 // 2: Island (well-known bit value needed for decoding)
1006 for (unsigned i = 0; i < BitWidth; ++i) {
1007 Val = Value(Insn[i]);
1008 bool Filtered = PositionFiltered(i);
1010 default: llvm_unreachable("Unreachable code!");
1013 if (Filtered || Val == -1)
1014 State = 1; // Still in Water
1016 State = 2; // Into the Island
1018 StartBits.push_back(i);
1023 if (Filtered || Val == -1) {
1024 State = 1; // Into the Water
1025 EndBits.push_back(i - 1);
1026 FieldVals.push_back(FieldVal);
1029 State = 2; // Still in Island
1031 FieldVal = FieldVal | Val << BitNo;
1036 // If we are still in Island after the loop, do some housekeeping.
1038 EndBits.push_back(BitWidth - 1);
1039 FieldVals.push_back(FieldVal);
1043 assert(StartBits.size() == Num && EndBits.size() == Num &&
1044 FieldVals.size() == Num);
1048 void FilterChooser::emitBinaryParser(raw_ostream &o, unsigned &Indentation,
1049 const OperandInfo &OpInfo) const {
1050 const std::string &Decoder = OpInfo.Decoder;
1052 if (OpInfo.numFields() == 1) {
1053 OperandInfo::const_iterator OI = OpInfo.begin();
1054 o.indent(Indentation) << "tmp = fieldFromInstruction"
1055 << "(insn, " << OI->Base << ", " << OI->Width
1058 o.indent(Indentation) << "tmp = 0;\n";
1059 for (OperandInfo::const_iterator OI = OpInfo.begin(), OE = OpInfo.end();
1061 o.indent(Indentation) << "tmp |= (fieldFromInstruction"
1062 << "(insn, " << OI->Base << ", " << OI->Width
1063 << ") << " << OI->Offset << ");\n";
1068 o.indent(Indentation) << Emitter->GuardPrefix << Decoder
1069 << "(MI, tmp, Address, Decoder)"
1070 << Emitter->GuardPostfix << "\n";
1072 o.indent(Indentation) << "MI.addOperand(MCOperand::CreateImm(tmp));\n";
1076 void FilterChooser::emitDecoder(raw_ostream &OS, unsigned Indentation,
1077 unsigned Opc) const {
1078 std::map<unsigned, std::vector<OperandInfo> >::const_iterator OpIter =
1080 const std::vector<OperandInfo>& InsnOperands = OpIter->second;
1081 for (std::vector<OperandInfo>::const_iterator
1082 I = InsnOperands.begin(), E = InsnOperands.end(); I != E; ++I) {
1083 // If a custom instruction decoder was specified, use that.
1084 if (I->numFields() == 0 && I->Decoder.size()) {
1085 OS.indent(Indentation) << Emitter->GuardPrefix << I->Decoder
1086 << "(MI, insn, Address, Decoder)"
1087 << Emitter->GuardPostfix << "\n";
1091 emitBinaryParser(OS, Indentation, *I);
1095 unsigned FilterChooser::getDecoderIndex(DecoderSet &Decoders,
1096 unsigned Opc) const {
1097 // Build up the predicate string.
1098 SmallString<256> Decoder;
1099 // FIXME: emitDecoder() function can take a buffer directly rather than
1101 raw_svector_ostream S(Decoder);
1103 emitDecoder(S, I, Opc);
1106 // Using the full decoder string as the key value here is a bit
1107 // heavyweight, but is effective. If the string comparisons become a
1108 // performance concern, we can implement a mangling of the predicate
1109 // data easilly enough with a map back to the actual string. That's
1110 // overkill for now, though.
1112 // Make sure the predicate is in the table.
1113 Decoders.insert(Decoder.str());
1114 // Now figure out the index for when we write out the table.
1115 DecoderSet::const_iterator P = std::find(Decoders.begin(),
1118 return (unsigned)(P - Decoders.begin());
1121 static void emitSinglePredicateMatch(raw_ostream &o, StringRef str,
1122 const std::string &PredicateNamespace) {
1124 o << "!(Bits & " << PredicateNamespace << "::"
1125 << str.slice(1,str.size()) << ")";
1127 o << "(Bits & " << PredicateNamespace << "::" << str << ")";
1130 bool FilterChooser::emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
1131 unsigned Opc) const {
1132 ListInit *Predicates =
1133 AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
1134 for (unsigned i = 0; i < Predicates->getSize(); ++i) {
1135 Record *Pred = Predicates->getElementAsRecord(i);
1136 if (!Pred->getValue("AssemblerMatcherPredicate"))
1139 std::string P = Pred->getValueAsString("AssemblerCondString");
1148 std::pair<StringRef, StringRef> pairs = SR.split(',');
1149 while (pairs.second.size()) {
1150 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
1152 pairs = pairs.second.split(',');
1154 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
1156 return Predicates->getSize() > 0;
1159 bool FilterChooser::doesOpcodeNeedPredicate(unsigned Opc) const {
1160 ListInit *Predicates =
1161 AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
1162 for (unsigned i = 0; i < Predicates->getSize(); ++i) {
1163 Record *Pred = Predicates->getElementAsRecord(i);
1164 if (!Pred->getValue("AssemblerMatcherPredicate"))
1167 std::string P = Pred->getValueAsString("AssemblerCondString");
1177 unsigned FilterChooser::getPredicateIndex(DecoderTableInfo &TableInfo,
1178 StringRef Predicate) const {
1179 // Using the full predicate string as the key value here is a bit
1180 // heavyweight, but is effective. If the string comparisons become a
1181 // performance concern, we can implement a mangling of the predicate
1182 // data easilly enough with a map back to the actual string. That's
1183 // overkill for now, though.
1185 // Make sure the predicate is in the table.
1186 TableInfo.Predicates.insert(Predicate.str());
1187 // Now figure out the index for when we write out the table.
1188 PredicateSet::const_iterator P = std::find(TableInfo.Predicates.begin(),
1189 TableInfo.Predicates.end(),
1191 return (unsigned)(P - TableInfo.Predicates.begin());
1194 void FilterChooser::emitPredicateTableEntry(DecoderTableInfo &TableInfo,
1195 unsigned Opc) const {
1196 if (!doesOpcodeNeedPredicate(Opc))
1199 // Build up the predicate string.
1200 SmallString<256> Predicate;
1201 // FIXME: emitPredicateMatch() functions can take a buffer directly rather
1203 raw_svector_ostream PS(Predicate);
1205 emitPredicateMatch(PS, I, Opc);
1207 // Figure out the index into the predicate table for the predicate just
1209 unsigned PIdx = getPredicateIndex(TableInfo, PS.str());
1210 SmallString<16> PBytes;
1211 raw_svector_ostream S(PBytes);
1212 encodeULEB128(PIdx, S);
1215 TableInfo.Table.push_back(MCD::OPC_CheckPredicate);
1217 for (unsigned i = 0, e = PBytes.size(); i != e; ++i)
1218 TableInfo.Table.push_back(PBytes[i]);
1219 // Push location for NumToSkip backpatching.
1220 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1221 TableInfo.Table.push_back(0);
1222 TableInfo.Table.push_back(0);
1225 void FilterChooser::emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
1226 unsigned Opc) const {
1228 AllInstructions[Opc]->TheDef->getValueAsBitsInit("SoftFail");
1229 if (!SFBits) return;
1230 BitsInit *InstBits = AllInstructions[Opc]->TheDef->getValueAsBitsInit("Inst");
1232 APInt PositiveMask(BitWidth, 0ULL);
1233 APInt NegativeMask(BitWidth, 0ULL);
1234 for (unsigned i = 0; i < BitWidth; ++i) {
1235 bit_value_t B = bitFromBits(*SFBits, i);
1236 bit_value_t IB = bitFromBits(*InstBits, i);
1238 if (B != BIT_TRUE) continue;
1242 // The bit is meant to be false, so emit a check to see if it is true.
1243 PositiveMask.setBit(i);
1246 // The bit is meant to be true, so emit a check to see if it is false.
1247 NegativeMask.setBit(i);
1250 // The bit is not set; this must be an error!
1251 StringRef Name = AllInstructions[Opc]->TheDef->getName();
1252 errs() << "SoftFail Conflict: bit SoftFail{" << i << "} in " << Name
1253 << " is set but Inst{" << i << "} is unset!\n"
1254 << " - You can only mark a bit as SoftFail if it is fully defined"
1255 << " (1/0 - not '?') in Inst\n";
1260 bool NeedPositiveMask = PositiveMask.getBoolValue();
1261 bool NeedNegativeMask = NegativeMask.getBoolValue();
1263 if (!NeedPositiveMask && !NeedNegativeMask)
1266 TableInfo.Table.push_back(MCD::OPC_SoftFail);
1268 SmallString<16> MaskBytes;
1269 raw_svector_ostream S(MaskBytes);
1270 if (NeedPositiveMask) {
1271 encodeULEB128(PositiveMask.getZExtValue(), S);
1273 for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
1274 TableInfo.Table.push_back(MaskBytes[i]);
1276 TableInfo.Table.push_back(0);
1277 if (NeedNegativeMask) {
1280 encodeULEB128(NegativeMask.getZExtValue(), S);
1282 for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
1283 TableInfo.Table.push_back(MaskBytes[i]);
1285 TableInfo.Table.push_back(0);
1288 // Emits table entries to decode the singleton.
1289 void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1290 unsigned Opc) const {
1291 std::vector<unsigned> StartBits;
1292 std::vector<unsigned> EndBits;
1293 std::vector<uint64_t> FieldVals;
1295 insnWithID(Insn, Opc);
1297 // Look for islands of undecoded bits of the singleton.
1298 getIslands(StartBits, EndBits, FieldVals, Insn);
1300 unsigned Size = StartBits.size();
1302 // Emit the predicate table entry if one is needed.
1303 emitPredicateTableEntry(TableInfo, Opc);
1305 // Check any additional encoding fields needed.
1306 for (unsigned I = Size; I != 0; --I) {
1307 unsigned NumBits = EndBits[I-1] - StartBits[I-1] + 1;
1308 TableInfo.Table.push_back(MCD::OPC_CheckField);
1309 TableInfo.Table.push_back(StartBits[I-1]);
1310 TableInfo.Table.push_back(NumBits);
1311 uint8_t Buffer[8], *p;
1312 encodeULEB128(FieldVals[I-1], Buffer);
1313 for (p = Buffer; *p >= 128 ; ++p)
1314 TableInfo.Table.push_back(*p);
1315 TableInfo.Table.push_back(*p);
1316 // Push location for NumToSkip backpatching.
1317 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1318 // The fixup is always 16-bits, so go ahead and allocate the space
1319 // in the table so all our relative position calculations work OK even
1320 // before we fully resolve the real value here.
1321 TableInfo.Table.push_back(0);
1322 TableInfo.Table.push_back(0);
1325 // Check for soft failure of the match.
1326 emitSoftFailTableEntry(TableInfo, Opc);
1328 TableInfo.Table.push_back(MCD::OPC_Decode);
1329 uint8_t Buffer[8], *p;
1330 encodeULEB128(Opc, Buffer);
1331 for (p = Buffer; *p >= 128 ; ++p)
1332 TableInfo.Table.push_back(*p);
1333 TableInfo.Table.push_back(*p);
1335 unsigned DIdx = getDecoderIndex(TableInfo.Decoders, Opc);
1336 SmallString<16> Bytes;
1337 raw_svector_ostream S(Bytes);
1338 encodeULEB128(DIdx, S);
1342 for (unsigned i = 0, e = Bytes.size(); i != e; ++i)
1343 TableInfo.Table.push_back(Bytes[i]);
1346 // Emits table entries to decode the singleton, and then to decode the rest.
1347 void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1348 const Filter &Best) const {
1349 unsigned Opc = Best.getSingletonOpc();
1351 // complex singletons need predicate checks from the first singleton
1352 // to refer forward to the variable filterchooser that follows.
1353 TableInfo.FixupStack.push_back(FixupList());
1355 emitSingletonTableEntry(TableInfo, Opc);
1357 resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
1358 TableInfo.Table.size());
1359 TableInfo.FixupStack.pop_back();
1361 Best.getVariableFC().emitTableEntries(TableInfo);
1365 // Assign a single filter and run with it. Top level API client can initialize
1366 // with a single filter to start the filtering process.
1367 void FilterChooser::runSingleFilter(unsigned startBit, unsigned numBit,
1370 Filters.push_back(Filter(*this, startBit, numBit, true));
1371 BestIndex = 0; // Sole Filter instance to choose from.
1372 bestFilter().recurse();
1375 // reportRegion is a helper function for filterProcessor to mark a region as
1376 // eligible for use as a filter region.
1377 void FilterChooser::reportRegion(bitAttr_t RA, unsigned StartBit,
1378 unsigned BitIndex, bool AllowMixed) {
1379 if (RA == ATTR_MIXED && AllowMixed)
1380 Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, true));
1381 else if (RA == ATTR_ALL_SET && !AllowMixed)
1382 Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, false));
1385 // FilterProcessor scans the well-known encoding bits of the instructions and
1386 // builds up a list of candidate filters. It chooses the best filter and
1387 // recursively descends down the decoding tree.
1388 bool FilterChooser::filterProcessor(bool AllowMixed, bool Greedy) {
1391 unsigned numInstructions = Opcodes.size();
1393 assert(numInstructions && "Filter created with no instructions");
1395 // No further filtering is necessary.
1396 if (numInstructions == 1)
1399 // Heuristics. See also doFilter()'s "Heuristics" comment when num of
1400 // instructions is 3.
1401 if (AllowMixed && !Greedy) {
1402 assert(numInstructions == 3);
1404 for (unsigned i = 0; i < Opcodes.size(); ++i) {
1405 std::vector<unsigned> StartBits;
1406 std::vector<unsigned> EndBits;
1407 std::vector<uint64_t> FieldVals;
1410 insnWithID(Insn, Opcodes[i]);
1412 // Look for islands of undecoded bits of any instruction.
1413 if (getIslands(StartBits, EndBits, FieldVals, Insn) > 0) {
1414 // Found an instruction with island(s). Now just assign a filter.
1415 runSingleFilter(StartBits[0], EndBits[0] - StartBits[0] + 1, true);
1423 // We maintain BIT_WIDTH copies of the bitAttrs automaton.
1424 // The automaton consumes the corresponding bit from each
1427 // Input symbols: 0, 1, and _ (unset).
1428 // States: NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED.
1429 // Initial state: NONE.
1431 // (NONE) ------- [01] -> (ALL_SET)
1432 // (NONE) ------- _ ----> (ALL_UNSET)
1433 // (ALL_SET) ---- [01] -> (ALL_SET)
1434 // (ALL_SET) ---- _ ----> (MIXED)
1435 // (ALL_UNSET) -- [01] -> (MIXED)
1436 // (ALL_UNSET) -- _ ----> (ALL_UNSET)
1437 // (MIXED) ------ . ----> (MIXED)
1438 // (FILTERED)---- . ----> (FILTERED)
1440 std::vector<bitAttr_t> bitAttrs;
1442 // FILTERED bit positions provide no entropy and are not worthy of pursuing.
1443 // Filter::recurse() set either BIT_TRUE or BIT_FALSE for each position.
1444 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex)
1445 if (FilterBitValues[BitIndex] == BIT_TRUE ||
1446 FilterBitValues[BitIndex] == BIT_FALSE)
1447 bitAttrs.push_back(ATTR_FILTERED);
1449 bitAttrs.push_back(ATTR_NONE);
1451 for (unsigned InsnIndex = 0; InsnIndex < numInstructions; ++InsnIndex) {
1454 insnWithID(insn, Opcodes[InsnIndex]);
1456 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
1457 switch (bitAttrs[BitIndex]) {
1459 if (insn[BitIndex] == BIT_UNSET)
1460 bitAttrs[BitIndex] = ATTR_ALL_UNSET;
1462 bitAttrs[BitIndex] = ATTR_ALL_SET;
1465 if (insn[BitIndex] == BIT_UNSET)
1466 bitAttrs[BitIndex] = ATTR_MIXED;
1468 case ATTR_ALL_UNSET:
1469 if (insn[BitIndex] != BIT_UNSET)
1470 bitAttrs[BitIndex] = ATTR_MIXED;
1479 // The regionAttr automaton consumes the bitAttrs automatons' state,
1480 // lowest-to-highest.
1482 // Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed)
1483 // States: NONE, ALL_SET, MIXED
1484 // Initial state: NONE
1486 // (NONE) ----- F --> (NONE)
1487 // (NONE) ----- S --> (ALL_SET) ; and set region start
1488 // (NONE) ----- U --> (NONE)
1489 // (NONE) ----- M --> (MIXED) ; and set region start
1490 // (ALL_SET) -- F --> (NONE) ; and report an ALL_SET region
1491 // (ALL_SET) -- S --> (ALL_SET)
1492 // (ALL_SET) -- U --> (NONE) ; and report an ALL_SET region
1493 // (ALL_SET) -- M --> (MIXED) ; and report an ALL_SET region
1494 // (MIXED) ---- F --> (NONE) ; and report a MIXED region
1495 // (MIXED) ---- S --> (ALL_SET) ; and report a MIXED region
1496 // (MIXED) ---- U --> (NONE) ; and report a MIXED region
1497 // (MIXED) ---- M --> (MIXED)
1499 bitAttr_t RA = ATTR_NONE;
1500 unsigned StartBit = 0;
1502 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
1503 bitAttr_t bitAttr = bitAttrs[BitIndex];
1505 assert(bitAttr != ATTR_NONE && "Bit without attributes");
1513 StartBit = BitIndex;
1516 case ATTR_ALL_UNSET:
1519 StartBit = BitIndex;
1523 llvm_unreachable("Unexpected bitAttr!");
1529 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1534 case ATTR_ALL_UNSET:
1535 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1539 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1540 StartBit = BitIndex;
1544 llvm_unreachable("Unexpected bitAttr!");
1550 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1551 StartBit = BitIndex;
1555 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1556 StartBit = BitIndex;
1559 case ATTR_ALL_UNSET:
1560 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1566 llvm_unreachable("Unexpected bitAttr!");
1569 case ATTR_ALL_UNSET:
1570 llvm_unreachable("regionAttr state machine has no ATTR_UNSET state");
1572 llvm_unreachable("regionAttr state machine has no ATTR_FILTERED state");
1576 // At the end, if we're still in ALL_SET or MIXED states, report a region
1583 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1585 case ATTR_ALL_UNSET:
1588 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1592 // We have finished with the filter processings. Now it's time to choose
1593 // the best performing filter.
1595 bool AllUseless = true;
1596 unsigned BestScore = 0;
1598 for (unsigned i = 0, e = Filters.size(); i != e; ++i) {
1599 unsigned Usefulness = Filters[i].usefulness();
1604 if (Usefulness > BestScore) {
1606 BestScore = Usefulness;
1611 bestFilter().recurse();
1614 } // end of FilterChooser::filterProcessor(bool)
1616 // Decides on the best configuration of filter(s) to use in order to decode
1617 // the instructions. A conflict of instructions may occur, in which case we
1618 // dump the conflict set to the standard error.
1619 void FilterChooser::doFilter() {
1620 unsigned Num = Opcodes.size();
1621 assert(Num && "FilterChooser created with no instructions");
1623 // Try regions of consecutive known bit values first.
1624 if (filterProcessor(false))
1627 // Then regions of mixed bits (both known and unitialized bit values allowed).
1628 if (filterProcessor(true))
1631 // Heuristics to cope with conflict set {t2CMPrs, t2SUBSrr, t2SUBSrs} where
1632 // no single instruction for the maximum ATTR_MIXED region Inst{14-4} has a
1633 // well-known encoding pattern. In such case, we backtrack and scan for the
1634 // the very first consecutive ATTR_ALL_SET region and assign a filter to it.
1635 if (Num == 3 && filterProcessor(true, false))
1638 // If we come to here, the instruction decoding has failed.
1639 // Set the BestIndex to -1 to indicate so.
1643 // emitTableEntries - Emit state machine entries to decode our share of
1645 void FilterChooser::emitTableEntries(DecoderTableInfo &TableInfo) const {
1646 if (Opcodes.size() == 1) {
1647 // There is only one instruction in the set, which is great!
1648 // Call emitSingletonDecoder() to see whether there are any remaining
1650 emitSingletonTableEntry(TableInfo, Opcodes[0]);
1654 // Choose the best filter to do the decodings!
1655 if (BestIndex != -1) {
1656 const Filter &Best = Filters[BestIndex];
1657 if (Best.getNumFiltered() == 1)
1658 emitSingletonTableEntry(TableInfo, Best);
1660 Best.emitTableEntry(TableInfo);
1664 // We don't know how to decode these instructions! Dump the
1665 // conflict set and bail.
1667 // Print out useful conflict information for postmortem analysis.
1668 errs() << "Decoding Conflict:\n";
1670 dumpStack(errs(), "\t\t");
1672 for (unsigned i = 0; i < Opcodes.size(); ++i) {
1673 const std::string &Name = nameWithID(Opcodes[i]);
1675 errs() << '\t' << Name << " ";
1677 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
1682 static bool populateInstruction(CodeGenTarget &Target,
1683 const CodeGenInstruction &CGI, unsigned Opc,
1684 std::map<unsigned, std::vector<OperandInfo> > &Operands){
1685 const Record &Def = *CGI.TheDef;
1686 // If all the bit positions are not specified; do not decode this instruction.
1687 // We are bound to fail! For proper disassembly, the well-known encoding bits
1688 // of the instruction must be fully specified.
1690 BitsInit &Bits = getBitsField(Def, "Inst");
1691 if (Bits.allInComplete()) return false;
1693 std::vector<OperandInfo> InsnOperands;
1695 // If the instruction has specified a custom decoding hook, use that instead
1696 // of trying to auto-generate the decoder.
1697 std::string InstDecoder = Def.getValueAsString("DecoderMethod");
1698 if (InstDecoder != "") {
1699 InsnOperands.push_back(OperandInfo(InstDecoder));
1700 Operands[Opc] = InsnOperands;
1704 // Generate a description of the operand of the instruction that we know
1705 // how to decode automatically.
1706 // FIXME: We'll need to have a way to manually override this as needed.
1708 // Gather the outputs/inputs of the instruction, so we can find their
1709 // positions in the encoding. This assumes for now that they appear in the
1710 // MCInst in the order that they're listed.
1711 std::vector<std::pair<Init*, std::string> > InOutOperands;
1712 DagInit *Out = Def.getValueAsDag("OutOperandList");
1713 DagInit *In = Def.getValueAsDag("InOperandList");
1714 for (unsigned i = 0; i < Out->getNumArgs(); ++i)
1715 InOutOperands.push_back(std::make_pair(Out->getArg(i), Out->getArgName(i)));
1716 for (unsigned i = 0; i < In->getNumArgs(); ++i)
1717 InOutOperands.push_back(std::make_pair(In->getArg(i), In->getArgName(i)));
1719 // Search for tied operands, so that we can correctly instantiate
1720 // operands that are not explicitly represented in the encoding.
1721 std::map<std::string, std::string> TiedNames;
1722 for (unsigned i = 0; i < CGI.Operands.size(); ++i) {
1723 int tiedTo = CGI.Operands[i].getTiedRegister();
1725 std::pair<unsigned, unsigned> SO =
1726 CGI.Operands.getSubOperandNumber(tiedTo);
1727 TiedNames[InOutOperands[i].second] = InOutOperands[SO.first].second;
1728 TiedNames[InOutOperands[SO.first].second] = InOutOperands[i].second;
1732 std::map<std::string, std::vector<OperandInfo> > NumberedInsnOperands;
1733 std::set<std::string> NumberedInsnOperandsNoTie;
1734 if (Target.getInstructionSet()->
1735 getValueAsBit("decodePositionallyEncodedOperands")) {
1736 const std::vector<RecordVal> &Vals = Def.getValues();
1737 unsigned NumberedOp = 0;
1739 std::set<unsigned> NamedOpIndices;
1740 if (Target.getInstructionSet()->
1741 getValueAsBit("noNamedPositionallyEncodedOperands"))
1742 // Collect the set of operand indices that might correspond to named
1743 // operand, and skip these when assigning operands based on position.
1744 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1746 if (!CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
1749 NamedOpIndices.insert(OpIdx);
1752 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1753 // Ignore fixed fields in the record, we're looking for values like:
1754 // bits<5> RST = { ?, ?, ?, ?, ? };
1755 if (Vals[i].getPrefix() || Vals[i].getValue()->isComplete())
1758 // Determine if Vals[i] actually contributes to the Inst encoding.
1760 for (; bi < Bits.getNumBits(); ++bi) {
1761 VarInit *Var = nullptr;
1762 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1764 Var = dyn_cast<VarInit>(BI->getBitVar());
1766 Var = dyn_cast<VarInit>(Bits.getBit(bi));
1768 if (Var && Var->getName() == Vals[i].getName())
1772 if (bi == Bits.getNumBits())
1775 // Skip variables that correspond to explicitly-named operands.
1777 if (CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
1780 // Get the bit range for this operand:
1781 unsigned bitStart = bi++, bitWidth = 1;
1782 for (; bi < Bits.getNumBits(); ++bi) {
1783 VarInit *Var = nullptr;
1784 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1786 Var = dyn_cast<VarInit>(BI->getBitVar());
1788 Var = dyn_cast<VarInit>(Bits.getBit(bi));
1793 if (Var->getName() != Vals[i].getName())
1799 unsigned NumberOps = CGI.Operands.size();
1800 while (NumberedOp < NumberOps &&
1801 (CGI.Operands.isFlatOperandNotEmitted(NumberedOp) ||
1802 (NamedOpIndices.size() && NamedOpIndices.count(
1803 CGI.Operands.getSubOperandNumber(NumberedOp).first))))
1806 OpIdx = NumberedOp++;
1808 // OpIdx now holds the ordered operand number of Vals[i].
1809 std::pair<unsigned, unsigned> SO =
1810 CGI.Operands.getSubOperandNumber(OpIdx);
1811 const std::string &Name = CGI.Operands[SO.first].Name;
1813 DEBUG(dbgs() << "Numbered operand mapping for " << Def.getName() << ": " <<
1814 Name << "(" << SO.first << ", " << SO.second << ") => " <<
1815 Vals[i].getName() << "\n");
1817 std::string Decoder = "";
1818 Record *TypeRecord = CGI.Operands[SO.first].Rec;
1820 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
1821 StringInit *String = DecoderString ?
1822 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
1823 if (String && String->getValue() != "")
1824 Decoder = String->getValue();
1826 if (Decoder == "" &&
1827 CGI.Operands[SO.first].MIOperandInfo &&
1828 CGI.Operands[SO.first].MIOperandInfo->getNumArgs()) {
1829 Init *Arg = CGI.Operands[SO.first].MIOperandInfo->
1831 if (TypedInit *TI = cast<TypedInit>(Arg)) {
1832 RecordRecTy *Type = cast<RecordRecTy>(TI->getType());
1833 TypeRecord = Type->getRecord();
1838 if (TypeRecord->isSubClassOf("RegisterOperand"))
1839 TypeRecord = TypeRecord->getValueAsDef("RegClass");
1840 if (TypeRecord->isSubClassOf("RegisterClass")) {
1841 Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
1843 } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) {
1844 Decoder = "DecodePointerLikeRegClass" +
1845 utostr(TypeRecord->getValueAsInt("RegClassKind"));
1849 DecoderString = TypeRecord->getValue("DecoderMethod");
1850 String = DecoderString ?
1851 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
1852 if (!isReg && String && String->getValue() != "")
1853 Decoder = String->getValue();
1855 OperandInfo OpInfo(Decoder);
1856 OpInfo.addField(bitStart, bitWidth, 0);
1858 NumberedInsnOperands[Name].push_back(OpInfo);
1860 // FIXME: For complex operands with custom decoders we can't handle tied
1861 // sub-operands automatically. Skip those here and assume that this is
1862 // fixed up elsewhere.
1863 if (CGI.Operands[SO.first].MIOperandInfo &&
1864 CGI.Operands[SO.first].MIOperandInfo->getNumArgs() > 1 &&
1865 String && String->getValue() != "")
1866 NumberedInsnOperandsNoTie.insert(Name);
1870 // For each operand, see if we can figure out where it is encoded.
1871 for (std::vector<std::pair<Init*, std::string> >::const_iterator
1872 NI = InOutOperands.begin(), NE = InOutOperands.end(); NI != NE; ++NI) {
1873 if (!NumberedInsnOperands[NI->second].empty()) {
1874 InsnOperands.insert(InsnOperands.end(),
1875 NumberedInsnOperands[NI->second].begin(),
1876 NumberedInsnOperands[NI->second].end());
1878 } else if (!NumberedInsnOperands[TiedNames[NI->second]].empty()) {
1879 if (!NumberedInsnOperandsNoTie.count(TiedNames[NI->second])) {
1880 // Figure out to which (sub)operand we're tied.
1881 unsigned i = CGI.Operands.getOperandNamed(TiedNames[NI->second]);
1882 int tiedTo = CGI.Operands[i].getTiedRegister();
1884 i = CGI.Operands.getOperandNamed(NI->second);
1885 tiedTo = CGI.Operands[i].getTiedRegister();
1889 std::pair<unsigned, unsigned> SO =
1890 CGI.Operands.getSubOperandNumber(tiedTo);
1892 InsnOperands.push_back(NumberedInsnOperands[TiedNames[NI->second]]
1899 std::string Decoder = "";
1901 // At this point, we can locate the field, but we need to know how to
1902 // interpret it. As a first step, require the target to provide callbacks
1903 // for decoding register classes.
1904 // FIXME: This need to be extended to handle instructions with custom
1905 // decoder methods, and operands with (simple) MIOperandInfo's.
1906 TypedInit *TI = cast<TypedInit>(NI->first);
1907 RecordRecTy *Type = cast<RecordRecTy>(TI->getType());
1908 Record *TypeRecord = Type->getRecord();
1910 if (TypeRecord->isSubClassOf("RegisterOperand"))
1911 TypeRecord = TypeRecord->getValueAsDef("RegClass");
1912 if (TypeRecord->isSubClassOf("RegisterClass")) {
1913 Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
1915 } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) {
1916 Decoder = "DecodePointerLikeRegClass" +
1917 utostr(TypeRecord->getValueAsInt("RegClassKind"));
1921 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
1922 StringInit *String = DecoderString ?
1923 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
1924 if (!isReg && String && String->getValue() != "")
1925 Decoder = String->getValue();
1927 OperandInfo OpInfo(Decoder);
1928 unsigned Base = ~0U;
1930 unsigned Offset = 0;
1932 for (unsigned bi = 0; bi < Bits.getNumBits(); ++bi) {
1933 VarInit *Var = nullptr;
1934 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1936 Var = dyn_cast<VarInit>(BI->getBitVar());
1938 Var = dyn_cast<VarInit>(Bits.getBit(bi));
1942 OpInfo.addField(Base, Width, Offset);
1950 if (Var->getName() != NI->second &&
1951 Var->getName() != TiedNames[NI->second]) {
1953 OpInfo.addField(Base, Width, Offset);
1964 Offset = BI ? BI->getBitNum() : 0;
1965 } else if (BI && BI->getBitNum() != Offset + Width) {
1966 OpInfo.addField(Base, Width, Offset);
1969 Offset = BI->getBitNum();
1976 OpInfo.addField(Base, Width, Offset);
1978 if (OpInfo.numFields() > 0)
1979 InsnOperands.push_back(OpInfo);
1982 Operands[Opc] = InsnOperands;
1987 // Dumps the instruction encoding bits.
1988 dumpBits(errs(), Bits);
1992 // Dumps the list of operand info.
1993 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
1994 const CGIOperandList::OperandInfo &Info = CGI.Operands[i];
1995 const std::string &OperandName = Info.Name;
1996 const Record &OperandDef = *Info.Rec;
1998 errs() << "\t" << OperandName << " (" << OperandDef.getName() << ")\n";
2006 // emitFieldFromInstruction - Emit the templated helper function
2007 // fieldFromInstruction().
2008 static void emitFieldFromInstruction(formatted_raw_ostream &OS) {
2009 OS << "// Helper function for extracting fields from encoded instructions.\n"
2010 << "template<typename InsnType>\n"
2011 << "static InsnType fieldFromInstruction(InsnType insn, unsigned startBit,\n"
2012 << " unsigned numBits) {\n"
2013 << " assert(startBit + numBits <= (sizeof(InsnType)*8) &&\n"
2014 << " \"Instruction field out of bounds!\");\n"
2015 << " InsnType fieldMask;\n"
2016 << " if (numBits == sizeof(InsnType)*8)\n"
2017 << " fieldMask = (InsnType)(-1LL);\n"
2019 << " fieldMask = (((InsnType)1 << numBits) - 1) << startBit;\n"
2020 << " return (insn & fieldMask) >> startBit;\n"
2024 // emitDecodeInstruction - Emit the templated helper function
2025 // decodeInstruction().
2026 static void emitDecodeInstruction(formatted_raw_ostream &OS) {
2027 OS << "template<typename InsnType>\n"
2028 << "static DecodeStatus decodeInstruction(const uint8_t DecodeTable[], MCInst &MI,\n"
2029 << " InsnType insn, uint64_t Address,\n"
2030 << " const void *DisAsm,\n"
2031 << " const MCSubtargetInfo &STI) {\n"
2032 << " uint64_t Bits = STI.getFeatureBits();\n"
2034 << " const uint8_t *Ptr = DecodeTable;\n"
2035 << " uint32_t CurFieldValue = 0;\n"
2036 << " DecodeStatus S = MCDisassembler::Success;\n"
2038 << " ptrdiff_t Loc = Ptr - DecodeTable;\n"
2039 << " switch (*Ptr) {\n"
2041 << " errs() << Loc << \": Unexpected decode table opcode!\\n\";\n"
2042 << " return MCDisassembler::Fail;\n"
2043 << " case MCD::OPC_ExtractField: {\n"
2044 << " unsigned Start = *++Ptr;\n"
2045 << " unsigned Len = *++Ptr;\n"
2047 << " CurFieldValue = fieldFromInstruction(insn, Start, Len);\n"
2048 << " DEBUG(dbgs() << Loc << \": OPC_ExtractField(\" << Start << \", \"\n"
2049 << " << Len << \"): \" << CurFieldValue << \"\\n\");\n"
2052 << " case MCD::OPC_FilterValue: {\n"
2053 << " // Decode the field value.\n"
2054 << " unsigned Len;\n"
2055 << " InsnType Val = decodeULEB128(++Ptr, &Len);\n"
2057 << " // NumToSkip is a plain 16-bit integer.\n"
2058 << " unsigned NumToSkip = *Ptr++;\n"
2059 << " NumToSkip |= (*Ptr++) << 8;\n"
2061 << " // Perform the filter operation.\n"
2062 << " if (Val != CurFieldValue)\n"
2063 << " Ptr += NumToSkip;\n"
2064 << " DEBUG(dbgs() << Loc << \": OPC_FilterValue(\" << Val << \", \" << NumToSkip\n"
2065 << " << \"): \" << ((Val != CurFieldValue) ? \"FAIL:\" : \"PASS:\")\n"
2066 << " << \" continuing at \" << (Ptr - DecodeTable) << \"\\n\");\n"
2070 << " case MCD::OPC_CheckField: {\n"
2071 << " unsigned Start = *++Ptr;\n"
2072 << " unsigned Len = *++Ptr;\n"
2073 << " InsnType FieldValue = fieldFromInstruction(insn, Start, Len);\n"
2074 << " // Decode the field value.\n"
2075 << " uint32_t ExpectedValue = decodeULEB128(++Ptr, &Len);\n"
2077 << " // NumToSkip is a plain 16-bit integer.\n"
2078 << " unsigned NumToSkip = *Ptr++;\n"
2079 << " NumToSkip |= (*Ptr++) << 8;\n"
2081 << " // If the actual and expected values don't match, skip.\n"
2082 << " if (ExpectedValue != FieldValue)\n"
2083 << " Ptr += NumToSkip;\n"
2084 << " DEBUG(dbgs() << Loc << \": OPC_CheckField(\" << Start << \", \"\n"
2085 << " << Len << \", \" << ExpectedValue << \", \" << NumToSkip\n"
2086 << " << \"): FieldValue = \" << FieldValue << \", ExpectedValue = \"\n"
2087 << " << ExpectedValue << \": \"\n"
2088 << " << ((ExpectedValue == FieldValue) ? \"PASS\\n\" : \"FAIL\\n\"));\n"
2091 << " case MCD::OPC_CheckPredicate: {\n"
2092 << " unsigned Len;\n"
2093 << " // Decode the Predicate Index value.\n"
2094 << " unsigned PIdx = decodeULEB128(++Ptr, &Len);\n"
2096 << " // NumToSkip is a plain 16-bit integer.\n"
2097 << " unsigned NumToSkip = *Ptr++;\n"
2098 << " NumToSkip |= (*Ptr++) << 8;\n"
2099 << " // Check the predicate.\n"
2101 << " if (!(Pred = checkDecoderPredicate(PIdx, Bits)))\n"
2102 << " Ptr += NumToSkip;\n"
2104 << " DEBUG(dbgs() << Loc << \": OPC_CheckPredicate(\" << PIdx << \"): \"\n"
2105 << " << (Pred ? \"PASS\\n\" : \"FAIL\\n\"));\n"
2109 << " case MCD::OPC_Decode: {\n"
2110 << " unsigned Len;\n"
2111 << " // Decode the Opcode value.\n"
2112 << " unsigned Opc = decodeULEB128(++Ptr, &Len);\n"
2114 << " unsigned DecodeIdx = decodeULEB128(Ptr, &Len);\n"
2116 << " DEBUG(dbgs() << Loc << \": OPC_Decode: opcode \" << Opc\n"
2117 << " << \", using decoder \" << DecodeIdx << \"\\n\" );\n"
2118 << " DEBUG(dbgs() << \"----- DECODE SUCCESSFUL -----\\n\");\n"
2120 << " MI.setOpcode(Opc);\n"
2121 << " return decodeToMCInst(S, DecodeIdx, insn, MI, Address, DisAsm);\n"
2123 << " case MCD::OPC_SoftFail: {\n"
2124 << " // Decode the mask values.\n"
2125 << " unsigned Len;\n"
2126 << " InsnType PositiveMask = decodeULEB128(++Ptr, &Len);\n"
2128 << " InsnType NegativeMask = decodeULEB128(Ptr, &Len);\n"
2130 << " bool Fail = (insn & PositiveMask) || (~insn & NegativeMask);\n"
2132 << " S = MCDisassembler::SoftFail;\n"
2133 << " DEBUG(dbgs() << Loc << \": OPC_SoftFail: \" << (Fail ? \"FAIL\\n\":\"PASS\\n\"));\n"
2136 << " case MCD::OPC_Fail: {\n"
2137 << " DEBUG(dbgs() << Loc << \": OPC_Fail\\n\");\n"
2138 << " return MCDisassembler::Fail;\n"
2142 << " llvm_unreachable(\"bogosity detected in disassembler state machine!\");\n"
2146 // Emits disassembler code for instruction decoding.
2147 void FixedLenDecoderEmitter::run(raw_ostream &o) {
2148 formatted_raw_ostream OS(o);
2149 OS << "#include \"llvm/MC/MCInst.h\"\n";
2150 OS << "#include \"llvm/Support/Debug.h\"\n";
2151 OS << "#include \"llvm/Support/DataTypes.h\"\n";
2152 OS << "#include \"llvm/Support/LEB128.h\"\n";
2153 OS << "#include \"llvm/Support/raw_ostream.h\"\n";
2154 OS << "#include <assert.h>\n";
2156 OS << "namespace llvm {\n\n";
2158 emitFieldFromInstruction(OS);
2160 Target.reverseBitsForLittleEndianEncoding();
2162 // Parameterize the decoders based on namespace and instruction width.
2163 NumberedInstructions = &Target.getInstructionsByEnumValue();
2164 std::map<std::pair<std::string, unsigned>,
2165 std::vector<unsigned> > OpcMap;
2166 std::map<unsigned, std::vector<OperandInfo> > Operands;
2168 for (unsigned i = 0; i < NumberedInstructions->size(); ++i) {
2169 const CodeGenInstruction *Inst = NumberedInstructions->at(i);
2170 const Record *Def = Inst->TheDef;
2171 unsigned Size = Def->getValueAsInt("Size");
2172 if (Def->getValueAsString("Namespace") == "TargetOpcode" ||
2173 Def->getValueAsBit("isPseudo") ||
2174 Def->getValueAsBit("isAsmParserOnly") ||
2175 Def->getValueAsBit("isCodeGenOnly"))
2178 std::string DecoderNamespace = Def->getValueAsString("DecoderNamespace");
2181 if (populateInstruction(Target, *Inst, i, Operands)) {
2182 OpcMap[std::make_pair(DecoderNamespace, Size)].push_back(i);
2187 DecoderTableInfo TableInfo;
2188 for (std::map<std::pair<std::string, unsigned>,
2189 std::vector<unsigned> >::const_iterator
2190 I = OpcMap.begin(), E = OpcMap.end(); I != E; ++I) {
2191 // Emit the decoder for this namespace+width combination.
2192 FilterChooser FC(*NumberedInstructions, I->second, Operands,
2193 8*I->first.second, this);
2195 // The decode table is cleared for each top level decoder function. The
2196 // predicates and decoders themselves, however, are shared across all
2197 // decoders to give more opportunities for uniqueing.
2198 TableInfo.Table.clear();
2199 TableInfo.FixupStack.clear();
2200 TableInfo.Table.reserve(16384);
2201 TableInfo.FixupStack.push_back(FixupList());
2202 FC.emitTableEntries(TableInfo);
2203 // Any NumToSkip fixups in the top level scope can resolve to the
2204 // OPC_Fail at the end of the table.
2205 assert(TableInfo.FixupStack.size() == 1 && "fixup stack phasing error!");
2206 // Resolve any NumToSkip fixups in the current scope.
2207 resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
2208 TableInfo.Table.size());
2209 TableInfo.FixupStack.clear();
2211 TableInfo.Table.push_back(MCD::OPC_Fail);
2213 // Print the table to the output stream.
2214 emitTable(OS, TableInfo.Table, 0, FC.getBitWidth(), I->first.first);
2218 // Emit the predicate function.
2219 emitPredicateFunction(OS, TableInfo.Predicates, 0);
2221 // Emit the decoder function.
2222 emitDecoderFunction(OS, TableInfo.Decoders, 0);
2224 // Emit the main entry point for the decoder, decodeInstruction().
2225 emitDecodeInstruction(OS);
2227 OS << "\n} // End llvm namespace\n";
2232 void EmitFixedLenDecoder(RecordKeeper &RK, raw_ostream &OS,
2233 std::string PredicateNamespace,
2234 std::string GPrefix,
2235 std::string GPostfix,
2239 FixedLenDecoderEmitter(RK, PredicateNamespace, GPrefix, GPostfix,
2240 ROK, RFail, L).run(OS);
2243 } // End llvm namespace