[llvm-exegesis] Fix wrong index type.
[llvm-core.git] / utils / TableGen / FixedLenDecoderEmitter.cpp
blob76ba1c001092a7bc9e5233c3ea36f18041ffa2a0
1 //===------------ FixedLenDecoderEmitter.cpp - Decoder Generator ----------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // It contains the tablegen backend that emits the decoder functions for
11 // targets with fixed length instruction set.
13 //===----------------------------------------------------------------------===//
15 #include "CodeGenInstruction.h"
16 #include "CodeGenTarget.h"
17 #include "llvm/ADT/APInt.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/CachedHashString.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/StringRef.h"
25 #include "llvm/MC/MCFixedLenDisassembler.h"
26 #include "llvm/Support/Casting.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/FormattedStream.h"
30 #include "llvm/Support/LEB128.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/TableGen/Error.h"
33 #include "llvm/TableGen/Record.h"
34 #include <algorithm>
35 #include <cassert>
36 #include <cstddef>
37 #include <cstdint>
38 #include <map>
39 #include <memory>
40 #include <set>
41 #include <string>
42 #include <utility>
43 #include <vector>
45 using namespace llvm;
47 #define DEBUG_TYPE "decoder-emitter"
49 namespace {
51 struct EncodingField {
52 unsigned Base, Width, Offset;
53 EncodingField(unsigned B, unsigned W, unsigned O)
54 : Base(B), Width(W), Offset(O) { }
57 struct OperandInfo {
58 std::vector<EncodingField> Fields;
59 std::string Decoder;
60 bool HasCompleteDecoder;
62 OperandInfo(std::string D, bool HCD)
63 : Decoder(std::move(D)), HasCompleteDecoder(HCD) {}
65 void addField(unsigned Base, unsigned Width, unsigned Offset) {
66 Fields.push_back(EncodingField(Base, Width, Offset));
69 unsigned numFields() const { return Fields.size(); }
71 typedef std::vector<EncodingField>::const_iterator const_iterator;
73 const_iterator begin() const { return Fields.begin(); }
74 const_iterator end() const { return Fields.end(); }
77 typedef std::vector<uint8_t> DecoderTable;
78 typedef uint32_t DecoderFixup;
79 typedef std::vector<DecoderFixup> FixupList;
80 typedef std::vector<FixupList> FixupScopeList;
81 typedef SmallSetVector<CachedHashString, 16> PredicateSet;
82 typedef SmallSetVector<CachedHashString, 16> DecoderSet;
83 struct DecoderTableInfo {
84 DecoderTable Table;
85 FixupScopeList FixupStack;
86 PredicateSet Predicates;
87 DecoderSet Decoders;
90 class FixedLenDecoderEmitter {
91 ArrayRef<const CodeGenInstruction *> NumberedInstructions;
93 public:
94 // Defaults preserved here for documentation, even though they aren't
95 // strictly necessary given the way that this is currently being called.
96 FixedLenDecoderEmitter(RecordKeeper &R, std::string PredicateNamespace,
97 std::string GPrefix = "if (",
98 std::string GPostfix = " == MCDisassembler::Fail)",
99 std::string ROK = "MCDisassembler::Success",
100 std::string RFail = "MCDisassembler::Fail",
101 std::string L = "")
102 : Target(R), PredicateNamespace(std::move(PredicateNamespace)),
103 GuardPrefix(std::move(GPrefix)), GuardPostfix(std::move(GPostfix)),
104 ReturnOK(std::move(ROK)), ReturnFail(std::move(RFail)),
105 Locals(std::move(L)) {}
107 // Emit the decoder state machine table.
108 void emitTable(formatted_raw_ostream &o, DecoderTable &Table,
109 unsigned Indentation, unsigned BitWidth,
110 StringRef Namespace) const;
111 void emitPredicateFunction(formatted_raw_ostream &OS,
112 PredicateSet &Predicates,
113 unsigned Indentation) const;
114 void emitDecoderFunction(formatted_raw_ostream &OS,
115 DecoderSet &Decoders,
116 unsigned Indentation) const;
118 // run - Output the code emitter
119 void run(raw_ostream &o);
121 private:
122 CodeGenTarget Target;
124 public:
125 std::string PredicateNamespace;
126 std::string GuardPrefix, GuardPostfix;
127 std::string ReturnOK, ReturnFail;
128 std::string Locals;
131 } // end anonymous namespace
133 // The set (BIT_TRUE, BIT_FALSE, BIT_UNSET) represents a ternary logic system
134 // for a bit value.
136 // BIT_UNFILTERED is used as the init value for a filter position. It is used
137 // only for filter processings.
138 typedef enum {
139 BIT_TRUE, // '1'
140 BIT_FALSE, // '0'
141 BIT_UNSET, // '?'
142 BIT_UNFILTERED // unfiltered
143 } bit_value_t;
145 static bool ValueSet(bit_value_t V) {
146 return (V == BIT_TRUE || V == BIT_FALSE);
149 static bool ValueNotSet(bit_value_t V) {
150 return (V == BIT_UNSET);
153 static int Value(bit_value_t V) {
154 return ValueNotSet(V) ? -1 : (V == BIT_FALSE ? 0 : 1);
157 static bit_value_t bitFromBits(const BitsInit &bits, unsigned index) {
158 if (BitInit *bit = dyn_cast<BitInit>(bits.getBit(index)))
159 return bit->getValue() ? BIT_TRUE : BIT_FALSE;
161 // The bit is uninitialized.
162 return BIT_UNSET;
165 // Prints the bit value for each position.
166 static void dumpBits(raw_ostream &o, const BitsInit &bits) {
167 for (unsigned index = bits.getNumBits(); index > 0; --index) {
168 switch (bitFromBits(bits, index - 1)) {
169 case BIT_TRUE:
170 o << "1";
171 break;
172 case BIT_FALSE:
173 o << "0";
174 break;
175 case BIT_UNSET:
176 o << "_";
177 break;
178 default:
179 llvm_unreachable("unexpected return value from bitFromBits");
184 static BitsInit &getBitsField(const Record &def, StringRef str) {
185 BitsInit *bits = def.getValueAsBitsInit(str);
186 return *bits;
189 // Representation of the instruction to work on.
190 typedef std::vector<bit_value_t> insn_t;
192 namespace {
194 class FilterChooser;
196 /// Filter - Filter works with FilterChooser to produce the decoding tree for
197 /// the ISA.
199 /// It is useful to think of a Filter as governing the switch stmts of the
200 /// decoding tree in a certain level. Each case stmt delegates to an inferior
201 /// FilterChooser to decide what further decoding logic to employ, or in another
202 /// words, what other remaining bits to look at. The FilterChooser eventually
203 /// chooses a best Filter to do its job.
205 /// This recursive scheme ends when the number of Opcodes assigned to the
206 /// FilterChooser becomes 1 or if there is a conflict. A conflict happens when
207 /// the Filter/FilterChooser combo does not know how to distinguish among the
208 /// Opcodes assigned.
210 /// An example of a conflict is
212 /// Conflict:
213 /// 111101000.00........00010000....
214 /// 111101000.00........0001........
215 /// 1111010...00........0001........
216 /// 1111010...00....................
217 /// 1111010.........................
218 /// 1111............................
219 /// ................................
220 /// VST4q8a 111101000_00________00010000____
221 /// VST4q8b 111101000_00________00010000____
223 /// The Debug output shows the path that the decoding tree follows to reach the
224 /// the conclusion that there is a conflict. VST4q8a is a vst4 to double-spaced
225 /// even registers, while VST4q8b is a vst4 to double-spaced odd registers.
227 /// The encoding info in the .td files does not specify this meta information,
228 /// which could have been used by the decoder to resolve the conflict. The
229 /// decoder could try to decode the even/odd register numbering and assign to
230 /// VST4q8a or VST4q8b, but for the time being, the decoder chooses the "a"
231 /// version and return the Opcode since the two have the same Asm format string.
232 class Filter {
233 protected:
234 const FilterChooser *Owner;// points to the FilterChooser who owns this filter
235 unsigned StartBit; // the starting bit position
236 unsigned NumBits; // number of bits to filter
237 bool Mixed; // a mixed region contains both set and unset bits
239 // Map of well-known segment value to the set of uid's with that value.
240 std::map<uint64_t, std::vector<unsigned>> FilteredInstructions;
242 // Set of uid's with non-constant segment values.
243 std::vector<unsigned> VariableInstructions;
245 // Map of well-known segment value to its delegate.
246 std::map<unsigned, std::unique_ptr<const FilterChooser>> FilterChooserMap;
248 // Number of instructions which fall under FilteredInstructions category.
249 unsigned NumFiltered;
251 // Keeps track of the last opcode in the filtered bucket.
252 unsigned LastOpcFiltered;
254 public:
255 Filter(Filter &&f);
256 Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, bool mixed);
258 ~Filter() = default;
260 unsigned getNumFiltered() const { return NumFiltered; }
262 unsigned getSingletonOpc() const {
263 assert(NumFiltered == 1);
264 return LastOpcFiltered;
267 // Return the filter chooser for the group of instructions without constant
268 // segment values.
269 const FilterChooser &getVariableFC() const {
270 assert(NumFiltered == 1);
271 assert(FilterChooserMap.size() == 1);
272 return *(FilterChooserMap.find((unsigned)-1)->second);
275 // Divides the decoding task into sub tasks and delegates them to the
276 // inferior FilterChooser's.
278 // A special case arises when there's only one entry in the filtered
279 // instructions. In order to unambiguously decode the singleton, we need to
280 // match the remaining undecoded encoding bits against the singleton.
281 void recurse();
283 // Emit table entries to decode instructions given a segment or segments of
284 // bits.
285 void emitTableEntry(DecoderTableInfo &TableInfo) const;
287 // Returns the number of fanout produced by the filter. More fanout implies
288 // the filter distinguishes more categories of instructions.
289 unsigned usefulness() const;
290 }; // end class Filter
292 } // end anonymous namespace
294 // These are states of our finite state machines used in FilterChooser's
295 // filterProcessor() which produces the filter candidates to use.
296 typedef enum {
297 ATTR_NONE,
298 ATTR_FILTERED,
299 ATTR_ALL_SET,
300 ATTR_ALL_UNSET,
301 ATTR_MIXED
302 } bitAttr_t;
304 /// FilterChooser - FilterChooser chooses the best filter among a set of Filters
305 /// in order to perform the decoding of instructions at the current level.
307 /// Decoding proceeds from the top down. Based on the well-known encoding bits
308 /// of instructions available, FilterChooser builds up the possible Filters that
309 /// can further the task of decoding by distinguishing among the remaining
310 /// candidate instructions.
312 /// Once a filter has been chosen, it is called upon to divide the decoding task
313 /// into sub-tasks and delegates them to its inferior FilterChoosers for further
314 /// processings.
316 /// It is useful to think of a Filter as governing the switch stmts of the
317 /// decoding tree. And each case is delegated to an inferior FilterChooser to
318 /// decide what further remaining bits to look at.
319 namespace {
321 class FilterChooser {
322 protected:
323 friend class Filter;
325 // Vector of codegen instructions to choose our filter.
326 ArrayRef<const CodeGenInstruction *> AllInstructions;
328 // Vector of uid's for this filter chooser to work on.
329 const std::vector<unsigned> &Opcodes;
331 // Lookup table for the operand decoding of instructions.
332 const std::map<unsigned, std::vector<OperandInfo>> &Operands;
334 // Vector of candidate filters.
335 std::vector<Filter> Filters;
337 // Array of bit values passed down from our parent.
338 // Set to all BIT_UNFILTERED's for Parent == NULL.
339 std::vector<bit_value_t> FilterBitValues;
341 // Links to the FilterChooser above us in the decoding tree.
342 const FilterChooser *Parent;
344 // Index of the best filter from Filters.
345 int BestIndex;
347 // Width of instructions
348 unsigned BitWidth;
350 // Parent emitter
351 const FixedLenDecoderEmitter *Emitter;
353 public:
354 FilterChooser(ArrayRef<const CodeGenInstruction *> Insts,
355 const std::vector<unsigned> &IDs,
356 const std::map<unsigned, std::vector<OperandInfo>> &Ops,
357 unsigned BW,
358 const FixedLenDecoderEmitter *E)
359 : AllInstructions(Insts), Opcodes(IDs), Operands(Ops),
360 FilterBitValues(BW, BIT_UNFILTERED), Parent(nullptr), BestIndex(-1),
361 BitWidth(BW), Emitter(E) {
362 doFilter();
365 FilterChooser(ArrayRef<const CodeGenInstruction *> Insts,
366 const std::vector<unsigned> &IDs,
367 const std::map<unsigned, std::vector<OperandInfo>> &Ops,
368 const std::vector<bit_value_t> &ParentFilterBitValues,
369 const FilterChooser &parent)
370 : AllInstructions(Insts), Opcodes(IDs), Operands(Ops),
371 FilterBitValues(ParentFilterBitValues), Parent(&parent), BestIndex(-1),
372 BitWidth(parent.BitWidth), Emitter(parent.Emitter) {
373 doFilter();
376 FilterChooser(const FilterChooser &) = delete;
377 void operator=(const FilterChooser &) = delete;
379 unsigned getBitWidth() const { return BitWidth; }
381 protected:
382 // Populates the insn given the uid.
383 void insnWithID(insn_t &Insn, unsigned Opcode) const {
384 BitsInit &Bits = getBitsField(*AllInstructions[Opcode]->TheDef, "Inst");
386 // We may have a SoftFail bitmask, which specifies a mask where an encoding
387 // may differ from the value in "Inst" and yet still be valid, but the
388 // disassembler should return SoftFail instead of Success.
390 // This is used for marking UNPREDICTABLE instructions in the ARM world.
391 BitsInit *SFBits =
392 AllInstructions[Opcode]->TheDef->getValueAsBitsInit("SoftFail");
394 for (unsigned i = 0; i < BitWidth; ++i) {
395 if (SFBits && bitFromBits(*SFBits, i) == BIT_TRUE)
396 Insn.push_back(BIT_UNSET);
397 else
398 Insn.push_back(bitFromBits(Bits, i));
402 // Returns the record name.
403 const StringRef nameWithID(unsigned Opcode) const {
404 return AllInstructions[Opcode]->TheDef->getName();
407 // Populates the field of the insn given the start position and the number of
408 // consecutive bits to scan for.
410 // Returns false if there exists any uninitialized bit value in the range.
411 // Returns true, otherwise.
412 bool fieldFromInsn(uint64_t &Field, insn_t &Insn, unsigned StartBit,
413 unsigned NumBits) const;
415 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
416 /// filter array as a series of chars.
417 void dumpFilterArray(raw_ostream &o,
418 const std::vector<bit_value_t> & filter) const;
420 /// dumpStack - dumpStack traverses the filter chooser chain and calls
421 /// dumpFilterArray on each filter chooser up to the top level one.
422 void dumpStack(raw_ostream &o, const char *prefix) const;
424 Filter &bestFilter() {
425 assert(BestIndex != -1 && "BestIndex not set");
426 return Filters[BestIndex];
429 bool PositionFiltered(unsigned i) const {
430 return ValueSet(FilterBitValues[i]);
433 // Calculates the island(s) needed to decode the instruction.
434 // This returns a lit of undecoded bits of an instructions, for example,
435 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
436 // decoded bits in order to verify that the instruction matches the Opcode.
437 unsigned getIslands(std::vector<unsigned> &StartBits,
438 std::vector<unsigned> &EndBits,
439 std::vector<uint64_t> &FieldVals,
440 const insn_t &Insn) const;
442 // Emits code to check the Predicates member of an instruction are true.
443 // Returns true if predicate matches were emitted, false otherwise.
444 bool emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
445 unsigned Opc) const;
447 bool doesOpcodeNeedPredicate(unsigned Opc) const;
448 unsigned getPredicateIndex(DecoderTableInfo &TableInfo, StringRef P) const;
449 void emitPredicateTableEntry(DecoderTableInfo &TableInfo,
450 unsigned Opc) const;
452 void emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
453 unsigned Opc) const;
455 // Emits table entries to decode the singleton.
456 void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
457 unsigned Opc) const;
459 // Emits code to decode the singleton, and then to decode the rest.
460 void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
461 const Filter &Best) const;
463 void emitBinaryParser(raw_ostream &o, unsigned &Indentation,
464 const OperandInfo &OpInfo,
465 bool &OpHasCompleteDecoder) const;
467 void emitDecoder(raw_ostream &OS, unsigned Indentation, unsigned Opc,
468 bool &HasCompleteDecoder) const;
469 unsigned getDecoderIndex(DecoderSet &Decoders, unsigned Opc,
470 bool &HasCompleteDecoder) const;
472 // Assign a single filter and run with it.
473 void runSingleFilter(unsigned startBit, unsigned numBit, bool mixed);
475 // reportRegion is a helper function for filterProcessor to mark a region as
476 // eligible for use as a filter region.
477 void reportRegion(bitAttr_t RA, unsigned StartBit, unsigned BitIndex,
478 bool AllowMixed);
480 // FilterProcessor scans the well-known encoding bits of the instructions and
481 // builds up a list of candidate filters. It chooses the best filter and
482 // recursively descends down the decoding tree.
483 bool filterProcessor(bool AllowMixed, bool Greedy = true);
485 // Decides on the best configuration of filter(s) to use in order to decode
486 // the instructions. A conflict of instructions may occur, in which case we
487 // dump the conflict set to the standard error.
488 void doFilter();
490 public:
491 // emitTableEntries - Emit state machine entries to decode our share of
492 // instructions.
493 void emitTableEntries(DecoderTableInfo &TableInfo) const;
496 } // end anonymous namespace
498 ///////////////////////////
499 // //
500 // Filter Implementation //
501 // //
502 ///////////////////////////
504 Filter::Filter(Filter &&f)
505 : Owner(f.Owner), StartBit(f.StartBit), NumBits(f.NumBits), Mixed(f.Mixed),
506 FilteredInstructions(std::move(f.FilteredInstructions)),
507 VariableInstructions(std::move(f.VariableInstructions)),
508 FilterChooserMap(std::move(f.FilterChooserMap)), NumFiltered(f.NumFiltered),
509 LastOpcFiltered(f.LastOpcFiltered) {
512 Filter::Filter(FilterChooser &owner, unsigned startBit, unsigned numBits,
513 bool mixed)
514 : Owner(&owner), StartBit(startBit), NumBits(numBits), Mixed(mixed) {
515 assert(StartBit + NumBits - 1 < Owner->BitWidth);
517 NumFiltered = 0;
518 LastOpcFiltered = 0;
520 for (unsigned i = 0, e = Owner->Opcodes.size(); i != e; ++i) {
521 insn_t Insn;
523 // Populates the insn given the uid.
524 Owner->insnWithID(Insn, Owner->Opcodes[i]);
526 uint64_t Field;
527 // Scans the segment for possibly well-specified encoding bits.
528 bool ok = Owner->fieldFromInsn(Field, Insn, StartBit, NumBits);
530 if (ok) {
531 // The encoding bits are well-known. Lets add the uid of the
532 // instruction into the bucket keyed off the constant field value.
533 LastOpcFiltered = Owner->Opcodes[i];
534 FilteredInstructions[Field].push_back(LastOpcFiltered);
535 ++NumFiltered;
536 } else {
537 // Some of the encoding bit(s) are unspecified. This contributes to
538 // one additional member of "Variable" instructions.
539 VariableInstructions.push_back(Owner->Opcodes[i]);
543 assert((FilteredInstructions.size() + VariableInstructions.size() > 0)
544 && "Filter returns no instruction categories");
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 // Starts by inheriting our parent filter chooser's filter bit values.
555 std::vector<bit_value_t> BitValueArray(Owner->FilterBitValues);
557 if (!VariableInstructions.empty()) {
558 // Conservatively marks each segment position as BIT_UNSET.
559 for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex)
560 BitValueArray[StartBit + bitIndex] = BIT_UNSET;
562 // Delegates to an inferior filter chooser for further processing on this
563 // group of instructions whose segment values are variable.
564 FilterChooserMap.insert(
565 std::make_pair(-1U, llvm::make_unique<FilterChooser>(
566 Owner->AllInstructions, VariableInstructions,
567 Owner->Operands, BitValueArray, *Owner)));
570 // No need to recurse for a singleton filtered instruction.
571 // See also Filter::emit*().
572 if (getNumFiltered() == 1) {
573 assert(FilterChooserMap.size() == 1);
574 return;
577 // Otherwise, create sub choosers.
578 for (const auto &Inst : FilteredInstructions) {
580 // Marks all the segment positions with either BIT_TRUE or BIT_FALSE.
581 for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex) {
582 if (Inst.first & (1ULL << bitIndex))
583 BitValueArray[StartBit + bitIndex] = BIT_TRUE;
584 else
585 BitValueArray[StartBit + bitIndex] = BIT_FALSE;
588 // Delegates to an inferior filter chooser for further processing on this
589 // category of instructions.
590 FilterChooserMap.insert(std::make_pair(
591 Inst.first, llvm::make_unique<FilterChooser>(
592 Owner->AllInstructions, Inst.second,
593 Owner->Operands, BitValueArray, *Owner)));
597 static void resolveTableFixups(DecoderTable &Table, const FixupList &Fixups,
598 uint32_t DestIdx) {
599 // Any NumToSkip fixups in the current scope can resolve to the
600 // current location.
601 for (FixupList::const_reverse_iterator I = Fixups.rbegin(),
602 E = Fixups.rend();
603 I != E; ++I) {
604 // Calculate the distance from the byte following the fixup entry byte
605 // to the destination. The Target is calculated from after the 16-bit
606 // NumToSkip entry itself, so subtract two from the displacement here
607 // to account for that.
608 uint32_t FixupIdx = *I;
609 uint32_t Delta = DestIdx - FixupIdx - 3;
610 // Our NumToSkip entries are 24-bits. Make sure our table isn't too
611 // big.
612 assert(Delta < (1u << 24));
613 Table[FixupIdx] = (uint8_t)Delta;
614 Table[FixupIdx + 1] = (uint8_t)(Delta >> 8);
615 Table[FixupIdx + 2] = (uint8_t)(Delta >> 16);
619 // Emit table entries to decode instructions given a segment or segments
620 // of bits.
621 void Filter::emitTableEntry(DecoderTableInfo &TableInfo) const {
622 TableInfo.Table.push_back(MCD::OPC_ExtractField);
623 TableInfo.Table.push_back(StartBit);
624 TableInfo.Table.push_back(NumBits);
626 // A new filter entry begins a new scope for fixup resolution.
627 TableInfo.FixupStack.emplace_back();
629 DecoderTable &Table = TableInfo.Table;
631 size_t PrevFilter = 0;
632 bool HasFallthrough = false;
633 for (auto &Filter : FilterChooserMap) {
634 // Field value -1 implies a non-empty set of variable instructions.
635 // See also recurse().
636 if (Filter.first == (unsigned)-1) {
637 HasFallthrough = true;
639 // Each scope should always have at least one filter value to check
640 // for.
641 assert(PrevFilter != 0 && "empty filter set!");
642 FixupList &CurScope = TableInfo.FixupStack.back();
643 // Resolve any NumToSkip fixups in the current scope.
644 resolveTableFixups(Table, CurScope, Table.size());
645 CurScope.clear();
646 PrevFilter = 0; // Don't re-process the filter's fallthrough.
647 } else {
648 Table.push_back(MCD::OPC_FilterValue);
649 // Encode and emit the value to filter against.
650 uint8_t Buffer[16];
651 unsigned Len = encodeULEB128(Filter.first, Buffer);
652 Table.insert(Table.end(), Buffer, Buffer + Len);
653 // Reserve space for the NumToSkip entry. We'll backpatch the value
654 // later.
655 PrevFilter = Table.size();
656 Table.push_back(0);
657 Table.push_back(0);
658 Table.push_back(0);
661 // We arrive at a category of instructions with the same segment value.
662 // Now delegate to the sub filter chooser for further decodings.
663 // The case may fallthrough, which happens if the remaining well-known
664 // encoding bits do not match exactly.
665 Filter.second->emitTableEntries(TableInfo);
667 // Now that we've emitted the body of the handler, update the NumToSkip
668 // of the filter itself to be able to skip forward when false. Subtract
669 // two as to account for the width of the NumToSkip field itself.
670 if (PrevFilter) {
671 uint32_t NumToSkip = Table.size() - PrevFilter - 3;
672 assert(NumToSkip < (1u << 24) && "disassembler decoding table too large!");
673 Table[PrevFilter] = (uint8_t)NumToSkip;
674 Table[PrevFilter + 1] = (uint8_t)(NumToSkip >> 8);
675 Table[PrevFilter + 2] = (uint8_t)(NumToSkip >> 16);
679 // Any remaining unresolved fixups bubble up to the parent fixup scope.
680 assert(TableInfo.FixupStack.size() > 1 && "fixup stack underflow!");
681 FixupScopeList::iterator Source = TableInfo.FixupStack.end() - 1;
682 FixupScopeList::iterator Dest = Source - 1;
683 Dest->insert(Dest->end(), Source->begin(), Source->end());
684 TableInfo.FixupStack.pop_back();
686 // If there is no fallthrough, then the final filter should get fixed
687 // up according to the enclosing scope rather than the current position.
688 if (!HasFallthrough)
689 TableInfo.FixupStack.back().push_back(PrevFilter);
692 // Returns the number of fanout produced by the filter. More fanout implies
693 // the filter distinguishes more categories of instructions.
694 unsigned Filter::usefulness() const {
695 if (!VariableInstructions.empty())
696 return FilteredInstructions.size();
697 else
698 return FilteredInstructions.size() + 1;
701 //////////////////////////////////
702 // //
703 // Filterchooser Implementation //
704 // //
705 //////////////////////////////////
707 // Emit the decoder state machine table.
708 void FixedLenDecoderEmitter::emitTable(formatted_raw_ostream &OS,
709 DecoderTable &Table,
710 unsigned Indentation,
711 unsigned BitWidth,
712 StringRef Namespace) const {
713 OS.indent(Indentation) << "static const uint8_t DecoderTable" << Namespace
714 << BitWidth << "[] = {\n";
716 Indentation += 2;
718 // FIXME: We may be able to use the NumToSkip values to recover
719 // appropriate indentation levels.
720 DecoderTable::const_iterator I = Table.begin();
721 DecoderTable::const_iterator E = Table.end();
722 while (I != E) {
723 assert (I < E && "incomplete decode table entry!");
725 uint64_t Pos = I - Table.begin();
726 OS << "/* " << Pos << " */";
727 OS.PadToColumn(12);
729 switch (*I) {
730 default:
731 PrintFatalError("invalid decode table opcode");
732 case MCD::OPC_ExtractField: {
733 ++I;
734 unsigned Start = *I++;
735 unsigned Len = *I++;
736 OS.indent(Indentation) << "MCD::OPC_ExtractField, " << Start << ", "
737 << Len << ", // Inst{";
738 if (Len > 1)
739 OS << (Start + Len - 1) << "-";
740 OS << Start << "} ...\n";
741 break;
743 case MCD::OPC_FilterValue: {
744 ++I;
745 OS.indent(Indentation) << "MCD::OPC_FilterValue, ";
746 // The filter value is ULEB128 encoded.
747 while (*I >= 128)
748 OS << (unsigned)*I++ << ", ";
749 OS << (unsigned)*I++ << ", ";
751 // 24-bit numtoskip value.
752 uint8_t Byte = *I++;
753 uint32_t NumToSkip = Byte;
754 OS << (unsigned)Byte << ", ";
755 Byte = *I++;
756 OS << (unsigned)Byte << ", ";
757 NumToSkip |= Byte << 8;
758 Byte = *I++;
759 OS << utostr(Byte) << ", ";
760 NumToSkip |= Byte << 16;
761 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
762 break;
764 case MCD::OPC_CheckField: {
765 ++I;
766 unsigned Start = *I++;
767 unsigned Len = *I++;
768 OS.indent(Indentation) << "MCD::OPC_CheckField, " << Start << ", "
769 << Len << ", ";// << Val << ", " << NumToSkip << ",\n";
770 // ULEB128 encoded field value.
771 for (; *I >= 128; ++I)
772 OS << (unsigned)*I << ", ";
773 OS << (unsigned)*I++ << ", ";
774 // 24-bit numtoskip value.
775 uint8_t Byte = *I++;
776 uint32_t NumToSkip = Byte;
777 OS << (unsigned)Byte << ", ";
778 Byte = *I++;
779 OS << (unsigned)Byte << ", ";
780 NumToSkip |= Byte << 8;
781 Byte = *I++;
782 OS << utostr(Byte) << ", ";
783 NumToSkip |= Byte << 16;
784 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
785 break;
787 case MCD::OPC_CheckPredicate: {
788 ++I;
789 OS.indent(Indentation) << "MCD::OPC_CheckPredicate, ";
790 for (; *I >= 128; ++I)
791 OS << (unsigned)*I << ", ";
792 OS << (unsigned)*I++ << ", ";
794 // 24-bit numtoskip value.
795 uint8_t Byte = *I++;
796 uint32_t NumToSkip = Byte;
797 OS << (unsigned)Byte << ", ";
798 Byte = *I++;
799 OS << (unsigned)Byte << ", ";
800 NumToSkip |= Byte << 8;
801 Byte = *I++;
802 OS << utostr(Byte) << ", ";
803 NumToSkip |= Byte << 16;
804 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
805 break;
807 case MCD::OPC_Decode:
808 case MCD::OPC_TryDecode: {
809 bool IsTry = *I == MCD::OPC_TryDecode;
810 ++I;
811 // Extract the ULEB128 encoded Opcode to a buffer.
812 uint8_t Buffer[16], *p = Buffer;
813 while ((*p++ = *I++) >= 128)
814 assert((p - Buffer) <= (ptrdiff_t)sizeof(Buffer)
815 && "ULEB128 value too large!");
816 // Decode the Opcode value.
817 unsigned Opc = decodeULEB128(Buffer);
818 OS.indent(Indentation) << "MCD::OPC_" << (IsTry ? "Try" : "")
819 << "Decode, ";
820 for (p = Buffer; *p >= 128; ++p)
821 OS << (unsigned)*p << ", ";
822 OS << (unsigned)*p << ", ";
824 // Decoder index.
825 for (; *I >= 128; ++I)
826 OS << (unsigned)*I << ", ";
827 OS << (unsigned)*I++ << ", ";
829 if (!IsTry) {
830 OS << "// Opcode: "
831 << NumberedInstructions[Opc]->TheDef->getName() << "\n";
832 break;
835 // Fallthrough for OPC_TryDecode.
837 // 24-bit numtoskip value.
838 uint8_t Byte = *I++;
839 uint32_t NumToSkip = Byte;
840 OS << (unsigned)Byte << ", ";
841 Byte = *I++;
842 OS << (unsigned)Byte << ", ";
843 NumToSkip |= Byte << 8;
844 Byte = *I++;
845 OS << utostr(Byte) << ", ";
846 NumToSkip |= Byte << 16;
848 OS << "// Opcode: "
849 << NumberedInstructions[Opc]->TheDef->getName()
850 << ", skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
851 break;
853 case MCD::OPC_SoftFail: {
854 ++I;
855 OS.indent(Indentation) << "MCD::OPC_SoftFail";
856 // Positive mask
857 uint64_t Value = 0;
858 unsigned Shift = 0;
859 do {
860 OS << ", " << (unsigned)*I;
861 Value += (*I & 0x7f) << Shift;
862 Shift += 7;
863 } while (*I++ >= 128);
864 if (Value > 127) {
865 OS << " /* 0x";
866 OS.write_hex(Value);
867 OS << " */";
869 // Negative mask
870 Value = 0;
871 Shift = 0;
872 do {
873 OS << ", " << (unsigned)*I;
874 Value += (*I & 0x7f) << Shift;
875 Shift += 7;
876 } while (*I++ >= 128);
877 if (Value > 127) {
878 OS << " /* 0x";
879 OS.write_hex(Value);
880 OS << " */";
882 OS << ",\n";
883 break;
885 case MCD::OPC_Fail: {
886 ++I;
887 OS.indent(Indentation) << "MCD::OPC_Fail,\n";
888 break;
892 OS.indent(Indentation) << "0\n";
894 Indentation -= 2;
896 OS.indent(Indentation) << "};\n\n";
899 void FixedLenDecoderEmitter::
900 emitPredicateFunction(formatted_raw_ostream &OS, PredicateSet &Predicates,
901 unsigned Indentation) const {
902 // The predicate function is just a big switch statement based on the
903 // input predicate index.
904 OS.indent(Indentation) << "static bool checkDecoderPredicate(unsigned Idx, "
905 << "const FeatureBitset& Bits) {\n";
906 Indentation += 2;
907 if (!Predicates.empty()) {
908 OS.indent(Indentation) << "switch (Idx) {\n";
909 OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
910 unsigned Index = 0;
911 for (const auto &Predicate : Predicates) {
912 OS.indent(Indentation) << "case " << Index++ << ":\n";
913 OS.indent(Indentation+2) << "return (" << Predicate << ");\n";
915 OS.indent(Indentation) << "}\n";
916 } else {
917 // No case statement to emit
918 OS.indent(Indentation) << "llvm_unreachable(\"Invalid index!\");\n";
920 Indentation -= 2;
921 OS.indent(Indentation) << "}\n\n";
924 void FixedLenDecoderEmitter::
925 emitDecoderFunction(formatted_raw_ostream &OS, DecoderSet &Decoders,
926 unsigned Indentation) const {
927 // The decoder function is just a big switch statement based on the
928 // input decoder index.
929 OS.indent(Indentation) << "template<typename InsnType>\n";
930 OS.indent(Indentation) << "static DecodeStatus decodeToMCInst(DecodeStatus S,"
931 << " unsigned Idx, InsnType insn, MCInst &MI,\n";
932 OS.indent(Indentation) << " uint64_t "
933 << "Address, const void *Decoder, bool &DecodeComplete) {\n";
934 Indentation += 2;
935 OS.indent(Indentation) << "DecodeComplete = true;\n";
936 OS.indent(Indentation) << "InsnType tmp;\n";
937 OS.indent(Indentation) << "switch (Idx) {\n";
938 OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
939 unsigned Index = 0;
940 for (const auto &Decoder : Decoders) {
941 OS.indent(Indentation) << "case " << Index++ << ":\n";
942 OS << Decoder;
943 OS.indent(Indentation+2) << "return S;\n";
945 OS.indent(Indentation) << "}\n";
946 Indentation -= 2;
947 OS.indent(Indentation) << "}\n\n";
950 // Populates the field of the insn given the start position and the number of
951 // consecutive bits to scan for.
953 // Returns false if and on the first uninitialized bit value encountered.
954 // Returns true, otherwise.
955 bool FilterChooser::fieldFromInsn(uint64_t &Field, insn_t &Insn,
956 unsigned StartBit, unsigned NumBits) const {
957 Field = 0;
959 for (unsigned i = 0; i < NumBits; ++i) {
960 if (Insn[StartBit + i] == BIT_UNSET)
961 return false;
963 if (Insn[StartBit + i] == BIT_TRUE)
964 Field = Field | (1ULL << i);
967 return true;
970 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
971 /// filter array as a series of chars.
972 void FilterChooser::dumpFilterArray(raw_ostream &o,
973 const std::vector<bit_value_t> &filter) const {
974 for (unsigned bitIndex = BitWidth; bitIndex > 0; bitIndex--) {
975 switch (filter[bitIndex - 1]) {
976 case BIT_UNFILTERED:
977 o << ".";
978 break;
979 case BIT_UNSET:
980 o << "_";
981 break;
982 case BIT_TRUE:
983 o << "1";
984 break;
985 case BIT_FALSE:
986 o << "0";
987 break;
992 /// dumpStack - dumpStack traverses the filter chooser chain and calls
993 /// dumpFilterArray on each filter chooser up to the top level one.
994 void FilterChooser::dumpStack(raw_ostream &o, const char *prefix) const {
995 const FilterChooser *current = this;
997 while (current) {
998 o << prefix;
999 dumpFilterArray(o, current->FilterBitValues);
1000 o << '\n';
1001 current = current->Parent;
1005 // Calculates the island(s) needed to decode the instruction.
1006 // This returns a list of undecoded bits of an instructions, for example,
1007 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
1008 // decoded bits in order to verify that the instruction matches the Opcode.
1009 unsigned FilterChooser::getIslands(std::vector<unsigned> &StartBits,
1010 std::vector<unsigned> &EndBits,
1011 std::vector<uint64_t> &FieldVals,
1012 const insn_t &Insn) const {
1013 unsigned Num, BitNo;
1014 Num = BitNo = 0;
1016 uint64_t FieldVal = 0;
1018 // 0: Init
1019 // 1: Water (the bit value does not affect decoding)
1020 // 2: Island (well-known bit value needed for decoding)
1021 int State = 0;
1022 int Val = -1;
1024 for (unsigned i = 0; i < BitWidth; ++i) {
1025 Val = Value(Insn[i]);
1026 bool Filtered = PositionFiltered(i);
1027 switch (State) {
1028 default: llvm_unreachable("Unreachable code!");
1029 case 0:
1030 case 1:
1031 if (Filtered || Val == -1)
1032 State = 1; // Still in Water
1033 else {
1034 State = 2; // Into the Island
1035 BitNo = 0;
1036 StartBits.push_back(i);
1037 FieldVal = Val;
1039 break;
1040 case 2:
1041 if (Filtered || Val == -1) {
1042 State = 1; // Into the Water
1043 EndBits.push_back(i - 1);
1044 FieldVals.push_back(FieldVal);
1045 ++Num;
1046 } else {
1047 State = 2; // Still in Island
1048 ++BitNo;
1049 FieldVal = FieldVal | Val << BitNo;
1051 break;
1054 // If we are still in Island after the loop, do some housekeeping.
1055 if (State == 2) {
1056 EndBits.push_back(BitWidth - 1);
1057 FieldVals.push_back(FieldVal);
1058 ++Num;
1061 assert(StartBits.size() == Num && EndBits.size() == Num &&
1062 FieldVals.size() == Num);
1063 return Num;
1066 void FilterChooser::emitBinaryParser(raw_ostream &o, unsigned &Indentation,
1067 const OperandInfo &OpInfo,
1068 bool &OpHasCompleteDecoder) const {
1069 const std::string &Decoder = OpInfo.Decoder;
1071 if (OpInfo.numFields() != 1)
1072 o.indent(Indentation) << "tmp = 0;\n";
1074 for (const EncodingField &EF : OpInfo) {
1075 o.indent(Indentation) << "tmp ";
1076 if (OpInfo.numFields() != 1) o << '|';
1077 o << "= fieldFromInstruction"
1078 << "(insn, " << EF.Base << ", " << EF.Width << ')';
1079 if (OpInfo.numFields() != 1 || EF.Offset != 0)
1080 o << " << " << EF.Offset;
1081 o << ";\n";
1084 if (Decoder != "") {
1085 OpHasCompleteDecoder = OpInfo.HasCompleteDecoder;
1086 o.indent(Indentation) << Emitter->GuardPrefix << Decoder
1087 << "(MI, tmp, Address, Decoder)"
1088 << Emitter->GuardPostfix
1089 << " { " << (OpHasCompleteDecoder ? "" : "DecodeComplete = false; ")
1090 << "return MCDisassembler::Fail; }\n";
1091 } else {
1092 OpHasCompleteDecoder = true;
1093 o.indent(Indentation) << "MI.addOperand(MCOperand::createImm(tmp));\n";
1097 void FilterChooser::emitDecoder(raw_ostream &OS, unsigned Indentation,
1098 unsigned Opc, bool &HasCompleteDecoder) const {
1099 HasCompleteDecoder = true;
1101 for (const auto &Op : Operands.find(Opc)->second) {
1102 // If a custom instruction decoder was specified, use that.
1103 if (Op.numFields() == 0 && !Op.Decoder.empty()) {
1104 HasCompleteDecoder = Op.HasCompleteDecoder;
1105 OS.indent(Indentation) << Emitter->GuardPrefix << Op.Decoder
1106 << "(MI, insn, Address, Decoder)"
1107 << Emitter->GuardPostfix
1108 << " { " << (HasCompleteDecoder ? "" : "DecodeComplete = false; ")
1109 << "return MCDisassembler::Fail; }\n";
1110 break;
1113 bool OpHasCompleteDecoder;
1114 emitBinaryParser(OS, Indentation, Op, OpHasCompleteDecoder);
1115 if (!OpHasCompleteDecoder)
1116 HasCompleteDecoder = false;
1120 unsigned FilterChooser::getDecoderIndex(DecoderSet &Decoders,
1121 unsigned Opc,
1122 bool &HasCompleteDecoder) const {
1123 // Build up the predicate string.
1124 SmallString<256> Decoder;
1125 // FIXME: emitDecoder() function can take a buffer directly rather than
1126 // a stream.
1127 raw_svector_ostream S(Decoder);
1128 unsigned I = 4;
1129 emitDecoder(S, I, Opc, HasCompleteDecoder);
1131 // Using the full decoder string as the key value here is a bit
1132 // heavyweight, but is effective. If the string comparisons become a
1133 // performance concern, we can implement a mangling of the predicate
1134 // data easily enough with a map back to the actual string. That's
1135 // overkill for now, though.
1137 // Make sure the predicate is in the table.
1138 Decoders.insert(CachedHashString(Decoder));
1139 // Now figure out the index for when we write out the table.
1140 DecoderSet::const_iterator P = find(Decoders, Decoder.str());
1141 return (unsigned)(P - Decoders.begin());
1144 static void emitSinglePredicateMatch(raw_ostream &o, StringRef str,
1145 const std::string &PredicateNamespace) {
1146 if (str[0] == '!')
1147 o << "!Bits[" << PredicateNamespace << "::"
1148 << str.slice(1,str.size()) << "]";
1149 else
1150 o << "Bits[" << PredicateNamespace << "::" << str << "]";
1153 bool FilterChooser::emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
1154 unsigned Opc) const {
1155 ListInit *Predicates =
1156 AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
1157 bool IsFirstEmission = true;
1158 for (unsigned i = 0; i < Predicates->size(); ++i) {
1159 Record *Pred = Predicates->getElementAsRecord(i);
1160 if (!Pred->getValue("AssemblerMatcherPredicate"))
1161 continue;
1163 StringRef P = Pred->getValueAsString("AssemblerCondString");
1165 if (P.empty())
1166 continue;
1168 if (!IsFirstEmission)
1169 o << " && ";
1171 std::pair<StringRef, StringRef> pairs = P.split(',');
1172 while (!pairs.second.empty()) {
1173 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
1174 o << " && ";
1175 pairs = pairs.second.split(',');
1177 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
1178 IsFirstEmission = false;
1180 return !Predicates->empty();
1183 bool FilterChooser::doesOpcodeNeedPredicate(unsigned Opc) const {
1184 ListInit *Predicates =
1185 AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
1186 for (unsigned i = 0; i < Predicates->size(); ++i) {
1187 Record *Pred = Predicates->getElementAsRecord(i);
1188 if (!Pred->getValue("AssemblerMatcherPredicate"))
1189 continue;
1191 StringRef P = Pred->getValueAsString("AssemblerCondString");
1193 if (P.empty())
1194 continue;
1196 return true;
1198 return false;
1201 unsigned FilterChooser::getPredicateIndex(DecoderTableInfo &TableInfo,
1202 StringRef Predicate) const {
1203 // Using the full predicate string as the key value here is a bit
1204 // heavyweight, but is effective. If the string comparisons become a
1205 // performance concern, we can implement a mangling of the predicate
1206 // data easily enough with a map back to the actual string. That's
1207 // overkill for now, though.
1209 // Make sure the predicate is in the table.
1210 TableInfo.Predicates.insert(CachedHashString(Predicate));
1211 // Now figure out the index for when we write out the table.
1212 PredicateSet::const_iterator P = find(TableInfo.Predicates, Predicate);
1213 return (unsigned)(P - TableInfo.Predicates.begin());
1216 void FilterChooser::emitPredicateTableEntry(DecoderTableInfo &TableInfo,
1217 unsigned Opc) const {
1218 if (!doesOpcodeNeedPredicate(Opc))
1219 return;
1221 // Build up the predicate string.
1222 SmallString<256> Predicate;
1223 // FIXME: emitPredicateMatch() functions can take a buffer directly rather
1224 // than a stream.
1225 raw_svector_ostream PS(Predicate);
1226 unsigned I = 0;
1227 emitPredicateMatch(PS, I, Opc);
1229 // Figure out the index into the predicate table for the predicate just
1230 // computed.
1231 unsigned PIdx = getPredicateIndex(TableInfo, PS.str());
1232 SmallString<16> PBytes;
1233 raw_svector_ostream S(PBytes);
1234 encodeULEB128(PIdx, S);
1236 TableInfo.Table.push_back(MCD::OPC_CheckPredicate);
1237 // Predicate index
1238 for (unsigned i = 0, e = PBytes.size(); i != e; ++i)
1239 TableInfo.Table.push_back(PBytes[i]);
1240 // Push location for NumToSkip backpatching.
1241 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1242 TableInfo.Table.push_back(0);
1243 TableInfo.Table.push_back(0);
1244 TableInfo.Table.push_back(0);
1247 void FilterChooser::emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
1248 unsigned Opc) const {
1249 BitsInit *SFBits =
1250 AllInstructions[Opc]->TheDef->getValueAsBitsInit("SoftFail");
1251 if (!SFBits) return;
1252 BitsInit *InstBits = AllInstructions[Opc]->TheDef->getValueAsBitsInit("Inst");
1254 APInt PositiveMask(BitWidth, 0ULL);
1255 APInt NegativeMask(BitWidth, 0ULL);
1256 for (unsigned i = 0; i < BitWidth; ++i) {
1257 bit_value_t B = bitFromBits(*SFBits, i);
1258 bit_value_t IB = bitFromBits(*InstBits, i);
1260 if (B != BIT_TRUE) continue;
1262 switch (IB) {
1263 case BIT_FALSE:
1264 // The bit is meant to be false, so emit a check to see if it is true.
1265 PositiveMask.setBit(i);
1266 break;
1267 case BIT_TRUE:
1268 // The bit is meant to be true, so emit a check to see if it is false.
1269 NegativeMask.setBit(i);
1270 break;
1271 default:
1272 // The bit is not set; this must be an error!
1273 StringRef Name = AllInstructions[Opc]->TheDef->getName();
1274 errs() << "SoftFail Conflict: bit SoftFail{" << i << "} in " << Name
1275 << " is set but Inst{" << i << "} is unset!\n"
1276 << " - You can only mark a bit as SoftFail if it is fully defined"
1277 << " (1/0 - not '?') in Inst\n";
1278 return;
1282 bool NeedPositiveMask = PositiveMask.getBoolValue();
1283 bool NeedNegativeMask = NegativeMask.getBoolValue();
1285 if (!NeedPositiveMask && !NeedNegativeMask)
1286 return;
1288 TableInfo.Table.push_back(MCD::OPC_SoftFail);
1290 SmallString<16> MaskBytes;
1291 raw_svector_ostream S(MaskBytes);
1292 if (NeedPositiveMask) {
1293 encodeULEB128(PositiveMask.getZExtValue(), S);
1294 for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
1295 TableInfo.Table.push_back(MaskBytes[i]);
1296 } else
1297 TableInfo.Table.push_back(0);
1298 if (NeedNegativeMask) {
1299 MaskBytes.clear();
1300 encodeULEB128(NegativeMask.getZExtValue(), S);
1301 for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
1302 TableInfo.Table.push_back(MaskBytes[i]);
1303 } else
1304 TableInfo.Table.push_back(0);
1307 // Emits table entries to decode the singleton.
1308 void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1309 unsigned Opc) const {
1310 std::vector<unsigned> StartBits;
1311 std::vector<unsigned> EndBits;
1312 std::vector<uint64_t> FieldVals;
1313 insn_t Insn;
1314 insnWithID(Insn, Opc);
1316 // Look for islands of undecoded bits of the singleton.
1317 getIslands(StartBits, EndBits, FieldVals, Insn);
1319 unsigned Size = StartBits.size();
1321 // Emit the predicate table entry if one is needed.
1322 emitPredicateTableEntry(TableInfo, Opc);
1324 // Check any additional encoding fields needed.
1325 for (unsigned I = Size; I != 0; --I) {
1326 unsigned NumBits = EndBits[I-1] - StartBits[I-1] + 1;
1327 TableInfo.Table.push_back(MCD::OPC_CheckField);
1328 TableInfo.Table.push_back(StartBits[I-1]);
1329 TableInfo.Table.push_back(NumBits);
1330 uint8_t Buffer[16], *p;
1331 encodeULEB128(FieldVals[I-1], Buffer);
1332 for (p = Buffer; *p >= 128 ; ++p)
1333 TableInfo.Table.push_back(*p);
1334 TableInfo.Table.push_back(*p);
1335 // Push location for NumToSkip backpatching.
1336 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1337 // The fixup is always 24-bits, so go ahead and allocate the space
1338 // in the table so all our relative position calculations work OK even
1339 // before we fully resolve the real value here.
1340 TableInfo.Table.push_back(0);
1341 TableInfo.Table.push_back(0);
1342 TableInfo.Table.push_back(0);
1345 // Check for soft failure of the match.
1346 emitSoftFailTableEntry(TableInfo, Opc);
1348 bool HasCompleteDecoder;
1349 unsigned DIdx = getDecoderIndex(TableInfo.Decoders, Opc, HasCompleteDecoder);
1351 // Produce OPC_Decode or OPC_TryDecode opcode based on the information
1352 // whether the instruction decoder is complete or not. If it is complete
1353 // then it handles all possible values of remaining variable/unfiltered bits
1354 // and for any value can determine if the bitpattern is a valid instruction
1355 // or not. This means OPC_Decode will be the final step in the decoding
1356 // process. If it is not complete, then the Fail return code from the
1357 // decoder method indicates that additional processing should be done to see
1358 // if there is any other instruction that also matches the bitpattern and
1359 // can decode it.
1360 TableInfo.Table.push_back(HasCompleteDecoder ? MCD::OPC_Decode :
1361 MCD::OPC_TryDecode);
1362 uint8_t Buffer[16], *p;
1363 encodeULEB128(Opc, Buffer);
1364 for (p = Buffer; *p >= 128 ; ++p)
1365 TableInfo.Table.push_back(*p);
1366 TableInfo.Table.push_back(*p);
1368 SmallString<16> Bytes;
1369 raw_svector_ostream S(Bytes);
1370 encodeULEB128(DIdx, S);
1372 // Decoder index
1373 for (unsigned i = 0, e = Bytes.size(); i != e; ++i)
1374 TableInfo.Table.push_back(Bytes[i]);
1376 if (!HasCompleteDecoder) {
1377 // Push location for NumToSkip backpatching.
1378 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1379 // Allocate the space for the fixup.
1380 TableInfo.Table.push_back(0);
1381 TableInfo.Table.push_back(0);
1382 TableInfo.Table.push_back(0);
1386 // Emits table entries to decode the singleton, and then to decode the rest.
1387 void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1388 const Filter &Best) const {
1389 unsigned Opc = Best.getSingletonOpc();
1391 // complex singletons need predicate checks from the first singleton
1392 // to refer forward to the variable filterchooser that follows.
1393 TableInfo.FixupStack.emplace_back();
1395 emitSingletonTableEntry(TableInfo, Opc);
1397 resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
1398 TableInfo.Table.size());
1399 TableInfo.FixupStack.pop_back();
1401 Best.getVariableFC().emitTableEntries(TableInfo);
1404 // Assign a single filter and run with it. Top level API client can initialize
1405 // with a single filter to start the filtering process.
1406 void FilterChooser::runSingleFilter(unsigned startBit, unsigned numBit,
1407 bool mixed) {
1408 Filters.clear();
1409 Filters.emplace_back(*this, startBit, numBit, true);
1410 BestIndex = 0; // Sole Filter instance to choose from.
1411 bestFilter().recurse();
1414 // reportRegion is a helper function for filterProcessor to mark a region as
1415 // eligible for use as a filter region.
1416 void FilterChooser::reportRegion(bitAttr_t RA, unsigned StartBit,
1417 unsigned BitIndex, bool AllowMixed) {
1418 if (RA == ATTR_MIXED && AllowMixed)
1419 Filters.emplace_back(*this, StartBit, BitIndex - StartBit, true);
1420 else if (RA == ATTR_ALL_SET && !AllowMixed)
1421 Filters.emplace_back(*this, StartBit, BitIndex - StartBit, false);
1424 // FilterProcessor scans the well-known encoding bits of the instructions and
1425 // builds up a list of candidate filters. It chooses the best filter and
1426 // recursively descends down the decoding tree.
1427 bool FilterChooser::filterProcessor(bool AllowMixed, bool Greedy) {
1428 Filters.clear();
1429 BestIndex = -1;
1430 unsigned numInstructions = Opcodes.size();
1432 assert(numInstructions && "Filter created with no instructions");
1434 // No further filtering is necessary.
1435 if (numInstructions == 1)
1436 return true;
1438 // Heuristics. See also doFilter()'s "Heuristics" comment when num of
1439 // instructions is 3.
1440 if (AllowMixed && !Greedy) {
1441 assert(numInstructions == 3);
1443 for (unsigned i = 0; i < Opcodes.size(); ++i) {
1444 std::vector<unsigned> StartBits;
1445 std::vector<unsigned> EndBits;
1446 std::vector<uint64_t> FieldVals;
1447 insn_t Insn;
1449 insnWithID(Insn, Opcodes[i]);
1451 // Look for islands of undecoded bits of any instruction.
1452 if (getIslands(StartBits, EndBits, FieldVals, Insn) > 0) {
1453 // Found an instruction with island(s). Now just assign a filter.
1454 runSingleFilter(StartBits[0], EndBits[0] - StartBits[0] + 1, true);
1455 return true;
1460 unsigned BitIndex;
1462 // We maintain BIT_WIDTH copies of the bitAttrs automaton.
1463 // The automaton consumes the corresponding bit from each
1464 // instruction.
1466 // Input symbols: 0, 1, and _ (unset).
1467 // States: NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED.
1468 // Initial state: NONE.
1470 // (NONE) ------- [01] -> (ALL_SET)
1471 // (NONE) ------- _ ----> (ALL_UNSET)
1472 // (ALL_SET) ---- [01] -> (ALL_SET)
1473 // (ALL_SET) ---- _ ----> (MIXED)
1474 // (ALL_UNSET) -- [01] -> (MIXED)
1475 // (ALL_UNSET) -- _ ----> (ALL_UNSET)
1476 // (MIXED) ------ . ----> (MIXED)
1477 // (FILTERED)---- . ----> (FILTERED)
1479 std::vector<bitAttr_t> bitAttrs;
1481 // FILTERED bit positions provide no entropy and are not worthy of pursuing.
1482 // Filter::recurse() set either BIT_TRUE or BIT_FALSE for each position.
1483 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex)
1484 if (FilterBitValues[BitIndex] == BIT_TRUE ||
1485 FilterBitValues[BitIndex] == BIT_FALSE)
1486 bitAttrs.push_back(ATTR_FILTERED);
1487 else
1488 bitAttrs.push_back(ATTR_NONE);
1490 for (unsigned InsnIndex = 0; InsnIndex < numInstructions; ++InsnIndex) {
1491 insn_t insn;
1493 insnWithID(insn, Opcodes[InsnIndex]);
1495 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
1496 switch (bitAttrs[BitIndex]) {
1497 case ATTR_NONE:
1498 if (insn[BitIndex] == BIT_UNSET)
1499 bitAttrs[BitIndex] = ATTR_ALL_UNSET;
1500 else
1501 bitAttrs[BitIndex] = ATTR_ALL_SET;
1502 break;
1503 case ATTR_ALL_SET:
1504 if (insn[BitIndex] == BIT_UNSET)
1505 bitAttrs[BitIndex] = ATTR_MIXED;
1506 break;
1507 case ATTR_ALL_UNSET:
1508 if (insn[BitIndex] != BIT_UNSET)
1509 bitAttrs[BitIndex] = ATTR_MIXED;
1510 break;
1511 case ATTR_MIXED:
1512 case ATTR_FILTERED:
1513 break;
1518 // The regionAttr automaton consumes the bitAttrs automatons' state,
1519 // lowest-to-highest.
1521 // Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed)
1522 // States: NONE, ALL_SET, MIXED
1523 // Initial state: NONE
1525 // (NONE) ----- F --> (NONE)
1526 // (NONE) ----- S --> (ALL_SET) ; and set region start
1527 // (NONE) ----- U --> (NONE)
1528 // (NONE) ----- M --> (MIXED) ; and set region start
1529 // (ALL_SET) -- F --> (NONE) ; and report an ALL_SET region
1530 // (ALL_SET) -- S --> (ALL_SET)
1531 // (ALL_SET) -- U --> (NONE) ; and report an ALL_SET region
1532 // (ALL_SET) -- M --> (MIXED) ; and report an ALL_SET region
1533 // (MIXED) ---- F --> (NONE) ; and report a MIXED region
1534 // (MIXED) ---- S --> (ALL_SET) ; and report a MIXED region
1535 // (MIXED) ---- U --> (NONE) ; and report a MIXED region
1536 // (MIXED) ---- M --> (MIXED)
1538 bitAttr_t RA = ATTR_NONE;
1539 unsigned StartBit = 0;
1541 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
1542 bitAttr_t bitAttr = bitAttrs[BitIndex];
1544 assert(bitAttr != ATTR_NONE && "Bit without attributes");
1546 switch (RA) {
1547 case ATTR_NONE:
1548 switch (bitAttr) {
1549 case ATTR_FILTERED:
1550 break;
1551 case ATTR_ALL_SET:
1552 StartBit = BitIndex;
1553 RA = ATTR_ALL_SET;
1554 break;
1555 case ATTR_ALL_UNSET:
1556 break;
1557 case ATTR_MIXED:
1558 StartBit = BitIndex;
1559 RA = ATTR_MIXED;
1560 break;
1561 default:
1562 llvm_unreachable("Unexpected bitAttr!");
1564 break;
1565 case ATTR_ALL_SET:
1566 switch (bitAttr) {
1567 case ATTR_FILTERED:
1568 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1569 RA = ATTR_NONE;
1570 break;
1571 case ATTR_ALL_SET:
1572 break;
1573 case ATTR_ALL_UNSET:
1574 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1575 RA = ATTR_NONE;
1576 break;
1577 case ATTR_MIXED:
1578 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1579 StartBit = BitIndex;
1580 RA = ATTR_MIXED;
1581 break;
1582 default:
1583 llvm_unreachable("Unexpected bitAttr!");
1585 break;
1586 case ATTR_MIXED:
1587 switch (bitAttr) {
1588 case ATTR_FILTERED:
1589 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1590 StartBit = BitIndex;
1591 RA = ATTR_NONE;
1592 break;
1593 case ATTR_ALL_SET:
1594 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1595 StartBit = BitIndex;
1596 RA = ATTR_ALL_SET;
1597 break;
1598 case ATTR_ALL_UNSET:
1599 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1600 RA = ATTR_NONE;
1601 break;
1602 case ATTR_MIXED:
1603 break;
1604 default:
1605 llvm_unreachable("Unexpected bitAttr!");
1607 break;
1608 case ATTR_ALL_UNSET:
1609 llvm_unreachable("regionAttr state machine has no ATTR_UNSET state");
1610 case ATTR_FILTERED:
1611 llvm_unreachable("regionAttr state machine has no ATTR_FILTERED state");
1615 // At the end, if we're still in ALL_SET or MIXED states, report a region
1616 switch (RA) {
1617 case ATTR_NONE:
1618 break;
1619 case ATTR_FILTERED:
1620 break;
1621 case ATTR_ALL_SET:
1622 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1623 break;
1624 case ATTR_ALL_UNSET:
1625 break;
1626 case ATTR_MIXED:
1627 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1628 break;
1631 // We have finished with the filter processings. Now it's time to choose
1632 // the best performing filter.
1633 BestIndex = 0;
1634 bool AllUseless = true;
1635 unsigned BestScore = 0;
1637 for (unsigned i = 0, e = Filters.size(); i != e; ++i) {
1638 unsigned Usefulness = Filters[i].usefulness();
1640 if (Usefulness)
1641 AllUseless = false;
1643 if (Usefulness > BestScore) {
1644 BestIndex = i;
1645 BestScore = Usefulness;
1649 if (!AllUseless)
1650 bestFilter().recurse();
1652 return !AllUseless;
1653 } // end of FilterChooser::filterProcessor(bool)
1655 // Decides on the best configuration of filter(s) to use in order to decode
1656 // the instructions. A conflict of instructions may occur, in which case we
1657 // dump the conflict set to the standard error.
1658 void FilterChooser::doFilter() {
1659 unsigned Num = Opcodes.size();
1660 assert(Num && "FilterChooser created with no instructions");
1662 // Try regions of consecutive known bit values first.
1663 if (filterProcessor(false))
1664 return;
1666 // Then regions of mixed bits (both known and unitialized bit values allowed).
1667 if (filterProcessor(true))
1668 return;
1670 // Heuristics to cope with conflict set {t2CMPrs, t2SUBSrr, t2SUBSrs} where
1671 // no single instruction for the maximum ATTR_MIXED region Inst{14-4} has a
1672 // well-known encoding pattern. In such case, we backtrack and scan for the
1673 // the very first consecutive ATTR_ALL_SET region and assign a filter to it.
1674 if (Num == 3 && filterProcessor(true, false))
1675 return;
1677 // If we come to here, the instruction decoding has failed.
1678 // Set the BestIndex to -1 to indicate so.
1679 BestIndex = -1;
1682 // emitTableEntries - Emit state machine entries to decode our share of
1683 // instructions.
1684 void FilterChooser::emitTableEntries(DecoderTableInfo &TableInfo) const {
1685 if (Opcodes.size() == 1) {
1686 // There is only one instruction in the set, which is great!
1687 // Call emitSingletonDecoder() to see whether there are any remaining
1688 // encodings bits.
1689 emitSingletonTableEntry(TableInfo, Opcodes[0]);
1690 return;
1693 // Choose the best filter to do the decodings!
1694 if (BestIndex != -1) {
1695 const Filter &Best = Filters[BestIndex];
1696 if (Best.getNumFiltered() == 1)
1697 emitSingletonTableEntry(TableInfo, Best);
1698 else
1699 Best.emitTableEntry(TableInfo);
1700 return;
1703 // We don't know how to decode these instructions! Dump the
1704 // conflict set and bail.
1706 // Print out useful conflict information for postmortem analysis.
1707 errs() << "Decoding Conflict:\n";
1709 dumpStack(errs(), "\t\t");
1711 for (unsigned i = 0; i < Opcodes.size(); ++i) {
1712 errs() << '\t' << nameWithID(Opcodes[i]) << " ";
1713 dumpBits(errs(),
1714 getBitsField(*AllInstructions[Opcodes[i]]->TheDef, "Inst"));
1715 errs() << '\n';
1719 static std::string findOperandDecoderMethod(TypedInit *TI) {
1720 std::string Decoder;
1722 Record *Record = cast<DefInit>(TI)->getDef();
1724 RecordVal *DecoderString = Record->getValue("DecoderMethod");
1725 StringInit *String = DecoderString ?
1726 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
1727 if (String) {
1728 Decoder = String->getValue();
1729 if (!Decoder.empty())
1730 return Decoder;
1733 if (Record->isSubClassOf("RegisterOperand"))
1734 Record = Record->getValueAsDef("RegClass");
1736 if (Record->isSubClassOf("RegisterClass")) {
1737 Decoder = "Decode" + Record->getName().str() + "RegisterClass";
1738 } else if (Record->isSubClassOf("PointerLikeRegClass")) {
1739 Decoder = "DecodePointerLikeRegClass" +
1740 utostr(Record->getValueAsInt("RegClassKind"));
1743 return Decoder;
1746 static bool populateInstruction(CodeGenTarget &Target,
1747 const CodeGenInstruction &CGI, unsigned Opc,
1748 std::map<unsigned, std::vector<OperandInfo>> &Operands){
1749 const Record &Def = *CGI.TheDef;
1750 // If all the bit positions are not specified; do not decode this instruction.
1751 // We are bound to fail! For proper disassembly, the well-known encoding bits
1752 // of the instruction must be fully specified.
1754 BitsInit &Bits = getBitsField(Def, "Inst");
1755 if (Bits.allInComplete()) return false;
1757 std::vector<OperandInfo> InsnOperands;
1759 // If the instruction has specified a custom decoding hook, use that instead
1760 // of trying to auto-generate the decoder.
1761 StringRef InstDecoder = Def.getValueAsString("DecoderMethod");
1762 if (InstDecoder != "") {
1763 bool HasCompleteInstDecoder = Def.getValueAsBit("hasCompleteDecoder");
1764 InsnOperands.push_back(OperandInfo(InstDecoder, HasCompleteInstDecoder));
1765 Operands[Opc] = InsnOperands;
1766 return true;
1769 // Generate a description of the operand of the instruction that we know
1770 // how to decode automatically.
1771 // FIXME: We'll need to have a way to manually override this as needed.
1773 // Gather the outputs/inputs of the instruction, so we can find their
1774 // positions in the encoding. This assumes for now that they appear in the
1775 // MCInst in the order that they're listed.
1776 std::vector<std::pair<Init*, StringRef>> InOutOperands;
1777 DagInit *Out = Def.getValueAsDag("OutOperandList");
1778 DagInit *In = Def.getValueAsDag("InOperandList");
1779 for (unsigned i = 0; i < Out->getNumArgs(); ++i)
1780 InOutOperands.push_back(std::make_pair(Out->getArg(i),
1781 Out->getArgNameStr(i)));
1782 for (unsigned i = 0; i < In->getNumArgs(); ++i)
1783 InOutOperands.push_back(std::make_pair(In->getArg(i),
1784 In->getArgNameStr(i)));
1786 // Search for tied operands, so that we can correctly instantiate
1787 // operands that are not explicitly represented in the encoding.
1788 std::map<std::string, std::string> TiedNames;
1789 for (unsigned i = 0; i < CGI.Operands.size(); ++i) {
1790 int tiedTo = CGI.Operands[i].getTiedRegister();
1791 if (tiedTo != -1) {
1792 std::pair<unsigned, unsigned> SO =
1793 CGI.Operands.getSubOperandNumber(tiedTo);
1794 TiedNames[InOutOperands[i].second] = InOutOperands[SO.first].second;
1795 TiedNames[InOutOperands[SO.first].second] = InOutOperands[i].second;
1799 std::map<std::string, std::vector<OperandInfo>> NumberedInsnOperands;
1800 std::set<std::string> NumberedInsnOperandsNoTie;
1801 if (Target.getInstructionSet()->
1802 getValueAsBit("decodePositionallyEncodedOperands")) {
1803 const std::vector<RecordVal> &Vals = Def.getValues();
1804 unsigned NumberedOp = 0;
1806 std::set<unsigned> NamedOpIndices;
1807 if (Target.getInstructionSet()->
1808 getValueAsBit("noNamedPositionallyEncodedOperands"))
1809 // Collect the set of operand indices that might correspond to named
1810 // operand, and skip these when assigning operands based on position.
1811 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1812 unsigned OpIdx;
1813 if (!CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
1814 continue;
1816 NamedOpIndices.insert(OpIdx);
1819 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1820 // Ignore fixed fields in the record, we're looking for values like:
1821 // bits<5> RST = { ?, ?, ?, ?, ? };
1822 if (Vals[i].getPrefix() || Vals[i].getValue()->isComplete())
1823 continue;
1825 // Determine if Vals[i] actually contributes to the Inst encoding.
1826 unsigned bi = 0;
1827 for (; bi < Bits.getNumBits(); ++bi) {
1828 VarInit *Var = nullptr;
1829 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1830 if (BI)
1831 Var = dyn_cast<VarInit>(BI->getBitVar());
1832 else
1833 Var = dyn_cast<VarInit>(Bits.getBit(bi));
1835 if (Var && Var->getName() == Vals[i].getName())
1836 break;
1839 if (bi == Bits.getNumBits())
1840 continue;
1842 // Skip variables that correspond to explicitly-named operands.
1843 unsigned OpIdx;
1844 if (CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
1845 continue;
1847 // Get the bit range for this operand:
1848 unsigned bitStart = bi++, bitWidth = 1;
1849 for (; bi < Bits.getNumBits(); ++bi) {
1850 VarInit *Var = nullptr;
1851 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1852 if (BI)
1853 Var = dyn_cast<VarInit>(BI->getBitVar());
1854 else
1855 Var = dyn_cast<VarInit>(Bits.getBit(bi));
1857 if (!Var)
1858 break;
1860 if (Var->getName() != Vals[i].getName())
1861 break;
1863 ++bitWidth;
1866 unsigned NumberOps = CGI.Operands.size();
1867 while (NumberedOp < NumberOps &&
1868 (CGI.Operands.isFlatOperandNotEmitted(NumberedOp) ||
1869 (!NamedOpIndices.empty() && NamedOpIndices.count(
1870 CGI.Operands.getSubOperandNumber(NumberedOp).first))))
1871 ++NumberedOp;
1873 OpIdx = NumberedOp++;
1875 // OpIdx now holds the ordered operand number of Vals[i].
1876 std::pair<unsigned, unsigned> SO =
1877 CGI.Operands.getSubOperandNumber(OpIdx);
1878 const std::string &Name = CGI.Operands[SO.first].Name;
1880 LLVM_DEBUG(dbgs() << "Numbered operand mapping for " << Def.getName()
1881 << ": " << Name << "(" << SO.first << ", " << SO.second
1882 << ") => " << Vals[i].getName() << "\n");
1884 std::string Decoder;
1885 Record *TypeRecord = CGI.Operands[SO.first].Rec;
1887 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
1888 StringInit *String = DecoderString ?
1889 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
1890 if (String && String->getValue() != "")
1891 Decoder = String->getValue();
1893 if (Decoder == "" &&
1894 CGI.Operands[SO.first].MIOperandInfo &&
1895 CGI.Operands[SO.first].MIOperandInfo->getNumArgs()) {
1896 Init *Arg = CGI.Operands[SO.first].MIOperandInfo->
1897 getArg(SO.second);
1898 if (DefInit *DI = cast<DefInit>(Arg))
1899 TypeRecord = DI->getDef();
1902 bool isReg = false;
1903 if (TypeRecord->isSubClassOf("RegisterOperand"))
1904 TypeRecord = TypeRecord->getValueAsDef("RegClass");
1905 if (TypeRecord->isSubClassOf("RegisterClass")) {
1906 Decoder = "Decode" + TypeRecord->getName().str() + "RegisterClass";
1907 isReg = true;
1908 } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) {
1909 Decoder = "DecodePointerLikeRegClass" +
1910 utostr(TypeRecord->getValueAsInt("RegClassKind"));
1911 isReg = true;
1914 DecoderString = TypeRecord->getValue("DecoderMethod");
1915 String = DecoderString ?
1916 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
1917 if (!isReg && String && String->getValue() != "")
1918 Decoder = String->getValue();
1920 RecordVal *HasCompleteDecoderVal =
1921 TypeRecord->getValue("hasCompleteDecoder");
1922 BitInit *HasCompleteDecoderBit = HasCompleteDecoderVal ?
1923 dyn_cast<BitInit>(HasCompleteDecoderVal->getValue()) : nullptr;
1924 bool HasCompleteDecoder = HasCompleteDecoderBit ?
1925 HasCompleteDecoderBit->getValue() : true;
1927 OperandInfo OpInfo(Decoder, HasCompleteDecoder);
1928 OpInfo.addField(bitStart, bitWidth, 0);
1930 NumberedInsnOperands[Name].push_back(OpInfo);
1932 // FIXME: For complex operands with custom decoders we can't handle tied
1933 // sub-operands automatically. Skip those here and assume that this is
1934 // fixed up elsewhere.
1935 if (CGI.Operands[SO.first].MIOperandInfo &&
1936 CGI.Operands[SO.first].MIOperandInfo->getNumArgs() > 1 &&
1937 String && String->getValue() != "")
1938 NumberedInsnOperandsNoTie.insert(Name);
1942 // For each operand, see if we can figure out where it is encoded.
1943 for (const auto &Op : InOutOperands) {
1944 if (!NumberedInsnOperands[Op.second].empty()) {
1945 InsnOperands.insert(InsnOperands.end(),
1946 NumberedInsnOperands[Op.second].begin(),
1947 NumberedInsnOperands[Op.second].end());
1948 continue;
1950 if (!NumberedInsnOperands[TiedNames[Op.second]].empty()) {
1951 if (!NumberedInsnOperandsNoTie.count(TiedNames[Op.second])) {
1952 // Figure out to which (sub)operand we're tied.
1953 unsigned i = CGI.Operands.getOperandNamed(TiedNames[Op.second]);
1954 int tiedTo = CGI.Operands[i].getTiedRegister();
1955 if (tiedTo == -1) {
1956 i = CGI.Operands.getOperandNamed(Op.second);
1957 tiedTo = CGI.Operands[i].getTiedRegister();
1960 if (tiedTo != -1) {
1961 std::pair<unsigned, unsigned> SO =
1962 CGI.Operands.getSubOperandNumber(tiedTo);
1964 InsnOperands.push_back(NumberedInsnOperands[TiedNames[Op.second]]
1965 [SO.second]);
1968 continue;
1971 TypedInit *TI = cast<TypedInit>(Op.first);
1973 // At this point, we can locate the decoder field, but we need to know how
1974 // to interpret it. As a first step, require the target to provide
1975 // callbacks for decoding register classes.
1976 std::string Decoder = findOperandDecoderMethod(TI);
1977 Record *TypeRecord = cast<DefInit>(TI)->getDef();
1979 RecordVal *HasCompleteDecoderVal =
1980 TypeRecord->getValue("hasCompleteDecoder");
1981 BitInit *HasCompleteDecoderBit = HasCompleteDecoderVal ?
1982 dyn_cast<BitInit>(HasCompleteDecoderVal->getValue()) : nullptr;
1983 bool HasCompleteDecoder = HasCompleteDecoderBit ?
1984 HasCompleteDecoderBit->getValue() : true;
1986 OperandInfo OpInfo(Decoder, HasCompleteDecoder);
1987 unsigned Base = ~0U;
1988 unsigned Width = 0;
1989 unsigned Offset = 0;
1991 for (unsigned bi = 0; bi < Bits.getNumBits(); ++bi) {
1992 VarInit *Var = nullptr;
1993 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1994 if (BI)
1995 Var = dyn_cast<VarInit>(BI->getBitVar());
1996 else
1997 Var = dyn_cast<VarInit>(Bits.getBit(bi));
1999 if (!Var) {
2000 if (Base != ~0U) {
2001 OpInfo.addField(Base, Width, Offset);
2002 Base = ~0U;
2003 Width = 0;
2004 Offset = 0;
2006 continue;
2009 if (Var->getName() != Op.second &&
2010 Var->getName() != TiedNames[Op.second]) {
2011 if (Base != ~0U) {
2012 OpInfo.addField(Base, Width, Offset);
2013 Base = ~0U;
2014 Width = 0;
2015 Offset = 0;
2017 continue;
2020 if (Base == ~0U) {
2021 Base = bi;
2022 Width = 1;
2023 Offset = BI ? BI->getBitNum() : 0;
2024 } else if (BI && BI->getBitNum() != Offset + Width) {
2025 OpInfo.addField(Base, Width, Offset);
2026 Base = bi;
2027 Width = 1;
2028 Offset = BI->getBitNum();
2029 } else {
2030 ++Width;
2034 if (Base != ~0U)
2035 OpInfo.addField(Base, Width, Offset);
2037 if (OpInfo.numFields() > 0)
2038 InsnOperands.push_back(OpInfo);
2041 Operands[Opc] = InsnOperands;
2043 #if 0
2044 LLVM_DEBUG({
2045 // Dumps the instruction encoding bits.
2046 dumpBits(errs(), Bits);
2048 errs() << '\n';
2050 // Dumps the list of operand info.
2051 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
2052 const CGIOperandList::OperandInfo &Info = CGI.Operands[i];
2053 const std::string &OperandName = Info.Name;
2054 const Record &OperandDef = *Info.Rec;
2056 errs() << "\t" << OperandName << " (" << OperandDef.getName() << ")\n";
2059 #endif
2061 return true;
2064 // emitFieldFromInstruction - Emit the templated helper function
2065 // fieldFromInstruction().
2066 // On Windows we make sure that this function is not inlined when
2067 // using the VS compiler. It has a bug which causes the function
2068 // to be optimized out in some circustances. See llvm.org/pr38292
2069 static void emitFieldFromInstruction(formatted_raw_ostream &OS) {
2070 OS << "// Helper function for extracting fields from encoded instructions.\n"
2071 << "template<typename InsnType>\n"
2072 << "#if defined(_MSC_VER) && !defined(__clang__)\n"
2073 << "__declspec(noinline)\n"
2074 << "#endif\n"
2075 << "static InsnType fieldFromInstruction(InsnType insn, unsigned startBit,\n"
2076 << " unsigned numBits) {\n"
2077 << " assert(startBit + numBits <= (sizeof(InsnType)*8) &&\n"
2078 << " \"Instruction field out of bounds!\");\n"
2079 << " InsnType fieldMask;\n"
2080 << " if (numBits == sizeof(InsnType)*8)\n"
2081 << " fieldMask = (InsnType)(-1LL);\n"
2082 << " else\n"
2083 << " fieldMask = (((InsnType)1 << numBits) - 1) << startBit;\n"
2084 << " return (insn & fieldMask) >> startBit;\n"
2085 << "}\n\n";
2088 // emitDecodeInstruction - Emit the templated helper function
2089 // decodeInstruction().
2090 static void emitDecodeInstruction(formatted_raw_ostream &OS) {
2091 OS << "template<typename InsnType>\n"
2092 << "static DecodeStatus decodeInstruction(const uint8_t DecodeTable[], "
2093 "MCInst &MI,\n"
2094 << " InsnType insn, uint64_t "
2095 "Address,\n"
2096 << " const void *DisAsm,\n"
2097 << " const MCSubtargetInfo &STI) {\n"
2098 << " const FeatureBitset& Bits = STI.getFeatureBits();\n"
2099 << "\n"
2100 << " const uint8_t *Ptr = DecodeTable;\n"
2101 << " uint32_t CurFieldValue = 0;\n"
2102 << " DecodeStatus S = MCDisassembler::Success;\n"
2103 << " while (true) {\n"
2104 << " ptrdiff_t Loc = Ptr - DecodeTable;\n"
2105 << " switch (*Ptr) {\n"
2106 << " default:\n"
2107 << " errs() << Loc << \": Unexpected decode table opcode!\\n\";\n"
2108 << " return MCDisassembler::Fail;\n"
2109 << " case MCD::OPC_ExtractField: {\n"
2110 << " unsigned Start = *++Ptr;\n"
2111 << " unsigned Len = *++Ptr;\n"
2112 << " ++Ptr;\n"
2113 << " CurFieldValue = fieldFromInstruction(insn, Start, Len);\n"
2114 << " LLVM_DEBUG(dbgs() << Loc << \": OPC_ExtractField(\" << Start << "
2115 "\", \"\n"
2116 << " << Len << \"): \" << CurFieldValue << \"\\n\");\n"
2117 << " break;\n"
2118 << " }\n"
2119 << " case MCD::OPC_FilterValue: {\n"
2120 << " // Decode the field value.\n"
2121 << " unsigned Len;\n"
2122 << " InsnType Val = decodeULEB128(++Ptr, &Len);\n"
2123 << " Ptr += Len;\n"
2124 << " // NumToSkip is a plain 24-bit integer.\n"
2125 << " unsigned NumToSkip = *Ptr++;\n"
2126 << " NumToSkip |= (*Ptr++) << 8;\n"
2127 << " NumToSkip |= (*Ptr++) << 16;\n"
2128 << "\n"
2129 << " // Perform the filter operation.\n"
2130 << " if (Val != CurFieldValue)\n"
2131 << " Ptr += NumToSkip;\n"
2132 << " LLVM_DEBUG(dbgs() << Loc << \": OPC_FilterValue(\" << Val << "
2133 "\", \" << NumToSkip\n"
2134 << " << \"): \" << ((Val != CurFieldValue) ? \"FAIL:\" "
2135 ": \"PASS:\")\n"
2136 << " << \" continuing at \" << (Ptr - DecodeTable) << "
2137 "\"\\n\");\n"
2138 << "\n"
2139 << " break;\n"
2140 << " }\n"
2141 << " case MCD::OPC_CheckField: {\n"
2142 << " unsigned Start = *++Ptr;\n"
2143 << " unsigned Len = *++Ptr;\n"
2144 << " InsnType FieldValue = fieldFromInstruction(insn, Start, Len);\n"
2145 << " // Decode the field value.\n"
2146 << " uint32_t ExpectedValue = decodeULEB128(++Ptr, &Len);\n"
2147 << " Ptr += Len;\n"
2148 << " // NumToSkip is a plain 24-bit integer.\n"
2149 << " unsigned NumToSkip = *Ptr++;\n"
2150 << " NumToSkip |= (*Ptr++) << 8;\n"
2151 << " NumToSkip |= (*Ptr++) << 16;\n"
2152 << "\n"
2153 << " // If the actual and expected values don't match, skip.\n"
2154 << " if (ExpectedValue != FieldValue)\n"
2155 << " Ptr += NumToSkip;\n"
2156 << " LLVM_DEBUG(dbgs() << Loc << \": OPC_CheckField(\" << Start << "
2157 "\", \"\n"
2158 << " << Len << \", \" << ExpectedValue << \", \" << "
2159 "NumToSkip\n"
2160 << " << \"): FieldValue = \" << FieldValue << \", "
2161 "ExpectedValue = \"\n"
2162 << " << ExpectedValue << \": \"\n"
2163 << " << ((ExpectedValue == FieldValue) ? \"PASS\\n\" : "
2164 "\"FAIL\\n\"));\n"
2165 << " break;\n"
2166 << " }\n"
2167 << " case MCD::OPC_CheckPredicate: {\n"
2168 << " unsigned Len;\n"
2169 << " // Decode the Predicate Index value.\n"
2170 << " unsigned PIdx = decodeULEB128(++Ptr, &Len);\n"
2171 << " Ptr += Len;\n"
2172 << " // NumToSkip is a plain 24-bit integer.\n"
2173 << " unsigned NumToSkip = *Ptr++;\n"
2174 << " NumToSkip |= (*Ptr++) << 8;\n"
2175 << " NumToSkip |= (*Ptr++) << 16;\n"
2176 << " // Check the predicate.\n"
2177 << " bool Pred;\n"
2178 << " if (!(Pred = checkDecoderPredicate(PIdx, Bits)))\n"
2179 << " Ptr += NumToSkip;\n"
2180 << " (void)Pred;\n"
2181 << " LLVM_DEBUG(dbgs() << Loc << \": OPC_CheckPredicate(\" << PIdx "
2182 "<< \"): \"\n"
2183 << " << (Pred ? \"PASS\\n\" : \"FAIL\\n\"));\n"
2184 << "\n"
2185 << " break;\n"
2186 << " }\n"
2187 << " case MCD::OPC_Decode: {\n"
2188 << " unsigned Len;\n"
2189 << " // Decode the Opcode value.\n"
2190 << " unsigned Opc = decodeULEB128(++Ptr, &Len);\n"
2191 << " Ptr += Len;\n"
2192 << " unsigned DecodeIdx = decodeULEB128(Ptr, &Len);\n"
2193 << " Ptr += Len;\n"
2194 << "\n"
2195 << " MI.clear();\n"
2196 << " MI.setOpcode(Opc);\n"
2197 << " bool DecodeComplete;\n"
2198 << " S = decodeToMCInst(S, DecodeIdx, insn, MI, Address, DisAsm, "
2199 "DecodeComplete);\n"
2200 << " assert(DecodeComplete);\n"
2201 << "\n"
2202 << " LLVM_DEBUG(dbgs() << Loc << \": OPC_Decode: opcode \" << Opc\n"
2203 << " << \", using decoder \" << DecodeIdx << \": \"\n"
2204 << " << (S != MCDisassembler::Fail ? \"PASS\" : "
2205 "\"FAIL\") << \"\\n\");\n"
2206 << " return S;\n"
2207 << " }\n"
2208 << " case MCD::OPC_TryDecode: {\n"
2209 << " unsigned Len;\n"
2210 << " // Decode the Opcode value.\n"
2211 << " unsigned Opc = decodeULEB128(++Ptr, &Len);\n"
2212 << " Ptr += Len;\n"
2213 << " unsigned DecodeIdx = decodeULEB128(Ptr, &Len);\n"
2214 << " Ptr += Len;\n"
2215 << " // NumToSkip is a plain 24-bit integer.\n"
2216 << " unsigned NumToSkip = *Ptr++;\n"
2217 << " NumToSkip |= (*Ptr++) << 8;\n"
2218 << " NumToSkip |= (*Ptr++) << 16;\n"
2219 << "\n"
2220 << " // Perform the decode operation.\n"
2221 << " MCInst TmpMI;\n"
2222 << " TmpMI.setOpcode(Opc);\n"
2223 << " bool DecodeComplete;\n"
2224 << " S = decodeToMCInst(S, DecodeIdx, insn, TmpMI, Address, DisAsm, "
2225 "DecodeComplete);\n"
2226 << " LLVM_DEBUG(dbgs() << Loc << \": OPC_TryDecode: opcode \" << "
2227 "Opc\n"
2228 << " << \", using decoder \" << DecodeIdx << \": \");\n"
2229 << "\n"
2230 << " if (DecodeComplete) {\n"
2231 << " // Decoding complete.\n"
2232 << " LLVM_DEBUG(dbgs() << (S != MCDisassembler::Fail ? \"PASS\" : "
2233 "\"FAIL\") << \"\\n\");\n"
2234 << " MI = TmpMI;\n"
2235 << " return S;\n"
2236 << " } else {\n"
2237 << " assert(S == MCDisassembler::Fail);\n"
2238 << " // If the decoding was incomplete, skip.\n"
2239 << " Ptr += NumToSkip;\n"
2240 << " LLVM_DEBUG(dbgs() << \"FAIL: continuing at \" << (Ptr - "
2241 "DecodeTable) << \"\\n\");\n"
2242 << " // Reset decode status. This also drops a SoftFail status "
2243 "that could be\n"
2244 << " // set before the decode attempt.\n"
2245 << " S = MCDisassembler::Success;\n"
2246 << " }\n"
2247 << " break;\n"
2248 << " }\n"
2249 << " case MCD::OPC_SoftFail: {\n"
2250 << " // Decode the mask values.\n"
2251 << " unsigned Len;\n"
2252 << " InsnType PositiveMask = decodeULEB128(++Ptr, &Len);\n"
2253 << " Ptr += Len;\n"
2254 << " InsnType NegativeMask = decodeULEB128(Ptr, &Len);\n"
2255 << " Ptr += Len;\n"
2256 << " bool Fail = (insn & PositiveMask) || (~insn & NegativeMask);\n"
2257 << " if (Fail)\n"
2258 << " S = MCDisassembler::SoftFail;\n"
2259 << " LLVM_DEBUG(dbgs() << Loc << \": OPC_SoftFail: \" << (Fail ? "
2260 "\"FAIL\\n\":\"PASS\\n\"));\n"
2261 << " break;\n"
2262 << " }\n"
2263 << " case MCD::OPC_Fail: {\n"
2264 << " LLVM_DEBUG(dbgs() << Loc << \": OPC_Fail\\n\");\n"
2265 << " return MCDisassembler::Fail;\n"
2266 << " }\n"
2267 << " }\n"
2268 << " }\n"
2269 << " llvm_unreachable(\"bogosity detected in disassembler state "
2270 "machine!\");\n"
2271 << "}\n\n";
2274 // Emits disassembler code for instruction decoding.
2275 void FixedLenDecoderEmitter::run(raw_ostream &o) {
2276 formatted_raw_ostream OS(o);
2277 OS << "#include \"llvm/MC/MCInst.h\"\n";
2278 OS << "#include \"llvm/Support/Debug.h\"\n";
2279 OS << "#include \"llvm/Support/DataTypes.h\"\n";
2280 OS << "#include \"llvm/Support/LEB128.h\"\n";
2281 OS << "#include \"llvm/Support/raw_ostream.h\"\n";
2282 OS << "#include <assert.h>\n";
2283 OS << '\n';
2284 OS << "namespace llvm {\n\n";
2286 emitFieldFromInstruction(OS);
2288 Target.reverseBitsForLittleEndianEncoding();
2290 // Parameterize the decoders based on namespace and instruction width.
2291 NumberedInstructions = Target.getInstructionsByEnumValue();
2292 std::map<std::pair<std::string, unsigned>,
2293 std::vector<unsigned>> OpcMap;
2294 std::map<unsigned, std::vector<OperandInfo>> Operands;
2296 for (unsigned i = 0; i < NumberedInstructions.size(); ++i) {
2297 const CodeGenInstruction *Inst = NumberedInstructions[i];
2298 const Record *Def = Inst->TheDef;
2299 unsigned Size = Def->getValueAsInt("Size");
2300 if (Def->getValueAsString("Namespace") == "TargetOpcode" ||
2301 Def->getValueAsBit("isPseudo") ||
2302 Def->getValueAsBit("isAsmParserOnly") ||
2303 Def->getValueAsBit("isCodeGenOnly"))
2304 continue;
2306 StringRef DecoderNamespace = Def->getValueAsString("DecoderNamespace");
2308 if (Size) {
2309 if (populateInstruction(Target, *Inst, i, Operands)) {
2310 OpcMap[std::make_pair(DecoderNamespace, Size)].push_back(i);
2315 DecoderTableInfo TableInfo;
2316 for (const auto &Opc : OpcMap) {
2317 // Emit the decoder for this namespace+width combination.
2318 FilterChooser FC(NumberedInstructions, Opc.second, Operands,
2319 8*Opc.first.second, this);
2321 // The decode table is cleared for each top level decoder function. The
2322 // predicates and decoders themselves, however, are shared across all
2323 // decoders to give more opportunities for uniqueing.
2324 TableInfo.Table.clear();
2325 TableInfo.FixupStack.clear();
2326 TableInfo.Table.reserve(16384);
2327 TableInfo.FixupStack.emplace_back();
2328 FC.emitTableEntries(TableInfo);
2329 // Any NumToSkip fixups in the top level scope can resolve to the
2330 // OPC_Fail at the end of the table.
2331 assert(TableInfo.FixupStack.size() == 1 && "fixup stack phasing error!");
2332 // Resolve any NumToSkip fixups in the current scope.
2333 resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
2334 TableInfo.Table.size());
2335 TableInfo.FixupStack.clear();
2337 TableInfo.Table.push_back(MCD::OPC_Fail);
2339 // Print the table to the output stream.
2340 emitTable(OS, TableInfo.Table, 0, FC.getBitWidth(), Opc.first.first);
2341 OS.flush();
2344 // Emit the predicate function.
2345 emitPredicateFunction(OS, TableInfo.Predicates, 0);
2347 // Emit the decoder function.
2348 emitDecoderFunction(OS, TableInfo.Decoders, 0);
2350 // Emit the main entry point for the decoder, decodeInstruction().
2351 emitDecodeInstruction(OS);
2353 OS << "\n} // End llvm namespace\n";
2356 namespace llvm {
2358 void EmitFixedLenDecoder(RecordKeeper &RK, raw_ostream &OS,
2359 const std::string &PredicateNamespace,
2360 const std::string &GPrefix,
2361 const std::string &GPostfix, const std::string &ROK,
2362 const std::string &RFail, const std::string &L) {
2363 FixedLenDecoderEmitter(RK, PredicateNamespace, GPrefix, GPostfix,
2364 ROK, RFail, L).run(OS);
2367 } // end namespace llvm