1 //===------------ FixedLenDecoderEmitter.cpp - Decoder Generator ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // It contains the tablegen backend that emits the decoder functions for
11 // targets with fixed length instruction set.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "decoder-emitter"
17 #include "CodeGenTarget.h"
18 #include "llvm/TableGen/Error.h"
19 #include "llvm/TableGen/Record.h"
20 #include "llvm/ADT/APInt.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/MC/MCFixedLenDisassembler.h"
26 #include "llvm/Support/DataTypes.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/FormattedStream.h"
29 #include "llvm/Support/LEB128.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/TableGen/TableGenBackend.h"
40 struct EncodingField {
41 unsigned Base, Width, Offset;
42 EncodingField(unsigned B, unsigned W, unsigned O)
43 : Base(B), Width(W), Offset(O) { }
47 std::vector<EncodingField> Fields;
50 OperandInfo(std::string D)
53 void addField(unsigned Base, unsigned Width, unsigned Offset) {
54 Fields.push_back(EncodingField(Base, Width, Offset));
57 unsigned numFields() const { return Fields.size(); }
59 typedef std::vector<EncodingField>::const_iterator const_iterator;
61 const_iterator begin() const { return Fields.begin(); }
62 const_iterator end() const { return Fields.end(); }
65 typedef std::vector<uint8_t> DecoderTable;
66 typedef uint32_t DecoderFixup;
67 typedef std::vector<DecoderFixup> FixupList;
68 typedef std::vector<FixupList> FixupScopeList;
69 typedef SetVector<std::string> PredicateSet;
70 typedef SetVector<std::string> DecoderSet;
71 struct DecoderTableInfo {
73 FixupScopeList FixupStack;
74 PredicateSet Predicates;
78 } // End anonymous namespace
81 class FixedLenDecoderEmitter {
82 const std::vector<const CodeGenInstruction*> *NumberedInstructions;
85 // Defaults preserved here for documentation, even though they aren't
86 // strictly necessary given the way that this is currently being called.
87 FixedLenDecoderEmitter(RecordKeeper &R,
88 std::string PredicateNamespace,
89 std::string GPrefix = "if (",
90 std::string GPostfix = " == MCDisassembler::Fail)"
91 " return MCDisassembler::Fail;",
92 std::string ROK = "MCDisassembler::Success",
93 std::string RFail = "MCDisassembler::Fail",
96 PredicateNamespace(PredicateNamespace),
97 GuardPrefix(GPrefix), GuardPostfix(GPostfix),
98 ReturnOK(ROK), ReturnFail(RFail), Locals(L) {}
100 // Emit the decoder state machine table.
101 void emitTable(formatted_raw_ostream &o, DecoderTable &Table,
102 unsigned Indentation, unsigned BitWidth,
103 StringRef Namespace) const;
104 void emitPredicateFunction(formatted_raw_ostream &OS,
105 PredicateSet &Predicates,
106 unsigned Indentation) const;
107 void emitDecoderFunction(formatted_raw_ostream &OS,
108 DecoderSet &Decoders,
109 unsigned Indentation) const;
111 // run - Output the code emitter
112 void run(raw_ostream &o);
115 CodeGenTarget Target;
117 std::string PredicateNamespace;
118 std::string GuardPrefix, GuardPostfix;
119 std::string ReturnOK, ReturnFail;
122 } // End anonymous namespace
124 // The set (BIT_TRUE, BIT_FALSE, BIT_UNSET) represents a ternary logic system
127 // BIT_UNFILTERED is used as the init value for a filter position. It is used
128 // only for filter processings.
133 BIT_UNFILTERED // unfiltered
136 static bool ValueSet(bit_value_t V) {
137 return (V == BIT_TRUE || V == BIT_FALSE);
139 static bool ValueNotSet(bit_value_t V) {
140 return (V == BIT_UNSET);
142 static int Value(bit_value_t V) {
143 return ValueNotSet(V) ? -1 : (V == BIT_FALSE ? 0 : 1);
145 static bit_value_t bitFromBits(const BitsInit &bits, unsigned index) {
146 if (BitInit *bit = dyn_cast<BitInit>(bits.getBit(index)))
147 return bit->getValue() ? BIT_TRUE : BIT_FALSE;
149 // The bit is uninitialized.
152 // Prints the bit value for each position.
153 static void dumpBits(raw_ostream &o, const BitsInit &bits) {
154 for (unsigned index = bits.getNumBits(); index > 0; --index) {
155 switch (bitFromBits(bits, index - 1)) {
166 llvm_unreachable("unexpected return value from bitFromBits");
171 static BitsInit &getBitsField(const Record &def, const char *str) {
172 BitsInit *bits = def.getValueAsBitsInit(str);
176 // Forward declaration.
179 } // End anonymous namespace
181 // Representation of the instruction to work on.
182 typedef std::vector<bit_value_t> insn_t;
184 /// Filter - Filter works with FilterChooser to produce the decoding tree for
187 /// It is useful to think of a Filter as governing the switch stmts of the
188 /// decoding tree in a certain level. Each case stmt delegates to an inferior
189 /// FilterChooser to decide what further decoding logic to employ, or in another
190 /// words, what other remaining bits to look at. The FilterChooser eventually
191 /// chooses a best Filter to do its job.
193 /// This recursive scheme ends when the number of Opcodes assigned to the
194 /// FilterChooser becomes 1 or if there is a conflict. A conflict happens when
195 /// the Filter/FilterChooser combo does not know how to distinguish among the
196 /// Opcodes assigned.
198 /// An example of a conflict is
201 /// 111101000.00........00010000....
202 /// 111101000.00........0001........
203 /// 1111010...00........0001........
204 /// 1111010...00....................
205 /// 1111010.........................
206 /// 1111............................
207 /// ................................
208 /// VST4q8a 111101000_00________00010000____
209 /// VST4q8b 111101000_00________00010000____
211 /// The Debug output shows the path that the decoding tree follows to reach the
212 /// the conclusion that there is a conflict. VST4q8a is a vst4 to double-spaced
213 /// even registers, while VST4q8b is a vst4 to double-spaced odd regsisters.
215 /// The encoding info in the .td files does not specify this meta information,
216 /// which could have been used by the decoder to resolve the conflict. The
217 /// decoder could try to decode the even/odd register numbering and assign to
218 /// VST4q8a or VST4q8b, but for the time being, the decoder chooses the "a"
219 /// version and return the Opcode since the two have the same Asm format string.
223 const FilterChooser *Owner;// points to the FilterChooser who owns this filter
224 unsigned StartBit; // the starting bit position
225 unsigned NumBits; // number of bits to filter
226 bool Mixed; // a mixed region contains both set and unset bits
228 // Map of well-known segment value to the set of uid's with that value.
229 std::map<uint64_t, std::vector<unsigned> > FilteredInstructions;
231 // Set of uid's with non-constant segment values.
232 std::vector<unsigned> VariableInstructions;
234 // Map of well-known segment value to its delegate.
235 std::map<unsigned, const FilterChooser*> FilterChooserMap;
237 // Number of instructions which fall under FilteredInstructions category.
238 unsigned NumFiltered;
240 // Keeps track of the last opcode in the filtered bucket.
241 unsigned LastOpcFiltered;
244 unsigned getNumFiltered() const { return NumFiltered; }
245 unsigned getSingletonOpc() const {
246 assert(NumFiltered == 1);
247 return LastOpcFiltered;
249 // Return the filter chooser for the group of instructions without constant
251 const FilterChooser &getVariableFC() const {
252 assert(NumFiltered == 1);
253 assert(FilterChooserMap.size() == 1);
254 return *(FilterChooserMap.find((unsigned)-1)->second);
257 Filter(const Filter &f);
258 Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, bool mixed);
262 // Divides the decoding task into sub tasks and delegates them to the
263 // inferior FilterChooser's.
265 // A special case arises when there's only one entry in the filtered
266 // instructions. In order to unambiguously decode the singleton, we need to
267 // match the remaining undecoded encoding bits against the singleton.
270 // Emit table entries to decode instructions given a segment or segments of
272 void emitTableEntry(DecoderTableInfo &TableInfo) const;
274 // Returns the number of fanout produced by the filter. More fanout implies
275 // the filter distinguishes more categories of instructions.
276 unsigned usefulness() const;
277 }; // End of class Filter
278 } // End anonymous namespace
280 // These are states of our finite state machines used in FilterChooser's
281 // filterProcessor() which produces the filter candidates to use.
290 /// FilterChooser - FilterChooser chooses the best filter among a set of Filters
291 /// in order to perform the decoding of instructions at the current level.
293 /// Decoding proceeds from the top down. Based on the well-known encoding bits
294 /// of instructions available, FilterChooser builds up the possible Filters that
295 /// can further the task of decoding by distinguishing among the remaining
296 /// candidate instructions.
298 /// Once a filter has been chosen, it is called upon to divide the decoding task
299 /// into sub-tasks and delegates them to its inferior FilterChoosers for further
302 /// It is useful to think of a Filter as governing the switch stmts of the
303 /// decoding tree. And each case is delegated to an inferior FilterChooser to
304 /// decide what further remaining bits to look at.
306 class FilterChooser {
310 // Vector of codegen instructions to choose our filter.
311 const std::vector<const CodeGenInstruction*> &AllInstructions;
313 // Vector of uid's for this filter chooser to work on.
314 const std::vector<unsigned> &Opcodes;
316 // Lookup table for the operand decoding of instructions.
317 const std::map<unsigned, std::vector<OperandInfo> > &Operands;
319 // Vector of candidate filters.
320 std::vector<Filter> Filters;
322 // Array of bit values passed down from our parent.
323 // Set to all BIT_UNFILTERED's for Parent == NULL.
324 std::vector<bit_value_t> FilterBitValues;
326 // Links to the FilterChooser above us in the decoding tree.
327 const FilterChooser *Parent;
329 // Index of the best filter from Filters.
332 // Width of instructions
336 const FixedLenDecoderEmitter *Emitter;
339 FilterChooser(const FilterChooser &FC)
340 : AllInstructions(FC.AllInstructions), Opcodes(FC.Opcodes),
341 Operands(FC.Operands), Filters(FC.Filters),
342 FilterBitValues(FC.FilterBitValues), Parent(FC.Parent),
343 BestIndex(FC.BestIndex), BitWidth(FC.BitWidth),
344 Emitter(FC.Emitter) { }
346 FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
347 const std::vector<unsigned> &IDs,
348 const std::map<unsigned, std::vector<OperandInfo> > &Ops,
350 const FixedLenDecoderEmitter *E)
351 : AllInstructions(Insts), Opcodes(IDs), Operands(Ops), Filters(),
352 Parent(NULL), BestIndex(-1), BitWidth(BW), Emitter(E) {
353 for (unsigned i = 0; i < BitWidth; ++i)
354 FilterBitValues.push_back(BIT_UNFILTERED);
359 FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
360 const std::vector<unsigned> &IDs,
361 const std::map<unsigned, std::vector<OperandInfo> > &Ops,
362 const std::vector<bit_value_t> &ParentFilterBitValues,
363 const FilterChooser &parent)
364 : AllInstructions(Insts), Opcodes(IDs), Operands(Ops),
365 Filters(), FilterBitValues(ParentFilterBitValues),
366 Parent(&parent), BestIndex(-1), BitWidth(parent.BitWidth),
367 Emitter(parent.Emitter) {
371 unsigned getBitWidth() const { return BitWidth; }
374 // Populates the insn given the uid.
375 void insnWithID(insn_t &Insn, unsigned Opcode) const {
376 BitsInit &Bits = getBitsField(*AllInstructions[Opcode]->TheDef, "Inst");
378 // We may have a SoftFail bitmask, which specifies a mask where an encoding
379 // may differ from the value in "Inst" and yet still be valid, but the
380 // disassembler should return SoftFail instead of Success.
382 // This is used for marking UNPREDICTABLE instructions in the ARM world.
384 AllInstructions[Opcode]->TheDef->getValueAsBitsInit("SoftFail");
386 for (unsigned i = 0; i < BitWidth; ++i) {
387 if (SFBits && bitFromBits(*SFBits, i) == BIT_TRUE)
388 Insn.push_back(BIT_UNSET);
390 Insn.push_back(bitFromBits(Bits, i));
394 // Returns the record name.
395 const std::string &nameWithID(unsigned Opcode) const {
396 return AllInstructions[Opcode]->TheDef->getName();
399 // Populates the field of the insn given the start position and the number of
400 // consecutive bits to scan for.
402 // Returns false if there exists any uninitialized bit value in the range.
403 // Returns true, otherwise.
404 bool fieldFromInsn(uint64_t &Field, insn_t &Insn, unsigned StartBit,
405 unsigned NumBits) const;
407 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
408 /// filter array as a series of chars.
409 void dumpFilterArray(raw_ostream &o,
410 const std::vector<bit_value_t> & filter) const;
412 /// dumpStack - dumpStack traverses the filter chooser chain and calls
413 /// dumpFilterArray on each filter chooser up to the top level one.
414 void dumpStack(raw_ostream &o, const char *prefix) const;
416 Filter &bestFilter() {
417 assert(BestIndex != -1 && "BestIndex not set");
418 return Filters[BestIndex];
421 // Called from Filter::recurse() when singleton exists. For debug purpose.
422 void SingletonExists(unsigned Opc) const;
424 bool PositionFiltered(unsigned i) const {
425 return ValueSet(FilterBitValues[i]);
428 // Calculates the island(s) needed to decode the instruction.
429 // This returns a lit of undecoded bits of an instructions, for example,
430 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
431 // decoded bits in order to verify that the instruction matches the Opcode.
432 unsigned getIslands(std::vector<unsigned> &StartBits,
433 std::vector<unsigned> &EndBits,
434 std::vector<uint64_t> &FieldVals,
435 const insn_t &Insn) const;
437 // Emits code to check the Predicates member of an instruction are true.
438 // Returns true if predicate matches were emitted, false otherwise.
439 bool emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
442 bool doesOpcodeNeedPredicate(unsigned Opc) const;
443 unsigned getPredicateIndex(DecoderTableInfo &TableInfo, StringRef P) const;
444 void emitPredicateTableEntry(DecoderTableInfo &TableInfo,
447 void emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
450 // Emits table entries to decode the singleton.
451 void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
454 // Emits code to decode the singleton, and then to decode the rest.
455 void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
456 const Filter &Best) const;
458 void emitBinaryParser(raw_ostream &o, unsigned &Indentation,
459 const OperandInfo &OpInfo) const;
461 void emitDecoder(raw_ostream &OS, unsigned Indentation, unsigned Opc) const;
462 unsigned getDecoderIndex(DecoderSet &Decoders, unsigned Opc) const;
464 // Assign a single filter and run with it.
465 void runSingleFilter(unsigned startBit, unsigned numBit, bool mixed);
467 // reportRegion is a helper function for filterProcessor to mark a region as
468 // eligible for use as a filter region.
469 void reportRegion(bitAttr_t RA, unsigned StartBit, unsigned BitIndex,
472 // FilterProcessor scans the well-known encoding bits of the instructions and
473 // builds up a list of candidate filters. It chooses the best filter and
474 // recursively descends down the decoding tree.
475 bool filterProcessor(bool AllowMixed, bool Greedy = true);
477 // Decides on the best configuration of filter(s) to use in order to decode
478 // the instructions. A conflict of instructions may occur, in which case we
479 // dump the conflict set to the standard error.
483 // emitTableEntries - Emit state machine entries to decode our share of
485 void emitTableEntries(DecoderTableInfo &TableInfo) const;
487 } // End anonymous namespace
489 ///////////////////////////
491 // Filter Implementation //
493 ///////////////////////////
495 Filter::Filter(const Filter &f)
496 : Owner(f.Owner), StartBit(f.StartBit), NumBits(f.NumBits), Mixed(f.Mixed),
497 FilteredInstructions(f.FilteredInstructions),
498 VariableInstructions(f.VariableInstructions),
499 FilterChooserMap(f.FilterChooserMap), NumFiltered(f.NumFiltered),
500 LastOpcFiltered(f.LastOpcFiltered) {
503 Filter::Filter(FilterChooser &owner, unsigned startBit, unsigned numBits,
505 : Owner(&owner), StartBit(startBit), NumBits(numBits), Mixed(mixed) {
506 assert(StartBit + NumBits - 1 < Owner->BitWidth);
511 for (unsigned i = 0, e = Owner->Opcodes.size(); i != e; ++i) {
514 // Populates the insn given the uid.
515 Owner->insnWithID(Insn, Owner->Opcodes[i]);
518 // Scans the segment for possibly well-specified encoding bits.
519 bool ok = Owner->fieldFromInsn(Field, Insn, StartBit, NumBits);
522 // The encoding bits are well-known. Lets add the uid of the
523 // instruction into the bucket keyed off the constant field value.
524 LastOpcFiltered = Owner->Opcodes[i];
525 FilteredInstructions[Field].push_back(LastOpcFiltered);
528 // Some of the encoding bit(s) are unspecified. This contributes to
529 // one additional member of "Variable" instructions.
530 VariableInstructions.push_back(Owner->Opcodes[i]);
534 assert((FilteredInstructions.size() + VariableInstructions.size() > 0)
535 && "Filter returns no instruction categories");
539 std::map<unsigned, const FilterChooser*>::iterator filterIterator;
540 for (filterIterator = FilterChooserMap.begin();
541 filterIterator != FilterChooserMap.end();
543 delete filterIterator->second;
547 // Divides the decoding task into sub tasks and delegates them to the
548 // inferior FilterChooser's.
550 // A special case arises when there's only one entry in the filtered
551 // instructions. In order to unambiguously decode the singleton, we need to
552 // match the remaining undecoded encoding bits against the singleton.
553 void Filter::recurse() {
554 std::map<uint64_t, std::vector<unsigned> >::const_iterator mapIterator;
556 // Starts by inheriting our parent filter chooser's filter bit values.
557 std::vector<bit_value_t> BitValueArray(Owner->FilterBitValues);
559 if (VariableInstructions.size()) {
560 // Conservatively marks each segment position as BIT_UNSET.
561 for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex)
562 BitValueArray[StartBit + bitIndex] = BIT_UNSET;
564 // Delegates to an inferior filter chooser for further processing on this
565 // group of instructions whose segment values are variable.
566 FilterChooserMap.insert(std::pair<unsigned, const FilterChooser*>(
568 new FilterChooser(Owner->AllInstructions,
569 VariableInstructions,
576 // No need to recurse for a singleton filtered instruction.
577 // See also Filter::emit*().
578 if (getNumFiltered() == 1) {
579 //Owner->SingletonExists(LastOpcFiltered);
580 assert(FilterChooserMap.size() == 1);
584 // Otherwise, create sub choosers.
585 for (mapIterator = FilteredInstructions.begin();
586 mapIterator != FilteredInstructions.end();
589 // Marks all the segment positions with either BIT_TRUE or BIT_FALSE.
590 for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex) {
591 if (mapIterator->first & (1ULL << bitIndex))
592 BitValueArray[StartBit + bitIndex] = BIT_TRUE;
594 BitValueArray[StartBit + bitIndex] = BIT_FALSE;
597 // Delegates to an inferior filter chooser for further processing on this
598 // category of instructions.
599 FilterChooserMap.insert(std::pair<unsigned, const FilterChooser*>(
601 new FilterChooser(Owner->AllInstructions,
610 static void resolveTableFixups(DecoderTable &Table, const FixupList &Fixups,
612 // Any NumToSkip fixups in the current scope can resolve to the
614 for (FixupList::const_reverse_iterator I = Fixups.rbegin(),
617 // Calculate the distance from the byte following the fixup entry byte
618 // to the destination. The Target is calculated from after the 16-bit
619 // NumToSkip entry itself, so subtract two from the displacement here
620 // to account for that.
621 uint32_t FixupIdx = *I;
622 uint32_t Delta = DestIdx - FixupIdx - 2;
623 // Our NumToSkip entries are 16-bits. Make sure our table isn't too
625 assert(Delta < 65536U && "disassembler decoding table too large!");
626 Table[FixupIdx] = (uint8_t)Delta;
627 Table[FixupIdx + 1] = (uint8_t)(Delta >> 8);
631 // Emit table entries to decode instructions given a segment or segments
633 void Filter::emitTableEntry(DecoderTableInfo &TableInfo) const {
634 TableInfo.Table.push_back(MCD::OPC_ExtractField);
635 TableInfo.Table.push_back(StartBit);
636 TableInfo.Table.push_back(NumBits);
638 // A new filter entry begins a new scope for fixup resolution.
639 TableInfo.FixupStack.push_back(FixupList());
641 std::map<unsigned, const FilterChooser*>::const_iterator filterIterator;
643 DecoderTable &Table = TableInfo.Table;
645 size_t PrevFilter = 0;
646 bool HasFallthrough = false;
647 for (filterIterator = FilterChooserMap.begin();
648 filterIterator != FilterChooserMap.end();
650 // Field value -1 implies a non-empty set of variable instructions.
651 // See also recurse().
652 if (filterIterator->first == (unsigned)-1) {
653 HasFallthrough = true;
655 // Each scope should always have at least one filter value to check
657 assert(PrevFilter != 0 && "empty filter set!");
658 FixupList &CurScope = TableInfo.FixupStack.back();
659 // Resolve any NumToSkip fixups in the current scope.
660 resolveTableFixups(Table, CurScope, Table.size());
662 PrevFilter = 0; // Don't re-process the filter's fallthrough.
664 Table.push_back(MCD::OPC_FilterValue);
665 // Encode and emit the value to filter against.
667 unsigned Len = encodeULEB128(filterIterator->first, Buffer);
668 Table.insert(Table.end(), Buffer, Buffer + Len);
669 // Reserve space for the NumToSkip entry. We'll backpatch the value
671 PrevFilter = Table.size();
676 // We arrive at a category of instructions with the same segment value.
677 // Now delegate to the sub filter chooser for further decodings.
678 // The case may fallthrough, which happens if the remaining well-known
679 // encoding bits do not match exactly.
680 filterIterator->second->emitTableEntries(TableInfo);
682 // Now that we've emitted the body of the handler, update the NumToSkip
683 // of the filter itself to be able to skip forward when false. Subtract
684 // two as to account for the width of the NumToSkip field itself.
686 uint32_t NumToSkip = Table.size() - PrevFilter - 2;
687 assert(NumToSkip < 65536U && "disassembler decoding table too large!");
688 Table[PrevFilter] = (uint8_t)NumToSkip;
689 Table[PrevFilter + 1] = (uint8_t)(NumToSkip >> 8);
693 // Any remaining unresolved fixups bubble up to the parent fixup scope.
694 assert(TableInfo.FixupStack.size() > 1 && "fixup stack underflow!");
695 FixupScopeList::iterator Source = TableInfo.FixupStack.end() - 1;
696 FixupScopeList::iterator Dest = Source - 1;
697 Dest->insert(Dest->end(), Source->begin(), Source->end());
698 TableInfo.FixupStack.pop_back();
700 // If there is no fallthrough, then the final filter should get fixed
701 // up according to the enclosing scope rather than the current position.
703 TableInfo.FixupStack.back().push_back(PrevFilter);
706 // Returns the number of fanout produced by the filter. More fanout implies
707 // the filter distinguishes more categories of instructions.
708 unsigned Filter::usefulness() const {
709 if (VariableInstructions.size())
710 return FilteredInstructions.size();
712 return FilteredInstructions.size() + 1;
715 //////////////////////////////////
717 // Filterchooser Implementation //
719 //////////////////////////////////
721 // Emit the decoder state machine table.
722 void FixedLenDecoderEmitter::emitTable(formatted_raw_ostream &OS,
724 unsigned Indentation,
726 StringRef Namespace) const {
727 OS.indent(Indentation) << "static const uint8_t DecoderTable" << Namespace
728 << BitWidth << "[] = {\n";
732 // FIXME: We may be able to use the NumToSkip values to recover
733 // appropriate indentation levels.
734 DecoderTable::const_iterator I = Table.begin();
735 DecoderTable::const_iterator E = Table.end();
737 assert (I < E && "incomplete decode table entry!");
739 uint64_t Pos = I - Table.begin();
740 OS << "/* " << Pos << " */";
745 PrintFatalError("invalid decode table opcode");
746 case MCD::OPC_ExtractField: {
748 unsigned Start = *I++;
750 OS.indent(Indentation) << "MCD::OPC_ExtractField, " << Start << ", "
751 << Len << ", // Inst{";
753 OS << (Start + Len - 1) << "-";
754 OS << Start << "} ...\n";
757 case MCD::OPC_FilterValue: {
759 OS.indent(Indentation) << "MCD::OPC_FilterValue, ";
760 // The filter value is ULEB128 encoded.
762 OS << utostr(*I++) << ", ";
763 OS << utostr(*I++) << ", ";
765 // 16-bit numtoskip value.
767 uint32_t NumToSkip = Byte;
768 OS << utostr(Byte) << ", ";
770 OS << utostr(Byte) << ", ";
771 NumToSkip |= Byte << 8;
772 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
775 case MCD::OPC_CheckField: {
777 unsigned Start = *I++;
779 OS.indent(Indentation) << "MCD::OPC_CheckField, " << Start << ", "
780 << Len << ", ";// << Val << ", " << NumToSkip << ",\n";
781 // ULEB128 encoded field value.
782 for (; *I >= 128; ++I)
783 OS << utostr(*I) << ", ";
784 OS << utostr(*I++) << ", ";
785 // 16-bit numtoskip value.
787 uint32_t NumToSkip = Byte;
788 OS << utostr(Byte) << ", ";
790 OS << utostr(Byte) << ", ";
791 NumToSkip |= Byte << 8;
792 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
795 case MCD::OPC_CheckPredicate: {
797 OS.indent(Indentation) << "MCD::OPC_CheckPredicate, ";
798 for (; *I >= 128; ++I)
799 OS << utostr(*I) << ", ";
800 OS << utostr(*I++) << ", ";
802 // 16-bit numtoskip value.
804 uint32_t NumToSkip = Byte;
805 OS << utostr(Byte) << ", ";
807 OS << utostr(Byte) << ", ";
808 NumToSkip |= Byte << 8;
809 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
812 case MCD::OPC_Decode: {
814 // Extract the ULEB128 encoded Opcode to a buffer.
815 uint8_t Buffer[8], *p = Buffer;
816 while ((*p++ = *I++) >= 128)
817 assert((p - Buffer) <= (ptrdiff_t)sizeof(Buffer)
818 && "ULEB128 value too large!");
819 // Decode the Opcode value.
820 unsigned Opc = decodeULEB128(Buffer);
821 OS.indent(Indentation) << "MCD::OPC_Decode, ";
822 for (p = Buffer; *p >= 128; ++p)
823 OS << utostr(*p) << ", ";
824 OS << utostr(*p) << ", ";
827 for (; *I >= 128; ++I)
828 OS << utostr(*I) << ", ";
829 OS << utostr(*I++) << ", ";
832 << NumberedInstructions->at(Opc)->TheDef->getName() << "\n";
835 case MCD::OPC_SoftFail: {
837 OS.indent(Indentation) << "MCD::OPC_SoftFail";
842 OS << ", " << utostr(*I);
843 Value += (*I & 0x7f) << Shift;
845 } while (*I++ >= 128);
847 OS << " /* 0x" << utohexstr(Value) << " */";
852 OS << ", " << utostr(*I);
853 Value += (*I & 0x7f) << Shift;
855 } while (*I++ >= 128);
857 OS << " /* 0x" << utohexstr(Value) << " */";
861 case MCD::OPC_Fail: {
863 OS.indent(Indentation) << "MCD::OPC_Fail,\n";
868 OS.indent(Indentation) << "0\n";
872 OS.indent(Indentation) << "};\n\n";
875 void FixedLenDecoderEmitter::
876 emitPredicateFunction(formatted_raw_ostream &OS, PredicateSet &Predicates,
877 unsigned Indentation) const {
878 // The predicate function is just a big switch statement based on the
879 // input predicate index.
880 OS.indent(Indentation) << "static bool checkDecoderPredicate(unsigned Idx, "
881 << "uint64_t Bits) {\n";
883 OS.indent(Indentation) << "switch (Idx) {\n";
884 OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
886 for (PredicateSet::const_iterator I = Predicates.begin(), E = Predicates.end();
887 I != E; ++I, ++Index) {
888 OS.indent(Indentation) << "case " << Index << ":\n";
889 OS.indent(Indentation+2) << "return (" << *I << ");\n";
891 OS.indent(Indentation) << "}\n";
893 OS.indent(Indentation) << "}\n\n";
896 void FixedLenDecoderEmitter::
897 emitDecoderFunction(formatted_raw_ostream &OS, DecoderSet &Decoders,
898 unsigned Indentation) const {
899 // The decoder function is just a big switch statement based on the
900 // input decoder index.
901 OS.indent(Indentation) << "template<typename InsnType>\n";
902 OS.indent(Indentation) << "static DecodeStatus decodeToMCInst(DecodeStatus S,"
903 << " unsigned Idx, InsnType insn, MCInst &MI,\n";
904 OS.indent(Indentation) << " uint64_t "
905 << "Address, const void *Decoder) {\n";
907 OS.indent(Indentation) << "InsnType tmp;\n";
908 OS.indent(Indentation) << "switch (Idx) {\n";
909 OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
911 for (DecoderSet::const_iterator I = Decoders.begin(), E = Decoders.end();
912 I != E; ++I, ++Index) {
913 OS.indent(Indentation) << "case " << Index << ":\n";
915 OS.indent(Indentation+2) << "return S;\n";
917 OS.indent(Indentation) << "}\n";
919 OS.indent(Indentation) << "}\n\n";
922 // Populates the field of the insn given the start position and the number of
923 // consecutive bits to scan for.
925 // Returns false if and on the first uninitialized bit value encountered.
926 // Returns true, otherwise.
927 bool FilterChooser::fieldFromInsn(uint64_t &Field, insn_t &Insn,
928 unsigned StartBit, unsigned NumBits) const {
931 for (unsigned i = 0; i < NumBits; ++i) {
932 if (Insn[StartBit + i] == BIT_UNSET)
935 if (Insn[StartBit + i] == BIT_TRUE)
936 Field = Field | (1ULL << i);
942 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
943 /// filter array as a series of chars.
944 void FilterChooser::dumpFilterArray(raw_ostream &o,
945 const std::vector<bit_value_t> &filter) const {
946 for (unsigned bitIndex = BitWidth; bitIndex > 0; bitIndex--) {
947 switch (filter[bitIndex - 1]) {
964 /// dumpStack - dumpStack traverses the filter chooser chain and calls
965 /// dumpFilterArray on each filter chooser up to the top level one.
966 void FilterChooser::dumpStack(raw_ostream &o, const char *prefix) const {
967 const FilterChooser *current = this;
971 dumpFilterArray(o, current->FilterBitValues);
973 current = current->Parent;
977 // Called from Filter::recurse() when singleton exists. For debug purpose.
978 void FilterChooser::SingletonExists(unsigned Opc) const {
980 insnWithID(Insn0, Opc);
982 errs() << "Singleton exists: " << nameWithID(Opc)
983 << " with its decoding dominating ";
984 for (unsigned i = 0; i < Opcodes.size(); ++i) {
985 if (Opcodes[i] == Opc) continue;
986 errs() << nameWithID(Opcodes[i]) << ' ';
990 dumpStack(errs(), "\t\t");
991 for (unsigned i = 0; i < Opcodes.size(); ++i) {
992 const std::string &Name = nameWithID(Opcodes[i]);
994 errs() << '\t' << Name << " ";
996 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
1001 // Calculates the island(s) needed to decode the instruction.
1002 // This returns a list of undecoded bits of an instructions, for example,
1003 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
1004 // decoded bits in order to verify that the instruction matches the Opcode.
1005 unsigned FilterChooser::getIslands(std::vector<unsigned> &StartBits,
1006 std::vector<unsigned> &EndBits,
1007 std::vector<uint64_t> &FieldVals,
1008 const insn_t &Insn) const {
1009 unsigned Num, BitNo;
1012 uint64_t FieldVal = 0;
1015 // 1: Water (the bit value does not affect decoding)
1016 // 2: Island (well-known bit value needed for decoding)
1020 for (unsigned i = 0; i < BitWidth; ++i) {
1021 Val = Value(Insn[i]);
1022 bool Filtered = PositionFiltered(i);
1024 default: llvm_unreachable("Unreachable code!");
1027 if (Filtered || Val == -1)
1028 State = 1; // Still in Water
1030 State = 2; // Into the Island
1032 StartBits.push_back(i);
1037 if (Filtered || Val == -1) {
1038 State = 1; // Into the Water
1039 EndBits.push_back(i - 1);
1040 FieldVals.push_back(FieldVal);
1043 State = 2; // Still in Island
1045 FieldVal = FieldVal | Val << BitNo;
1050 // If we are still in Island after the loop, do some housekeeping.
1052 EndBits.push_back(BitWidth - 1);
1053 FieldVals.push_back(FieldVal);
1057 assert(StartBits.size() == Num && EndBits.size() == Num &&
1058 FieldVals.size() == Num);
1062 void FilterChooser::emitBinaryParser(raw_ostream &o, unsigned &Indentation,
1063 const OperandInfo &OpInfo) const {
1064 const std::string &Decoder = OpInfo.Decoder;
1066 if (OpInfo.numFields() == 1) {
1067 OperandInfo::const_iterator OI = OpInfo.begin();
1068 o.indent(Indentation) << "tmp = fieldFromInstruction"
1069 << "(insn, " << OI->Base << ", " << OI->Width
1072 o.indent(Indentation) << "tmp = 0;\n";
1073 for (OperandInfo::const_iterator OI = OpInfo.begin(), OE = OpInfo.end();
1075 o.indent(Indentation) << "tmp |= (fieldFromInstruction"
1076 << "(insn, " << OI->Base << ", " << OI->Width
1077 << ") << " << OI->Offset << ");\n";
1082 o.indent(Indentation) << Emitter->GuardPrefix << Decoder
1083 << "(MI, tmp, Address, Decoder)"
1084 << Emitter->GuardPostfix << "\n";
1086 o.indent(Indentation) << "MI.addOperand(MCOperand::CreateImm(tmp));\n";
1090 void FilterChooser::emitDecoder(raw_ostream &OS, unsigned Indentation,
1091 unsigned Opc) const {
1092 std::map<unsigned, std::vector<OperandInfo> >::const_iterator OpIter =
1094 const std::vector<OperandInfo>& InsnOperands = OpIter->second;
1095 for (std::vector<OperandInfo>::const_iterator
1096 I = InsnOperands.begin(), E = InsnOperands.end(); I != E; ++I) {
1097 // If a custom instruction decoder was specified, use that.
1098 if (I->numFields() == 0 && I->Decoder.size()) {
1099 OS.indent(Indentation) << Emitter->GuardPrefix << I->Decoder
1100 << "(MI, insn, Address, Decoder)"
1101 << Emitter->GuardPostfix << "\n";
1105 emitBinaryParser(OS, Indentation, *I);
1109 unsigned FilterChooser::getDecoderIndex(DecoderSet &Decoders,
1110 unsigned Opc) const {
1111 // Build up the predicate string.
1112 SmallString<256> Decoder;
1113 // FIXME: emitDecoder() function can take a buffer directly rather than
1115 raw_svector_ostream S(Decoder);
1117 emitDecoder(S, I, Opc);
1120 // Using the full decoder string as the key value here is a bit
1121 // heavyweight, but is effective. If the string comparisons become a
1122 // performance concern, we can implement a mangling of the predicate
1123 // data easilly enough with a map back to the actual string. That's
1124 // overkill for now, though.
1126 // Make sure the predicate is in the table.
1127 Decoders.insert(Decoder.str());
1128 // Now figure out the index for when we write out the table.
1129 DecoderSet::const_iterator P = std::find(Decoders.begin(),
1132 return (unsigned)(P - Decoders.begin());
1135 static void emitSinglePredicateMatch(raw_ostream &o, StringRef str,
1136 const std::string &PredicateNamespace) {
1138 o << "!(Bits & " << PredicateNamespace << "::"
1139 << str.slice(1,str.size()) << ")";
1141 o << "(Bits & " << PredicateNamespace << "::" << str << ")";
1144 bool FilterChooser::emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
1145 unsigned Opc) const {
1146 ListInit *Predicates =
1147 AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
1148 for (unsigned i = 0; i < Predicates->getSize(); ++i) {
1149 Record *Pred = Predicates->getElementAsRecord(i);
1150 if (!Pred->getValue("AssemblerMatcherPredicate"))
1153 std::string P = Pred->getValueAsString("AssemblerCondString");
1162 std::pair<StringRef, StringRef> pairs = SR.split(',');
1163 while (pairs.second.size()) {
1164 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
1166 pairs = pairs.second.split(',');
1168 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
1170 return Predicates->getSize() > 0;
1173 bool FilterChooser::doesOpcodeNeedPredicate(unsigned Opc) const {
1174 ListInit *Predicates =
1175 AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
1176 for (unsigned i = 0; i < Predicates->getSize(); ++i) {
1177 Record *Pred = Predicates->getElementAsRecord(i);
1178 if (!Pred->getValue("AssemblerMatcherPredicate"))
1181 std::string P = Pred->getValueAsString("AssemblerCondString");
1191 unsigned FilterChooser::getPredicateIndex(DecoderTableInfo &TableInfo,
1192 StringRef Predicate) const {
1193 // Using the full predicate string as the key value here is a bit
1194 // heavyweight, but is effective. If the string comparisons become a
1195 // performance concern, we can implement a mangling of the predicate
1196 // data easilly enough with a map back to the actual string. That's
1197 // overkill for now, though.
1199 // Make sure the predicate is in the table.
1200 TableInfo.Predicates.insert(Predicate.str());
1201 // Now figure out the index for when we write out the table.
1202 PredicateSet::const_iterator P = std::find(TableInfo.Predicates.begin(),
1203 TableInfo.Predicates.end(),
1205 return (unsigned)(P - TableInfo.Predicates.begin());
1208 void FilterChooser::emitPredicateTableEntry(DecoderTableInfo &TableInfo,
1209 unsigned Opc) const {
1210 if (!doesOpcodeNeedPredicate(Opc))
1213 // Build up the predicate string.
1214 SmallString<256> Predicate;
1215 // FIXME: emitPredicateMatch() functions can take a buffer directly rather
1217 raw_svector_ostream PS(Predicate);
1219 emitPredicateMatch(PS, I, Opc);
1221 // Figure out the index into the predicate table for the predicate just
1223 unsigned PIdx = getPredicateIndex(TableInfo, PS.str());
1224 SmallString<16> PBytes;
1225 raw_svector_ostream S(PBytes);
1226 encodeULEB128(PIdx, S);
1229 TableInfo.Table.push_back(MCD::OPC_CheckPredicate);
1231 for (unsigned i = 0, e = PBytes.size(); i != e; ++i)
1232 TableInfo.Table.push_back(PBytes[i]);
1233 // Push location for NumToSkip backpatching.
1234 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1235 TableInfo.Table.push_back(0);
1236 TableInfo.Table.push_back(0);
1239 void FilterChooser::emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
1240 unsigned Opc) const {
1242 AllInstructions[Opc]->TheDef->getValueAsBitsInit("SoftFail");
1243 if (!SFBits) return;
1244 BitsInit *InstBits = AllInstructions[Opc]->TheDef->getValueAsBitsInit("Inst");
1246 APInt PositiveMask(BitWidth, 0ULL);
1247 APInt NegativeMask(BitWidth, 0ULL);
1248 for (unsigned i = 0; i < BitWidth; ++i) {
1249 bit_value_t B = bitFromBits(*SFBits, i);
1250 bit_value_t IB = bitFromBits(*InstBits, i);
1252 if (B != BIT_TRUE) continue;
1256 // The bit is meant to be false, so emit a check to see if it is true.
1257 PositiveMask.setBit(i);
1260 // The bit is meant to be true, so emit a check to see if it is false.
1261 NegativeMask.setBit(i);
1264 // The bit is not set; this must be an error!
1265 StringRef Name = AllInstructions[Opc]->TheDef->getName();
1266 errs() << "SoftFail Conflict: bit SoftFail{" << i << "} in " << Name
1267 << " is set but Inst{" << i << "} is unset!\n"
1268 << " - You can only mark a bit as SoftFail if it is fully defined"
1269 << " (1/0 - not '?') in Inst\n";
1274 bool NeedPositiveMask = PositiveMask.getBoolValue();
1275 bool NeedNegativeMask = NegativeMask.getBoolValue();
1277 if (!NeedPositiveMask && !NeedNegativeMask)
1280 TableInfo.Table.push_back(MCD::OPC_SoftFail);
1282 SmallString<16> MaskBytes;
1283 raw_svector_ostream S(MaskBytes);
1284 if (NeedPositiveMask) {
1285 encodeULEB128(PositiveMask.getZExtValue(), S);
1287 for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
1288 TableInfo.Table.push_back(MaskBytes[i]);
1290 TableInfo.Table.push_back(0);
1291 if (NeedNegativeMask) {
1294 encodeULEB128(NegativeMask.getZExtValue(), S);
1296 for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
1297 TableInfo.Table.push_back(MaskBytes[i]);
1299 TableInfo.Table.push_back(0);
1302 // Emits table entries to decode the singleton.
1303 void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1304 unsigned Opc) const {
1305 std::vector<unsigned> StartBits;
1306 std::vector<unsigned> EndBits;
1307 std::vector<uint64_t> FieldVals;
1309 insnWithID(Insn, Opc);
1311 // Look for islands of undecoded bits of the singleton.
1312 getIslands(StartBits, EndBits, FieldVals, Insn);
1314 unsigned Size = StartBits.size();
1316 // Emit the predicate table entry if one is needed.
1317 emitPredicateTableEntry(TableInfo, Opc);
1319 // Check any additional encoding fields needed.
1320 for (unsigned I = Size; I != 0; --I) {
1321 unsigned NumBits = EndBits[I-1] - StartBits[I-1] + 1;
1322 TableInfo.Table.push_back(MCD::OPC_CheckField);
1323 TableInfo.Table.push_back(StartBits[I-1]);
1324 TableInfo.Table.push_back(NumBits);
1325 uint8_t Buffer[8], *p;
1326 encodeULEB128(FieldVals[I-1], Buffer);
1327 for (p = Buffer; *p >= 128 ; ++p)
1328 TableInfo.Table.push_back(*p);
1329 TableInfo.Table.push_back(*p);
1330 // Push location for NumToSkip backpatching.
1331 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1332 // The fixup is always 16-bits, so go ahead and allocate the space
1333 // in the table so all our relative position calculations work OK even
1334 // before we fully resolve the real value here.
1335 TableInfo.Table.push_back(0);
1336 TableInfo.Table.push_back(0);
1339 // Check for soft failure of the match.
1340 emitSoftFailTableEntry(TableInfo, Opc);
1342 TableInfo.Table.push_back(MCD::OPC_Decode);
1343 uint8_t Buffer[8], *p;
1344 encodeULEB128(Opc, Buffer);
1345 for (p = Buffer; *p >= 128 ; ++p)
1346 TableInfo.Table.push_back(*p);
1347 TableInfo.Table.push_back(*p);
1349 unsigned DIdx = getDecoderIndex(TableInfo.Decoders, Opc);
1350 SmallString<16> Bytes;
1351 raw_svector_ostream S(Bytes);
1352 encodeULEB128(DIdx, S);
1356 for (unsigned i = 0, e = Bytes.size(); i != e; ++i)
1357 TableInfo.Table.push_back(Bytes[i]);
1360 // Emits table entries to decode the singleton, and then to decode the rest.
1361 void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1362 const Filter &Best) const {
1363 unsigned Opc = Best.getSingletonOpc();
1365 // complex singletons need predicate checks from the first singleton
1366 // to refer forward to the variable filterchooser that follows.
1367 TableInfo.FixupStack.push_back(FixupList());
1369 emitSingletonTableEntry(TableInfo, Opc);
1371 resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
1372 TableInfo.Table.size());
1373 TableInfo.FixupStack.pop_back();
1375 Best.getVariableFC().emitTableEntries(TableInfo);
1379 // Assign a single filter and run with it. Top level API client can initialize
1380 // with a single filter to start the filtering process.
1381 void FilterChooser::runSingleFilter(unsigned startBit, unsigned numBit,
1384 Filter F(*this, startBit, numBit, true);
1385 Filters.push_back(F);
1386 BestIndex = 0; // Sole Filter instance to choose from.
1387 bestFilter().recurse();
1390 // reportRegion is a helper function for filterProcessor to mark a region as
1391 // eligible for use as a filter region.
1392 void FilterChooser::reportRegion(bitAttr_t RA, unsigned StartBit,
1393 unsigned BitIndex, bool AllowMixed) {
1394 if (RA == ATTR_MIXED && AllowMixed)
1395 Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, true));
1396 else if (RA == ATTR_ALL_SET && !AllowMixed)
1397 Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, false));
1400 // FilterProcessor scans the well-known encoding bits of the instructions and
1401 // builds up a list of candidate filters. It chooses the best filter and
1402 // recursively descends down the decoding tree.
1403 bool FilterChooser::filterProcessor(bool AllowMixed, bool Greedy) {
1406 unsigned numInstructions = Opcodes.size();
1408 assert(numInstructions && "Filter created with no instructions");
1410 // No further filtering is necessary.
1411 if (numInstructions == 1)
1414 // Heuristics. See also doFilter()'s "Heuristics" comment when num of
1415 // instructions is 3.
1416 if (AllowMixed && !Greedy) {
1417 assert(numInstructions == 3);
1419 for (unsigned i = 0; i < Opcodes.size(); ++i) {
1420 std::vector<unsigned> StartBits;
1421 std::vector<unsigned> EndBits;
1422 std::vector<uint64_t> FieldVals;
1425 insnWithID(Insn, Opcodes[i]);
1427 // Look for islands of undecoded bits of any instruction.
1428 if (getIslands(StartBits, EndBits, FieldVals, Insn) > 0) {
1429 // Found an instruction with island(s). Now just assign a filter.
1430 runSingleFilter(StartBits[0], EndBits[0] - StartBits[0] + 1, true);
1438 // We maintain BIT_WIDTH copies of the bitAttrs automaton.
1439 // The automaton consumes the corresponding bit from each
1442 // Input symbols: 0, 1, and _ (unset).
1443 // States: NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED.
1444 // Initial state: NONE.
1446 // (NONE) ------- [01] -> (ALL_SET)
1447 // (NONE) ------- _ ----> (ALL_UNSET)
1448 // (ALL_SET) ---- [01] -> (ALL_SET)
1449 // (ALL_SET) ---- _ ----> (MIXED)
1450 // (ALL_UNSET) -- [01] -> (MIXED)
1451 // (ALL_UNSET) -- _ ----> (ALL_UNSET)
1452 // (MIXED) ------ . ----> (MIXED)
1453 // (FILTERED)---- . ----> (FILTERED)
1455 std::vector<bitAttr_t> bitAttrs;
1457 // FILTERED bit positions provide no entropy and are not worthy of pursuing.
1458 // Filter::recurse() set either BIT_TRUE or BIT_FALSE for each position.
1459 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex)
1460 if (FilterBitValues[BitIndex] == BIT_TRUE ||
1461 FilterBitValues[BitIndex] == BIT_FALSE)
1462 bitAttrs.push_back(ATTR_FILTERED);
1464 bitAttrs.push_back(ATTR_NONE);
1466 for (unsigned InsnIndex = 0; InsnIndex < numInstructions; ++InsnIndex) {
1469 insnWithID(insn, Opcodes[InsnIndex]);
1471 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
1472 switch (bitAttrs[BitIndex]) {
1474 if (insn[BitIndex] == BIT_UNSET)
1475 bitAttrs[BitIndex] = ATTR_ALL_UNSET;
1477 bitAttrs[BitIndex] = ATTR_ALL_SET;
1480 if (insn[BitIndex] == BIT_UNSET)
1481 bitAttrs[BitIndex] = ATTR_MIXED;
1483 case ATTR_ALL_UNSET:
1484 if (insn[BitIndex] != BIT_UNSET)
1485 bitAttrs[BitIndex] = ATTR_MIXED;
1494 // The regionAttr automaton consumes the bitAttrs automatons' state,
1495 // lowest-to-highest.
1497 // Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed)
1498 // States: NONE, ALL_SET, MIXED
1499 // Initial state: NONE
1501 // (NONE) ----- F --> (NONE)
1502 // (NONE) ----- S --> (ALL_SET) ; and set region start
1503 // (NONE) ----- U --> (NONE)
1504 // (NONE) ----- M --> (MIXED) ; and set region start
1505 // (ALL_SET) -- F --> (NONE) ; and report an ALL_SET region
1506 // (ALL_SET) -- S --> (ALL_SET)
1507 // (ALL_SET) -- U --> (NONE) ; and report an ALL_SET region
1508 // (ALL_SET) -- M --> (MIXED) ; and report an ALL_SET region
1509 // (MIXED) ---- F --> (NONE) ; and report a MIXED region
1510 // (MIXED) ---- S --> (ALL_SET) ; and report a MIXED region
1511 // (MIXED) ---- U --> (NONE) ; and report a MIXED region
1512 // (MIXED) ---- M --> (MIXED)
1514 bitAttr_t RA = ATTR_NONE;
1515 unsigned StartBit = 0;
1517 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
1518 bitAttr_t bitAttr = bitAttrs[BitIndex];
1520 assert(bitAttr != ATTR_NONE && "Bit without attributes");
1528 StartBit = BitIndex;
1531 case ATTR_ALL_UNSET:
1534 StartBit = BitIndex;
1538 llvm_unreachable("Unexpected bitAttr!");
1544 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1549 case ATTR_ALL_UNSET:
1550 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1554 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1555 StartBit = BitIndex;
1559 llvm_unreachable("Unexpected bitAttr!");
1565 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1566 StartBit = BitIndex;
1570 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1571 StartBit = BitIndex;
1574 case ATTR_ALL_UNSET:
1575 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1581 llvm_unreachable("Unexpected bitAttr!");
1584 case ATTR_ALL_UNSET:
1585 llvm_unreachable("regionAttr state machine has no ATTR_UNSET state");
1587 llvm_unreachable("regionAttr state machine has no ATTR_FILTERED state");
1591 // At the end, if we're still in ALL_SET or MIXED states, report a region
1598 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1600 case ATTR_ALL_UNSET:
1603 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1607 // We have finished with the filter processings. Now it's time to choose
1608 // the best performing filter.
1610 bool AllUseless = true;
1611 unsigned BestScore = 0;
1613 for (unsigned i = 0, e = Filters.size(); i != e; ++i) {
1614 unsigned Usefulness = Filters[i].usefulness();
1619 if (Usefulness > BestScore) {
1621 BestScore = Usefulness;
1626 bestFilter().recurse();
1629 } // end of FilterChooser::filterProcessor(bool)
1631 // Decides on the best configuration of filter(s) to use in order to decode
1632 // the instructions. A conflict of instructions may occur, in which case we
1633 // dump the conflict set to the standard error.
1634 void FilterChooser::doFilter() {
1635 unsigned Num = Opcodes.size();
1636 assert(Num && "FilterChooser created with no instructions");
1638 // Try regions of consecutive known bit values first.
1639 if (filterProcessor(false))
1642 // Then regions of mixed bits (both known and unitialized bit values allowed).
1643 if (filterProcessor(true))
1646 // Heuristics to cope with conflict set {t2CMPrs, t2SUBSrr, t2SUBSrs} where
1647 // no single instruction for the maximum ATTR_MIXED region Inst{14-4} has a
1648 // well-known encoding pattern. In such case, we backtrack and scan for the
1649 // the very first consecutive ATTR_ALL_SET region and assign a filter to it.
1650 if (Num == 3 && filterProcessor(true, false))
1653 // If we come to here, the instruction decoding has failed.
1654 // Set the BestIndex to -1 to indicate so.
1658 // emitTableEntries - Emit state machine entries to decode our share of
1660 void FilterChooser::emitTableEntries(DecoderTableInfo &TableInfo) const {
1661 if (Opcodes.size() == 1) {
1662 // There is only one instruction in the set, which is great!
1663 // Call emitSingletonDecoder() to see whether there are any remaining
1665 emitSingletonTableEntry(TableInfo, Opcodes[0]);
1669 // Choose the best filter to do the decodings!
1670 if (BestIndex != -1) {
1671 const Filter &Best = Filters[BestIndex];
1672 if (Best.getNumFiltered() == 1)
1673 emitSingletonTableEntry(TableInfo, Best);
1675 Best.emitTableEntry(TableInfo);
1679 // We don't know how to decode these instructions! Dump the
1680 // conflict set and bail.
1682 // Print out useful conflict information for postmortem analysis.
1683 errs() << "Decoding Conflict:\n";
1685 dumpStack(errs(), "\t\t");
1687 for (unsigned i = 0; i < Opcodes.size(); ++i) {
1688 const std::string &Name = nameWithID(Opcodes[i]);
1690 errs() << '\t' << Name << " ";
1692 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
1697 static bool populateInstruction(const CodeGenInstruction &CGI, unsigned Opc,
1698 std::map<unsigned, std::vector<OperandInfo> > &Operands){
1699 const Record &Def = *CGI.TheDef;
1700 // If all the bit positions are not specified; do not decode this instruction.
1701 // We are bound to fail! For proper disassembly, the well-known encoding bits
1702 // of the instruction must be fully specified.
1704 // This also removes pseudo instructions from considerations of disassembly,
1705 // which is a better design and less fragile than the name matchings.
1706 // Ignore "asm parser only" instructions.
1707 if (Def.getValueAsBit("isAsmParserOnly") ||
1708 Def.getValueAsBit("isCodeGenOnly"))
1711 BitsInit &Bits = getBitsField(Def, "Inst");
1712 if (Bits.allInComplete()) return false;
1714 std::vector<OperandInfo> InsnOperands;
1716 // If the instruction has specified a custom decoding hook, use that instead
1717 // of trying to auto-generate the decoder.
1718 std::string InstDecoder = Def.getValueAsString("DecoderMethod");
1719 if (InstDecoder != "") {
1720 InsnOperands.push_back(OperandInfo(InstDecoder));
1721 Operands[Opc] = InsnOperands;
1725 // Generate a description of the operand of the instruction that we know
1726 // how to decode automatically.
1727 // FIXME: We'll need to have a way to manually override this as needed.
1729 // Gather the outputs/inputs of the instruction, so we can find their
1730 // positions in the encoding. This assumes for now that they appear in the
1731 // MCInst in the order that they're listed.
1732 std::vector<std::pair<Init*, std::string> > InOutOperands;
1733 DagInit *Out = Def.getValueAsDag("OutOperandList");
1734 DagInit *In = Def.getValueAsDag("InOperandList");
1735 for (unsigned i = 0; i < Out->getNumArgs(); ++i)
1736 InOutOperands.push_back(std::make_pair(Out->getArg(i), Out->getArgName(i)));
1737 for (unsigned i = 0; i < In->getNumArgs(); ++i)
1738 InOutOperands.push_back(std::make_pair(In->getArg(i), In->getArgName(i)));
1740 // Search for tied operands, so that we can correctly instantiate
1741 // operands that are not explicitly represented in the encoding.
1742 std::map<std::string, std::string> TiedNames;
1743 for (unsigned i = 0; i < CGI.Operands.size(); ++i) {
1744 int tiedTo = CGI.Operands[i].getTiedRegister();
1746 TiedNames[InOutOperands[i].second] = InOutOperands[tiedTo].second;
1747 TiedNames[InOutOperands[tiedTo].second] = InOutOperands[i].second;
1751 // For each operand, see if we can figure out where it is encoded.
1752 for (std::vector<std::pair<Init*, std::string> >::const_iterator
1753 NI = InOutOperands.begin(), NE = InOutOperands.end(); NI != NE; ++NI) {
1754 std::string Decoder = "";
1756 // At this point, we can locate the field, but we need to know how to
1757 // interpret it. As a first step, require the target to provide callbacks
1758 // for decoding register classes.
1759 // FIXME: This need to be extended to handle instructions with custom
1760 // decoder methods, and operands with (simple) MIOperandInfo's.
1761 TypedInit *TI = cast<TypedInit>(NI->first);
1762 RecordRecTy *Type = cast<RecordRecTy>(TI->getType());
1763 Record *TypeRecord = Type->getRecord();
1765 if (TypeRecord->isSubClassOf("RegisterOperand"))
1766 TypeRecord = TypeRecord->getValueAsDef("RegClass");
1767 if (TypeRecord->isSubClassOf("RegisterClass")) {
1768 Decoder = "Decode" + TypeRecord->getName() + "RegisterClass";
1772 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
1773 StringInit *String = DecoderString ?
1774 dyn_cast<StringInit>(DecoderString->getValue()) : 0;
1775 if (!isReg && String && String->getValue() != "")
1776 Decoder = String->getValue();
1778 OperandInfo OpInfo(Decoder);
1779 unsigned Base = ~0U;
1781 unsigned Offset = 0;
1783 for (unsigned bi = 0; bi < Bits.getNumBits(); ++bi) {
1785 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1787 Var = dyn_cast<VarInit>(BI->getBitVar());
1789 Var = dyn_cast<VarInit>(Bits.getBit(bi));
1793 OpInfo.addField(Base, Width, Offset);
1801 if (Var->getName() != NI->second &&
1802 Var->getName() != TiedNames[NI->second]) {
1804 OpInfo.addField(Base, Width, Offset);
1815 Offset = BI ? BI->getBitNum() : 0;
1816 } else if (BI && BI->getBitNum() != Offset + Width) {
1817 OpInfo.addField(Base, Width, Offset);
1820 Offset = BI->getBitNum();
1827 OpInfo.addField(Base, Width, Offset);
1829 if (OpInfo.numFields() > 0)
1830 InsnOperands.push_back(OpInfo);
1833 Operands[Opc] = InsnOperands;
1838 // Dumps the instruction encoding bits.
1839 dumpBits(errs(), Bits);
1843 // Dumps the list of operand info.
1844 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
1845 const CGIOperandList::OperandInfo &Info = CGI.Operands[i];
1846 const std::string &OperandName = Info.Name;
1847 const Record &OperandDef = *Info.Rec;
1849 errs() << "\t" << OperandName << " (" << OperandDef.getName() << ")\n";
1857 // emitFieldFromInstruction - Emit the templated helper function
1858 // fieldFromInstruction().
1859 static void emitFieldFromInstruction(formatted_raw_ostream &OS) {
1860 OS << "// Helper function for extracting fields from encoded instructions.\n"
1861 << "template<typename InsnType>\n"
1862 << "static InsnType fieldFromInstruction(InsnType insn, unsigned startBit,\n"
1863 << " unsigned numBits) {\n"
1864 << " assert(startBit + numBits <= (sizeof(InsnType)*8) &&\n"
1865 << " \"Instruction field out of bounds!\");\n"
1866 << " InsnType fieldMask;\n"
1867 << " if (numBits == sizeof(InsnType)*8)\n"
1868 << " fieldMask = (InsnType)(-1LL);\n"
1870 << " fieldMask = ((1 << numBits) - 1) << startBit;\n"
1871 << " return (insn & fieldMask) >> startBit;\n"
1875 // emitDecodeInstruction - Emit the templated helper function
1876 // decodeInstruction().
1877 static void emitDecodeInstruction(formatted_raw_ostream &OS) {
1878 OS << "template<typename InsnType>\n"
1879 << "static DecodeStatus decodeInstruction(const uint8_t DecodeTable[], MCInst &MI,\n"
1880 << " InsnType insn, uint64_t Address,\n"
1881 << " const void *DisAsm,\n"
1882 << " const MCSubtargetInfo &STI) {\n"
1883 << " uint64_t Bits = STI.getFeatureBits();\n"
1885 << " const uint8_t *Ptr = DecodeTable;\n"
1886 << " uint32_t CurFieldValue = 0;\n"
1887 << " DecodeStatus S = MCDisassembler::Success;\n"
1889 << " ptrdiff_t Loc = Ptr - DecodeTable;\n"
1890 << " switch (*Ptr) {\n"
1892 << " errs() << Loc << \": Unexpected decode table opcode!\\n\";\n"
1893 << " return MCDisassembler::Fail;\n"
1894 << " case MCD::OPC_ExtractField: {\n"
1895 << " unsigned Start = *++Ptr;\n"
1896 << " unsigned Len = *++Ptr;\n"
1898 << " CurFieldValue = fieldFromInstruction(insn, Start, Len);\n"
1899 << " DEBUG(dbgs() << Loc << \": OPC_ExtractField(\" << Start << \", \"\n"
1900 << " << Len << \"): \" << CurFieldValue << \"\\n\");\n"
1903 << " case MCD::OPC_FilterValue: {\n"
1904 << " // Decode the field value.\n"
1905 << " unsigned Len;\n"
1906 << " InsnType Val = decodeULEB128(++Ptr, &Len);\n"
1908 << " // NumToSkip is a plain 16-bit integer.\n"
1909 << " unsigned NumToSkip = *Ptr++;\n"
1910 << " NumToSkip |= (*Ptr++) << 8;\n"
1912 << " // Perform the filter operation.\n"
1913 << " if (Val != CurFieldValue)\n"
1914 << " Ptr += NumToSkip;\n"
1915 << " DEBUG(dbgs() << Loc << \": OPC_FilterValue(\" << Val << \", \" << NumToSkip\n"
1916 << " << \"): \" << ((Val != CurFieldValue) ? \"FAIL:\" : \"PASS:\")\n"
1917 << " << \" continuing at \" << (Ptr - DecodeTable) << \"\\n\");\n"
1921 << " case MCD::OPC_CheckField: {\n"
1922 << " unsigned Start = *++Ptr;\n"
1923 << " unsigned Len = *++Ptr;\n"
1924 << " InsnType FieldValue = fieldFromInstruction(insn, Start, Len);\n"
1925 << " // Decode the field value.\n"
1926 << " uint32_t ExpectedValue = decodeULEB128(++Ptr, &Len);\n"
1928 << " // NumToSkip is a plain 16-bit integer.\n"
1929 << " unsigned NumToSkip = *Ptr++;\n"
1930 << " NumToSkip |= (*Ptr++) << 8;\n"
1932 << " // If the actual and expected values don't match, skip.\n"
1933 << " if (ExpectedValue != FieldValue)\n"
1934 << " Ptr += NumToSkip;\n"
1935 << " DEBUG(dbgs() << Loc << \": OPC_CheckField(\" << Start << \", \"\n"
1936 << " << Len << \", \" << ExpectedValue << \", \" << NumToSkip\n"
1937 << " << \"): FieldValue = \" << FieldValue << \", ExpectedValue = \"\n"
1938 << " << ExpectedValue << \": \"\n"
1939 << " << ((ExpectedValue == FieldValue) ? \"PASS\\n\" : \"FAIL\\n\"));\n"
1942 << " case MCD::OPC_CheckPredicate: {\n"
1943 << " unsigned Len;\n"
1944 << " // Decode the Predicate Index value.\n"
1945 << " unsigned PIdx = decodeULEB128(++Ptr, &Len);\n"
1947 << " // NumToSkip is a plain 16-bit integer.\n"
1948 << " unsigned NumToSkip = *Ptr++;\n"
1949 << " NumToSkip |= (*Ptr++) << 8;\n"
1950 << " // Check the predicate.\n"
1952 << " if (!(Pred = checkDecoderPredicate(PIdx, Bits)))\n"
1953 << " Ptr += NumToSkip;\n"
1955 << " DEBUG(dbgs() << Loc << \": OPC_CheckPredicate(\" << PIdx << \"): \"\n"
1956 << " << (Pred ? \"PASS\\n\" : \"FAIL\\n\"));\n"
1960 << " case MCD::OPC_Decode: {\n"
1961 << " unsigned Len;\n"
1962 << " // Decode the Opcode value.\n"
1963 << " unsigned Opc = decodeULEB128(++Ptr, &Len);\n"
1965 << " unsigned DecodeIdx = decodeULEB128(Ptr, &Len);\n"
1967 << " DEBUG(dbgs() << Loc << \": OPC_Decode: opcode \" << Opc\n"
1968 << " << \", using decoder \" << DecodeIdx << \"\\n\" );\n"
1969 << " DEBUG(dbgs() << \"----- DECODE SUCCESSFUL -----\\n\");\n"
1971 << " MI.setOpcode(Opc);\n"
1972 << " return decodeToMCInst(S, DecodeIdx, insn, MI, Address, DisAsm);\n"
1974 << " case MCD::OPC_SoftFail: {\n"
1975 << " // Decode the mask values.\n"
1976 << " unsigned Len;\n"
1977 << " InsnType PositiveMask = decodeULEB128(++Ptr, &Len);\n"
1979 << " InsnType NegativeMask = decodeULEB128(Ptr, &Len);\n"
1981 << " bool Fail = (insn & PositiveMask) || (~insn & NegativeMask);\n"
1983 << " S = MCDisassembler::SoftFail;\n"
1984 << " DEBUG(dbgs() << Loc << \": OPC_SoftFail: \" << (Fail ? \"FAIL\\n\":\"PASS\\n\"));\n"
1987 << " case MCD::OPC_Fail: {\n"
1988 << " DEBUG(dbgs() << Loc << \": OPC_Fail\\n\");\n"
1989 << " return MCDisassembler::Fail;\n"
1993 << " llvm_unreachable(\"bogosity detected in disassembler state machine!\");\n"
1997 // Emits disassembler code for instruction decoding.
1998 void FixedLenDecoderEmitter::run(raw_ostream &o) {
1999 formatted_raw_ostream OS(o);
2000 OS << "#include \"llvm/MC/MCInst.h\"\n";
2001 OS << "#include \"llvm/Support/Debug.h\"\n";
2002 OS << "#include \"llvm/Support/DataTypes.h\"\n";
2003 OS << "#include \"llvm/Support/LEB128.h\"\n";
2004 OS << "#include \"llvm/Support/raw_ostream.h\"\n";
2005 OS << "#include <assert.h>\n";
2007 OS << "namespace llvm {\n\n";
2009 emitFieldFromInstruction(OS);
2011 // Parameterize the decoders based on namespace and instruction width.
2012 NumberedInstructions = &Target.getInstructionsByEnumValue();
2013 std::map<std::pair<std::string, unsigned>,
2014 std::vector<unsigned> > OpcMap;
2015 std::map<unsigned, std::vector<OperandInfo> > Operands;
2017 for (unsigned i = 0; i < NumberedInstructions->size(); ++i) {
2018 const CodeGenInstruction *Inst = NumberedInstructions->at(i);
2019 const Record *Def = Inst->TheDef;
2020 unsigned Size = Def->getValueAsInt("Size");
2021 if (Def->getValueAsString("Namespace") == "TargetOpcode" ||
2022 Def->getValueAsBit("isPseudo") ||
2023 Def->getValueAsBit("isAsmParserOnly") ||
2024 Def->getValueAsBit("isCodeGenOnly"))
2027 std::string DecoderNamespace = Def->getValueAsString("DecoderNamespace");
2030 if (populateInstruction(*Inst, i, Operands)) {
2031 OpcMap[std::make_pair(DecoderNamespace, Size)].push_back(i);
2036 DecoderTableInfo TableInfo;
2037 std::set<unsigned> Sizes;
2038 for (std::map<std::pair<std::string, unsigned>,
2039 std::vector<unsigned> >::const_iterator
2040 I = OpcMap.begin(), E = OpcMap.end(); I != E; ++I) {
2041 // Emit the decoder for this namespace+width combination.
2042 FilterChooser FC(*NumberedInstructions, I->second, Operands,
2043 8*I->first.second, this);
2045 // The decode table is cleared for each top level decoder function. The
2046 // predicates and decoders themselves, however, are shared across all
2047 // decoders to give more opportunities for uniqueing.
2048 TableInfo.Table.clear();
2049 TableInfo.FixupStack.clear();
2050 TableInfo.Table.reserve(16384);
2051 TableInfo.FixupStack.push_back(FixupList());
2052 FC.emitTableEntries(TableInfo);
2053 // Any NumToSkip fixups in the top level scope can resolve to the
2054 // OPC_Fail at the end of the table.
2055 assert(TableInfo.FixupStack.size() == 1 && "fixup stack phasing error!");
2056 // Resolve any NumToSkip fixups in the current scope.
2057 resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
2058 TableInfo.Table.size());
2059 TableInfo.FixupStack.clear();
2061 TableInfo.Table.push_back(MCD::OPC_Fail);
2063 // Print the table to the output stream.
2064 emitTable(OS, TableInfo.Table, 0, FC.getBitWidth(), I->first.first);
2068 // Emit the predicate function.
2069 emitPredicateFunction(OS, TableInfo.Predicates, 0);
2071 // Emit the decoder function.
2072 emitDecoderFunction(OS, TableInfo.Decoders, 0);
2074 // Emit the main entry point for the decoder, decodeInstruction().
2075 emitDecodeInstruction(OS);
2077 OS << "\n} // End llvm namespace\n";
2082 void EmitFixedLenDecoder(RecordKeeper &RK, raw_ostream &OS,
2083 std::string PredicateNamespace,
2084 std::string GPrefix,
2085 std::string GPostfix,
2089 FixedLenDecoderEmitter(RK, PredicateNamespace, GPrefix, GPostfix,
2090 ROK, RFail, L).run(OS);
2093 } // End llvm namespace