[ARM] Fixup pipeline test. NFC
[llvm-complete.git] / utils / TableGen / FixedLenDecoderEmitter.cpp
blob01f4115aa1dd6b08106f6ef047fd95884737d3c8
1 //===------------ FixedLenDecoderEmitter.cpp - Decoder Generator ----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // It contains the tablegen backend that emits the decoder functions for
10 // targets with fixed length instruction set.
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenInstruction.h"
15 #include "CodeGenTarget.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/CachedHashString.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/Statistic.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 STATISTIC(NumEncodings, "Number of encodings considered");
52 STATISTIC(NumEncodingsLackingDisasm, "Number of encodings without disassembler info");
53 STATISTIC(NumInstructions, "Number of instructions considered");
54 STATISTIC(NumEncodingsSupported, "Number of encodings supported");
55 STATISTIC(NumEncodingsOmitted, "Number of encodings omitted");
57 struct EncodingField {
58 unsigned Base, Width, Offset;
59 EncodingField(unsigned B, unsigned W, unsigned O)
60 : Base(B), Width(W), Offset(O) { }
63 struct OperandInfo {
64 std::vector<EncodingField> Fields;
65 std::string Decoder;
66 bool HasCompleteDecoder;
67 uint64_t InitValue;
69 OperandInfo(std::string D, bool HCD)
70 : Decoder(std::move(D)), HasCompleteDecoder(HCD), InitValue(0) {}
72 void addField(unsigned Base, unsigned Width, unsigned Offset) {
73 Fields.push_back(EncodingField(Base, Width, Offset));
76 unsigned numFields() const { return Fields.size(); }
78 typedef std::vector<EncodingField>::const_iterator const_iterator;
80 const_iterator begin() const { return Fields.begin(); }
81 const_iterator end() const { return Fields.end(); }
84 typedef std::vector<uint8_t> DecoderTable;
85 typedef uint32_t DecoderFixup;
86 typedef std::vector<DecoderFixup> FixupList;
87 typedef std::vector<FixupList> FixupScopeList;
88 typedef SmallSetVector<CachedHashString, 16> PredicateSet;
89 typedef SmallSetVector<CachedHashString, 16> DecoderSet;
90 struct DecoderTableInfo {
91 DecoderTable Table;
92 FixupScopeList FixupStack;
93 PredicateSet Predicates;
94 DecoderSet Decoders;
97 struct EncodingAndInst {
98 const Record *EncodingDef;
99 const CodeGenInstruction *Inst;
101 EncodingAndInst(const Record *EncodingDef, const CodeGenInstruction *Inst)
102 : EncodingDef(EncodingDef), Inst(Inst) {}
105 struct EncodingIDAndOpcode {
106 unsigned EncodingID;
107 unsigned Opcode;
109 EncodingIDAndOpcode() : EncodingID(0), Opcode(0) {}
110 EncodingIDAndOpcode(unsigned EncodingID, unsigned Opcode)
111 : EncodingID(EncodingID), Opcode(Opcode) {}
114 raw_ostream &operator<<(raw_ostream &OS, const EncodingAndInst &Value) {
115 if (Value.EncodingDef != Value.Inst->TheDef)
116 OS << Value.EncodingDef->getName() << ":";
117 OS << Value.Inst->TheDef->getName();
118 return OS;
121 class FixedLenDecoderEmitter {
122 RecordKeeper &RK;
123 std::vector<EncodingAndInst> NumberedEncodings;
125 public:
126 // Defaults preserved here for documentation, even though they aren't
127 // strictly necessary given the way that this is currently being called.
128 FixedLenDecoderEmitter(RecordKeeper &R, std::string PredicateNamespace,
129 std::string GPrefix = "if (",
130 std::string GPostfix = " == MCDisassembler::Fail)",
131 std::string ROK = "MCDisassembler::Success",
132 std::string RFail = "MCDisassembler::Fail",
133 std::string L = "")
134 : RK(R), Target(R), PredicateNamespace(std::move(PredicateNamespace)),
135 GuardPrefix(std::move(GPrefix)), GuardPostfix(std::move(GPostfix)),
136 ReturnOK(std::move(ROK)), ReturnFail(std::move(RFail)),
137 Locals(std::move(L)) {}
139 // Emit the decoder state machine table.
140 void emitTable(formatted_raw_ostream &o, DecoderTable &Table,
141 unsigned Indentation, unsigned BitWidth,
142 StringRef Namespace) const;
143 void emitPredicateFunction(formatted_raw_ostream &OS,
144 PredicateSet &Predicates,
145 unsigned Indentation) const;
146 void emitDecoderFunction(formatted_raw_ostream &OS,
147 DecoderSet &Decoders,
148 unsigned Indentation) const;
150 // run - Output the code emitter
151 void run(raw_ostream &o);
153 private:
154 CodeGenTarget Target;
156 public:
157 std::string PredicateNamespace;
158 std::string GuardPrefix, GuardPostfix;
159 std::string ReturnOK, ReturnFail;
160 std::string Locals;
163 } // end anonymous namespace
165 // The set (BIT_TRUE, BIT_FALSE, BIT_UNSET) represents a ternary logic system
166 // for a bit value.
168 // BIT_UNFILTERED is used as the init value for a filter position. It is used
169 // only for filter processings.
170 typedef enum {
171 BIT_TRUE, // '1'
172 BIT_FALSE, // '0'
173 BIT_UNSET, // '?'
174 BIT_UNFILTERED // unfiltered
175 } bit_value_t;
177 static bool ValueSet(bit_value_t V) {
178 return (V == BIT_TRUE || V == BIT_FALSE);
181 static bool ValueNotSet(bit_value_t V) {
182 return (V == BIT_UNSET);
185 static int Value(bit_value_t V) {
186 return ValueNotSet(V) ? -1 : (V == BIT_FALSE ? 0 : 1);
189 static bit_value_t bitFromBits(const BitsInit &bits, unsigned index) {
190 if (BitInit *bit = dyn_cast<BitInit>(bits.getBit(index)))
191 return bit->getValue() ? BIT_TRUE : BIT_FALSE;
193 // The bit is uninitialized.
194 return BIT_UNSET;
197 // Prints the bit value for each position.
198 static void dumpBits(raw_ostream &o, const BitsInit &bits) {
199 for (unsigned index = bits.getNumBits(); index > 0; --index) {
200 switch (bitFromBits(bits, index - 1)) {
201 case BIT_TRUE:
202 o << "1";
203 break;
204 case BIT_FALSE:
205 o << "0";
206 break;
207 case BIT_UNSET:
208 o << "_";
209 break;
210 default:
211 llvm_unreachable("unexpected return value from bitFromBits");
216 static BitsInit &getBitsField(const Record &def, StringRef str) {
217 BitsInit *bits = def.getValueAsBitsInit(str);
218 return *bits;
221 // Representation of the instruction to work on.
222 typedef std::vector<bit_value_t> insn_t;
224 namespace {
226 class FilterChooser;
228 /// Filter - Filter works with FilterChooser to produce the decoding tree for
229 /// the ISA.
231 /// It is useful to think of a Filter as governing the switch stmts of the
232 /// decoding tree in a certain level. Each case stmt delegates to an inferior
233 /// FilterChooser to decide what further decoding logic to employ, or in another
234 /// words, what other remaining bits to look at. The FilterChooser eventually
235 /// chooses a best Filter to do its job.
237 /// This recursive scheme ends when the number of Opcodes assigned to the
238 /// FilterChooser becomes 1 or if there is a conflict. A conflict happens when
239 /// the Filter/FilterChooser combo does not know how to distinguish among the
240 /// Opcodes assigned.
242 /// An example of a conflict is
244 /// Conflict:
245 /// 111101000.00........00010000....
246 /// 111101000.00........0001........
247 /// 1111010...00........0001........
248 /// 1111010...00....................
249 /// 1111010.........................
250 /// 1111............................
251 /// ................................
252 /// VST4q8a 111101000_00________00010000____
253 /// VST4q8b 111101000_00________00010000____
255 /// The Debug output shows the path that the decoding tree follows to reach the
256 /// the conclusion that there is a conflict. VST4q8a is a vst4 to double-spaced
257 /// even registers, while VST4q8b is a vst4 to double-spaced odd registers.
259 /// The encoding info in the .td files does not specify this meta information,
260 /// which could have been used by the decoder to resolve the conflict. The
261 /// decoder could try to decode the even/odd register numbering and assign to
262 /// VST4q8a or VST4q8b, but for the time being, the decoder chooses the "a"
263 /// version and return the Opcode since the two have the same Asm format string.
264 class Filter {
265 protected:
266 const FilterChooser *Owner;// points to the FilterChooser who owns this filter
267 unsigned StartBit; // the starting bit position
268 unsigned NumBits; // number of bits to filter
269 bool Mixed; // a mixed region contains both set and unset bits
271 // Map of well-known segment value to the set of uid's with that value.
272 std::map<uint64_t, std::vector<EncodingIDAndOpcode>>
273 FilteredInstructions;
275 // Set of uid's with non-constant segment values.
276 std::vector<EncodingIDAndOpcode> VariableInstructions;
278 // Map of well-known segment value to its delegate.
279 std::map<unsigned, std::unique_ptr<const FilterChooser>> FilterChooserMap;
281 // Number of instructions which fall under FilteredInstructions category.
282 unsigned NumFiltered;
284 // Keeps track of the last opcode in the filtered bucket.
285 EncodingIDAndOpcode LastOpcFiltered;
287 public:
288 Filter(Filter &&f);
289 Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, bool mixed);
291 ~Filter() = default;
293 unsigned getNumFiltered() const { return NumFiltered; }
295 EncodingIDAndOpcode getSingletonOpc() const {
296 assert(NumFiltered == 1);
297 return LastOpcFiltered;
300 // Return the filter chooser for the group of instructions without constant
301 // segment values.
302 const FilterChooser &getVariableFC() const {
303 assert(NumFiltered == 1);
304 assert(FilterChooserMap.size() == 1);
305 return *(FilterChooserMap.find((unsigned)-1)->second);
308 // Divides the decoding task into sub tasks and delegates them to the
309 // inferior FilterChooser's.
311 // A special case arises when there's only one entry in the filtered
312 // instructions. In order to unambiguously decode the singleton, we need to
313 // match the remaining undecoded encoding bits against the singleton.
314 void recurse();
316 // Emit table entries to decode instructions given a segment or segments of
317 // bits.
318 void emitTableEntry(DecoderTableInfo &TableInfo) const;
320 // Returns the number of fanout produced by the filter. More fanout implies
321 // the filter distinguishes more categories of instructions.
322 unsigned usefulness() const;
323 }; // end class Filter
325 } // end anonymous namespace
327 // These are states of our finite state machines used in FilterChooser's
328 // filterProcessor() which produces the filter candidates to use.
329 typedef enum {
330 ATTR_NONE,
331 ATTR_FILTERED,
332 ATTR_ALL_SET,
333 ATTR_ALL_UNSET,
334 ATTR_MIXED
335 } bitAttr_t;
337 /// FilterChooser - FilterChooser chooses the best filter among a set of Filters
338 /// in order to perform the decoding of instructions at the current level.
340 /// Decoding proceeds from the top down. Based on the well-known encoding bits
341 /// of instructions available, FilterChooser builds up the possible Filters that
342 /// can further the task of decoding by distinguishing among the remaining
343 /// candidate instructions.
345 /// Once a filter has been chosen, it is called upon to divide the decoding task
346 /// into sub-tasks and delegates them to its inferior FilterChoosers for further
347 /// processings.
349 /// It is useful to think of a Filter as governing the switch stmts of the
350 /// decoding tree. And each case is delegated to an inferior FilterChooser to
351 /// decide what further remaining bits to look at.
352 namespace {
354 class FilterChooser {
355 protected:
356 friend class Filter;
358 // Vector of codegen instructions to choose our filter.
359 ArrayRef<EncodingAndInst> AllInstructions;
361 // Vector of uid's for this filter chooser to work on.
362 // The first member of the pair is the opcode id being decoded, the second is
363 // the opcode id that should be emitted.
364 const std::vector<EncodingIDAndOpcode> &Opcodes;
366 // Lookup table for the operand decoding of instructions.
367 const std::map<unsigned, std::vector<OperandInfo>> &Operands;
369 // Vector of candidate filters.
370 std::vector<Filter> Filters;
372 // Array of bit values passed down from our parent.
373 // Set to all BIT_UNFILTERED's for Parent == NULL.
374 std::vector<bit_value_t> FilterBitValues;
376 // Links to the FilterChooser above us in the decoding tree.
377 const FilterChooser *Parent;
379 // Index of the best filter from Filters.
380 int BestIndex;
382 // Width of instructions
383 unsigned BitWidth;
385 // Parent emitter
386 const FixedLenDecoderEmitter *Emitter;
388 public:
389 FilterChooser(ArrayRef<EncodingAndInst> Insts,
390 const std::vector<EncodingIDAndOpcode> &IDs,
391 const std::map<unsigned, std::vector<OperandInfo>> &Ops,
392 unsigned BW, const FixedLenDecoderEmitter *E)
393 : AllInstructions(Insts), Opcodes(IDs), Operands(Ops),
394 FilterBitValues(BW, BIT_UNFILTERED), Parent(nullptr), BestIndex(-1),
395 BitWidth(BW), Emitter(E) {
396 doFilter();
399 FilterChooser(ArrayRef<EncodingAndInst> Insts,
400 const std::vector<EncodingIDAndOpcode> &IDs,
401 const std::map<unsigned, std::vector<OperandInfo>> &Ops,
402 const std::vector<bit_value_t> &ParentFilterBitValues,
403 const FilterChooser &parent)
404 : AllInstructions(Insts), Opcodes(IDs), Operands(Ops),
405 FilterBitValues(ParentFilterBitValues), Parent(&parent), BestIndex(-1),
406 BitWidth(parent.BitWidth), Emitter(parent.Emitter) {
407 doFilter();
410 FilterChooser(const FilterChooser &) = delete;
411 void operator=(const FilterChooser &) = delete;
413 unsigned getBitWidth() const { return BitWidth; }
415 protected:
416 // Populates the insn given the uid.
417 void insnWithID(insn_t &Insn, unsigned Opcode) const {
418 BitsInit &Bits = getBitsField(*AllInstructions[Opcode].EncodingDef, "Inst");
420 // We may have a SoftFail bitmask, which specifies a mask where an encoding
421 // may differ from the value in "Inst" and yet still be valid, but the
422 // disassembler should return SoftFail instead of Success.
424 // This is used for marking UNPREDICTABLE instructions in the ARM world.
425 BitsInit *SFBits =
426 AllInstructions[Opcode].EncodingDef->getValueAsBitsInit("SoftFail");
428 for (unsigned i = 0; i < BitWidth; ++i) {
429 if (SFBits && bitFromBits(*SFBits, i) == BIT_TRUE)
430 Insn.push_back(BIT_UNSET);
431 else
432 Insn.push_back(bitFromBits(Bits, i));
436 // Emit the name of the encoding/instruction pair.
437 void emitNameWithID(raw_ostream &OS, unsigned Opcode) const {
438 const Record *EncodingDef = AllInstructions[Opcode].EncodingDef;
439 const Record *InstDef = AllInstructions[Opcode].Inst->TheDef;
440 if (EncodingDef != InstDef)
441 OS << EncodingDef->getName() << ":";
442 OS << InstDef->getName();
445 // Populates the field of the insn given the start position and the number of
446 // consecutive bits to scan for.
448 // Returns false if there exists any uninitialized bit value in the range.
449 // Returns true, otherwise.
450 bool fieldFromInsn(uint64_t &Field, insn_t &Insn, unsigned StartBit,
451 unsigned NumBits) const;
453 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
454 /// filter array as a series of chars.
455 void dumpFilterArray(raw_ostream &o,
456 const std::vector<bit_value_t> & filter) const;
458 /// dumpStack - dumpStack traverses the filter chooser chain and calls
459 /// dumpFilterArray on each filter chooser up to the top level one.
460 void dumpStack(raw_ostream &o, const char *prefix) const;
462 Filter &bestFilter() {
463 assert(BestIndex != -1 && "BestIndex not set");
464 return Filters[BestIndex];
467 bool PositionFiltered(unsigned i) const {
468 return ValueSet(FilterBitValues[i]);
471 // Calculates the island(s) needed to decode the instruction.
472 // This returns a lit of undecoded bits of an instructions, for example,
473 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
474 // decoded bits in order to verify that the instruction matches the Opcode.
475 unsigned getIslands(std::vector<unsigned> &StartBits,
476 std::vector<unsigned> &EndBits,
477 std::vector<uint64_t> &FieldVals,
478 const insn_t &Insn) const;
480 // Emits code to check the Predicates member of an instruction are true.
481 // Returns true if predicate matches were emitted, false otherwise.
482 bool emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
483 unsigned Opc) const;
485 bool doesOpcodeNeedPredicate(unsigned Opc) const;
486 unsigned getPredicateIndex(DecoderTableInfo &TableInfo, StringRef P) const;
487 void emitPredicateTableEntry(DecoderTableInfo &TableInfo,
488 unsigned Opc) const;
490 void emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
491 unsigned Opc) const;
493 // Emits table entries to decode the singleton.
494 void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
495 EncodingIDAndOpcode Opc) const;
497 // Emits code to decode the singleton, and then to decode the rest.
498 void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
499 const Filter &Best) const;
501 void emitBinaryParser(raw_ostream &o, unsigned &Indentation,
502 const OperandInfo &OpInfo,
503 bool &OpHasCompleteDecoder) const;
505 void emitDecoder(raw_ostream &OS, unsigned Indentation, unsigned Opc,
506 bool &HasCompleteDecoder) const;
507 unsigned getDecoderIndex(DecoderSet &Decoders, unsigned Opc,
508 bool &HasCompleteDecoder) const;
510 // Assign a single filter and run with it.
511 void runSingleFilter(unsigned startBit, unsigned numBit, bool mixed);
513 // reportRegion is a helper function for filterProcessor to mark a region as
514 // eligible for use as a filter region.
515 void reportRegion(bitAttr_t RA, unsigned StartBit, unsigned BitIndex,
516 bool AllowMixed);
518 // FilterProcessor scans the well-known encoding bits of the instructions and
519 // builds up a list of candidate filters. It chooses the best filter and
520 // recursively descends down the decoding tree.
521 bool filterProcessor(bool AllowMixed, bool Greedy = true);
523 // Decides on the best configuration of filter(s) to use in order to decode
524 // the instructions. A conflict of instructions may occur, in which case we
525 // dump the conflict set to the standard error.
526 void doFilter();
528 public:
529 // emitTableEntries - Emit state machine entries to decode our share of
530 // instructions.
531 void emitTableEntries(DecoderTableInfo &TableInfo) const;
534 } // end anonymous namespace
536 ///////////////////////////
537 // //
538 // Filter Implementation //
539 // //
540 ///////////////////////////
542 Filter::Filter(Filter &&f)
543 : Owner(f.Owner), StartBit(f.StartBit), NumBits(f.NumBits), Mixed(f.Mixed),
544 FilteredInstructions(std::move(f.FilteredInstructions)),
545 VariableInstructions(std::move(f.VariableInstructions)),
546 FilterChooserMap(std::move(f.FilterChooserMap)), NumFiltered(f.NumFiltered),
547 LastOpcFiltered(f.LastOpcFiltered) {
550 Filter::Filter(FilterChooser &owner, unsigned startBit, unsigned numBits,
551 bool mixed)
552 : Owner(&owner), StartBit(startBit), NumBits(numBits), Mixed(mixed) {
553 assert(StartBit + NumBits - 1 < Owner->BitWidth);
555 NumFiltered = 0;
556 LastOpcFiltered = {0, 0};
558 for (unsigned i = 0, e = Owner->Opcodes.size(); i != e; ++i) {
559 insn_t Insn;
561 // Populates the insn given the uid.
562 Owner->insnWithID(Insn, Owner->Opcodes[i].EncodingID);
564 uint64_t Field;
565 // Scans the segment for possibly well-specified encoding bits.
566 bool ok = Owner->fieldFromInsn(Field, Insn, StartBit, NumBits);
568 if (ok) {
569 // The encoding bits are well-known. Lets add the uid of the
570 // instruction into the bucket keyed off the constant field value.
571 LastOpcFiltered = Owner->Opcodes[i];
572 FilteredInstructions[Field].push_back(LastOpcFiltered);
573 ++NumFiltered;
574 } else {
575 // Some of the encoding bit(s) are unspecified. This contributes to
576 // one additional member of "Variable" instructions.
577 VariableInstructions.push_back(Owner->Opcodes[i]);
581 assert((FilteredInstructions.size() + VariableInstructions.size() > 0)
582 && "Filter returns no instruction categories");
585 // Divides the decoding task into sub tasks and delegates them to the
586 // inferior FilterChooser's.
588 // A special case arises when there's only one entry in the filtered
589 // instructions. In order to unambiguously decode the singleton, we need to
590 // match the remaining undecoded encoding bits against the singleton.
591 void Filter::recurse() {
592 // Starts by inheriting our parent filter chooser's filter bit values.
593 std::vector<bit_value_t> BitValueArray(Owner->FilterBitValues);
595 if (!VariableInstructions.empty()) {
596 // Conservatively marks each segment position as BIT_UNSET.
597 for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex)
598 BitValueArray[StartBit + bitIndex] = BIT_UNSET;
600 // Delegates to an inferior filter chooser for further processing on this
601 // group of instructions whose segment values are variable.
602 FilterChooserMap.insert(
603 std::make_pair(-1U, std::make_unique<FilterChooser>(
604 Owner->AllInstructions, VariableInstructions,
605 Owner->Operands, BitValueArray, *Owner)));
608 // No need to recurse for a singleton filtered instruction.
609 // See also Filter::emit*().
610 if (getNumFiltered() == 1) {
611 assert(FilterChooserMap.size() == 1);
612 return;
615 // Otherwise, create sub choosers.
616 for (const auto &Inst : FilteredInstructions) {
618 // Marks all the segment positions with either BIT_TRUE or BIT_FALSE.
619 for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex) {
620 if (Inst.first & (1ULL << bitIndex))
621 BitValueArray[StartBit + bitIndex] = BIT_TRUE;
622 else
623 BitValueArray[StartBit + bitIndex] = BIT_FALSE;
626 // Delegates to an inferior filter chooser for further processing on this
627 // category of instructions.
628 FilterChooserMap.insert(std::make_pair(
629 Inst.first, std::make_unique<FilterChooser>(
630 Owner->AllInstructions, Inst.second,
631 Owner->Operands, BitValueArray, *Owner)));
635 static void resolveTableFixups(DecoderTable &Table, const FixupList &Fixups,
636 uint32_t DestIdx) {
637 // Any NumToSkip fixups in the current scope can resolve to the
638 // current location.
639 for (FixupList::const_reverse_iterator I = Fixups.rbegin(),
640 E = Fixups.rend();
641 I != E; ++I) {
642 // Calculate the distance from the byte following the fixup entry byte
643 // to the destination. The Target is calculated from after the 16-bit
644 // NumToSkip entry itself, so subtract two from the displacement here
645 // to account for that.
646 uint32_t FixupIdx = *I;
647 uint32_t Delta = DestIdx - FixupIdx - 3;
648 // Our NumToSkip entries are 24-bits. Make sure our table isn't too
649 // big.
650 assert(Delta < (1u << 24));
651 Table[FixupIdx] = (uint8_t)Delta;
652 Table[FixupIdx + 1] = (uint8_t)(Delta >> 8);
653 Table[FixupIdx + 2] = (uint8_t)(Delta >> 16);
657 // Emit table entries to decode instructions given a segment or segments
658 // of bits.
659 void Filter::emitTableEntry(DecoderTableInfo &TableInfo) const {
660 TableInfo.Table.push_back(MCD::OPC_ExtractField);
661 TableInfo.Table.push_back(StartBit);
662 TableInfo.Table.push_back(NumBits);
664 // A new filter entry begins a new scope for fixup resolution.
665 TableInfo.FixupStack.emplace_back();
667 DecoderTable &Table = TableInfo.Table;
669 size_t PrevFilter = 0;
670 bool HasFallthrough = false;
671 for (auto &Filter : FilterChooserMap) {
672 // Field value -1 implies a non-empty set of variable instructions.
673 // See also recurse().
674 if (Filter.first == (unsigned)-1) {
675 HasFallthrough = true;
677 // Each scope should always have at least one filter value to check
678 // for.
679 assert(PrevFilter != 0 && "empty filter set!");
680 FixupList &CurScope = TableInfo.FixupStack.back();
681 // Resolve any NumToSkip fixups in the current scope.
682 resolveTableFixups(Table, CurScope, Table.size());
683 CurScope.clear();
684 PrevFilter = 0; // Don't re-process the filter's fallthrough.
685 } else {
686 Table.push_back(MCD::OPC_FilterValue);
687 // Encode and emit the value to filter against.
688 uint8_t Buffer[16];
689 unsigned Len = encodeULEB128(Filter.first, Buffer);
690 Table.insert(Table.end(), Buffer, Buffer + Len);
691 // Reserve space for the NumToSkip entry. We'll backpatch the value
692 // later.
693 PrevFilter = Table.size();
694 Table.push_back(0);
695 Table.push_back(0);
696 Table.push_back(0);
699 // We arrive at a category of instructions with the same segment value.
700 // Now delegate to the sub filter chooser for further decodings.
701 // The case may fallthrough, which happens if the remaining well-known
702 // encoding bits do not match exactly.
703 Filter.second->emitTableEntries(TableInfo);
705 // Now that we've emitted the body of the handler, update the NumToSkip
706 // of the filter itself to be able to skip forward when false. Subtract
707 // two as to account for the width of the NumToSkip field itself.
708 if (PrevFilter) {
709 uint32_t NumToSkip = Table.size() - PrevFilter - 3;
710 assert(NumToSkip < (1u << 24) && "disassembler decoding table too large!");
711 Table[PrevFilter] = (uint8_t)NumToSkip;
712 Table[PrevFilter + 1] = (uint8_t)(NumToSkip >> 8);
713 Table[PrevFilter + 2] = (uint8_t)(NumToSkip >> 16);
717 // Any remaining unresolved fixups bubble up to the parent fixup scope.
718 assert(TableInfo.FixupStack.size() > 1 && "fixup stack underflow!");
719 FixupScopeList::iterator Source = TableInfo.FixupStack.end() - 1;
720 FixupScopeList::iterator Dest = Source - 1;
721 Dest->insert(Dest->end(), Source->begin(), Source->end());
722 TableInfo.FixupStack.pop_back();
724 // If there is no fallthrough, then the final filter should get fixed
725 // up according to the enclosing scope rather than the current position.
726 if (!HasFallthrough)
727 TableInfo.FixupStack.back().push_back(PrevFilter);
730 // Returns the number of fanout produced by the filter. More fanout implies
731 // the filter distinguishes more categories of instructions.
732 unsigned Filter::usefulness() const {
733 if (!VariableInstructions.empty())
734 return FilteredInstructions.size();
735 else
736 return FilteredInstructions.size() + 1;
739 //////////////////////////////////
740 // //
741 // Filterchooser Implementation //
742 // //
743 //////////////////////////////////
745 // Emit the decoder state machine table.
746 void FixedLenDecoderEmitter::emitTable(formatted_raw_ostream &OS,
747 DecoderTable &Table,
748 unsigned Indentation,
749 unsigned BitWidth,
750 StringRef Namespace) const {
751 OS.indent(Indentation) << "static const uint8_t DecoderTable" << Namespace
752 << BitWidth << "[] = {\n";
754 Indentation += 2;
756 // FIXME: We may be able to use the NumToSkip values to recover
757 // appropriate indentation levels.
758 DecoderTable::const_iterator I = Table.begin();
759 DecoderTable::const_iterator E = Table.end();
760 while (I != E) {
761 assert (I < E && "incomplete decode table entry!");
763 uint64_t Pos = I - Table.begin();
764 OS << "/* " << Pos << " */";
765 OS.PadToColumn(12);
767 switch (*I) {
768 default:
769 PrintFatalError("invalid decode table opcode");
770 case MCD::OPC_ExtractField: {
771 ++I;
772 unsigned Start = *I++;
773 unsigned Len = *I++;
774 OS.indent(Indentation) << "MCD::OPC_ExtractField, " << Start << ", "
775 << Len << ", // Inst{";
776 if (Len > 1)
777 OS << (Start + Len - 1) << "-";
778 OS << Start << "} ...\n";
779 break;
781 case MCD::OPC_FilterValue: {
782 ++I;
783 OS.indent(Indentation) << "MCD::OPC_FilterValue, ";
784 // The filter value is ULEB128 encoded.
785 while (*I >= 128)
786 OS << (unsigned)*I++ << ", ";
787 OS << (unsigned)*I++ << ", ";
789 // 24-bit numtoskip value.
790 uint8_t Byte = *I++;
791 uint32_t NumToSkip = Byte;
792 OS << (unsigned)Byte << ", ";
793 Byte = *I++;
794 OS << (unsigned)Byte << ", ";
795 NumToSkip |= Byte << 8;
796 Byte = *I++;
797 OS << utostr(Byte) << ", ";
798 NumToSkip |= Byte << 16;
799 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
800 break;
802 case MCD::OPC_CheckField: {
803 ++I;
804 unsigned Start = *I++;
805 unsigned Len = *I++;
806 OS.indent(Indentation) << "MCD::OPC_CheckField, " << Start << ", "
807 << Len << ", ";// << Val << ", " << NumToSkip << ",\n";
808 // ULEB128 encoded field value.
809 for (; *I >= 128; ++I)
810 OS << (unsigned)*I << ", ";
811 OS << (unsigned)*I++ << ", ";
812 // 24-bit numtoskip value.
813 uint8_t Byte = *I++;
814 uint32_t NumToSkip = Byte;
815 OS << (unsigned)Byte << ", ";
816 Byte = *I++;
817 OS << (unsigned)Byte << ", ";
818 NumToSkip |= Byte << 8;
819 Byte = *I++;
820 OS << utostr(Byte) << ", ";
821 NumToSkip |= Byte << 16;
822 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
823 break;
825 case MCD::OPC_CheckPredicate: {
826 ++I;
827 OS.indent(Indentation) << "MCD::OPC_CheckPredicate, ";
828 for (; *I >= 128; ++I)
829 OS << (unsigned)*I << ", ";
830 OS << (unsigned)*I++ << ", ";
832 // 24-bit numtoskip value.
833 uint8_t Byte = *I++;
834 uint32_t NumToSkip = Byte;
835 OS << (unsigned)Byte << ", ";
836 Byte = *I++;
837 OS << (unsigned)Byte << ", ";
838 NumToSkip |= Byte << 8;
839 Byte = *I++;
840 OS << utostr(Byte) << ", ";
841 NumToSkip |= Byte << 16;
842 OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
843 break;
845 case MCD::OPC_Decode:
846 case MCD::OPC_TryDecode: {
847 bool IsTry = *I == MCD::OPC_TryDecode;
848 ++I;
849 // Extract the ULEB128 encoded Opcode to a buffer.
850 uint8_t Buffer[16], *p = Buffer;
851 while ((*p++ = *I++) >= 128)
852 assert((p - Buffer) <= (ptrdiff_t)sizeof(Buffer)
853 && "ULEB128 value too large!");
854 // Decode the Opcode value.
855 unsigned Opc = decodeULEB128(Buffer);
856 OS.indent(Indentation) << "MCD::OPC_" << (IsTry ? "Try" : "")
857 << "Decode, ";
858 for (p = Buffer; *p >= 128; ++p)
859 OS << (unsigned)*p << ", ";
860 OS << (unsigned)*p << ", ";
862 // Decoder index.
863 for (; *I >= 128; ++I)
864 OS << (unsigned)*I << ", ";
865 OS << (unsigned)*I++ << ", ";
867 if (!IsTry) {
868 OS << "// Opcode: " << NumberedEncodings[Opc] << "\n";
869 break;
872 // Fallthrough for OPC_TryDecode.
874 // 24-bit numtoskip value.
875 uint8_t Byte = *I++;
876 uint32_t NumToSkip = Byte;
877 OS << (unsigned)Byte << ", ";
878 Byte = *I++;
879 OS << (unsigned)Byte << ", ";
880 NumToSkip |= Byte << 8;
881 Byte = *I++;
882 OS << utostr(Byte) << ", ";
883 NumToSkip |= Byte << 16;
885 OS << "// Opcode: " << NumberedEncodings[Opc]
886 << ", skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
887 break;
889 case MCD::OPC_SoftFail: {
890 ++I;
891 OS.indent(Indentation) << "MCD::OPC_SoftFail";
892 // Positive mask
893 uint64_t Value = 0;
894 unsigned Shift = 0;
895 do {
896 OS << ", " << (unsigned)*I;
897 Value += (*I & 0x7f) << Shift;
898 Shift += 7;
899 } while (*I++ >= 128);
900 if (Value > 127) {
901 OS << " /* 0x";
902 OS.write_hex(Value);
903 OS << " */";
905 // Negative mask
906 Value = 0;
907 Shift = 0;
908 do {
909 OS << ", " << (unsigned)*I;
910 Value += (*I & 0x7f) << Shift;
911 Shift += 7;
912 } while (*I++ >= 128);
913 if (Value > 127) {
914 OS << " /* 0x";
915 OS.write_hex(Value);
916 OS << " */";
918 OS << ",\n";
919 break;
921 case MCD::OPC_Fail: {
922 ++I;
923 OS.indent(Indentation) << "MCD::OPC_Fail,\n";
924 break;
928 OS.indent(Indentation) << "0\n";
930 Indentation -= 2;
932 OS.indent(Indentation) << "};\n\n";
935 void FixedLenDecoderEmitter::
936 emitPredicateFunction(formatted_raw_ostream &OS, PredicateSet &Predicates,
937 unsigned Indentation) const {
938 // The predicate function is just a big switch statement based on the
939 // input predicate index.
940 OS.indent(Indentation) << "static bool checkDecoderPredicate(unsigned Idx, "
941 << "const FeatureBitset& Bits) {\n";
942 Indentation += 2;
943 if (!Predicates.empty()) {
944 OS.indent(Indentation) << "switch (Idx) {\n";
945 OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
946 unsigned Index = 0;
947 for (const auto &Predicate : Predicates) {
948 OS.indent(Indentation) << "case " << Index++ << ":\n";
949 OS.indent(Indentation+2) << "return (" << Predicate << ");\n";
951 OS.indent(Indentation) << "}\n";
952 } else {
953 // No case statement to emit
954 OS.indent(Indentation) << "llvm_unreachable(\"Invalid index!\");\n";
956 Indentation -= 2;
957 OS.indent(Indentation) << "}\n\n";
960 void FixedLenDecoderEmitter::
961 emitDecoderFunction(formatted_raw_ostream &OS, DecoderSet &Decoders,
962 unsigned Indentation) const {
963 // The decoder function is just a big switch statement based on the
964 // input decoder index.
965 OS.indent(Indentation) << "template<typename InsnType>\n";
966 OS.indent(Indentation) << "static DecodeStatus decodeToMCInst(DecodeStatus S,"
967 << " unsigned Idx, InsnType insn, MCInst &MI,\n";
968 OS.indent(Indentation) << " uint64_t "
969 << "Address, const void *Decoder, bool &DecodeComplete) {\n";
970 Indentation += 2;
971 OS.indent(Indentation) << "DecodeComplete = true;\n";
972 OS.indent(Indentation) << "InsnType tmp;\n";
973 OS.indent(Indentation) << "switch (Idx) {\n";
974 OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
975 unsigned Index = 0;
976 for (const auto &Decoder : Decoders) {
977 OS.indent(Indentation) << "case " << Index++ << ":\n";
978 OS << Decoder;
979 OS.indent(Indentation+2) << "return S;\n";
981 OS.indent(Indentation) << "}\n";
982 Indentation -= 2;
983 OS.indent(Indentation) << "}\n\n";
986 // Populates the field of the insn given the start position and the number of
987 // consecutive bits to scan for.
989 // Returns false if and on the first uninitialized bit value encountered.
990 // Returns true, otherwise.
991 bool FilterChooser::fieldFromInsn(uint64_t &Field, insn_t &Insn,
992 unsigned StartBit, unsigned NumBits) const {
993 Field = 0;
995 for (unsigned i = 0; i < NumBits; ++i) {
996 if (Insn[StartBit + i] == BIT_UNSET)
997 return false;
999 if (Insn[StartBit + i] == BIT_TRUE)
1000 Field = Field | (1ULL << i);
1003 return true;
1006 /// dumpFilterArray - dumpFilterArray prints out debugging info for the given
1007 /// filter array as a series of chars.
1008 void FilterChooser::dumpFilterArray(raw_ostream &o,
1009 const std::vector<bit_value_t> &filter) const {
1010 for (unsigned bitIndex = BitWidth; bitIndex > 0; bitIndex--) {
1011 switch (filter[bitIndex - 1]) {
1012 case BIT_UNFILTERED:
1013 o << ".";
1014 break;
1015 case BIT_UNSET:
1016 o << "_";
1017 break;
1018 case BIT_TRUE:
1019 o << "1";
1020 break;
1021 case BIT_FALSE:
1022 o << "0";
1023 break;
1028 /// dumpStack - dumpStack traverses the filter chooser chain and calls
1029 /// dumpFilterArray on each filter chooser up to the top level one.
1030 void FilterChooser::dumpStack(raw_ostream &o, const char *prefix) const {
1031 const FilterChooser *current = this;
1033 while (current) {
1034 o << prefix;
1035 dumpFilterArray(o, current->FilterBitValues);
1036 o << '\n';
1037 current = current->Parent;
1041 // Calculates the island(s) needed to decode the instruction.
1042 // This returns a list of undecoded bits of an instructions, for example,
1043 // Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be
1044 // decoded bits in order to verify that the instruction matches the Opcode.
1045 unsigned FilterChooser::getIslands(std::vector<unsigned> &StartBits,
1046 std::vector<unsigned> &EndBits,
1047 std::vector<uint64_t> &FieldVals,
1048 const insn_t &Insn) const {
1049 unsigned Num, BitNo;
1050 Num = BitNo = 0;
1052 uint64_t FieldVal = 0;
1054 // 0: Init
1055 // 1: Water (the bit value does not affect decoding)
1056 // 2: Island (well-known bit value needed for decoding)
1057 int State = 0;
1058 int64_t Val = -1;
1060 for (unsigned i = 0; i < BitWidth; ++i) {
1061 Val = Value(Insn[i]);
1062 bool Filtered = PositionFiltered(i);
1063 switch (State) {
1064 default: llvm_unreachable("Unreachable code!");
1065 case 0:
1066 case 1:
1067 if (Filtered || Val == -1)
1068 State = 1; // Still in Water
1069 else {
1070 State = 2; // Into the Island
1071 BitNo = 0;
1072 StartBits.push_back(i);
1073 FieldVal = Val;
1075 break;
1076 case 2:
1077 if (Filtered || Val == -1) {
1078 State = 1; // Into the Water
1079 EndBits.push_back(i - 1);
1080 FieldVals.push_back(FieldVal);
1081 ++Num;
1082 } else {
1083 State = 2; // Still in Island
1084 ++BitNo;
1085 FieldVal = FieldVal | Val << BitNo;
1087 break;
1090 // If we are still in Island after the loop, do some housekeeping.
1091 if (State == 2) {
1092 EndBits.push_back(BitWidth - 1);
1093 FieldVals.push_back(FieldVal);
1094 ++Num;
1097 assert(StartBits.size() == Num && EndBits.size() == Num &&
1098 FieldVals.size() == Num);
1099 return Num;
1102 void FilterChooser::emitBinaryParser(raw_ostream &o, unsigned &Indentation,
1103 const OperandInfo &OpInfo,
1104 bool &OpHasCompleteDecoder) const {
1105 const std::string &Decoder = OpInfo.Decoder;
1107 if (OpInfo.numFields() != 1 || OpInfo.InitValue != 0) {
1108 o.indent(Indentation) << "tmp = 0x";
1109 o.write_hex(OpInfo.InitValue);
1110 o << ";\n";
1113 for (const EncodingField &EF : OpInfo) {
1114 o.indent(Indentation) << "tmp ";
1115 if (OpInfo.numFields() != 1 || OpInfo.InitValue != 0) o << '|';
1116 o << "= fieldFromInstruction"
1117 << "(insn, " << EF.Base << ", " << EF.Width << ')';
1118 if (OpInfo.numFields() != 1 || EF.Offset != 0)
1119 o << " << " << EF.Offset;
1120 o << ";\n";
1123 if (Decoder != "") {
1124 OpHasCompleteDecoder = OpInfo.HasCompleteDecoder;
1125 o.indent(Indentation) << Emitter->GuardPrefix << Decoder
1126 << "(MI, tmp, Address, Decoder)"
1127 << Emitter->GuardPostfix
1128 << " { " << (OpHasCompleteDecoder ? "" : "DecodeComplete = false; ")
1129 << "return MCDisassembler::Fail; }\n";
1130 } else {
1131 OpHasCompleteDecoder = true;
1132 o.indent(Indentation) << "MI.addOperand(MCOperand::createImm(tmp));\n";
1136 void FilterChooser::emitDecoder(raw_ostream &OS, unsigned Indentation,
1137 unsigned Opc, bool &HasCompleteDecoder) const {
1138 HasCompleteDecoder = true;
1140 for (const auto &Op : Operands.find(Opc)->second) {
1141 // If a custom instruction decoder was specified, use that.
1142 if (Op.numFields() == 0 && !Op.Decoder.empty()) {
1143 HasCompleteDecoder = Op.HasCompleteDecoder;
1144 OS.indent(Indentation) << Emitter->GuardPrefix << Op.Decoder
1145 << "(MI, insn, Address, Decoder)"
1146 << Emitter->GuardPostfix
1147 << " { " << (HasCompleteDecoder ? "" : "DecodeComplete = false; ")
1148 << "return MCDisassembler::Fail; }\n";
1149 break;
1152 bool OpHasCompleteDecoder;
1153 emitBinaryParser(OS, Indentation, Op, OpHasCompleteDecoder);
1154 if (!OpHasCompleteDecoder)
1155 HasCompleteDecoder = false;
1159 unsigned FilterChooser::getDecoderIndex(DecoderSet &Decoders,
1160 unsigned Opc,
1161 bool &HasCompleteDecoder) const {
1162 // Build up the predicate string.
1163 SmallString<256> Decoder;
1164 // FIXME: emitDecoder() function can take a buffer directly rather than
1165 // a stream.
1166 raw_svector_ostream S(Decoder);
1167 unsigned I = 4;
1168 emitDecoder(S, I, Opc, HasCompleteDecoder);
1170 // Using the full decoder string as the key value here is a bit
1171 // heavyweight, but is effective. If the string comparisons become a
1172 // performance concern, we can implement a mangling of the predicate
1173 // data easily enough with a map back to the actual string. That's
1174 // overkill for now, though.
1176 // Make sure the predicate is in the table.
1177 Decoders.insert(CachedHashString(Decoder));
1178 // Now figure out the index for when we write out the table.
1179 DecoderSet::const_iterator P = find(Decoders, Decoder.str());
1180 return (unsigned)(P - Decoders.begin());
1183 static void emitSinglePredicateMatch(raw_ostream &o, StringRef str,
1184 const std::string &PredicateNamespace) {
1185 if (str[0] == '!')
1186 o << "!Bits[" << PredicateNamespace << "::"
1187 << str.slice(1,str.size()) << "]";
1188 else
1189 o << "Bits[" << PredicateNamespace << "::" << str << "]";
1192 bool FilterChooser::emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
1193 unsigned Opc) const {
1194 ListInit *Predicates =
1195 AllInstructions[Opc].EncodingDef->getValueAsListInit("Predicates");
1196 bool IsFirstEmission = true;
1197 for (unsigned i = 0; i < Predicates->size(); ++i) {
1198 Record *Pred = Predicates->getElementAsRecord(i);
1199 if (!Pred->getValue("AssemblerMatcherPredicate"))
1200 continue;
1202 StringRef P = Pred->getValueAsString("AssemblerCondString");
1204 if (P.empty())
1205 continue;
1207 if (!IsFirstEmission)
1208 o << " && ";
1210 std::pair<StringRef, StringRef> pairs = P.split(',');
1211 while (!pairs.second.empty()) {
1212 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
1213 o << " && ";
1214 pairs = pairs.second.split(',');
1216 emitSinglePredicateMatch(o, pairs.first, Emitter->PredicateNamespace);
1217 IsFirstEmission = false;
1219 return !Predicates->empty();
1222 bool FilterChooser::doesOpcodeNeedPredicate(unsigned Opc) const {
1223 ListInit *Predicates =
1224 AllInstructions[Opc].EncodingDef->getValueAsListInit("Predicates");
1225 for (unsigned i = 0; i < Predicates->size(); ++i) {
1226 Record *Pred = Predicates->getElementAsRecord(i);
1227 if (!Pred->getValue("AssemblerMatcherPredicate"))
1228 continue;
1230 StringRef P = Pred->getValueAsString("AssemblerCondString");
1232 if (P.empty())
1233 continue;
1235 return true;
1237 return false;
1240 unsigned FilterChooser::getPredicateIndex(DecoderTableInfo &TableInfo,
1241 StringRef Predicate) const {
1242 // Using the full predicate string as the key value here is a bit
1243 // heavyweight, but is effective. If the string comparisons become a
1244 // performance concern, we can implement a mangling of the predicate
1245 // data easily enough with a map back to the actual string. That's
1246 // overkill for now, though.
1248 // Make sure the predicate is in the table.
1249 TableInfo.Predicates.insert(CachedHashString(Predicate));
1250 // Now figure out the index for when we write out the table.
1251 PredicateSet::const_iterator P = find(TableInfo.Predicates, Predicate);
1252 return (unsigned)(P - TableInfo.Predicates.begin());
1255 void FilterChooser::emitPredicateTableEntry(DecoderTableInfo &TableInfo,
1256 unsigned Opc) const {
1257 if (!doesOpcodeNeedPredicate(Opc))
1258 return;
1260 // Build up the predicate string.
1261 SmallString<256> Predicate;
1262 // FIXME: emitPredicateMatch() functions can take a buffer directly rather
1263 // than a stream.
1264 raw_svector_ostream PS(Predicate);
1265 unsigned I = 0;
1266 emitPredicateMatch(PS, I, Opc);
1268 // Figure out the index into the predicate table for the predicate just
1269 // computed.
1270 unsigned PIdx = getPredicateIndex(TableInfo, PS.str());
1271 SmallString<16> PBytes;
1272 raw_svector_ostream S(PBytes);
1273 encodeULEB128(PIdx, S);
1275 TableInfo.Table.push_back(MCD::OPC_CheckPredicate);
1276 // Predicate index
1277 for (unsigned i = 0, e = PBytes.size(); i != e; ++i)
1278 TableInfo.Table.push_back(PBytes[i]);
1279 // Push location for NumToSkip backpatching.
1280 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1281 TableInfo.Table.push_back(0);
1282 TableInfo.Table.push_back(0);
1283 TableInfo.Table.push_back(0);
1286 void FilterChooser::emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
1287 unsigned Opc) const {
1288 BitsInit *SFBits =
1289 AllInstructions[Opc].EncodingDef->getValueAsBitsInit("SoftFail");
1290 if (!SFBits) return;
1291 BitsInit *InstBits =
1292 AllInstructions[Opc].EncodingDef->getValueAsBitsInit("Inst");
1294 APInt PositiveMask(BitWidth, 0ULL);
1295 APInt NegativeMask(BitWidth, 0ULL);
1296 for (unsigned i = 0; i < BitWidth; ++i) {
1297 bit_value_t B = bitFromBits(*SFBits, i);
1298 bit_value_t IB = bitFromBits(*InstBits, i);
1300 if (B != BIT_TRUE) continue;
1302 switch (IB) {
1303 case BIT_FALSE:
1304 // The bit is meant to be false, so emit a check to see if it is true.
1305 PositiveMask.setBit(i);
1306 break;
1307 case BIT_TRUE:
1308 // The bit is meant to be true, so emit a check to see if it is false.
1309 NegativeMask.setBit(i);
1310 break;
1311 default:
1312 // The bit is not set; this must be an error!
1313 errs() << "SoftFail Conflict: bit SoftFail{" << i << "} in "
1314 << AllInstructions[Opc] << " is set but Inst{" << i
1315 << "} is unset!\n"
1316 << " - You can only mark a bit as SoftFail if it is fully defined"
1317 << " (1/0 - not '?') in Inst\n";
1318 return;
1322 bool NeedPositiveMask = PositiveMask.getBoolValue();
1323 bool NeedNegativeMask = NegativeMask.getBoolValue();
1325 if (!NeedPositiveMask && !NeedNegativeMask)
1326 return;
1328 TableInfo.Table.push_back(MCD::OPC_SoftFail);
1330 SmallString<16> MaskBytes;
1331 raw_svector_ostream S(MaskBytes);
1332 if (NeedPositiveMask) {
1333 encodeULEB128(PositiveMask.getZExtValue(), S);
1334 for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
1335 TableInfo.Table.push_back(MaskBytes[i]);
1336 } else
1337 TableInfo.Table.push_back(0);
1338 if (NeedNegativeMask) {
1339 MaskBytes.clear();
1340 encodeULEB128(NegativeMask.getZExtValue(), S);
1341 for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
1342 TableInfo.Table.push_back(MaskBytes[i]);
1343 } else
1344 TableInfo.Table.push_back(0);
1347 // Emits table entries to decode the singleton.
1348 void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1349 EncodingIDAndOpcode Opc) const {
1350 std::vector<unsigned> StartBits;
1351 std::vector<unsigned> EndBits;
1352 std::vector<uint64_t> FieldVals;
1353 insn_t Insn;
1354 insnWithID(Insn, Opc.EncodingID);
1356 // Look for islands of undecoded bits of the singleton.
1357 getIslands(StartBits, EndBits, FieldVals, Insn);
1359 unsigned Size = StartBits.size();
1361 // Emit the predicate table entry if one is needed.
1362 emitPredicateTableEntry(TableInfo, Opc.EncodingID);
1364 // Check any additional encoding fields needed.
1365 for (unsigned I = Size; I != 0; --I) {
1366 unsigned NumBits = EndBits[I-1] - StartBits[I-1] + 1;
1367 TableInfo.Table.push_back(MCD::OPC_CheckField);
1368 TableInfo.Table.push_back(StartBits[I-1]);
1369 TableInfo.Table.push_back(NumBits);
1370 uint8_t Buffer[16], *p;
1371 encodeULEB128(FieldVals[I-1], Buffer);
1372 for (p = Buffer; *p >= 128 ; ++p)
1373 TableInfo.Table.push_back(*p);
1374 TableInfo.Table.push_back(*p);
1375 // Push location for NumToSkip backpatching.
1376 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1377 // The fixup is always 24-bits, so go ahead and allocate the space
1378 // in the table so all our relative position calculations work OK even
1379 // before we fully resolve the real value here.
1380 TableInfo.Table.push_back(0);
1381 TableInfo.Table.push_back(0);
1382 TableInfo.Table.push_back(0);
1385 // Check for soft failure of the match.
1386 emitSoftFailTableEntry(TableInfo, Opc.EncodingID);
1388 bool HasCompleteDecoder;
1389 unsigned DIdx =
1390 getDecoderIndex(TableInfo.Decoders, Opc.EncodingID, HasCompleteDecoder);
1392 // Produce OPC_Decode or OPC_TryDecode opcode based on the information
1393 // whether the instruction decoder is complete or not. If it is complete
1394 // then it handles all possible values of remaining variable/unfiltered bits
1395 // and for any value can determine if the bitpattern is a valid instruction
1396 // or not. This means OPC_Decode will be the final step in the decoding
1397 // process. If it is not complete, then the Fail return code from the
1398 // decoder method indicates that additional processing should be done to see
1399 // if there is any other instruction that also matches the bitpattern and
1400 // can decode it.
1401 TableInfo.Table.push_back(HasCompleteDecoder ? MCD::OPC_Decode :
1402 MCD::OPC_TryDecode);
1403 NumEncodingsSupported++;
1404 uint8_t Buffer[16], *p;
1405 encodeULEB128(Opc.Opcode, Buffer);
1406 for (p = Buffer; *p >= 128 ; ++p)
1407 TableInfo.Table.push_back(*p);
1408 TableInfo.Table.push_back(*p);
1410 SmallString<16> Bytes;
1411 raw_svector_ostream S(Bytes);
1412 encodeULEB128(DIdx, S);
1414 // Decoder index
1415 for (unsigned i = 0, e = Bytes.size(); i != e; ++i)
1416 TableInfo.Table.push_back(Bytes[i]);
1418 if (!HasCompleteDecoder) {
1419 // Push location for NumToSkip backpatching.
1420 TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
1421 // Allocate the space for the fixup.
1422 TableInfo.Table.push_back(0);
1423 TableInfo.Table.push_back(0);
1424 TableInfo.Table.push_back(0);
1428 // Emits table entries to decode the singleton, and then to decode the rest.
1429 void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
1430 const Filter &Best) const {
1431 EncodingIDAndOpcode Opc = Best.getSingletonOpc();
1433 // complex singletons need predicate checks from the first singleton
1434 // to refer forward to the variable filterchooser that follows.
1435 TableInfo.FixupStack.emplace_back();
1437 emitSingletonTableEntry(TableInfo, Opc);
1439 resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
1440 TableInfo.Table.size());
1441 TableInfo.FixupStack.pop_back();
1443 Best.getVariableFC().emitTableEntries(TableInfo);
1446 // Assign a single filter and run with it. Top level API client can initialize
1447 // with a single filter to start the filtering process.
1448 void FilterChooser::runSingleFilter(unsigned startBit, unsigned numBit,
1449 bool mixed) {
1450 Filters.clear();
1451 Filters.emplace_back(*this, startBit, numBit, true);
1452 BestIndex = 0; // Sole Filter instance to choose from.
1453 bestFilter().recurse();
1456 // reportRegion is a helper function for filterProcessor to mark a region as
1457 // eligible for use as a filter region.
1458 void FilterChooser::reportRegion(bitAttr_t RA, unsigned StartBit,
1459 unsigned BitIndex, bool AllowMixed) {
1460 if (RA == ATTR_MIXED && AllowMixed)
1461 Filters.emplace_back(*this, StartBit, BitIndex - StartBit, true);
1462 else if (RA == ATTR_ALL_SET && !AllowMixed)
1463 Filters.emplace_back(*this, StartBit, BitIndex - StartBit, false);
1466 // FilterProcessor scans the well-known encoding bits of the instructions and
1467 // builds up a list of candidate filters. It chooses the best filter and
1468 // recursively descends down the decoding tree.
1469 bool FilterChooser::filterProcessor(bool AllowMixed, bool Greedy) {
1470 Filters.clear();
1471 BestIndex = -1;
1472 unsigned numInstructions = Opcodes.size();
1474 assert(numInstructions && "Filter created with no instructions");
1476 // No further filtering is necessary.
1477 if (numInstructions == 1)
1478 return true;
1480 // Heuristics. See also doFilter()'s "Heuristics" comment when num of
1481 // instructions is 3.
1482 if (AllowMixed && !Greedy) {
1483 assert(numInstructions == 3);
1485 for (unsigned i = 0; i < Opcodes.size(); ++i) {
1486 std::vector<unsigned> StartBits;
1487 std::vector<unsigned> EndBits;
1488 std::vector<uint64_t> FieldVals;
1489 insn_t Insn;
1491 insnWithID(Insn, Opcodes[i].EncodingID);
1493 // Look for islands of undecoded bits of any instruction.
1494 if (getIslands(StartBits, EndBits, FieldVals, Insn) > 0) {
1495 // Found an instruction with island(s). Now just assign a filter.
1496 runSingleFilter(StartBits[0], EndBits[0] - StartBits[0] + 1, true);
1497 return true;
1502 unsigned BitIndex;
1504 // We maintain BIT_WIDTH copies of the bitAttrs automaton.
1505 // The automaton consumes the corresponding bit from each
1506 // instruction.
1508 // Input symbols: 0, 1, and _ (unset).
1509 // States: NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED.
1510 // Initial state: NONE.
1512 // (NONE) ------- [01] -> (ALL_SET)
1513 // (NONE) ------- _ ----> (ALL_UNSET)
1514 // (ALL_SET) ---- [01] -> (ALL_SET)
1515 // (ALL_SET) ---- _ ----> (MIXED)
1516 // (ALL_UNSET) -- [01] -> (MIXED)
1517 // (ALL_UNSET) -- _ ----> (ALL_UNSET)
1518 // (MIXED) ------ . ----> (MIXED)
1519 // (FILTERED)---- . ----> (FILTERED)
1521 std::vector<bitAttr_t> bitAttrs;
1523 // FILTERED bit positions provide no entropy and are not worthy of pursuing.
1524 // Filter::recurse() set either BIT_TRUE or BIT_FALSE for each position.
1525 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex)
1526 if (FilterBitValues[BitIndex] == BIT_TRUE ||
1527 FilterBitValues[BitIndex] == BIT_FALSE)
1528 bitAttrs.push_back(ATTR_FILTERED);
1529 else
1530 bitAttrs.push_back(ATTR_NONE);
1532 for (unsigned InsnIndex = 0; InsnIndex < numInstructions; ++InsnIndex) {
1533 insn_t insn;
1535 insnWithID(insn, Opcodes[InsnIndex].EncodingID);
1537 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
1538 switch (bitAttrs[BitIndex]) {
1539 case ATTR_NONE:
1540 if (insn[BitIndex] == BIT_UNSET)
1541 bitAttrs[BitIndex] = ATTR_ALL_UNSET;
1542 else
1543 bitAttrs[BitIndex] = ATTR_ALL_SET;
1544 break;
1545 case ATTR_ALL_SET:
1546 if (insn[BitIndex] == BIT_UNSET)
1547 bitAttrs[BitIndex] = ATTR_MIXED;
1548 break;
1549 case ATTR_ALL_UNSET:
1550 if (insn[BitIndex] != BIT_UNSET)
1551 bitAttrs[BitIndex] = ATTR_MIXED;
1552 break;
1553 case ATTR_MIXED:
1554 case ATTR_FILTERED:
1555 break;
1560 // The regionAttr automaton consumes the bitAttrs automatons' state,
1561 // lowest-to-highest.
1563 // Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed)
1564 // States: NONE, ALL_SET, MIXED
1565 // Initial state: NONE
1567 // (NONE) ----- F --> (NONE)
1568 // (NONE) ----- S --> (ALL_SET) ; and set region start
1569 // (NONE) ----- U --> (NONE)
1570 // (NONE) ----- M --> (MIXED) ; and set region start
1571 // (ALL_SET) -- F --> (NONE) ; and report an ALL_SET region
1572 // (ALL_SET) -- S --> (ALL_SET)
1573 // (ALL_SET) -- U --> (NONE) ; and report an ALL_SET region
1574 // (ALL_SET) -- M --> (MIXED) ; and report an ALL_SET region
1575 // (MIXED) ---- F --> (NONE) ; and report a MIXED region
1576 // (MIXED) ---- S --> (ALL_SET) ; and report a MIXED region
1577 // (MIXED) ---- U --> (NONE) ; and report a MIXED region
1578 // (MIXED) ---- M --> (MIXED)
1580 bitAttr_t RA = ATTR_NONE;
1581 unsigned StartBit = 0;
1583 for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
1584 bitAttr_t bitAttr = bitAttrs[BitIndex];
1586 assert(bitAttr != ATTR_NONE && "Bit without attributes");
1588 switch (RA) {
1589 case ATTR_NONE:
1590 switch (bitAttr) {
1591 case ATTR_FILTERED:
1592 break;
1593 case ATTR_ALL_SET:
1594 StartBit = BitIndex;
1595 RA = ATTR_ALL_SET;
1596 break;
1597 case ATTR_ALL_UNSET:
1598 break;
1599 case ATTR_MIXED:
1600 StartBit = BitIndex;
1601 RA = ATTR_MIXED;
1602 break;
1603 default:
1604 llvm_unreachable("Unexpected bitAttr!");
1606 break;
1607 case ATTR_ALL_SET:
1608 switch (bitAttr) {
1609 case ATTR_FILTERED:
1610 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1611 RA = ATTR_NONE;
1612 break;
1613 case ATTR_ALL_SET:
1614 break;
1615 case ATTR_ALL_UNSET:
1616 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1617 RA = ATTR_NONE;
1618 break;
1619 case ATTR_MIXED:
1620 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1621 StartBit = BitIndex;
1622 RA = ATTR_MIXED;
1623 break;
1624 default:
1625 llvm_unreachable("Unexpected bitAttr!");
1627 break;
1628 case ATTR_MIXED:
1629 switch (bitAttr) {
1630 case ATTR_FILTERED:
1631 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1632 StartBit = BitIndex;
1633 RA = ATTR_NONE;
1634 break;
1635 case ATTR_ALL_SET:
1636 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1637 StartBit = BitIndex;
1638 RA = ATTR_ALL_SET;
1639 break;
1640 case ATTR_ALL_UNSET:
1641 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1642 RA = ATTR_NONE;
1643 break;
1644 case ATTR_MIXED:
1645 break;
1646 default:
1647 llvm_unreachable("Unexpected bitAttr!");
1649 break;
1650 case ATTR_ALL_UNSET:
1651 llvm_unreachable("regionAttr state machine has no ATTR_UNSET state");
1652 case ATTR_FILTERED:
1653 llvm_unreachable("regionAttr state machine has no ATTR_FILTERED state");
1657 // At the end, if we're still in ALL_SET or MIXED states, report a region
1658 switch (RA) {
1659 case ATTR_NONE:
1660 break;
1661 case ATTR_FILTERED:
1662 break;
1663 case ATTR_ALL_SET:
1664 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1665 break;
1666 case ATTR_ALL_UNSET:
1667 break;
1668 case ATTR_MIXED:
1669 reportRegion(RA, StartBit, BitIndex, AllowMixed);
1670 break;
1673 // We have finished with the filter processings. Now it's time to choose
1674 // the best performing filter.
1675 BestIndex = 0;
1676 bool AllUseless = true;
1677 unsigned BestScore = 0;
1679 for (unsigned i = 0, e = Filters.size(); i != e; ++i) {
1680 unsigned Usefulness = Filters[i].usefulness();
1682 if (Usefulness)
1683 AllUseless = false;
1685 if (Usefulness > BestScore) {
1686 BestIndex = i;
1687 BestScore = Usefulness;
1691 if (!AllUseless)
1692 bestFilter().recurse();
1694 return !AllUseless;
1695 } // end of FilterChooser::filterProcessor(bool)
1697 // Decides on the best configuration of filter(s) to use in order to decode
1698 // the instructions. A conflict of instructions may occur, in which case we
1699 // dump the conflict set to the standard error.
1700 void FilterChooser::doFilter() {
1701 unsigned Num = Opcodes.size();
1702 assert(Num && "FilterChooser created with no instructions");
1704 // Try regions of consecutive known bit values first.
1705 if (filterProcessor(false))
1706 return;
1708 // Then regions of mixed bits (both known and unitialized bit values allowed).
1709 if (filterProcessor(true))
1710 return;
1712 // Heuristics to cope with conflict set {t2CMPrs, t2SUBSrr, t2SUBSrs} where
1713 // no single instruction for the maximum ATTR_MIXED region Inst{14-4} has a
1714 // well-known encoding pattern. In such case, we backtrack and scan for the
1715 // the very first consecutive ATTR_ALL_SET region and assign a filter to it.
1716 if (Num == 3 && filterProcessor(true, false))
1717 return;
1719 // If we come to here, the instruction decoding has failed.
1720 // Set the BestIndex to -1 to indicate so.
1721 BestIndex = -1;
1724 // emitTableEntries - Emit state machine entries to decode our share of
1725 // instructions.
1726 void FilterChooser::emitTableEntries(DecoderTableInfo &TableInfo) const {
1727 if (Opcodes.size() == 1) {
1728 // There is only one instruction in the set, which is great!
1729 // Call emitSingletonDecoder() to see whether there are any remaining
1730 // encodings bits.
1731 emitSingletonTableEntry(TableInfo, Opcodes[0]);
1732 return;
1735 // Choose the best filter to do the decodings!
1736 if (BestIndex != -1) {
1737 const Filter &Best = Filters[BestIndex];
1738 if (Best.getNumFiltered() == 1)
1739 emitSingletonTableEntry(TableInfo, Best);
1740 else
1741 Best.emitTableEntry(TableInfo);
1742 return;
1745 // We don't know how to decode these instructions! Dump the
1746 // conflict set and bail.
1748 // Print out useful conflict information for postmortem analysis.
1749 errs() << "Decoding Conflict:\n";
1751 dumpStack(errs(), "\t\t");
1753 for (unsigned i = 0; i < Opcodes.size(); ++i) {
1754 errs() << '\t';
1755 emitNameWithID(errs(), Opcodes[i].EncodingID);
1756 errs() << " ";
1757 dumpBits(
1758 errs(),
1759 getBitsField(*AllInstructions[Opcodes[i].EncodingID].EncodingDef, "Inst"));
1760 errs() << '\n';
1764 static std::string findOperandDecoderMethod(TypedInit *TI) {
1765 std::string Decoder;
1767 Record *Record = cast<DefInit>(TI)->getDef();
1769 RecordVal *DecoderString = Record->getValue("DecoderMethod");
1770 StringInit *String = DecoderString ?
1771 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
1772 if (String) {
1773 Decoder = String->getValue();
1774 if (!Decoder.empty())
1775 return Decoder;
1778 if (Record->isSubClassOf("RegisterOperand"))
1779 Record = Record->getValueAsDef("RegClass");
1781 if (Record->isSubClassOf("RegisterClass")) {
1782 Decoder = "Decode" + Record->getName().str() + "RegisterClass";
1783 } else if (Record->isSubClassOf("PointerLikeRegClass")) {
1784 Decoder = "DecodePointerLikeRegClass" +
1785 utostr(Record->getValueAsInt("RegClassKind"));
1788 return Decoder;
1791 static bool
1792 populateInstruction(CodeGenTarget &Target, const Record &EncodingDef,
1793 const CodeGenInstruction &CGI, unsigned Opc,
1794 std::map<unsigned, std::vector<OperandInfo>> &Operands) {
1795 const Record &Def = *CGI.TheDef;
1796 // If all the bit positions are not specified; do not decode this instruction.
1797 // We are bound to fail! For proper disassembly, the well-known encoding bits
1798 // of the instruction must be fully specified.
1800 BitsInit &Bits = getBitsField(EncodingDef, "Inst");
1801 if (Bits.allInComplete()) return false;
1803 std::vector<OperandInfo> InsnOperands;
1805 // If the instruction has specified a custom decoding hook, use that instead
1806 // of trying to auto-generate the decoder.
1807 StringRef InstDecoder = EncodingDef.getValueAsString("DecoderMethod");
1808 if (InstDecoder != "") {
1809 bool HasCompleteInstDecoder = EncodingDef.getValueAsBit("hasCompleteDecoder");
1810 InsnOperands.push_back(OperandInfo(InstDecoder, HasCompleteInstDecoder));
1811 Operands[Opc] = InsnOperands;
1812 return true;
1815 // Generate a description of the operand of the instruction that we know
1816 // how to decode automatically.
1817 // FIXME: We'll need to have a way to manually override this as needed.
1819 // Gather the outputs/inputs of the instruction, so we can find their
1820 // positions in the encoding. This assumes for now that they appear in the
1821 // MCInst in the order that they're listed.
1822 std::vector<std::pair<Init*, StringRef>> InOutOperands;
1823 DagInit *Out = Def.getValueAsDag("OutOperandList");
1824 DagInit *In = Def.getValueAsDag("InOperandList");
1825 for (unsigned i = 0; i < Out->getNumArgs(); ++i)
1826 InOutOperands.push_back(std::make_pair(Out->getArg(i),
1827 Out->getArgNameStr(i)));
1828 for (unsigned i = 0; i < In->getNumArgs(); ++i)
1829 InOutOperands.push_back(std::make_pair(In->getArg(i),
1830 In->getArgNameStr(i)));
1832 // Search for tied operands, so that we can correctly instantiate
1833 // operands that are not explicitly represented in the encoding.
1834 std::map<std::string, std::string> TiedNames;
1835 for (unsigned i = 0; i < CGI.Operands.size(); ++i) {
1836 int tiedTo = CGI.Operands[i].getTiedRegister();
1837 if (tiedTo != -1) {
1838 std::pair<unsigned, unsigned> SO =
1839 CGI.Operands.getSubOperandNumber(tiedTo);
1840 TiedNames[InOutOperands[i].second] = InOutOperands[SO.first].second;
1841 TiedNames[InOutOperands[SO.first].second] = InOutOperands[i].second;
1845 std::map<std::string, std::vector<OperandInfo>> NumberedInsnOperands;
1846 std::set<std::string> NumberedInsnOperandsNoTie;
1847 if (Target.getInstructionSet()->
1848 getValueAsBit("decodePositionallyEncodedOperands")) {
1849 const std::vector<RecordVal> &Vals = Def.getValues();
1850 unsigned NumberedOp = 0;
1852 std::set<unsigned> NamedOpIndices;
1853 if (Target.getInstructionSet()->
1854 getValueAsBit("noNamedPositionallyEncodedOperands"))
1855 // Collect the set of operand indices that might correspond to named
1856 // operand, and skip these when assigning operands based on position.
1857 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1858 unsigned OpIdx;
1859 if (!CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
1860 continue;
1862 NamedOpIndices.insert(OpIdx);
1865 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1866 // Ignore fixed fields in the record, we're looking for values like:
1867 // bits<5> RST = { ?, ?, ?, ?, ? };
1868 if (Vals[i].getPrefix() || Vals[i].getValue()->isComplete())
1869 continue;
1871 // Determine if Vals[i] actually contributes to the Inst encoding.
1872 unsigned bi = 0;
1873 for (; bi < Bits.getNumBits(); ++bi) {
1874 VarInit *Var = nullptr;
1875 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1876 if (BI)
1877 Var = dyn_cast<VarInit>(BI->getBitVar());
1878 else
1879 Var = dyn_cast<VarInit>(Bits.getBit(bi));
1881 if (Var && Var->getName() == Vals[i].getName())
1882 break;
1885 if (bi == Bits.getNumBits())
1886 continue;
1888 // Skip variables that correspond to explicitly-named operands.
1889 unsigned OpIdx;
1890 if (CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
1891 continue;
1893 // Get the bit range for this operand:
1894 unsigned bitStart = bi++, bitWidth = 1;
1895 for (; bi < Bits.getNumBits(); ++bi) {
1896 VarInit *Var = nullptr;
1897 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
1898 if (BI)
1899 Var = dyn_cast<VarInit>(BI->getBitVar());
1900 else
1901 Var = dyn_cast<VarInit>(Bits.getBit(bi));
1903 if (!Var)
1904 break;
1906 if (Var->getName() != Vals[i].getName())
1907 break;
1909 ++bitWidth;
1912 unsigned NumberOps = CGI.Operands.size();
1913 while (NumberedOp < NumberOps &&
1914 (CGI.Operands.isFlatOperandNotEmitted(NumberedOp) ||
1915 (!NamedOpIndices.empty() && NamedOpIndices.count(
1916 CGI.Operands.getSubOperandNumber(NumberedOp).first))))
1917 ++NumberedOp;
1919 OpIdx = NumberedOp++;
1921 // OpIdx now holds the ordered operand number of Vals[i].
1922 std::pair<unsigned, unsigned> SO =
1923 CGI.Operands.getSubOperandNumber(OpIdx);
1924 const std::string &Name = CGI.Operands[SO.first].Name;
1926 LLVM_DEBUG(dbgs() << "Numbered operand mapping for " << Def.getName()
1927 << ": " << Name << "(" << SO.first << ", " << SO.second
1928 << ") => " << Vals[i].getName() << "\n");
1930 std::string Decoder;
1931 Record *TypeRecord = CGI.Operands[SO.first].Rec;
1933 RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
1934 StringInit *String = DecoderString ?
1935 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
1936 if (String && String->getValue() != "")
1937 Decoder = String->getValue();
1939 if (Decoder == "" &&
1940 CGI.Operands[SO.first].MIOperandInfo &&
1941 CGI.Operands[SO.first].MIOperandInfo->getNumArgs()) {
1942 Init *Arg = CGI.Operands[SO.first].MIOperandInfo->
1943 getArg(SO.second);
1944 if (DefInit *DI = cast<DefInit>(Arg))
1945 TypeRecord = DI->getDef();
1948 bool isReg = false;
1949 if (TypeRecord->isSubClassOf("RegisterOperand"))
1950 TypeRecord = TypeRecord->getValueAsDef("RegClass");
1951 if (TypeRecord->isSubClassOf("RegisterClass")) {
1952 Decoder = "Decode" + TypeRecord->getName().str() + "RegisterClass";
1953 isReg = true;
1954 } else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) {
1955 Decoder = "DecodePointerLikeRegClass" +
1956 utostr(TypeRecord->getValueAsInt("RegClassKind"));
1957 isReg = true;
1960 DecoderString = TypeRecord->getValue("DecoderMethod");
1961 String = DecoderString ?
1962 dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
1963 if (!isReg && String && String->getValue() != "")
1964 Decoder = String->getValue();
1966 RecordVal *HasCompleteDecoderVal =
1967 TypeRecord->getValue("hasCompleteDecoder");
1968 BitInit *HasCompleteDecoderBit = HasCompleteDecoderVal ?
1969 dyn_cast<BitInit>(HasCompleteDecoderVal->getValue()) : nullptr;
1970 bool HasCompleteDecoder = HasCompleteDecoderBit ?
1971 HasCompleteDecoderBit->getValue() : true;
1973 OperandInfo OpInfo(Decoder, HasCompleteDecoder);
1974 OpInfo.addField(bitStart, bitWidth, 0);
1976 NumberedInsnOperands[Name].push_back(OpInfo);
1978 // FIXME: For complex operands with custom decoders we can't handle tied
1979 // sub-operands automatically. Skip those here and assume that this is
1980 // fixed up elsewhere.
1981 if (CGI.Operands[SO.first].MIOperandInfo &&
1982 CGI.Operands[SO.first].MIOperandInfo->getNumArgs() > 1 &&
1983 String && String->getValue() != "")
1984 NumberedInsnOperandsNoTie.insert(Name);
1988 // For each operand, see if we can figure out where it is encoded.
1989 for (const auto &Op : InOutOperands) {
1990 if (!NumberedInsnOperands[Op.second].empty()) {
1991 InsnOperands.insert(InsnOperands.end(),
1992 NumberedInsnOperands[Op.second].begin(),
1993 NumberedInsnOperands[Op.second].end());
1994 continue;
1996 if (!NumberedInsnOperands[TiedNames[Op.second]].empty()) {
1997 if (!NumberedInsnOperandsNoTie.count(TiedNames[Op.second])) {
1998 // Figure out to which (sub)operand we're tied.
1999 unsigned i = CGI.Operands.getOperandNamed(TiedNames[Op.second]);
2000 int tiedTo = CGI.Operands[i].getTiedRegister();
2001 if (tiedTo == -1) {
2002 i = CGI.Operands.getOperandNamed(Op.second);
2003 tiedTo = CGI.Operands[i].getTiedRegister();
2006 if (tiedTo != -1) {
2007 std::pair<unsigned, unsigned> SO =
2008 CGI.Operands.getSubOperandNumber(tiedTo);
2010 InsnOperands.push_back(NumberedInsnOperands[TiedNames[Op.second]]
2011 [SO.second]);
2014 continue;
2017 TypedInit *TI = cast<TypedInit>(Op.first);
2019 // At this point, we can locate the decoder field, but we need to know how
2020 // to interpret it. As a first step, require the target to provide
2021 // callbacks for decoding register classes.
2022 std::string Decoder = findOperandDecoderMethod(TI);
2023 Record *TypeRecord = cast<DefInit>(TI)->getDef();
2025 RecordVal *HasCompleteDecoderVal =
2026 TypeRecord->getValue("hasCompleteDecoder");
2027 BitInit *HasCompleteDecoderBit = HasCompleteDecoderVal ?
2028 dyn_cast<BitInit>(HasCompleteDecoderVal->getValue()) : nullptr;
2029 bool HasCompleteDecoder = HasCompleteDecoderBit ?
2030 HasCompleteDecoderBit->getValue() : true;
2032 OperandInfo OpInfo(Decoder, HasCompleteDecoder);
2034 // Some bits of the operand may be required to be 1 depending on the
2035 // instruction's encoding. Collect those bits.
2036 if (const RecordVal *EncodedValue = EncodingDef.getValue(Op.second))
2037 if (const BitsInit *OpBits = dyn_cast<BitsInit>(EncodedValue->getValue()))
2038 for (unsigned I = 0; I < OpBits->getNumBits(); ++I)
2039 if (const BitInit *OpBit = dyn_cast<BitInit>(OpBits->getBit(I)))
2040 if (OpBit->getValue())
2041 OpInfo.InitValue |= 1ULL << I;
2043 unsigned Base = ~0U;
2044 unsigned Width = 0;
2045 unsigned Offset = 0;
2047 for (unsigned bi = 0; bi < Bits.getNumBits(); ++bi) {
2048 VarInit *Var = nullptr;
2049 VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
2050 if (BI)
2051 Var = dyn_cast<VarInit>(BI->getBitVar());
2052 else
2053 Var = dyn_cast<VarInit>(Bits.getBit(bi));
2055 if (!Var) {
2056 if (Base != ~0U) {
2057 OpInfo.addField(Base, Width, Offset);
2058 Base = ~0U;
2059 Width = 0;
2060 Offset = 0;
2062 continue;
2065 if (Var->getName() != Op.second &&
2066 Var->getName() != TiedNames[Op.second]) {
2067 if (Base != ~0U) {
2068 OpInfo.addField(Base, Width, Offset);
2069 Base = ~0U;
2070 Width = 0;
2071 Offset = 0;
2073 continue;
2076 if (Base == ~0U) {
2077 Base = bi;
2078 Width = 1;
2079 Offset = BI ? BI->getBitNum() : 0;
2080 } else if (BI && BI->getBitNum() != Offset + Width) {
2081 OpInfo.addField(Base, Width, Offset);
2082 Base = bi;
2083 Width = 1;
2084 Offset = BI->getBitNum();
2085 } else {
2086 ++Width;
2090 if (Base != ~0U)
2091 OpInfo.addField(Base, Width, Offset);
2093 if (OpInfo.numFields() > 0)
2094 InsnOperands.push_back(OpInfo);
2097 Operands[Opc] = InsnOperands;
2099 #if 0
2100 LLVM_DEBUG({
2101 // Dumps the instruction encoding bits.
2102 dumpBits(errs(), Bits);
2104 errs() << '\n';
2106 // Dumps the list of operand info.
2107 for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {
2108 const CGIOperandList::OperandInfo &Info = CGI.Operands[i];
2109 const std::string &OperandName = Info.Name;
2110 const Record &OperandDef = *Info.Rec;
2112 errs() << "\t" << OperandName << " (" << OperandDef.getName() << ")\n";
2115 #endif
2117 return true;
2120 // emitFieldFromInstruction - Emit the templated helper function
2121 // fieldFromInstruction().
2122 // On Windows we make sure that this function is not inlined when
2123 // using the VS compiler. It has a bug which causes the function
2124 // to be optimized out in some circustances. See llvm.org/pr38292
2125 static void emitFieldFromInstruction(formatted_raw_ostream &OS) {
2126 OS << "// Helper functions for extracting fields from encoded instructions.\n"
2127 << "// InsnType must either be integral or an APInt-like object that "
2128 "must:\n"
2129 << "// * Have a static const max_size_in_bits equal to the number of bits "
2130 "in the\n"
2131 << "// encoding.\n"
2132 << "// * be default-constructible and copy-constructible\n"
2133 << "// * be constructible from a uint64_t\n"
2134 << "// * be constructible from an APInt (this can be private)\n"
2135 << "// * Support getBitsSet(loBit, hiBit)\n"
2136 << "// * be convertible to uint64_t\n"
2137 << "// * Support the ~, &, ==, !=, and |= operators with other objects of "
2138 "the same type\n"
2139 << "// * Support shift (<<, >>) with signed and unsigned integers on the "
2140 "RHS\n"
2141 << "// * Support put (<<) to raw_ostream&\n"
2142 << "template<typename InsnType>\n"
2143 << "#if defined(_MSC_VER) && !defined(__clang__)\n"
2144 << "__declspec(noinline)\n"
2145 << "#endif\n"
2146 << "static InsnType fieldFromInstruction(InsnType insn, unsigned "
2147 "startBit,\n"
2148 << " unsigned numBits, "
2149 "std::true_type) {\n"
2150 << " assert(startBit + numBits <= 64 && \"Cannot support >64-bit "
2151 "extractions!\");\n"
2152 << " assert(startBit + numBits <= (sizeof(InsnType) * 8) &&\n"
2153 << " \"Instruction field out of bounds!\");\n"
2154 << " InsnType fieldMask;\n"
2155 << " if (numBits == sizeof(InsnType) * 8)\n"
2156 << " fieldMask = (InsnType)(-1LL);\n"
2157 << " else\n"
2158 << " fieldMask = (((InsnType)1 << numBits) - 1) << startBit;\n"
2159 << " return (insn & fieldMask) >> startBit;\n"
2160 << "}\n"
2161 << "\n"
2162 << "template<typename InsnType>\n"
2163 << "static InsnType fieldFromInstruction(InsnType insn, unsigned "
2164 "startBit,\n"
2165 << " unsigned numBits, "
2166 "std::false_type) {\n"
2167 << " assert(startBit + numBits <= InsnType::max_size_in_bits && "
2168 "\"Instruction field out of bounds!\");\n"
2169 << " InsnType fieldMask = InsnType::getBitsSet(0, numBits);\n"
2170 << " return (insn >> startBit) & fieldMask;\n"
2171 << "}\n"
2172 << "\n"
2173 << "template<typename InsnType>\n"
2174 << "static InsnType fieldFromInstruction(InsnType insn, unsigned "
2175 "startBit,\n"
2176 << " unsigned numBits) {\n"
2177 << " return fieldFromInstruction(insn, startBit, numBits, "
2178 "std::is_integral<InsnType>());\n"
2179 << "}\n\n";
2182 // emitDecodeInstruction - Emit the templated helper function
2183 // decodeInstruction().
2184 static void emitDecodeInstruction(formatted_raw_ostream &OS) {
2185 OS << "template<typename InsnType>\n"
2186 << "static DecodeStatus decodeInstruction(const uint8_t DecodeTable[], "
2187 "MCInst &MI,\n"
2188 << " InsnType insn, uint64_t "
2189 "Address,\n"
2190 << " const void *DisAsm,\n"
2191 << " const MCSubtargetInfo &STI) {\n"
2192 << " const FeatureBitset& Bits = STI.getFeatureBits();\n"
2193 << "\n"
2194 << " const uint8_t *Ptr = DecodeTable;\n"
2195 << " InsnType CurFieldValue = 0;\n"
2196 << " DecodeStatus S = MCDisassembler::Success;\n"
2197 << " while (true) {\n"
2198 << " ptrdiff_t Loc = Ptr - DecodeTable;\n"
2199 << " switch (*Ptr) {\n"
2200 << " default:\n"
2201 << " errs() << Loc << \": Unexpected decode table opcode!\\n\";\n"
2202 << " return MCDisassembler::Fail;\n"
2203 << " case MCD::OPC_ExtractField: {\n"
2204 << " unsigned Start = *++Ptr;\n"
2205 << " unsigned Len = *++Ptr;\n"
2206 << " ++Ptr;\n"
2207 << " CurFieldValue = fieldFromInstruction(insn, Start, Len);\n"
2208 << " LLVM_DEBUG(dbgs() << Loc << \": OPC_ExtractField(\" << Start << "
2209 "\", \"\n"
2210 << " << Len << \"): \" << CurFieldValue << \"\\n\");\n"
2211 << " break;\n"
2212 << " }\n"
2213 << " case MCD::OPC_FilterValue: {\n"
2214 << " // Decode the field value.\n"
2215 << " unsigned Len;\n"
2216 << " InsnType Val = decodeULEB128(++Ptr, &Len);\n"
2217 << " Ptr += Len;\n"
2218 << " // NumToSkip is a plain 24-bit integer.\n"
2219 << " unsigned NumToSkip = *Ptr++;\n"
2220 << " NumToSkip |= (*Ptr++) << 8;\n"
2221 << " NumToSkip |= (*Ptr++) << 16;\n"
2222 << "\n"
2223 << " // Perform the filter operation.\n"
2224 << " if (Val != CurFieldValue)\n"
2225 << " Ptr += NumToSkip;\n"
2226 << " LLVM_DEBUG(dbgs() << Loc << \": OPC_FilterValue(\" << Val << "
2227 "\", \" << NumToSkip\n"
2228 << " << \"): \" << ((Val != CurFieldValue) ? \"FAIL:\" "
2229 ": \"PASS:\")\n"
2230 << " << \" continuing at \" << (Ptr - DecodeTable) << "
2231 "\"\\n\");\n"
2232 << "\n"
2233 << " break;\n"
2234 << " }\n"
2235 << " case MCD::OPC_CheckField: {\n"
2236 << " unsigned Start = *++Ptr;\n"
2237 << " unsigned Len = *++Ptr;\n"
2238 << " InsnType FieldValue = fieldFromInstruction(insn, Start, Len);\n"
2239 << " // Decode the field value.\n"
2240 << " InsnType ExpectedValue = decodeULEB128(++Ptr, &Len);\n"
2241 << " Ptr += Len;\n"
2242 << " // NumToSkip is a plain 24-bit integer.\n"
2243 << " unsigned NumToSkip = *Ptr++;\n"
2244 << " NumToSkip |= (*Ptr++) << 8;\n"
2245 << " NumToSkip |= (*Ptr++) << 16;\n"
2246 << "\n"
2247 << " // If the actual and expected values don't match, skip.\n"
2248 << " if (ExpectedValue != FieldValue)\n"
2249 << " Ptr += NumToSkip;\n"
2250 << " LLVM_DEBUG(dbgs() << Loc << \": OPC_CheckField(\" << Start << "
2251 "\", \"\n"
2252 << " << Len << \", \" << ExpectedValue << \", \" << "
2253 "NumToSkip\n"
2254 << " << \"): FieldValue = \" << FieldValue << \", "
2255 "ExpectedValue = \"\n"
2256 << " << ExpectedValue << \": \"\n"
2257 << " << ((ExpectedValue == FieldValue) ? \"PASS\\n\" : "
2258 "\"FAIL\\n\"));\n"
2259 << " break;\n"
2260 << " }\n"
2261 << " case MCD::OPC_CheckPredicate: {\n"
2262 << " unsigned Len;\n"
2263 << " // Decode the Predicate Index value.\n"
2264 << " unsigned PIdx = decodeULEB128(++Ptr, &Len);\n"
2265 << " Ptr += Len;\n"
2266 << " // NumToSkip is a plain 24-bit integer.\n"
2267 << " unsigned NumToSkip = *Ptr++;\n"
2268 << " NumToSkip |= (*Ptr++) << 8;\n"
2269 << " NumToSkip |= (*Ptr++) << 16;\n"
2270 << " // Check the predicate.\n"
2271 << " bool Pred;\n"
2272 << " if (!(Pred = checkDecoderPredicate(PIdx, Bits)))\n"
2273 << " Ptr += NumToSkip;\n"
2274 << " (void)Pred;\n"
2275 << " LLVM_DEBUG(dbgs() << Loc << \": OPC_CheckPredicate(\" << PIdx "
2276 "<< \"): \"\n"
2277 << " << (Pred ? \"PASS\\n\" : \"FAIL\\n\"));\n"
2278 << "\n"
2279 << " break;\n"
2280 << " }\n"
2281 << " case MCD::OPC_Decode: {\n"
2282 << " unsigned Len;\n"
2283 << " // Decode the Opcode value.\n"
2284 << " unsigned Opc = decodeULEB128(++Ptr, &Len);\n"
2285 << " Ptr += Len;\n"
2286 << " unsigned DecodeIdx = decodeULEB128(Ptr, &Len);\n"
2287 << " Ptr += Len;\n"
2288 << "\n"
2289 << " MI.clear();\n"
2290 << " MI.setOpcode(Opc);\n"
2291 << " bool DecodeComplete;\n"
2292 << " S = decodeToMCInst(S, DecodeIdx, insn, MI, Address, DisAsm, "
2293 "DecodeComplete);\n"
2294 << " assert(DecodeComplete);\n"
2295 << "\n"
2296 << " LLVM_DEBUG(dbgs() << Loc << \": OPC_Decode: opcode \" << Opc\n"
2297 << " << \", using decoder \" << DecodeIdx << \": \"\n"
2298 << " << (S != MCDisassembler::Fail ? \"PASS\" : "
2299 "\"FAIL\") << \"\\n\");\n"
2300 << " return S;\n"
2301 << " }\n"
2302 << " case MCD::OPC_TryDecode: {\n"
2303 << " unsigned Len;\n"
2304 << " // Decode the Opcode value.\n"
2305 << " unsigned Opc = decodeULEB128(++Ptr, &Len);\n"
2306 << " Ptr += Len;\n"
2307 << " unsigned DecodeIdx = decodeULEB128(Ptr, &Len);\n"
2308 << " Ptr += Len;\n"
2309 << " // NumToSkip is a plain 24-bit integer.\n"
2310 << " unsigned NumToSkip = *Ptr++;\n"
2311 << " NumToSkip |= (*Ptr++) << 8;\n"
2312 << " NumToSkip |= (*Ptr++) << 16;\n"
2313 << "\n"
2314 << " // Perform the decode operation.\n"
2315 << " MCInst TmpMI;\n"
2316 << " TmpMI.setOpcode(Opc);\n"
2317 << " bool DecodeComplete;\n"
2318 << " S = decodeToMCInst(S, DecodeIdx, insn, TmpMI, Address, DisAsm, "
2319 "DecodeComplete);\n"
2320 << " LLVM_DEBUG(dbgs() << Loc << \": OPC_TryDecode: opcode \" << "
2321 "Opc\n"
2322 << " << \", using decoder \" << DecodeIdx << \": \");\n"
2323 << "\n"
2324 << " if (DecodeComplete) {\n"
2325 << " // Decoding complete.\n"
2326 << " LLVM_DEBUG(dbgs() << (S != MCDisassembler::Fail ? \"PASS\" : "
2327 "\"FAIL\") << \"\\n\");\n"
2328 << " MI = TmpMI;\n"
2329 << " return S;\n"
2330 << " } else {\n"
2331 << " assert(S == MCDisassembler::Fail);\n"
2332 << " // If the decoding was incomplete, skip.\n"
2333 << " Ptr += NumToSkip;\n"
2334 << " LLVM_DEBUG(dbgs() << \"FAIL: continuing at \" << (Ptr - "
2335 "DecodeTable) << \"\\n\");\n"
2336 << " // Reset decode status. This also drops a SoftFail status "
2337 "that could be\n"
2338 << " // set before the decode attempt.\n"
2339 << " S = MCDisassembler::Success;\n"
2340 << " }\n"
2341 << " break;\n"
2342 << " }\n"
2343 << " case MCD::OPC_SoftFail: {\n"
2344 << " // Decode the mask values.\n"
2345 << " unsigned Len;\n"
2346 << " InsnType PositiveMask = decodeULEB128(++Ptr, &Len);\n"
2347 << " Ptr += Len;\n"
2348 << " InsnType NegativeMask = decodeULEB128(Ptr, &Len);\n"
2349 << " Ptr += Len;\n"
2350 << " bool Fail = (insn & PositiveMask) || (~insn & NegativeMask);\n"
2351 << " if (Fail)\n"
2352 << " S = MCDisassembler::SoftFail;\n"
2353 << " LLVM_DEBUG(dbgs() << Loc << \": OPC_SoftFail: \" << (Fail ? "
2354 "\"FAIL\\n\":\"PASS\\n\"));\n"
2355 << " break;\n"
2356 << " }\n"
2357 << " case MCD::OPC_Fail: {\n"
2358 << " LLVM_DEBUG(dbgs() << Loc << \": OPC_Fail\\n\");\n"
2359 << " return MCDisassembler::Fail;\n"
2360 << " }\n"
2361 << " }\n"
2362 << " }\n"
2363 << " llvm_unreachable(\"bogosity detected in disassembler state "
2364 "machine!\");\n"
2365 << "}\n\n";
2368 // Emits disassembler code for instruction decoding.
2369 void FixedLenDecoderEmitter::run(raw_ostream &o) {
2370 formatted_raw_ostream OS(o);
2371 OS << "#include \"llvm/MC/MCInst.h\"\n";
2372 OS << "#include \"llvm/Support/Debug.h\"\n";
2373 OS << "#include \"llvm/Support/DataTypes.h\"\n";
2374 OS << "#include \"llvm/Support/LEB128.h\"\n";
2375 OS << "#include \"llvm/Support/raw_ostream.h\"\n";
2376 OS << "#include <assert.h>\n";
2377 OS << '\n';
2378 OS << "namespace llvm {\n\n";
2380 emitFieldFromInstruction(OS);
2382 Target.reverseBitsForLittleEndianEncoding();
2384 // Parameterize the decoders based on namespace and instruction width.
2385 const auto &NumberedInstructions = Target.getInstructionsByEnumValue();
2386 NumberedEncodings.reserve(NumberedInstructions.size());
2387 DenseMap<Record *, unsigned> IndexOfInstruction;
2388 for (const auto &NumberedInstruction : NumberedInstructions) {
2389 IndexOfInstruction[NumberedInstruction->TheDef] = NumberedEncodings.size();
2390 NumberedEncodings.emplace_back(NumberedInstruction->TheDef, NumberedInstruction);
2392 for (const auto &NumberedAlias : RK.getAllDerivedDefinitions("AdditionalEncoding"))
2393 NumberedEncodings.emplace_back(
2394 NumberedAlias,
2395 &Target.getInstruction(NumberedAlias->getValueAsDef("AliasOf")));
2397 std::map<std::pair<std::string, unsigned>, std::vector<EncodingIDAndOpcode>>
2398 OpcMap;
2399 std::map<unsigned, std::vector<OperandInfo>> Operands;
2401 for (unsigned i = 0; i < NumberedEncodings.size(); ++i) {
2402 const Record *EncodingDef = NumberedEncodings[i].EncodingDef;
2403 const CodeGenInstruction *Inst = NumberedEncodings[i].Inst;
2404 const Record *Def = Inst->TheDef;
2405 unsigned Size = EncodingDef->getValueAsInt("Size");
2406 if (Def->getValueAsString("Namespace") == "TargetOpcode" ||
2407 Def->getValueAsBit("isPseudo") ||
2408 Def->getValueAsBit("isAsmParserOnly") ||
2409 Def->getValueAsBit("isCodeGenOnly")) {
2410 NumEncodingsLackingDisasm++;
2411 continue;
2414 if (i < NumberedInstructions.size())
2415 NumInstructions++;
2416 NumEncodings++;
2418 StringRef DecoderNamespace = EncodingDef->getValueAsString("DecoderNamespace");
2420 if (Size) {
2421 if (populateInstruction(Target, *EncodingDef, *Inst, i, Operands)) {
2422 OpcMap[std::make_pair(DecoderNamespace, Size)].emplace_back(i, IndexOfInstruction.find(Def)->second);
2423 } else
2424 NumEncodingsOmitted++;
2428 DecoderTableInfo TableInfo;
2429 for (const auto &Opc : OpcMap) {
2430 // Emit the decoder for this namespace+width combination.
2431 ArrayRef<EncodingAndInst> NumberedEncodingsRef(
2432 NumberedEncodings.data(), NumberedEncodings.size());
2433 FilterChooser FC(NumberedEncodingsRef, Opc.second, Operands,
2434 8 * Opc.first.second, this);
2436 // The decode table is cleared for each top level decoder function. The
2437 // predicates and decoders themselves, however, are shared across all
2438 // decoders to give more opportunities for uniqueing.
2439 TableInfo.Table.clear();
2440 TableInfo.FixupStack.clear();
2441 TableInfo.Table.reserve(16384);
2442 TableInfo.FixupStack.emplace_back();
2443 FC.emitTableEntries(TableInfo);
2444 // Any NumToSkip fixups in the top level scope can resolve to the
2445 // OPC_Fail at the end of the table.
2446 assert(TableInfo.FixupStack.size() == 1 && "fixup stack phasing error!");
2447 // Resolve any NumToSkip fixups in the current scope.
2448 resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
2449 TableInfo.Table.size());
2450 TableInfo.FixupStack.clear();
2452 TableInfo.Table.push_back(MCD::OPC_Fail);
2454 // Print the table to the output stream.
2455 emitTable(OS, TableInfo.Table, 0, FC.getBitWidth(), Opc.first.first);
2456 OS.flush();
2459 // Emit the predicate function.
2460 emitPredicateFunction(OS, TableInfo.Predicates, 0);
2462 // Emit the decoder function.
2463 emitDecoderFunction(OS, TableInfo.Decoders, 0);
2465 // Emit the main entry point for the decoder, decodeInstruction().
2466 emitDecodeInstruction(OS);
2468 OS << "\n} // end namespace llvm\n";
2471 namespace llvm {
2473 void EmitFixedLenDecoder(RecordKeeper &RK, raw_ostream &OS,
2474 const std::string &PredicateNamespace,
2475 const std::string &GPrefix,
2476 const std::string &GPostfix, const std::string &ROK,
2477 const std::string &RFail, const std::string &L) {
2478 FixedLenDecoderEmitter(RK, PredicateNamespace, GPrefix, GPostfix,
2479 ROK, RFail, L).run(OS);
2482 } // end namespace llvm