Path: blob/main/contrib/llvm-project/llvm/utils/TableGen/DecoderEmitter.cpp
35258 views
//===---------------- DecoderEmitter.cpp - Decoder Generator --------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// It contains the tablegen backend that emits the decoder functions for9// targets with fixed/variable length instruction set.10//11//===----------------------------------------------------------------------===//1213#include "Common/CodeGenHwModes.h"14#include "Common/CodeGenInstruction.h"15#include "Common/CodeGenTarget.h"16#include "Common/InfoByHwMode.h"17#include "Common/VarLenCodeEmitterGen.h"18#include "TableGenBackends.h"19#include "llvm/ADT/APInt.h"20#include "llvm/ADT/ArrayRef.h"21#include "llvm/ADT/CachedHashString.h"22#include "llvm/ADT/STLExtras.h"23#include "llvm/ADT/SetVector.h"24#include "llvm/ADT/SmallBitVector.h"25#include "llvm/ADT/SmallString.h"26#include "llvm/ADT/Statistic.h"27#include "llvm/ADT/StringExtras.h"28#include "llvm/ADT/StringRef.h"29#include "llvm/MC/MCDecoderOps.h"30#include "llvm/Support/Casting.h"31#include "llvm/Support/CommandLine.h"32#include "llvm/Support/Debug.h"33#include "llvm/Support/ErrorHandling.h"34#include "llvm/Support/FormattedStream.h"35#include "llvm/Support/LEB128.h"36#include "llvm/Support/raw_ostream.h"37#include "llvm/TableGen/Error.h"38#include "llvm/TableGen/Record.h"39#include <algorithm>40#include <cassert>41#include <cstddef>42#include <cstdint>43#include <map>44#include <memory>45#include <set>46#include <string>47#include <utility>48#include <vector>4950using namespace llvm;5152#define DEBUG_TYPE "decoder-emitter"5354extern cl::OptionCategory DisassemblerEmitterCat;5556enum SuppressLevel {57SUPPRESSION_DISABLE,58SUPPRESSION_LEVEL1,59SUPPRESSION_LEVEL260};6162cl::opt<SuppressLevel> DecoderEmitterSuppressDuplicates(63"suppress-per-hwmode-duplicates",64cl::desc("Suppress duplication of instrs into per-HwMode decoder tables"),65cl::values(66clEnumValN(67SUPPRESSION_DISABLE, "O0",68"Do not prevent DecoderTable duplications caused by HwModes"),69clEnumValN(70SUPPRESSION_LEVEL1, "O1",71"Remove duplicate DecoderTable entries generated due to HwModes"),72clEnumValN(73SUPPRESSION_LEVEL2, "O2",74"Extract HwModes-specific instructions into new DecoderTables, "75"significantly reducing Table Duplications")),76cl::init(SUPPRESSION_DISABLE), cl::cat(DisassemblerEmitterCat));7778namespace {7980STATISTIC(NumEncodings, "Number of encodings considered");81STATISTIC(NumEncodingsLackingDisasm,82"Number of encodings without disassembler info");83STATISTIC(NumInstructions, "Number of instructions considered");84STATISTIC(NumEncodingsSupported, "Number of encodings supported");85STATISTIC(NumEncodingsOmitted, "Number of encodings omitted");8687struct EncodingField {88unsigned Base, Width, Offset;89EncodingField(unsigned B, unsigned W, unsigned O)90: Base(B), Width(W), Offset(O) {}91};9293struct OperandInfo {94std::vector<EncodingField> Fields;95std::string Decoder;96bool HasCompleteDecoder;97uint64_t InitValue;9899OperandInfo(std::string D, bool HCD)100: Decoder(std::move(D)), HasCompleteDecoder(HCD), InitValue(0) {}101102void addField(unsigned Base, unsigned Width, unsigned Offset) {103Fields.push_back(EncodingField(Base, Width, Offset));104}105106unsigned numFields() const { return Fields.size(); }107108typedef std::vector<EncodingField>::const_iterator const_iterator;109110const_iterator begin() const { return Fields.begin(); }111const_iterator end() const { return Fields.end(); }112};113114typedef std::vector<uint8_t> DecoderTable;115typedef uint32_t DecoderFixup;116typedef std::vector<DecoderFixup> FixupList;117typedef std::vector<FixupList> FixupScopeList;118typedef SmallSetVector<CachedHashString, 16> PredicateSet;119typedef SmallSetVector<CachedHashString, 16> DecoderSet;120struct DecoderTableInfo {121DecoderTable Table;122FixupScopeList FixupStack;123PredicateSet Predicates;124DecoderSet Decoders;125};126127struct EncodingAndInst {128const Record *EncodingDef;129const CodeGenInstruction *Inst;130StringRef HwModeName;131132EncodingAndInst(const Record *EncodingDef, const CodeGenInstruction *Inst,133StringRef HwModeName = "")134: EncodingDef(EncodingDef), Inst(Inst), HwModeName(HwModeName) {}135};136137struct EncodingIDAndOpcode {138unsigned EncodingID;139unsigned Opcode;140141EncodingIDAndOpcode() : EncodingID(0), Opcode(0) {}142EncodingIDAndOpcode(unsigned EncodingID, unsigned Opcode)143: EncodingID(EncodingID), Opcode(Opcode) {}144};145146using EncodingIDsVec = std::vector<EncodingIDAndOpcode>;147using NamespacesHwModesMap = std::map<std::string, std::set<StringRef>>;148149raw_ostream &operator<<(raw_ostream &OS, const EncodingAndInst &Value) {150if (Value.EncodingDef != Value.Inst->TheDef)151OS << Value.EncodingDef->getName() << ":";152OS << Value.Inst->TheDef->getName();153return OS;154}155156class DecoderEmitter {157RecordKeeper &RK;158std::vector<EncodingAndInst> NumberedEncodings;159160public:161DecoderEmitter(RecordKeeper &R, std::string PredicateNamespace)162: RK(R), Target(R), PredicateNamespace(std::move(PredicateNamespace)) {}163164// Emit the decoder state machine table.165void emitTable(formatted_raw_ostream &o, DecoderTable &Table,166unsigned Indentation, unsigned BitWidth, StringRef Namespace,167const EncodingIDsVec &EncodingIDs) const;168void emitInstrLenTable(formatted_raw_ostream &OS,169std::vector<unsigned> &InstrLen) const;170void emitPredicateFunction(formatted_raw_ostream &OS,171PredicateSet &Predicates,172unsigned Indentation) const;173void emitDecoderFunction(formatted_raw_ostream &OS, DecoderSet &Decoders,174unsigned Indentation) const;175176// run - Output the code emitter177void run(raw_ostream &o);178179private:180CodeGenTarget Target;181182public:183std::string PredicateNamespace;184};185186} // end anonymous namespace187188// The set (BIT_TRUE, BIT_FALSE, BIT_UNSET) represents a ternary logic system189// for a bit value.190//191// BIT_UNFILTERED is used as the init value for a filter position. It is used192// only for filter processings.193typedef enum {194BIT_TRUE, // '1'195BIT_FALSE, // '0'196BIT_UNSET, // '?'197BIT_UNFILTERED // unfiltered198} bit_value_t;199200static bool ValueSet(bit_value_t V) {201return (V == BIT_TRUE || V == BIT_FALSE);202}203204static bool ValueNotSet(bit_value_t V) { return (V == BIT_UNSET); }205206static int Value(bit_value_t V) {207return ValueNotSet(V) ? -1 : (V == BIT_FALSE ? 0 : 1);208}209210static bit_value_t bitFromBits(const BitsInit &bits, unsigned index) {211if (BitInit *bit = dyn_cast<BitInit>(bits.getBit(index)))212return bit->getValue() ? BIT_TRUE : BIT_FALSE;213214// The bit is uninitialized.215return BIT_UNSET;216}217218// Prints the bit value for each position.219static void dumpBits(raw_ostream &o, const BitsInit &bits) {220for (unsigned index = bits.getNumBits(); index > 0; --index) {221switch (bitFromBits(bits, index - 1)) {222case BIT_TRUE:223o << "1";224break;225case BIT_FALSE:226o << "0";227break;228case BIT_UNSET:229o << "_";230break;231default:232llvm_unreachable("unexpected return value from bitFromBits");233}234}235}236237static BitsInit &getBitsField(const Record &def, StringRef str) {238const RecordVal *RV = def.getValue(str);239if (BitsInit *Bits = dyn_cast<BitsInit>(RV->getValue()))240return *Bits;241242// variable length instruction243VarLenInst VLI = VarLenInst(cast<DagInit>(RV->getValue()), RV);244SmallVector<Init *, 16> Bits;245246for (const auto &SI : VLI) {247if (const BitsInit *BI = dyn_cast<BitsInit>(SI.Value)) {248for (unsigned Idx = 0U; Idx < BI->getNumBits(); ++Idx) {249Bits.push_back(BI->getBit(Idx));250}251} else if (const BitInit *BI = dyn_cast<BitInit>(SI.Value)) {252Bits.push_back(const_cast<BitInit *>(BI));253} else {254for (unsigned Idx = 0U; Idx < SI.BitWidth; ++Idx)255Bits.push_back(UnsetInit::get(def.getRecords()));256}257}258259return *BitsInit::get(def.getRecords(), Bits);260}261262// Representation of the instruction to work on.263typedef std::vector<bit_value_t> insn_t;264265namespace {266267static const uint64_t NO_FIXED_SEGMENTS_SENTINEL = -1ULL;268269class FilterChooser;270271/// Filter - Filter works with FilterChooser to produce the decoding tree for272/// the ISA.273///274/// It is useful to think of a Filter as governing the switch stmts of the275/// decoding tree in a certain level. Each case stmt delegates to an inferior276/// FilterChooser to decide what further decoding logic to employ, or in another277/// words, what other remaining bits to look at. The FilterChooser eventually278/// chooses a best Filter to do its job.279///280/// This recursive scheme ends when the number of Opcodes assigned to the281/// FilterChooser becomes 1 or if there is a conflict. A conflict happens when282/// the Filter/FilterChooser combo does not know how to distinguish among the283/// Opcodes assigned.284///285/// An example of a conflict is286///287/// Conflict:288/// 111101000.00........00010000....289/// 111101000.00........0001........290/// 1111010...00........0001........291/// 1111010...00....................292/// 1111010.........................293/// 1111............................294/// ................................295/// VST4q8a 111101000_00________00010000____296/// VST4q8b 111101000_00________00010000____297///298/// The Debug output shows the path that the decoding tree follows to reach the299/// the conclusion that there is a conflict. VST4q8a is a vst4 to double-spaced300/// even registers, while VST4q8b is a vst4 to double-spaced odd registers.301///302/// The encoding info in the .td files does not specify this meta information,303/// which could have been used by the decoder to resolve the conflict. The304/// decoder could try to decode the even/odd register numbering and assign to305/// VST4q8a or VST4q8b, but for the time being, the decoder chooses the "a"306/// version and return the Opcode since the two have the same Asm format string.307class Filter {308protected:309const FilterChooser310*Owner; // points to the FilterChooser who owns this filter311unsigned StartBit; // the starting bit position312unsigned NumBits; // number of bits to filter313bool Mixed; // a mixed region contains both set and unset bits314315// Map of well-known segment value to the set of uid's with that value.316std::map<uint64_t, std::vector<EncodingIDAndOpcode>> FilteredInstructions;317318// Set of uid's with non-constant segment values.319std::vector<EncodingIDAndOpcode> VariableInstructions;320321// Map of well-known segment value to its delegate.322std::map<uint64_t, std::unique_ptr<const FilterChooser>> FilterChooserMap;323324// Number of instructions which fall under FilteredInstructions category.325unsigned NumFiltered;326327// Keeps track of the last opcode in the filtered bucket.328EncodingIDAndOpcode LastOpcFiltered;329330public:331Filter(Filter &&f);332Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, bool mixed);333334~Filter() = default;335336unsigned getNumFiltered() const { return NumFiltered; }337338EncodingIDAndOpcode getSingletonOpc() const {339assert(NumFiltered == 1);340return LastOpcFiltered;341}342343// Return the filter chooser for the group of instructions without constant344// segment values.345const FilterChooser &getVariableFC() const {346assert(NumFiltered == 1);347assert(FilterChooserMap.size() == 1);348return *(FilterChooserMap.find(NO_FIXED_SEGMENTS_SENTINEL)->second);349}350351// Divides the decoding task into sub tasks and delegates them to the352// inferior FilterChooser's.353//354// A special case arises when there's only one entry in the filtered355// instructions. In order to unambiguously decode the singleton, we need to356// match the remaining undecoded encoding bits against the singleton.357void recurse();358359// Emit table entries to decode instructions given a segment or segments of360// bits.361void emitTableEntry(DecoderTableInfo &TableInfo) const;362363// Returns the number of fanout produced by the filter. More fanout implies364// the filter distinguishes more categories of instructions.365unsigned usefulness() const;366}; // end class Filter367368} // end anonymous namespace369370// These are states of our finite state machines used in FilterChooser's371// filterProcessor() which produces the filter candidates to use.372typedef enum {373ATTR_NONE,374ATTR_FILTERED,375ATTR_ALL_SET,376ATTR_ALL_UNSET,377ATTR_MIXED378} bitAttr_t;379380/// FilterChooser - FilterChooser chooses the best filter among a set of Filters381/// in order to perform the decoding of instructions at the current level.382///383/// Decoding proceeds from the top down. Based on the well-known encoding bits384/// of instructions available, FilterChooser builds up the possible Filters that385/// can further the task of decoding by distinguishing among the remaining386/// candidate instructions.387///388/// Once a filter has been chosen, it is called upon to divide the decoding task389/// into sub-tasks and delegates them to its inferior FilterChoosers for further390/// processings.391///392/// It is useful to think of a Filter as governing the switch stmts of the393/// decoding tree. And each case is delegated to an inferior FilterChooser to394/// decide what further remaining bits to look at.395namespace {396397class FilterChooser {398protected:399friend class Filter;400401// Vector of codegen instructions to choose our filter.402ArrayRef<EncodingAndInst> AllInstructions;403404// Vector of uid's for this filter chooser to work on.405// The first member of the pair is the opcode id being decoded, the second is406// the opcode id that should be emitted.407const std::vector<EncodingIDAndOpcode> &Opcodes;408409// Lookup table for the operand decoding of instructions.410const std::map<unsigned, std::vector<OperandInfo>> &Operands;411412// Vector of candidate filters.413std::vector<Filter> Filters;414415// Array of bit values passed down from our parent.416// Set to all BIT_UNFILTERED's for Parent == NULL.417std::vector<bit_value_t> FilterBitValues;418419// Links to the FilterChooser above us in the decoding tree.420const FilterChooser *Parent;421422// Index of the best filter from Filters.423int BestIndex;424425// Width of instructions426unsigned BitWidth;427428// Parent emitter429const DecoderEmitter *Emitter;430431public:432FilterChooser(ArrayRef<EncodingAndInst> Insts,433const std::vector<EncodingIDAndOpcode> &IDs,434const std::map<unsigned, std::vector<OperandInfo>> &Ops,435unsigned BW, const DecoderEmitter *E)436: AllInstructions(Insts), Opcodes(IDs), Operands(Ops),437FilterBitValues(BW, BIT_UNFILTERED), Parent(nullptr), BestIndex(-1),438BitWidth(BW), Emitter(E) {439doFilter();440}441442FilterChooser(ArrayRef<EncodingAndInst> Insts,443const std::vector<EncodingIDAndOpcode> &IDs,444const std::map<unsigned, std::vector<OperandInfo>> &Ops,445const std::vector<bit_value_t> &ParentFilterBitValues,446const FilterChooser &parent)447: AllInstructions(Insts), Opcodes(IDs), Operands(Ops),448FilterBitValues(ParentFilterBitValues), Parent(&parent), BestIndex(-1),449BitWidth(parent.BitWidth), Emitter(parent.Emitter) {450doFilter();451}452453FilterChooser(const FilterChooser &) = delete;454void operator=(const FilterChooser &) = delete;455456unsigned getBitWidth() const { return BitWidth; }457458protected:459// Populates the insn given the uid.460void insnWithID(insn_t &Insn, unsigned Opcode) const {461const Record *EncodingDef = AllInstructions[Opcode].EncodingDef;462BitsInit &Bits = getBitsField(*EncodingDef, "Inst");463Insn.resize(std::max(BitWidth, Bits.getNumBits()), BIT_UNSET);464// We may have a SoftFail bitmask, which specifies a mask where an encoding465// may differ from the value in "Inst" and yet still be valid, but the466// disassembler should return SoftFail instead of Success.467//468// This is used for marking UNPREDICTABLE instructions in the ARM world.469const RecordVal *RV = EncodingDef->getValue("SoftFail");470const BitsInit *SFBits = RV ? dyn_cast<BitsInit>(RV->getValue()) : nullptr;471for (unsigned i = 0; i < Bits.getNumBits(); ++i) {472if (SFBits && bitFromBits(*SFBits, i) == BIT_TRUE)473Insn[i] = BIT_UNSET;474else475Insn[i] = bitFromBits(Bits, i);476}477}478479// Emit the name of the encoding/instruction pair.480void emitNameWithID(raw_ostream &OS, unsigned Opcode) const {481const Record *EncodingDef = AllInstructions[Opcode].EncodingDef;482const Record *InstDef = AllInstructions[Opcode].Inst->TheDef;483if (EncodingDef != InstDef)484OS << EncodingDef->getName() << ":";485OS << InstDef->getName();486}487488// Populates the field of the insn given the start position and the number of489// consecutive bits to scan for.490//491// Returns a pair of values (indicator, field), where the indicator is false492// if there exists any uninitialized bit value in the range and true if all493// bits are well-known. The second value is the potentially populated field.494std::pair<bool, uint64_t> fieldFromInsn(const insn_t &Insn, unsigned StartBit,495unsigned NumBits) const;496497/// dumpFilterArray - dumpFilterArray prints out debugging info for the given498/// filter array as a series of chars.499void dumpFilterArray(raw_ostream &o,500const std::vector<bit_value_t> &filter) const;501502/// dumpStack - dumpStack traverses the filter chooser chain and calls503/// dumpFilterArray on each filter chooser up to the top level one.504void dumpStack(raw_ostream &o, const char *prefix) const;505506Filter &bestFilter() {507assert(BestIndex != -1 && "BestIndex not set");508return Filters[BestIndex];509}510511bool PositionFiltered(unsigned i) const {512return ValueSet(FilterBitValues[i]);513}514515// Calculates the island(s) needed to decode the instruction.516// This returns a lit of undecoded bits of an instructions, for example,517// Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be518// decoded bits in order to verify that the instruction matches the Opcode.519unsigned getIslands(std::vector<unsigned> &StartBits,520std::vector<unsigned> &EndBits,521std::vector<uint64_t> &FieldVals,522const insn_t &Insn) const;523524// Emits code to check the Predicates member of an instruction are true.525// Returns true if predicate matches were emitted, false otherwise.526bool emitPredicateMatch(raw_ostream &o, unsigned &Indentation,527unsigned Opc) const;528bool emitPredicateMatchAux(const Init &Val, bool ParenIfBinOp,529raw_ostream &OS) const;530531bool doesOpcodeNeedPredicate(unsigned Opc) const;532unsigned getPredicateIndex(DecoderTableInfo &TableInfo, StringRef P) const;533void emitPredicateTableEntry(DecoderTableInfo &TableInfo, unsigned Opc) const;534535void emitSoftFailTableEntry(DecoderTableInfo &TableInfo, unsigned Opc) const;536537// Emits table entries to decode the singleton.538void emitSingletonTableEntry(DecoderTableInfo &TableInfo,539EncodingIDAndOpcode Opc) const;540541// Emits code to decode the singleton, and then to decode the rest.542void emitSingletonTableEntry(DecoderTableInfo &TableInfo,543const Filter &Best) const;544545void emitBinaryParser(raw_ostream &o, unsigned &Indentation,546const OperandInfo &OpInfo,547bool &OpHasCompleteDecoder) const;548549void emitDecoder(raw_ostream &OS, unsigned Indentation, unsigned Opc,550bool &HasCompleteDecoder) const;551unsigned getDecoderIndex(DecoderSet &Decoders, unsigned Opc,552bool &HasCompleteDecoder) const;553554// Assign a single filter and run with it.555void runSingleFilter(unsigned startBit, unsigned numBit, bool mixed);556557// reportRegion is a helper function for filterProcessor to mark a region as558// eligible for use as a filter region.559void reportRegion(bitAttr_t RA, unsigned StartBit, unsigned BitIndex,560bool AllowMixed);561562// FilterProcessor scans the well-known encoding bits of the instructions and563// builds up a list of candidate filters. It chooses the best filter and564// recursively descends down the decoding tree.565bool filterProcessor(bool AllowMixed, bool Greedy = true);566567// Decides on the best configuration of filter(s) to use in order to decode568// the instructions. A conflict of instructions may occur, in which case we569// dump the conflict set to the standard error.570void doFilter();571572public:573// emitTableEntries - Emit state machine entries to decode our share of574// instructions.575void emitTableEntries(DecoderTableInfo &TableInfo) const;576};577578} // end anonymous namespace579580///////////////////////////581// //582// Filter Implementation //583// //584///////////////////////////585586Filter::Filter(Filter &&f)587: Owner(f.Owner), StartBit(f.StartBit), NumBits(f.NumBits), Mixed(f.Mixed),588FilteredInstructions(std::move(f.FilteredInstructions)),589VariableInstructions(std::move(f.VariableInstructions)),590FilterChooserMap(std::move(f.FilterChooserMap)),591NumFiltered(f.NumFiltered), LastOpcFiltered(f.LastOpcFiltered) {}592593Filter::Filter(FilterChooser &owner, unsigned startBit, unsigned numBits,594bool mixed)595: Owner(&owner), StartBit(startBit), NumBits(numBits), Mixed(mixed) {596assert(StartBit + NumBits - 1 < Owner->BitWidth);597598NumFiltered = 0;599LastOpcFiltered = {0, 0};600601for (const auto &OpcPair : Owner->Opcodes) {602insn_t Insn;603604// Populates the insn given the uid.605Owner->insnWithID(Insn, OpcPair.EncodingID);606607// Scans the segment for possibly well-specified encoding bits.608auto [Ok, Field] = Owner->fieldFromInsn(Insn, StartBit, NumBits);609610if (Ok) {611// The encoding bits are well-known. Lets add the uid of the612// instruction into the bucket keyed off the constant field value.613LastOpcFiltered = OpcPair;614FilteredInstructions[Field].push_back(LastOpcFiltered);615++NumFiltered;616} else {617// Some of the encoding bit(s) are unspecified. This contributes to618// one additional member of "Variable" instructions.619VariableInstructions.push_back(OpcPair);620}621}622623assert((FilteredInstructions.size() + VariableInstructions.size() > 0) &&624"Filter returns no instruction categories");625}626627// Divides the decoding task into sub tasks and delegates them to the628// inferior FilterChooser's.629//630// A special case arises when there's only one entry in the filtered631// instructions. In order to unambiguously decode the singleton, we need to632// match the remaining undecoded encoding bits against the singleton.633void Filter::recurse() {634// Starts by inheriting our parent filter chooser's filter bit values.635std::vector<bit_value_t> BitValueArray(Owner->FilterBitValues);636637if (!VariableInstructions.empty()) {638// Conservatively marks each segment position as BIT_UNSET.639for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex)640BitValueArray[StartBit + bitIndex] = BIT_UNSET;641642// Delegates to an inferior filter chooser for further processing on this643// group of instructions whose segment values are variable.644FilterChooserMap.insert(std::pair(645NO_FIXED_SEGMENTS_SENTINEL,646std::make_unique<FilterChooser>(Owner->AllInstructions,647VariableInstructions, Owner->Operands,648BitValueArray, *Owner)));649}650651// No need to recurse for a singleton filtered instruction.652// See also Filter::emit*().653if (getNumFiltered() == 1) {654assert(FilterChooserMap.size() == 1);655return;656}657658// Otherwise, create sub choosers.659for (const auto &Inst : FilteredInstructions) {660661// Marks all the segment positions with either BIT_TRUE or BIT_FALSE.662for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex) {663if (Inst.first & (1ULL << bitIndex))664BitValueArray[StartBit + bitIndex] = BIT_TRUE;665else666BitValueArray[StartBit + bitIndex] = BIT_FALSE;667}668669// Delegates to an inferior filter chooser for further processing on this670// category of instructions.671FilterChooserMap.insert(672std::pair(Inst.first, std::make_unique<FilterChooser>(673Owner->AllInstructions, Inst.second,674Owner->Operands, BitValueArray, *Owner)));675}676}677678static void resolveTableFixups(DecoderTable &Table, const FixupList &Fixups,679uint32_t DestIdx) {680// Any NumToSkip fixups in the current scope can resolve to the681// current location.682for (FixupList::const_reverse_iterator I = Fixups.rbegin(), E = Fixups.rend();683I != E; ++I) {684// Calculate the distance from the byte following the fixup entry byte685// to the destination. The Target is calculated from after the 16-bit686// NumToSkip entry itself, so subtract two from the displacement here687// to account for that.688uint32_t FixupIdx = *I;689uint32_t Delta = DestIdx - FixupIdx - 3;690// Our NumToSkip entries are 24-bits. Make sure our table isn't too691// big.692assert(Delta < (1u << 24));693Table[FixupIdx] = (uint8_t)Delta;694Table[FixupIdx + 1] = (uint8_t)(Delta >> 8);695Table[FixupIdx + 2] = (uint8_t)(Delta >> 16);696}697}698699// Emit table entries to decode instructions given a segment or segments700// of bits.701void Filter::emitTableEntry(DecoderTableInfo &TableInfo) const {702assert((NumBits < (1u << 8)) && "NumBits overflowed uint8 table entry!");703TableInfo.Table.push_back(MCD::OPC_ExtractField);704705SmallString<16> SBytes;706raw_svector_ostream S(SBytes);707encodeULEB128(StartBit, S);708TableInfo.Table.insert(TableInfo.Table.end(), SBytes.begin(), SBytes.end());709TableInfo.Table.push_back(NumBits);710711// A new filter entry begins a new scope for fixup resolution.712TableInfo.FixupStack.emplace_back();713714DecoderTable &Table = TableInfo.Table;715716size_t PrevFilter = 0;717bool HasFallthrough = false;718for (const auto &Filter : FilterChooserMap) {719// Field value -1 implies a non-empty set of variable instructions.720// See also recurse().721if (Filter.first == NO_FIXED_SEGMENTS_SENTINEL) {722HasFallthrough = true;723724// Each scope should always have at least one filter value to check725// for.726assert(PrevFilter != 0 && "empty filter set!");727FixupList &CurScope = TableInfo.FixupStack.back();728// Resolve any NumToSkip fixups in the current scope.729resolveTableFixups(Table, CurScope, Table.size());730CurScope.clear();731PrevFilter = 0; // Don't re-process the filter's fallthrough.732} else {733Table.push_back(MCD::OPC_FilterValue);734// Encode and emit the value to filter against.735uint8_t Buffer[16];736unsigned Len = encodeULEB128(Filter.first, Buffer);737Table.insert(Table.end(), Buffer, Buffer + Len);738// Reserve space for the NumToSkip entry. We'll backpatch the value739// later.740PrevFilter = Table.size();741Table.push_back(0);742Table.push_back(0);743Table.push_back(0);744}745746// We arrive at a category of instructions with the same segment value.747// Now delegate to the sub filter chooser for further decodings.748// The case may fallthrough, which happens if the remaining well-known749// encoding bits do not match exactly.750Filter.second->emitTableEntries(TableInfo);751752// Now that we've emitted the body of the handler, update the NumToSkip753// of the filter itself to be able to skip forward when false. Subtract754// two as to account for the width of the NumToSkip field itself.755if (PrevFilter) {756uint32_t NumToSkip = Table.size() - PrevFilter - 3;757assert(NumToSkip < (1u << 24) &&758"disassembler decoding table too large!");759Table[PrevFilter] = (uint8_t)NumToSkip;760Table[PrevFilter + 1] = (uint8_t)(NumToSkip >> 8);761Table[PrevFilter + 2] = (uint8_t)(NumToSkip >> 16);762}763}764765// Any remaining unresolved fixups bubble up to the parent fixup scope.766assert(TableInfo.FixupStack.size() > 1 && "fixup stack underflow!");767FixupScopeList::iterator Source = TableInfo.FixupStack.end() - 1;768FixupScopeList::iterator Dest = Source - 1;769llvm::append_range(*Dest, *Source);770TableInfo.FixupStack.pop_back();771772// If there is no fallthrough, then the final filter should get fixed773// up according to the enclosing scope rather than the current position.774if (!HasFallthrough)775TableInfo.FixupStack.back().push_back(PrevFilter);776}777778// Returns the number of fanout produced by the filter. More fanout implies779// the filter distinguishes more categories of instructions.780unsigned Filter::usefulness() const {781if (!VariableInstructions.empty())782return FilteredInstructions.size();783else784return FilteredInstructions.size() + 1;785}786787//////////////////////////////////788// //789// Filterchooser Implementation //790// //791//////////////////////////////////792793// Emit the decoder state machine table.794void DecoderEmitter::emitTable(formatted_raw_ostream &OS, DecoderTable &Table,795unsigned Indentation, unsigned BitWidth,796StringRef Namespace,797const EncodingIDsVec &EncodingIDs) const {798// We'll need to be able to map from a decoded opcode into the corresponding799// EncodingID for this specific combination of BitWidth and Namespace. This800// is used below to index into NumberedEncodings.801DenseMap<unsigned, unsigned> OpcodeToEncodingID;802OpcodeToEncodingID.reserve(EncodingIDs.size());803for (const auto &EI : EncodingIDs)804OpcodeToEncodingID[EI.Opcode] = EI.EncodingID;805806OS.indent(Indentation) << "static const uint8_t DecoderTable" << Namespace807<< BitWidth << "[] = {\n";808809Indentation += 2;810811// Emit ULEB128 encoded value to OS, returning the number of bytes emitted.812auto emitULEB128 = [](DecoderTable::const_iterator I,813formatted_raw_ostream &OS) {814unsigned Len = 0;815while (*I >= 128) {816OS << (unsigned)*I++ << ", ";817Len++;818}819OS << (unsigned)*I++ << ", ";820return Len + 1;821};822823// Emit 24-bit numtoskip value to OS, returning the NumToSkip value.824auto emitNumToSkip = [](DecoderTable::const_iterator I,825formatted_raw_ostream &OS) {826uint8_t Byte = *I++;827uint32_t NumToSkip = Byte;828OS << (unsigned)Byte << ", ";829Byte = *I++;830OS << (unsigned)Byte << ", ";831NumToSkip |= Byte << 8;832Byte = *I++;833OS << utostr(Byte) << ", ";834NumToSkip |= Byte << 16;835return NumToSkip;836};837838// FIXME: We may be able to use the NumToSkip values to recover839// appropriate indentation levels.840DecoderTable::const_iterator I = Table.begin();841DecoderTable::const_iterator E = Table.end();842while (I != E) {843assert(I < E && "incomplete decode table entry!");844845uint64_t Pos = I - Table.begin();846OS << "/* " << Pos << " */";847OS.PadToColumn(12);848849switch (*I) {850default:851PrintFatalError("invalid decode table opcode");852case MCD::OPC_ExtractField: {853++I;854OS.indent(Indentation) << "MCD::OPC_ExtractField, ";855856// ULEB128 encoded start value.857const char *ErrMsg = nullptr;858unsigned Start = decodeULEB128(Table.data() + Pos + 1, nullptr,859Table.data() + Table.size(), &ErrMsg);860assert(ErrMsg == nullptr && "ULEB128 value too large!");861I += emitULEB128(I, OS);862863unsigned Len = *I++;864OS << Len << ", // Inst{";865if (Len > 1)866OS << (Start + Len - 1) << "-";867OS << Start << "} ...\n";868break;869}870case MCD::OPC_FilterValue: {871++I;872OS.indent(Indentation) << "MCD::OPC_FilterValue, ";873// The filter value is ULEB128 encoded.874I += emitULEB128(I, OS);875876// 24-bit numtoskip value.877uint32_t NumToSkip = emitNumToSkip(I, OS);878I += 3;879OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";880break;881}882case MCD::OPC_CheckField: {883++I;884OS.indent(Indentation) << "MCD::OPC_CheckField, ";885// ULEB128 encoded start value.886I += emitULEB128(I, OS);887// 8-bit length.888unsigned Len = *I++;889OS << Len << ", ";890// ULEB128 encoded field value.891I += emitULEB128(I, OS);892893// 24-bit numtoskip value.894uint32_t NumToSkip = emitNumToSkip(I, OS);895I += 3;896OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";897break;898}899case MCD::OPC_CheckPredicate: {900++I;901OS.indent(Indentation) << "MCD::OPC_CheckPredicate, ";902I += emitULEB128(I, OS);903904// 24-bit numtoskip value.905uint32_t NumToSkip = emitNumToSkip(I, OS);906I += 3;907OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";908break;909}910case MCD::OPC_Decode:911case MCD::OPC_TryDecode: {912bool IsTry = *I == MCD::OPC_TryDecode;913++I;914// Decode the Opcode value.915const char *ErrMsg = nullptr;916unsigned Opc = decodeULEB128(Table.data() + Pos + 1, nullptr,917Table.data() + Table.size(), &ErrMsg);918assert(ErrMsg == nullptr && "ULEB128 value too large!");919920OS.indent(Indentation)921<< "MCD::OPC_" << (IsTry ? "Try" : "") << "Decode, ";922I += emitULEB128(I, OS);923924// Decoder index.925I += emitULEB128(I, OS);926927auto EncI = OpcodeToEncodingID.find(Opc);928assert(EncI != OpcodeToEncodingID.end() && "no encoding entry");929auto EncodingID = EncI->second;930931if (!IsTry) {932OS << "// Opcode: " << NumberedEncodings[EncodingID] << "\n";933break;934}935936// Fallthrough for OPC_TryDecode.937938// 24-bit numtoskip value.939uint32_t NumToSkip = emitNumToSkip(I, OS);940I += 3;941942OS << "// Opcode: " << NumberedEncodings[EncodingID]943<< ", skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";944break;945}946case MCD::OPC_SoftFail: {947++I;948OS.indent(Indentation) << "MCD::OPC_SoftFail";949// Positive mask950uint64_t Value = 0;951unsigned Shift = 0;952do {953OS << ", " << (unsigned)*I;954Value += ((uint64_t)(*I & 0x7f)) << Shift;955Shift += 7;956} while (*I++ >= 128);957if (Value > 127) {958OS << " /* 0x";959OS.write_hex(Value);960OS << " */";961}962// Negative mask963Value = 0;964Shift = 0;965do {966OS << ", " << (unsigned)*I;967Value += ((uint64_t)(*I & 0x7f)) << Shift;968Shift += 7;969} while (*I++ >= 128);970if (Value > 127) {971OS << " /* 0x";972OS.write_hex(Value);973OS << " */";974}975OS << ",\n";976break;977}978case MCD::OPC_Fail: {979++I;980OS.indent(Indentation) << "MCD::OPC_Fail,\n";981break;982}983}984}985OS.indent(Indentation) << "0\n";986987Indentation -= 2;988989OS.indent(Indentation) << "};\n\n";990}991992void DecoderEmitter::emitInstrLenTable(formatted_raw_ostream &OS,993std::vector<unsigned> &InstrLen) const {994OS << "static const uint8_t InstrLenTable[] = {\n";995for (unsigned &Len : InstrLen) {996OS << Len << ",\n";997}998OS << "};\n\n";999}10001001void DecoderEmitter::emitPredicateFunction(formatted_raw_ostream &OS,1002PredicateSet &Predicates,1003unsigned Indentation) const {1004// The predicate function is just a big switch statement based on the1005// input predicate index.1006OS.indent(Indentation) << "static bool checkDecoderPredicate(unsigned Idx, "1007<< "const FeatureBitset &Bits) {\n";1008Indentation += 2;1009if (!Predicates.empty()) {1010OS.indent(Indentation) << "switch (Idx) {\n";1011OS.indent(Indentation)1012<< "default: llvm_unreachable(\"Invalid index!\");\n";1013unsigned Index = 0;1014for (const auto &Predicate : Predicates) {1015OS.indent(Indentation) << "case " << Index++ << ":\n";1016OS.indent(Indentation + 2) << "return (" << Predicate << ");\n";1017}1018OS.indent(Indentation) << "}\n";1019} else {1020// No case statement to emit1021OS.indent(Indentation) << "llvm_unreachable(\"Invalid index!\");\n";1022}1023Indentation -= 2;1024OS.indent(Indentation) << "}\n\n";1025}10261027void DecoderEmitter::emitDecoderFunction(formatted_raw_ostream &OS,1028DecoderSet &Decoders,1029unsigned Indentation) const {1030// The decoder function is just a big switch statement based on the1031// input decoder index.1032OS.indent(Indentation) << "template <typename InsnType>\n";1033OS.indent(Indentation) << "static DecodeStatus decodeToMCInst(DecodeStatus S,"1034<< " unsigned Idx, InsnType insn, MCInst &MI,\n";1035OS.indent(Indentation)1036<< " uint64_t "1037<< "Address, const MCDisassembler *Decoder, bool &DecodeComplete) {\n";1038Indentation += 2;1039OS.indent(Indentation) << "DecodeComplete = true;\n";1040// TODO: When InsnType is large, using uint64_t limits all fields to 64 bits1041// It would be better for emitBinaryParser to use a 64-bit tmp whenever1042// possible but fall back to an InsnType-sized tmp for truly large fields.1043OS.indent(Indentation) << "using TmpType = "1044"std::conditional_t<std::is_integral<InsnType>::"1045"value, InsnType, uint64_t>;\n";1046OS.indent(Indentation) << "TmpType tmp;\n";1047OS.indent(Indentation) << "switch (Idx) {\n";1048OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";1049unsigned Index = 0;1050for (const auto &Decoder : Decoders) {1051OS.indent(Indentation) << "case " << Index++ << ":\n";1052OS << Decoder;1053OS.indent(Indentation + 2) << "return S;\n";1054}1055OS.indent(Indentation) << "}\n";1056Indentation -= 2;1057OS.indent(Indentation) << "}\n";1058}10591060// Populates the field of the insn given the start position and the number of1061// consecutive bits to scan for.1062//1063// Returns a pair of values (indicator, field), where the indicator is false1064// if there exists any uninitialized bit value in the range and true if all1065// bits are well-known. The second value is the potentially populated field.1066std::pair<bool, uint64_t> FilterChooser::fieldFromInsn(const insn_t &Insn,1067unsigned StartBit,1068unsigned NumBits) const {1069uint64_t Field = 0;10701071for (unsigned i = 0; i < NumBits; ++i) {1072if (Insn[StartBit + i] == BIT_UNSET)1073return {false, Field};10741075if (Insn[StartBit + i] == BIT_TRUE)1076Field = Field | (1ULL << i);1077}10781079return {true, Field};1080}10811082/// dumpFilterArray - dumpFilterArray prints out debugging info for the given1083/// filter array as a series of chars.1084void FilterChooser::dumpFilterArray(1085raw_ostream &o, const std::vector<bit_value_t> &filter) const {1086for (unsigned bitIndex = BitWidth; bitIndex > 0; bitIndex--) {1087switch (filter[bitIndex - 1]) {1088case BIT_UNFILTERED:1089o << ".";1090break;1091case BIT_UNSET:1092o << "_";1093break;1094case BIT_TRUE:1095o << "1";1096break;1097case BIT_FALSE:1098o << "0";1099break;1100}1101}1102}11031104/// dumpStack - dumpStack traverses the filter chooser chain and calls1105/// dumpFilterArray on each filter chooser up to the top level one.1106void FilterChooser::dumpStack(raw_ostream &o, const char *prefix) const {1107const FilterChooser *current = this;11081109while (current) {1110o << prefix;1111dumpFilterArray(o, current->FilterBitValues);1112o << '\n';1113current = current->Parent;1114}1115}11161117// Calculates the island(s) needed to decode the instruction.1118// This returns a list of undecoded bits of an instructions, for example,1119// Inst{20} = 1 && Inst{3-0} == 0b1111 represents two islands of yet-to-be1120// decoded bits in order to verify that the instruction matches the Opcode.1121unsigned FilterChooser::getIslands(std::vector<unsigned> &StartBits,1122std::vector<unsigned> &EndBits,1123std::vector<uint64_t> &FieldVals,1124const insn_t &Insn) const {1125unsigned Num, BitNo;1126Num = BitNo = 0;11271128uint64_t FieldVal = 0;11291130// 0: Init1131// 1: Water (the bit value does not affect decoding)1132// 2: Island (well-known bit value needed for decoding)1133int State = 0;11341135for (unsigned i = 0; i < BitWidth; ++i) {1136int64_t Val = Value(Insn[i]);1137bool Filtered = PositionFiltered(i);1138switch (State) {1139default:1140llvm_unreachable("Unreachable code!");1141case 0:1142case 1:1143if (Filtered || Val == -1)1144State = 1; // Still in Water1145else {1146State = 2; // Into the Island1147BitNo = 0;1148StartBits.push_back(i);1149FieldVal = Val;1150}1151break;1152case 2:1153if (Filtered || Val == -1) {1154State = 1; // Into the Water1155EndBits.push_back(i - 1);1156FieldVals.push_back(FieldVal);1157++Num;1158} else {1159State = 2; // Still in Island1160++BitNo;1161FieldVal = FieldVal | Val << BitNo;1162}1163break;1164}1165}1166// If we are still in Island after the loop, do some housekeeping.1167if (State == 2) {1168EndBits.push_back(BitWidth - 1);1169FieldVals.push_back(FieldVal);1170++Num;1171}11721173assert(StartBits.size() == Num && EndBits.size() == Num &&1174FieldVals.size() == Num);1175return Num;1176}11771178void FilterChooser::emitBinaryParser(raw_ostream &o, unsigned &Indentation,1179const OperandInfo &OpInfo,1180bool &OpHasCompleteDecoder) const {1181const std::string &Decoder = OpInfo.Decoder;11821183bool UseInsertBits = OpInfo.numFields() != 1 || OpInfo.InitValue != 0;11841185if (UseInsertBits) {1186o.indent(Indentation) << "tmp = 0x";1187o.write_hex(OpInfo.InitValue);1188o << ";\n";1189}11901191for (const EncodingField &EF : OpInfo) {1192o.indent(Indentation);1193if (UseInsertBits)1194o << "insertBits(tmp, ";1195else1196o << "tmp = ";1197o << "fieldFromInstruction(insn, " << EF.Base << ", " << EF.Width << ')';1198if (UseInsertBits)1199o << ", " << EF.Offset << ", " << EF.Width << ')';1200else if (EF.Offset != 0)1201o << " << " << EF.Offset;1202o << ";\n";1203}12041205if (Decoder != "") {1206OpHasCompleteDecoder = OpInfo.HasCompleteDecoder;1207o.indent(Indentation) << "if (!Check(S, " << Decoder1208<< "(MI, tmp, Address, Decoder))) { "1209<< (OpHasCompleteDecoder ? ""1210: "DecodeComplete = false; ")1211<< "return MCDisassembler::Fail; }\n";1212} else {1213OpHasCompleteDecoder = true;1214o.indent(Indentation) << "MI.addOperand(MCOperand::createImm(tmp));\n";1215}1216}12171218void FilterChooser::emitDecoder(raw_ostream &OS, unsigned Indentation,1219unsigned Opc, bool &HasCompleteDecoder) const {1220HasCompleteDecoder = true;12211222for (const auto &Op : Operands.find(Opc)->second) {1223// If a custom instruction decoder was specified, use that.1224if (Op.numFields() == 0 && !Op.Decoder.empty()) {1225HasCompleteDecoder = Op.HasCompleteDecoder;1226OS.indent(Indentation)1227<< "if (!Check(S, " << Op.Decoder1228<< "(MI, insn, Address, Decoder))) { "1229<< (HasCompleteDecoder ? "" : "DecodeComplete = false; ")1230<< "return MCDisassembler::Fail; }\n";1231break;1232}12331234bool OpHasCompleteDecoder;1235emitBinaryParser(OS, Indentation, Op, OpHasCompleteDecoder);1236if (!OpHasCompleteDecoder)1237HasCompleteDecoder = false;1238}1239}12401241unsigned FilterChooser::getDecoderIndex(DecoderSet &Decoders, unsigned Opc,1242bool &HasCompleteDecoder) const {1243// Build up the predicate string.1244SmallString<256> Decoder;1245// FIXME: emitDecoder() function can take a buffer directly rather than1246// a stream.1247raw_svector_ostream S(Decoder);1248unsigned I = 4;1249emitDecoder(S, I, Opc, HasCompleteDecoder);12501251// Using the full decoder string as the key value here is a bit1252// heavyweight, but is effective. If the string comparisons become a1253// performance concern, we can implement a mangling of the predicate1254// data easily enough with a map back to the actual string. That's1255// overkill for now, though.12561257// Make sure the predicate is in the table.1258Decoders.insert(CachedHashString(Decoder));1259// Now figure out the index for when we write out the table.1260DecoderSet::const_iterator P = find(Decoders, Decoder.str());1261return (unsigned)(P - Decoders.begin());1262}12631264// If ParenIfBinOp is true, print a surrounding () if Val uses && or ||.1265bool FilterChooser::emitPredicateMatchAux(const Init &Val, bool ParenIfBinOp,1266raw_ostream &OS) const {1267if (const auto *D = dyn_cast<DefInit>(&Val)) {1268if (!D->getDef()->isSubClassOf("SubtargetFeature"))1269return true;1270OS << "Bits[" << Emitter->PredicateNamespace << "::" << D->getAsString()1271<< "]";1272return false;1273}1274if (const auto *D = dyn_cast<DagInit>(&Val)) {1275std::string Op = D->getOperator()->getAsString();1276if (Op == "not" && D->getNumArgs() == 1) {1277OS << '!';1278return emitPredicateMatchAux(*D->getArg(0), true, OS);1279}1280if ((Op == "any_of" || Op == "all_of") && D->getNumArgs() > 0) {1281bool Paren = D->getNumArgs() > 1 && std::exchange(ParenIfBinOp, true);1282if (Paren)1283OS << '(';1284ListSeparator LS(Op == "any_of" ? " || " : " && ");1285for (auto *Arg : D->getArgs()) {1286OS << LS;1287if (emitPredicateMatchAux(*Arg, ParenIfBinOp, OS))1288return true;1289}1290if (Paren)1291OS << ')';1292return false;1293}1294}1295return true;1296}12971298bool FilterChooser::emitPredicateMatch(raw_ostream &o, unsigned &Indentation,1299unsigned Opc) const {1300ListInit *Predicates =1301AllInstructions[Opc].EncodingDef->getValueAsListInit("Predicates");1302bool IsFirstEmission = true;1303for (unsigned i = 0; i < Predicates->size(); ++i) {1304Record *Pred = Predicates->getElementAsRecord(i);1305if (!Pred->getValue("AssemblerMatcherPredicate"))1306continue;13071308if (!isa<DagInit>(Pred->getValue("AssemblerCondDag")->getValue()))1309continue;13101311if (!IsFirstEmission)1312o << " && ";1313if (emitPredicateMatchAux(*Pred->getValueAsDag("AssemblerCondDag"),1314Predicates->size() > 1, o))1315PrintFatalError(Pred->getLoc(), "Invalid AssemblerCondDag!");1316IsFirstEmission = false;1317}1318return !Predicates->empty();1319}13201321bool FilterChooser::doesOpcodeNeedPredicate(unsigned Opc) const {1322ListInit *Predicates =1323AllInstructions[Opc].EncodingDef->getValueAsListInit("Predicates");1324for (unsigned i = 0; i < Predicates->size(); ++i) {1325Record *Pred = Predicates->getElementAsRecord(i);1326if (!Pred->getValue("AssemblerMatcherPredicate"))1327continue;13281329if (isa<DagInit>(Pred->getValue("AssemblerCondDag")->getValue()))1330return true;1331}1332return false;1333}13341335unsigned FilterChooser::getPredicateIndex(DecoderTableInfo &TableInfo,1336StringRef Predicate) const {1337// Using the full predicate string as the key value here is a bit1338// heavyweight, but is effective. If the string comparisons become a1339// performance concern, we can implement a mangling of the predicate1340// data easily enough with a map back to the actual string. That's1341// overkill for now, though.13421343// Make sure the predicate is in the table.1344TableInfo.Predicates.insert(CachedHashString(Predicate));1345// Now figure out the index for when we write out the table.1346PredicateSet::const_iterator P = find(TableInfo.Predicates, Predicate);1347return (unsigned)(P - TableInfo.Predicates.begin());1348}13491350void FilterChooser::emitPredicateTableEntry(DecoderTableInfo &TableInfo,1351unsigned Opc) const {1352if (!doesOpcodeNeedPredicate(Opc))1353return;13541355// Build up the predicate string.1356SmallString<256> Predicate;1357// FIXME: emitPredicateMatch() functions can take a buffer directly rather1358// than a stream.1359raw_svector_ostream PS(Predicate);1360unsigned I = 0;1361emitPredicateMatch(PS, I, Opc);13621363// Figure out the index into the predicate table for the predicate just1364// computed.1365unsigned PIdx = getPredicateIndex(TableInfo, PS.str());1366SmallString<16> PBytes;1367raw_svector_ostream S(PBytes);1368encodeULEB128(PIdx, S);13691370TableInfo.Table.push_back(MCD::OPC_CheckPredicate);1371// Predicate index.1372for (const auto PB : PBytes)1373TableInfo.Table.push_back(PB);1374// Push location for NumToSkip backpatching.1375TableInfo.FixupStack.back().push_back(TableInfo.Table.size());1376TableInfo.Table.push_back(0);1377TableInfo.Table.push_back(0);1378TableInfo.Table.push_back(0);1379}13801381void FilterChooser::emitSoftFailTableEntry(DecoderTableInfo &TableInfo,1382unsigned Opc) const {1383const Record *EncodingDef = AllInstructions[Opc].EncodingDef;1384const RecordVal *RV = EncodingDef->getValue("SoftFail");1385BitsInit *SFBits = RV ? dyn_cast<BitsInit>(RV->getValue()) : nullptr;13861387if (!SFBits)1388return;1389BitsInit *InstBits = EncodingDef->getValueAsBitsInit("Inst");13901391APInt PositiveMask(BitWidth, 0ULL);1392APInt NegativeMask(BitWidth, 0ULL);1393for (unsigned i = 0; i < BitWidth; ++i) {1394bit_value_t B = bitFromBits(*SFBits, i);1395bit_value_t IB = bitFromBits(*InstBits, i);13961397if (B != BIT_TRUE)1398continue;13991400switch (IB) {1401case BIT_FALSE:1402// The bit is meant to be false, so emit a check to see if it is true.1403PositiveMask.setBit(i);1404break;1405case BIT_TRUE:1406// The bit is meant to be true, so emit a check to see if it is false.1407NegativeMask.setBit(i);1408break;1409default:1410// The bit is not set; this must be an error!1411errs() << "SoftFail Conflict: bit SoftFail{" << i << "} in "1412<< AllInstructions[Opc] << " is set but Inst{" << i1413<< "} is unset!\n"1414<< " - You can only mark a bit as SoftFail if it is fully defined"1415<< " (1/0 - not '?') in Inst\n";1416return;1417}1418}14191420bool NeedPositiveMask = PositiveMask.getBoolValue();1421bool NeedNegativeMask = NegativeMask.getBoolValue();14221423if (!NeedPositiveMask && !NeedNegativeMask)1424return;14251426TableInfo.Table.push_back(MCD::OPC_SoftFail);14271428SmallString<16> MaskBytes;1429raw_svector_ostream S(MaskBytes);1430if (NeedPositiveMask) {1431encodeULEB128(PositiveMask.getZExtValue(), S);1432for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)1433TableInfo.Table.push_back(MaskBytes[i]);1434} else1435TableInfo.Table.push_back(0);1436if (NeedNegativeMask) {1437MaskBytes.clear();1438encodeULEB128(NegativeMask.getZExtValue(), S);1439for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)1440TableInfo.Table.push_back(MaskBytes[i]);1441} else1442TableInfo.Table.push_back(0);1443}14441445// Emits table entries to decode the singleton.1446void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,1447EncodingIDAndOpcode Opc) const {1448std::vector<unsigned> StartBits;1449std::vector<unsigned> EndBits;1450std::vector<uint64_t> FieldVals;1451insn_t Insn;1452insnWithID(Insn, Opc.EncodingID);14531454// Look for islands of undecoded bits of the singleton.1455getIslands(StartBits, EndBits, FieldVals, Insn);14561457unsigned Size = StartBits.size();14581459// Emit the predicate table entry if one is needed.1460emitPredicateTableEntry(TableInfo, Opc.EncodingID);14611462// Check any additional encoding fields needed.1463for (unsigned I = Size; I != 0; --I) {1464unsigned NumBits = EndBits[I - 1] - StartBits[I - 1] + 1;1465assert((NumBits < (1u << 8)) && "NumBits overflowed uint8 table entry!");1466TableInfo.Table.push_back(MCD::OPC_CheckField);1467uint8_t Buffer[16], *P;1468encodeULEB128(StartBits[I - 1], Buffer);1469for (P = Buffer; *P >= 128; ++P)1470TableInfo.Table.push_back(*P);1471TableInfo.Table.push_back(*P);1472TableInfo.Table.push_back(NumBits);1473encodeULEB128(FieldVals[I - 1], Buffer);1474for (P = Buffer; *P >= 128; ++P)1475TableInfo.Table.push_back(*P);1476TableInfo.Table.push_back(*P);1477// Push location for NumToSkip backpatching.1478TableInfo.FixupStack.back().push_back(TableInfo.Table.size());1479// The fixup is always 24-bits, so go ahead and allocate the space1480// in the table so all our relative position calculations work OK even1481// before we fully resolve the real value here.1482TableInfo.Table.push_back(0);1483TableInfo.Table.push_back(0);1484TableInfo.Table.push_back(0);1485}14861487// Check for soft failure of the match.1488emitSoftFailTableEntry(TableInfo, Opc.EncodingID);14891490bool HasCompleteDecoder;1491unsigned DIdx =1492getDecoderIndex(TableInfo.Decoders, Opc.EncodingID, HasCompleteDecoder);14931494// Produce OPC_Decode or OPC_TryDecode opcode based on the information1495// whether the instruction decoder is complete or not. If it is complete1496// then it handles all possible values of remaining variable/unfiltered bits1497// and for any value can determine if the bitpattern is a valid instruction1498// or not. This means OPC_Decode will be the final step in the decoding1499// process. If it is not complete, then the Fail return code from the1500// decoder method indicates that additional processing should be done to see1501// if there is any other instruction that also matches the bitpattern and1502// can decode it.1503TableInfo.Table.push_back(HasCompleteDecoder ? MCD::OPC_Decode1504: MCD::OPC_TryDecode);1505NumEncodingsSupported++;1506uint8_t Buffer[16], *p;1507encodeULEB128(Opc.Opcode, Buffer);1508for (p = Buffer; *p >= 128; ++p)1509TableInfo.Table.push_back(*p);1510TableInfo.Table.push_back(*p);15111512SmallString<16> Bytes;1513raw_svector_ostream S(Bytes);1514encodeULEB128(DIdx, S);15151516// Decoder index.1517for (const auto B : Bytes)1518TableInfo.Table.push_back(B);15191520if (!HasCompleteDecoder) {1521// Push location for NumToSkip backpatching.1522TableInfo.FixupStack.back().push_back(TableInfo.Table.size());1523// Allocate the space for the fixup.1524TableInfo.Table.push_back(0);1525TableInfo.Table.push_back(0);1526TableInfo.Table.push_back(0);1527}1528}15291530// Emits table entries to decode the singleton, and then to decode the rest.1531void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,1532const Filter &Best) const {1533EncodingIDAndOpcode Opc = Best.getSingletonOpc();15341535// complex singletons need predicate checks from the first singleton1536// to refer forward to the variable filterchooser that follows.1537TableInfo.FixupStack.emplace_back();15381539emitSingletonTableEntry(TableInfo, Opc);15401541resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),1542TableInfo.Table.size());1543TableInfo.FixupStack.pop_back();15441545Best.getVariableFC().emitTableEntries(TableInfo);1546}15471548// Assign a single filter and run with it. Top level API client can initialize1549// with a single filter to start the filtering process.1550void FilterChooser::runSingleFilter(unsigned startBit, unsigned numBit,1551bool mixed) {1552Filters.clear();1553Filters.emplace_back(*this, startBit, numBit, true);1554BestIndex = 0; // Sole Filter instance to choose from.1555bestFilter().recurse();1556}15571558// reportRegion is a helper function for filterProcessor to mark a region as1559// eligible for use as a filter region.1560void FilterChooser::reportRegion(bitAttr_t RA, unsigned StartBit,1561unsigned BitIndex, bool AllowMixed) {1562if (RA == ATTR_MIXED && AllowMixed)1563Filters.emplace_back(*this, StartBit, BitIndex - StartBit, true);1564else if (RA == ATTR_ALL_SET && !AllowMixed)1565Filters.emplace_back(*this, StartBit, BitIndex - StartBit, false);1566}15671568// FilterProcessor scans the well-known encoding bits of the instructions and1569// builds up a list of candidate filters. It chooses the best filter and1570// recursively descends down the decoding tree.1571bool FilterChooser::filterProcessor(bool AllowMixed, bool Greedy) {1572Filters.clear();1573BestIndex = -1;1574unsigned numInstructions = Opcodes.size();15751576assert(numInstructions && "Filter created with no instructions");15771578// No further filtering is necessary.1579if (numInstructions == 1)1580return true;15811582// Heuristics. See also doFilter()'s "Heuristics" comment when num of1583// instructions is 3.1584if (AllowMixed && !Greedy) {1585assert(numInstructions == 3);15861587for (const auto &Opcode : Opcodes) {1588std::vector<unsigned> StartBits;1589std::vector<unsigned> EndBits;1590std::vector<uint64_t> FieldVals;1591insn_t Insn;15921593insnWithID(Insn, Opcode.EncodingID);15941595// Look for islands of undecoded bits of any instruction.1596if (getIslands(StartBits, EndBits, FieldVals, Insn) > 0) {1597// Found an instruction with island(s). Now just assign a filter.1598runSingleFilter(StartBits[0], EndBits[0] - StartBits[0] + 1, true);1599return true;1600}1601}1602}16031604unsigned BitIndex;16051606// We maintain BIT_WIDTH copies of the bitAttrs automaton.1607// The automaton consumes the corresponding bit from each1608// instruction.1609//1610// Input symbols: 0, 1, and _ (unset).1611// States: NONE, FILTERED, ALL_SET, ALL_UNSET, and MIXED.1612// Initial state: NONE.1613//1614// (NONE) ------- [01] -> (ALL_SET)1615// (NONE) ------- _ ----> (ALL_UNSET)1616// (ALL_SET) ---- [01] -> (ALL_SET)1617// (ALL_SET) ---- _ ----> (MIXED)1618// (ALL_UNSET) -- [01] -> (MIXED)1619// (ALL_UNSET) -- _ ----> (ALL_UNSET)1620// (MIXED) ------ . ----> (MIXED)1621// (FILTERED)---- . ----> (FILTERED)16221623std::vector<bitAttr_t> bitAttrs;16241625// FILTERED bit positions provide no entropy and are not worthy of pursuing.1626// Filter::recurse() set either BIT_TRUE or BIT_FALSE for each position.1627for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex)1628if (FilterBitValues[BitIndex] == BIT_TRUE ||1629FilterBitValues[BitIndex] == BIT_FALSE)1630bitAttrs.push_back(ATTR_FILTERED);1631else1632bitAttrs.push_back(ATTR_NONE);16331634for (const auto &OpcPair : Opcodes) {1635insn_t insn;16361637insnWithID(insn, OpcPair.EncodingID);16381639for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {1640switch (bitAttrs[BitIndex]) {1641case ATTR_NONE:1642if (insn[BitIndex] == BIT_UNSET)1643bitAttrs[BitIndex] = ATTR_ALL_UNSET;1644else1645bitAttrs[BitIndex] = ATTR_ALL_SET;1646break;1647case ATTR_ALL_SET:1648if (insn[BitIndex] == BIT_UNSET)1649bitAttrs[BitIndex] = ATTR_MIXED;1650break;1651case ATTR_ALL_UNSET:1652if (insn[BitIndex] != BIT_UNSET)1653bitAttrs[BitIndex] = ATTR_MIXED;1654break;1655case ATTR_MIXED:1656case ATTR_FILTERED:1657break;1658}1659}1660}16611662// The regionAttr automaton consumes the bitAttrs automatons' state,1663// lowest-to-highest.1664//1665// Input symbols: F(iltered), (all_)S(et), (all_)U(nset), M(ixed)1666// States: NONE, ALL_SET, MIXED1667// Initial state: NONE1668//1669// (NONE) ----- F --> (NONE)1670// (NONE) ----- S --> (ALL_SET) ; and set region start1671// (NONE) ----- U --> (NONE)1672// (NONE) ----- M --> (MIXED) ; and set region start1673// (ALL_SET) -- F --> (NONE) ; and report an ALL_SET region1674// (ALL_SET) -- S --> (ALL_SET)1675// (ALL_SET) -- U --> (NONE) ; and report an ALL_SET region1676// (ALL_SET) -- M --> (MIXED) ; and report an ALL_SET region1677// (MIXED) ---- F --> (NONE) ; and report a MIXED region1678// (MIXED) ---- S --> (ALL_SET) ; and report a MIXED region1679// (MIXED) ---- U --> (NONE) ; and report a MIXED region1680// (MIXED) ---- M --> (MIXED)16811682bitAttr_t RA = ATTR_NONE;1683unsigned StartBit = 0;16841685for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {1686bitAttr_t bitAttr = bitAttrs[BitIndex];16871688assert(bitAttr != ATTR_NONE && "Bit without attributes");16891690switch (RA) {1691case ATTR_NONE:1692switch (bitAttr) {1693case ATTR_FILTERED:1694break;1695case ATTR_ALL_SET:1696StartBit = BitIndex;1697RA = ATTR_ALL_SET;1698break;1699case ATTR_ALL_UNSET:1700break;1701case ATTR_MIXED:1702StartBit = BitIndex;1703RA = ATTR_MIXED;1704break;1705default:1706llvm_unreachable("Unexpected bitAttr!");1707}1708break;1709case ATTR_ALL_SET:1710switch (bitAttr) {1711case ATTR_FILTERED:1712reportRegion(RA, StartBit, BitIndex, AllowMixed);1713RA = ATTR_NONE;1714break;1715case ATTR_ALL_SET:1716break;1717case ATTR_ALL_UNSET:1718reportRegion(RA, StartBit, BitIndex, AllowMixed);1719RA = ATTR_NONE;1720break;1721case ATTR_MIXED:1722reportRegion(RA, StartBit, BitIndex, AllowMixed);1723StartBit = BitIndex;1724RA = ATTR_MIXED;1725break;1726default:1727llvm_unreachable("Unexpected bitAttr!");1728}1729break;1730case ATTR_MIXED:1731switch (bitAttr) {1732case ATTR_FILTERED:1733reportRegion(RA, StartBit, BitIndex, AllowMixed);1734StartBit = BitIndex;1735RA = ATTR_NONE;1736break;1737case ATTR_ALL_SET:1738reportRegion(RA, StartBit, BitIndex, AllowMixed);1739StartBit = BitIndex;1740RA = ATTR_ALL_SET;1741break;1742case ATTR_ALL_UNSET:1743reportRegion(RA, StartBit, BitIndex, AllowMixed);1744RA = ATTR_NONE;1745break;1746case ATTR_MIXED:1747break;1748default:1749llvm_unreachable("Unexpected bitAttr!");1750}1751break;1752case ATTR_ALL_UNSET:1753llvm_unreachable("regionAttr state machine has no ATTR_UNSET state");1754case ATTR_FILTERED:1755llvm_unreachable("regionAttr state machine has no ATTR_FILTERED state");1756}1757}17581759// At the end, if we're still in ALL_SET or MIXED states, report a region1760switch (RA) {1761case ATTR_NONE:1762break;1763case ATTR_FILTERED:1764break;1765case ATTR_ALL_SET:1766reportRegion(RA, StartBit, BitIndex, AllowMixed);1767break;1768case ATTR_ALL_UNSET:1769break;1770case ATTR_MIXED:1771reportRegion(RA, StartBit, BitIndex, AllowMixed);1772break;1773}17741775// We have finished with the filter processings. Now it's time to choose1776// the best performing filter.1777BestIndex = 0;1778bool AllUseless = true;1779unsigned BestScore = 0;17801781for (const auto &[Idx, Filter] : enumerate(Filters)) {1782unsigned Usefulness = Filter.usefulness();17831784if (Usefulness)1785AllUseless = false;17861787if (Usefulness > BestScore) {1788BestIndex = Idx;1789BestScore = Usefulness;1790}1791}17921793if (!AllUseless)1794bestFilter().recurse();17951796return !AllUseless;1797} // end of FilterChooser::filterProcessor(bool)17981799// Decides on the best configuration of filter(s) to use in order to decode1800// the instructions. A conflict of instructions may occur, in which case we1801// dump the conflict set to the standard error.1802void FilterChooser::doFilter() {1803unsigned Num = Opcodes.size();1804assert(Num && "FilterChooser created with no instructions");18051806// Try regions of consecutive known bit values first.1807if (filterProcessor(false))1808return;18091810// Then regions of mixed bits (both known and unitialized bit values allowed).1811if (filterProcessor(true))1812return;18131814// Heuristics to cope with conflict set {t2CMPrs, t2SUBSrr, t2SUBSrs} where1815// no single instruction for the maximum ATTR_MIXED region Inst{14-4} has a1816// well-known encoding pattern. In such case, we backtrack and scan for the1817// the very first consecutive ATTR_ALL_SET region and assign a filter to it.1818if (Num == 3 && filterProcessor(true, false))1819return;18201821// If we come to here, the instruction decoding has failed.1822// Set the BestIndex to -1 to indicate so.1823BestIndex = -1;1824}18251826// emitTableEntries - Emit state machine entries to decode our share of1827// instructions.1828void FilterChooser::emitTableEntries(DecoderTableInfo &TableInfo) const {1829if (Opcodes.size() == 1) {1830// There is only one instruction in the set, which is great!1831// Call emitSingletonDecoder() to see whether there are any remaining1832// encodings bits.1833emitSingletonTableEntry(TableInfo, Opcodes[0]);1834return;1835}18361837// Choose the best filter to do the decodings!1838if (BestIndex != -1) {1839const Filter &Best = Filters[BestIndex];1840if (Best.getNumFiltered() == 1)1841emitSingletonTableEntry(TableInfo, Best);1842else1843Best.emitTableEntry(TableInfo);1844return;1845}18461847// We don't know how to decode these instructions! Dump the1848// conflict set and bail.18491850// Print out useful conflict information for postmortem analysis.1851errs() << "Decoding Conflict:\n";18521853dumpStack(errs(), "\t\t");18541855for (auto Opcode : Opcodes) {1856errs() << '\t';1857emitNameWithID(errs(), Opcode.EncodingID);1858errs() << " ";1859dumpBits(1860errs(),1861getBitsField(*AllInstructions[Opcode.EncodingID].EncodingDef, "Inst"));1862errs() << '\n';1863}1864}18651866static std::string findOperandDecoderMethod(Record *Record) {1867std::string Decoder;18681869RecordVal *DecoderString = Record->getValue("DecoderMethod");1870StringInit *String =1871DecoderString ? dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;1872if (String) {1873Decoder = std::string(String->getValue());1874if (!Decoder.empty())1875return Decoder;1876}18771878if (Record->isSubClassOf("RegisterOperand"))1879// Allows use of a DecoderMethod in referenced RegisterClass if set.1880return findOperandDecoderMethod(Record->getValueAsDef("RegClass"));18811882if (Record->isSubClassOf("RegisterClass")) {1883Decoder = "Decode" + Record->getName().str() + "RegisterClass";1884} else if (Record->isSubClassOf("PointerLikeRegClass")) {1885Decoder = "DecodePointerLikeRegClass" +1886utostr(Record->getValueAsInt("RegClassKind"));1887}18881889return Decoder;1890}18911892OperandInfo getOpInfo(Record *TypeRecord) {1893std::string Decoder = findOperandDecoderMethod(TypeRecord);18941895RecordVal *HasCompleteDecoderVal = TypeRecord->getValue("hasCompleteDecoder");1896BitInit *HasCompleteDecoderBit =1897HasCompleteDecoderVal1898? dyn_cast<BitInit>(HasCompleteDecoderVal->getValue())1899: nullptr;1900bool HasCompleteDecoder =1901HasCompleteDecoderBit ? HasCompleteDecoderBit->getValue() : true;19021903return OperandInfo(Decoder, HasCompleteDecoder);1904}19051906void parseVarLenInstOperand(const Record &Def,1907std::vector<OperandInfo> &Operands,1908const CodeGenInstruction &CGI) {19091910const RecordVal *RV = Def.getValue("Inst");1911VarLenInst VLI(cast<DagInit>(RV->getValue()), RV);1912SmallVector<int> TiedTo;19131914for (const auto &[Idx, Op] : enumerate(CGI.Operands)) {1915if (Op.MIOperandInfo && Op.MIOperandInfo->getNumArgs() > 0)1916for (auto *Arg : Op.MIOperandInfo->getArgs())1917Operands.push_back(getOpInfo(cast<DefInit>(Arg)->getDef()));1918else1919Operands.push_back(getOpInfo(Op.Rec));19201921int TiedReg = Op.getTiedRegister();1922TiedTo.push_back(-1);1923if (TiedReg != -1) {1924TiedTo[Idx] = TiedReg;1925TiedTo[TiedReg] = Idx;1926}1927}19281929unsigned CurrBitPos = 0;1930for (const auto &EncodingSegment : VLI) {1931unsigned Offset = 0;1932StringRef OpName;19331934if (const StringInit *SI = dyn_cast<StringInit>(EncodingSegment.Value)) {1935OpName = SI->getValue();1936} else if (const DagInit *DI = dyn_cast<DagInit>(EncodingSegment.Value)) {1937OpName = cast<StringInit>(DI->getArg(0))->getValue();1938Offset = cast<IntInit>(DI->getArg(2))->getValue();1939}19401941if (!OpName.empty()) {1942auto OpSubOpPair =1943const_cast<CodeGenInstruction &>(CGI).Operands.ParseOperandName(1944OpName);1945unsigned OpIdx = CGI.Operands.getFlattenedOperandNumber(OpSubOpPair);1946Operands[OpIdx].addField(CurrBitPos, EncodingSegment.BitWidth, Offset);1947if (!EncodingSegment.CustomDecoder.empty())1948Operands[OpIdx].Decoder = EncodingSegment.CustomDecoder.str();19491950int TiedReg = TiedTo[OpSubOpPair.first];1951if (TiedReg != -1) {1952unsigned OpIdx = CGI.Operands.getFlattenedOperandNumber(1953std::pair(TiedReg, OpSubOpPair.second));1954Operands[OpIdx].addField(CurrBitPos, EncodingSegment.BitWidth, Offset);1955}1956}19571958CurrBitPos += EncodingSegment.BitWidth;1959}1960}19611962static void debugDumpRecord(const Record &Rec) {1963// Dump the record, so we can see what's going on...1964std::string E;1965raw_string_ostream S(E);1966S << "Dumping record for previous error:\n";1967S << Rec;1968PrintNote(E);1969}19701971/// For an operand field named OpName: populate OpInfo.InitValue with the1972/// constant-valued bit values, and OpInfo.Fields with the ranges of bits to1973/// insert from the decoded instruction.1974static void addOneOperandFields(const Record &EncodingDef, const BitsInit &Bits,1975std::map<std::string, std::string> &TiedNames,1976StringRef OpName, OperandInfo &OpInfo) {1977// Some bits of the operand may be required to be 1 depending on the1978// instruction's encoding. Collect those bits.1979if (const RecordVal *EncodedValue = EncodingDef.getValue(OpName))1980if (const BitsInit *OpBits = dyn_cast<BitsInit>(EncodedValue->getValue()))1981for (unsigned I = 0; I < OpBits->getNumBits(); ++I)1982if (const BitInit *OpBit = dyn_cast<BitInit>(OpBits->getBit(I)))1983if (OpBit->getValue())1984OpInfo.InitValue |= 1ULL << I;19851986for (unsigned I = 0, J = 0; I != Bits.getNumBits(); I = J) {1987VarInit *Var;1988unsigned Offset = 0;1989for (; J != Bits.getNumBits(); ++J) {1990VarBitInit *BJ = dyn_cast<VarBitInit>(Bits.getBit(J));1991if (BJ) {1992Var = dyn_cast<VarInit>(BJ->getBitVar());1993if (I == J)1994Offset = BJ->getBitNum();1995else if (BJ->getBitNum() != Offset + J - I)1996break;1997} else {1998Var = dyn_cast<VarInit>(Bits.getBit(J));1999}2000if (!Var || (Var->getName() != OpName &&2001Var->getName() != TiedNames[std::string(OpName)]))2002break;2003}2004if (I == J)2005++J;2006else2007OpInfo.addField(I, J - I, Offset);2008}2009}20102011static unsigned2012populateInstruction(CodeGenTarget &Target, const Record &EncodingDef,2013const CodeGenInstruction &CGI, unsigned Opc,2014std::map<unsigned, std::vector<OperandInfo>> &Operands,2015bool IsVarLenInst) {2016const Record &Def = *CGI.TheDef;2017// If all the bit positions are not specified; do not decode this instruction.2018// We are bound to fail! For proper disassembly, the well-known encoding bits2019// of the instruction must be fully specified.20202021BitsInit &Bits = getBitsField(EncodingDef, "Inst");2022if (Bits.allInComplete())2023return 0;20242025std::vector<OperandInfo> InsnOperands;20262027// If the instruction has specified a custom decoding hook, use that instead2028// of trying to auto-generate the decoder.2029StringRef InstDecoder = EncodingDef.getValueAsString("DecoderMethod");2030if (InstDecoder != "") {2031bool HasCompleteInstDecoder =2032EncodingDef.getValueAsBit("hasCompleteDecoder");2033InsnOperands.push_back(2034OperandInfo(std::string(InstDecoder), HasCompleteInstDecoder));2035Operands[Opc] = InsnOperands;2036return Bits.getNumBits();2037}20382039// Generate a description of the operand of the instruction that we know2040// how to decode automatically.2041// FIXME: We'll need to have a way to manually override this as needed.20422043// Gather the outputs/inputs of the instruction, so we can find their2044// positions in the encoding. This assumes for now that they appear in the2045// MCInst in the order that they're listed.2046std::vector<std::pair<Init *, StringRef>> InOutOperands;2047DagInit *Out = Def.getValueAsDag("OutOperandList");2048DagInit *In = Def.getValueAsDag("InOperandList");2049for (const auto &[Idx, Arg] : enumerate(Out->getArgs()))2050InOutOperands.push_back(std::pair(Arg, Out->getArgNameStr(Idx)));2051for (const auto &[Idx, Arg] : enumerate(In->getArgs()))2052InOutOperands.push_back(std::pair(Arg, In->getArgNameStr(Idx)));20532054// Search for tied operands, so that we can correctly instantiate2055// operands that are not explicitly represented in the encoding.2056std::map<std::string, std::string> TiedNames;2057for (const auto &[I, Op] : enumerate(CGI.Operands)) {2058for (const auto &[J, CI] : enumerate(Op.Constraints)) {2059if (CI.isTied()) {2060std::pair<unsigned, unsigned> SO =2061CGI.Operands.getSubOperandNumber(CI.getTiedOperand());2062std::string TiedName = CGI.Operands[SO.first].SubOpNames[SO.second];2063if (TiedName.empty())2064TiedName = CGI.Operands[SO.first].Name;2065std::string MyName = Op.SubOpNames[J];2066if (MyName.empty())2067MyName = Op.Name;20682069TiedNames[MyName] = TiedName;2070TiedNames[TiedName] = MyName;2071}2072}2073}20742075if (IsVarLenInst) {2076parseVarLenInstOperand(EncodingDef, InsnOperands, CGI);2077} else {2078// For each operand, see if we can figure out where it is encoded.2079for (const auto &Op : InOutOperands) {2080Init *OpInit = Op.first;2081StringRef OpName = Op.second;20822083// We're ready to find the instruction encoding locations for this2084// operand.20852086// First, find the operand type ("OpInit"), and sub-op names2087// ("SubArgDag") if present.2088DagInit *SubArgDag = dyn_cast<DagInit>(OpInit);2089if (SubArgDag)2090OpInit = SubArgDag->getOperator();2091Record *OpTypeRec = cast<DefInit>(OpInit)->getDef();2092// Lookup the sub-operands from the operand type record (note that only2093// Operand subclasses have MIOperandInfo, see CodeGenInstruction.cpp).2094DagInit *SubOps = OpTypeRec->isSubClassOf("Operand")2095? OpTypeRec->getValueAsDag("MIOperandInfo")2096: nullptr;20972098// Lookup the decoder method and construct a new OperandInfo to hold our2099// result.2100OperandInfo OpInfo = getOpInfo(OpTypeRec);21012102// If we have named sub-operands...2103if (SubArgDag) {2104// Then there should not be a custom decoder specified on the top-level2105// type.2106if (!OpInfo.Decoder.empty()) {2107PrintError(EncodingDef.getLoc(),2108"DecoderEmitter: operand \"" + OpName + "\" has type \"" +2109OpInit->getAsString() +2110"\" with a custom DecoderMethod, but also named "2111"sub-operands.");2112continue;2113}21142115// Decode each of the sub-ops separately.2116assert(SubOps && SubArgDag->getNumArgs() == SubOps->getNumArgs());2117for (const auto &[I, Arg] : enumerate(SubOps->getArgs())) {2118StringRef SubOpName = SubArgDag->getArgNameStr(I);2119OperandInfo SubOpInfo = getOpInfo(cast<DefInit>(Arg)->getDef());21202121addOneOperandFields(EncodingDef, Bits, TiedNames, SubOpName,2122SubOpInfo);2123InsnOperands.push_back(SubOpInfo);2124}2125continue;2126}21272128// Otherwise, if we have an operand with sub-operands, but they aren't2129// named...2130if (SubOps && OpInfo.Decoder.empty()) {2131// If it's a single sub-operand, and no custom decoder, use the decoder2132// from the one sub-operand.2133if (SubOps->getNumArgs() == 1)2134OpInfo = getOpInfo(cast<DefInit>(SubOps->getArg(0))->getDef());21352136// If we have multiple sub-ops, there'd better have a custom2137// decoder. (Otherwise we don't know how to populate them properly...)2138if (SubOps->getNumArgs() > 1) {2139PrintError(EncodingDef.getLoc(),2140"DecoderEmitter: operand \"" + OpName +2141"\" uses MIOperandInfo with multiple ops, but doesn't "2142"have a custom decoder!");2143debugDumpRecord(EncodingDef);2144continue;2145}2146}21472148addOneOperandFields(EncodingDef, Bits, TiedNames, OpName, OpInfo);2149// FIXME: it should be an error not to find a definition for a given2150// operand, rather than just failing to add it to the resulting2151// instruction! (This is a longstanding bug, which will be addressed in an2152// upcoming change.)2153if (OpInfo.numFields() > 0)2154InsnOperands.push_back(OpInfo);2155}2156}2157Operands[Opc] = InsnOperands;21582159#if 02160LLVM_DEBUG({2161// Dumps the instruction encoding bits.2162dumpBits(errs(), Bits);21632164errs() << '\n';21652166// Dumps the list of operand info.2167for (unsigned i = 0, e = CGI.Operands.size(); i != e; ++i) {2168const CGIOperandList::OperandInfo &Info = CGI.Operands[i];2169const std::string &OperandName = Info.Name;2170const Record &OperandDef = *Info.Rec;21712172errs() << "\t" << OperandName << " (" << OperandDef.getName() << ")\n";2173}2174});2175#endif21762177return Bits.getNumBits();2178}21792180// emitFieldFromInstruction - Emit the templated helper function2181// fieldFromInstruction().2182// On Windows we make sure that this function is not inlined when2183// using the VS compiler. It has a bug which causes the function2184// to be optimized out in some circumstances. See llvm.org/pr382922185static void emitFieldFromInstruction(formatted_raw_ostream &OS) {2186OS << R"(2187// Helper functions for extracting fields from encoded instructions.2188// InsnType must either be integral or an APInt-like object that must:2189// * be default-constructible and copy-constructible2190// * be constructible from an APInt (this can be private)2191// * Support insertBits(bits, startBit, numBits)2192// * Support extractBitsAsZExtValue(numBits, startBit)2193// * Support the ~, &, ==, and != operators with other objects of the same type2194// * Support the != and bitwise & with uint64_t2195// * Support put (<<) to raw_ostream&2196template <typename InsnType>2197#if defined(_MSC_VER) && !defined(__clang__)2198__declspec(noinline)2199#endif2200static std::enable_if_t<std::is_integral<InsnType>::value, InsnType>2201fieldFromInstruction(const InsnType &insn, unsigned startBit,2202unsigned numBits) {2203assert(startBit + numBits <= 64 && "Cannot support >64-bit extractions!");2204assert(startBit + numBits <= (sizeof(InsnType) * 8) &&2205"Instruction field out of bounds!");2206InsnType fieldMask;2207if (numBits == sizeof(InsnType) * 8)2208fieldMask = (InsnType)(-1LL);2209else2210fieldMask = (((InsnType)1 << numBits) - 1) << startBit;2211return (insn & fieldMask) >> startBit;2212}22132214template <typename InsnType>2215static std::enable_if_t<!std::is_integral<InsnType>::value, uint64_t>2216fieldFromInstruction(const InsnType &insn, unsigned startBit,2217unsigned numBits) {2218return insn.extractBitsAsZExtValue(numBits, startBit);2219}2220)";2221}22222223// emitInsertBits - Emit the templated helper function insertBits().2224static void emitInsertBits(formatted_raw_ostream &OS) {2225OS << R"(2226// Helper function for inserting bits extracted from an encoded instruction into2227// a field.2228template <typename InsnType>2229static std::enable_if_t<std::is_integral<InsnType>::value>2230insertBits(InsnType &field, InsnType bits, unsigned startBit, unsigned numBits) {2231assert(startBit + numBits <= sizeof field * 8);2232field |= (InsnType)bits << startBit;2233}22342235template <typename InsnType>2236static std::enable_if_t<!std::is_integral<InsnType>::value>2237insertBits(InsnType &field, uint64_t bits, unsigned startBit, unsigned numBits) {2238field.insertBits(bits, startBit, numBits);2239}2240)";2241}22422243// emitDecodeInstruction - Emit the templated helper function2244// decodeInstruction().2245static void emitDecodeInstruction(formatted_raw_ostream &OS,2246bool IsVarLenInst) {2247OS << R"(2248template <typename InsnType>2249static DecodeStatus decodeInstruction(const uint8_t DecodeTable[], MCInst &MI,2250InsnType insn, uint64_t Address,2251const MCDisassembler *DisAsm,2252const MCSubtargetInfo &STI)";2253if (IsVarLenInst) {2254OS << ",\n "2255"llvm::function_ref<void(APInt &, uint64_t)> makeUp";2256}2257OS << R"() {2258const FeatureBitset &Bits = STI.getFeatureBits();22592260const uint8_t *Ptr = DecodeTable;2261uint64_t CurFieldValue = 0;2262DecodeStatus S = MCDisassembler::Success;2263while (true) {2264ptrdiff_t Loc = Ptr - DecodeTable;2265switch (*Ptr) {2266default:2267errs() << Loc << ": Unexpected decode table opcode!\n";2268return MCDisassembler::Fail;2269case MCD::OPC_ExtractField: {2270// Decode the start value.2271unsigned Start = decodeULEB128AndIncUnsafe(++Ptr);2272unsigned Len = *Ptr++;)";2273if (IsVarLenInst)2274OS << "\n makeUp(insn, Start + Len);";2275OS << R"(2276CurFieldValue = fieldFromInstruction(insn, Start, Len);2277LLVM_DEBUG(dbgs() << Loc << ": OPC_ExtractField(" << Start << ", "2278<< Len << "): " << CurFieldValue << "\n");2279break;2280}2281case MCD::OPC_FilterValue: {2282// Decode the field value.2283uint64_t Val = decodeULEB128AndIncUnsafe(++Ptr);2284// NumToSkip is a plain 24-bit integer.2285unsigned NumToSkip = *Ptr++;2286NumToSkip |= (*Ptr++) << 8;2287NumToSkip |= (*Ptr++) << 16;22882289// Perform the filter operation.2290if (Val != CurFieldValue)2291Ptr += NumToSkip;2292LLVM_DEBUG(dbgs() << Loc << ": OPC_FilterValue(" << Val << ", " << NumToSkip2293<< "): " << ((Val != CurFieldValue) ? "FAIL:" : "PASS:")2294<< " continuing at " << (Ptr - DecodeTable) << "\n");22952296break;2297}2298case MCD::OPC_CheckField: {2299// Decode the start value.2300unsigned Start = decodeULEB128AndIncUnsafe(++Ptr);2301unsigned Len = *Ptr;)";2302if (IsVarLenInst)2303OS << "\n makeUp(insn, Start + Len);";2304OS << R"(2305uint64_t FieldValue = fieldFromInstruction(insn, Start, Len);2306// Decode the field value.2307unsigned PtrLen = 0;2308uint64_t ExpectedValue = decodeULEB128(++Ptr, &PtrLen);2309Ptr += PtrLen;2310// NumToSkip is a plain 24-bit integer.2311unsigned NumToSkip = *Ptr++;2312NumToSkip |= (*Ptr++) << 8;2313NumToSkip |= (*Ptr++) << 16;23142315// If the actual and expected values don't match, skip.2316if (ExpectedValue != FieldValue)2317Ptr += NumToSkip;2318LLVM_DEBUG(dbgs() << Loc << ": OPC_CheckField(" << Start << ", "2319<< Len << ", " << ExpectedValue << ", " << NumToSkip2320<< "): FieldValue = " << FieldValue << ", ExpectedValue = "2321<< ExpectedValue << ": "2322<< ((ExpectedValue == FieldValue) ? "PASS\n" : "FAIL\n"));2323break;2324}2325case MCD::OPC_CheckPredicate: {2326// Decode the Predicate Index value.2327unsigned PIdx = decodeULEB128AndIncUnsafe(++Ptr);2328// NumToSkip is a plain 24-bit integer.2329unsigned NumToSkip = *Ptr++;2330NumToSkip |= (*Ptr++) << 8;2331NumToSkip |= (*Ptr++) << 16;2332// Check the predicate.2333bool Pred;2334if (!(Pred = checkDecoderPredicate(PIdx, Bits)))2335Ptr += NumToSkip;2336(void)Pred;2337LLVM_DEBUG(dbgs() << Loc << ": OPC_CheckPredicate(" << PIdx << "): "2338<< (Pred ? "PASS\n" : "FAIL\n"));23392340break;2341}2342case MCD::OPC_Decode: {2343// Decode the Opcode value.2344unsigned Opc = decodeULEB128AndIncUnsafe(++Ptr);2345unsigned DecodeIdx = decodeULEB128AndIncUnsafe(Ptr);23462347MI.clear();2348MI.setOpcode(Opc);2349bool DecodeComplete;)";2350if (IsVarLenInst) {2351OS << "\n unsigned Len = InstrLenTable[Opc];\n"2352<< " makeUp(insn, Len);";2353}2354OS << R"(2355S = decodeToMCInst(S, DecodeIdx, insn, MI, Address, DisAsm, DecodeComplete);2356assert(DecodeComplete);23572358LLVM_DEBUG(dbgs() << Loc << ": OPC_Decode: opcode " << Opc2359<< ", using decoder " << DecodeIdx << ": "2360<< (S != MCDisassembler::Fail ? "PASS" : "FAIL") << "\n");2361return S;2362}2363case MCD::OPC_TryDecode: {2364// Decode the Opcode value.2365unsigned Opc = decodeULEB128AndIncUnsafe(++Ptr);2366unsigned DecodeIdx = decodeULEB128AndIncUnsafe(Ptr);2367// NumToSkip is a plain 24-bit integer.2368unsigned NumToSkip = *Ptr++;2369NumToSkip |= (*Ptr++) << 8;2370NumToSkip |= (*Ptr++) << 16;23712372// Perform the decode operation.2373MCInst TmpMI;2374TmpMI.setOpcode(Opc);2375bool DecodeComplete;2376S = decodeToMCInst(S, DecodeIdx, insn, TmpMI, Address, DisAsm, DecodeComplete);2377LLVM_DEBUG(dbgs() << Loc << ": OPC_TryDecode: opcode " << Opc2378<< ", using decoder " << DecodeIdx << ": ");23792380if (DecodeComplete) {2381// Decoding complete.2382LLVM_DEBUG(dbgs() << (S != MCDisassembler::Fail ? "PASS" : "FAIL") << "\n");2383MI = TmpMI;2384return S;2385} else {2386assert(S == MCDisassembler::Fail);2387// If the decoding was incomplete, skip.2388Ptr += NumToSkip;2389LLVM_DEBUG(dbgs() << "FAIL: continuing at " << (Ptr - DecodeTable) << "\n");2390// Reset decode status. This also drops a SoftFail status that could be2391// set before the decode attempt.2392S = MCDisassembler::Success;2393}2394break;2395}2396case MCD::OPC_SoftFail: {2397// Decode the mask values.2398uint64_t PositiveMask = decodeULEB128AndIncUnsafe(++Ptr);2399uint64_t NegativeMask = decodeULEB128AndIncUnsafe(Ptr);2400bool Fail = (insn & PositiveMask) != 0 || (~insn & NegativeMask) != 0;2401if (Fail)2402S = MCDisassembler::SoftFail;2403LLVM_DEBUG(dbgs() << Loc << ": OPC_SoftFail: " << (Fail ? "FAIL\n" : "PASS\n"));2404break;2405}2406case MCD::OPC_Fail: {2407LLVM_DEBUG(dbgs() << Loc << ": OPC_Fail\n");2408return MCDisassembler::Fail;2409}2410}2411}2412llvm_unreachable("bogosity detected in disassembler state machine!");2413}24142415)";2416}24172418// Helper to propagate SoftFail status. Returns false if the status is Fail;2419// callers are expected to early-exit in that condition. (Note, the '&' operator2420// is correct to propagate the values of this enum; see comment on 'enum2421// DecodeStatus'.)2422static void emitCheck(formatted_raw_ostream &OS) {2423OS << R"(2424static bool Check(DecodeStatus &Out, DecodeStatus In) {2425Out = static_cast<DecodeStatus>(Out & In);2426return Out != MCDisassembler::Fail;2427}24282429)";2430}24312432// Collect all HwModes referenced by the target for encoding purposes,2433// returning a vector of corresponding names.2434static void collectHwModesReferencedForEncodings(2435const CodeGenHwModes &HWM, std::vector<StringRef> &Names,2436NamespacesHwModesMap &NamespacesWithHwModes) {2437SmallBitVector BV(HWM.getNumModeIds());2438for (const auto &MS : HWM.getHwModeSelects()) {2439for (const HwModeSelect::PairType &P : MS.second.Items) {2440if (P.second->isSubClassOf("InstructionEncoding")) {2441std::string DecoderNamespace =2442std::string(P.second->getValueAsString("DecoderNamespace"));2443if (P.first == DefaultMode) {2444NamespacesWithHwModes[DecoderNamespace].insert("");2445} else {2446NamespacesWithHwModes[DecoderNamespace].insert(2447HWM.getMode(P.first).Name);2448}2449BV.set(P.first);2450}2451}2452}2453transform(BV.set_bits(), std::back_inserter(Names), [&HWM](const int &M) {2454if (M == DefaultMode)2455return StringRef("");2456return HWM.getModeName(M, /*IncludeDefault=*/true);2457});2458}24592460static void2461handleHwModesUnrelatedEncodings(const CodeGenInstruction *Instr,2462const std::vector<StringRef> &HwModeNames,2463NamespacesHwModesMap &NamespacesWithHwModes,2464std::vector<EncodingAndInst> &GlobalEncodings) {2465const Record *InstDef = Instr->TheDef;24662467switch (DecoderEmitterSuppressDuplicates) {2468case SUPPRESSION_DISABLE: {2469for (StringRef HwModeName : HwModeNames)2470GlobalEncodings.emplace_back(InstDef, Instr, HwModeName);2471break;2472}2473case SUPPRESSION_LEVEL1: {2474std::string DecoderNamespace =2475std::string(InstDef->getValueAsString("DecoderNamespace"));2476auto It = NamespacesWithHwModes.find(DecoderNamespace);2477if (It != NamespacesWithHwModes.end()) {2478for (StringRef HwModeName : It->second)2479GlobalEncodings.emplace_back(InstDef, Instr, HwModeName);2480} else {2481// Only emit the encoding once, as it's DecoderNamespace doesn't2482// contain any HwModes.2483GlobalEncodings.emplace_back(InstDef, Instr, "");2484}2485break;2486}2487case SUPPRESSION_LEVEL2:2488GlobalEncodings.emplace_back(InstDef, Instr, "");2489break;2490}2491}24922493// Emits disassembler code for instruction decoding.2494void DecoderEmitter::run(raw_ostream &o) {2495formatted_raw_ostream OS(o);2496OS << R"(2497#include "llvm/MC/MCInst.h"2498#include "llvm/MC/MCSubtargetInfo.h"2499#include "llvm/Support/DataTypes.h"2500#include "llvm/Support/Debug.h"2501#include "llvm/Support/LEB128.h"2502#include "llvm/Support/raw_ostream.h"2503#include "llvm/TargetParser/SubtargetFeature.h"2504#include <assert.h>25052506namespace llvm {2507)";25082509emitFieldFromInstruction(OS);2510emitInsertBits(OS);2511emitCheck(OS);25122513Target.reverseBitsForLittleEndianEncoding();25142515// Parameterize the decoders based on namespace and instruction width.25162517// First, collect all encoding-related HwModes referenced by the target.2518// And establish a mapping table between DecoderNamespace and HwMode.2519// If HwModeNames is empty, add the empty string so we always have one HwMode.2520const CodeGenHwModes &HWM = Target.getHwModes();2521std::vector<StringRef> HwModeNames;2522NamespacesHwModesMap NamespacesWithHwModes;2523collectHwModesReferencedForEncodings(HWM, HwModeNames, NamespacesWithHwModes);2524if (HwModeNames.empty())2525HwModeNames.push_back("");25262527const auto &NumberedInstructions = Target.getInstructionsByEnumValue();2528NumberedEncodings.reserve(NumberedInstructions.size());2529for (const auto &NumberedInstruction : NumberedInstructions) {2530const Record *InstDef = NumberedInstruction->TheDef;2531if (const RecordVal *RV = InstDef->getValue("EncodingInfos")) {2532if (DefInit *DI = dyn_cast_or_null<DefInit>(RV->getValue())) {2533EncodingInfoByHwMode EBM(DI->getDef(), HWM);2534for (auto &[ModeId, Encoding] : EBM) {2535// DecoderTables with DefaultMode should not have any suffix.2536if (ModeId == DefaultMode) {2537NumberedEncodings.emplace_back(Encoding, NumberedInstruction, "");2538} else {2539NumberedEncodings.emplace_back(Encoding, NumberedInstruction,2540HWM.getMode(ModeId).Name);2541}2542}2543continue;2544}2545}2546// This instruction is encoded the same on all HwModes.2547// According to user needs, provide varying degrees of suppression.2548handleHwModesUnrelatedEncodings(NumberedInstruction, HwModeNames,2549NamespacesWithHwModes, NumberedEncodings);2550}2551for (const auto &NumberedAlias :2552RK.getAllDerivedDefinitions("AdditionalEncoding"))2553NumberedEncodings.emplace_back(2554NumberedAlias,2555&Target.getInstruction(NumberedAlias->getValueAsDef("AliasOf")));25562557std::map<std::pair<std::string, unsigned>, std::vector<EncodingIDAndOpcode>>2558OpcMap;2559std::map<unsigned, std::vector<OperandInfo>> Operands;2560std::vector<unsigned> InstrLen;2561bool IsVarLenInst = Target.hasVariableLengthEncodings();2562unsigned MaxInstLen = 0;25632564for (const auto &[NEI, NumberedEncoding] : enumerate(NumberedEncodings)) {2565const Record *EncodingDef = NumberedEncoding.EncodingDef;2566const CodeGenInstruction *Inst = NumberedEncoding.Inst;2567const Record *Def = Inst->TheDef;2568unsigned Size = EncodingDef->getValueAsInt("Size");2569if (Def->getValueAsString("Namespace") == "TargetOpcode" ||2570Def->getValueAsBit("isPseudo") ||2571Def->getValueAsBit("isAsmParserOnly") ||2572Def->getValueAsBit("isCodeGenOnly")) {2573NumEncodingsLackingDisasm++;2574continue;2575}25762577if (NEI < NumberedInstructions.size())2578NumInstructions++;2579NumEncodings++;25802581if (!Size && !IsVarLenInst)2582continue;25832584if (IsVarLenInst)2585InstrLen.resize(NumberedInstructions.size(), 0);25862587if (unsigned Len = populateInstruction(Target, *EncodingDef, *Inst, NEI,2588Operands, IsVarLenInst)) {2589if (IsVarLenInst) {2590MaxInstLen = std::max(MaxInstLen, Len);2591InstrLen[NEI] = Len;2592}2593std::string DecoderNamespace =2594std::string(EncodingDef->getValueAsString("DecoderNamespace"));2595if (!NumberedEncoding.HwModeName.empty())2596DecoderNamespace +=2597std::string("_") + NumberedEncoding.HwModeName.str();2598OpcMap[std::pair(DecoderNamespace, Size)].emplace_back(2599NEI, Target.getInstrIntValue(Def));2600} else {2601NumEncodingsOmitted++;2602}2603}26042605DecoderTableInfo TableInfo;2606for (const auto &Opc : OpcMap) {2607// Emit the decoder for this namespace+width combination.2608ArrayRef<EncodingAndInst> NumberedEncodingsRef(NumberedEncodings.data(),2609NumberedEncodings.size());2610FilterChooser FC(NumberedEncodingsRef, Opc.second, Operands,2611IsVarLenInst ? MaxInstLen : 8 * Opc.first.second, this);26122613// The decode table is cleared for each top level decoder function. The2614// predicates and decoders themselves, however, are shared across all2615// decoders to give more opportunities for uniqueing.2616TableInfo.Table.clear();2617TableInfo.FixupStack.clear();2618TableInfo.Table.reserve(16384);2619TableInfo.FixupStack.emplace_back();2620FC.emitTableEntries(TableInfo);2621// Any NumToSkip fixups in the top level scope can resolve to the2622// OPC_Fail at the end of the table.2623assert(TableInfo.FixupStack.size() == 1 && "fixup stack phasing error!");2624// Resolve any NumToSkip fixups in the current scope.2625resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),2626TableInfo.Table.size());2627TableInfo.FixupStack.clear();26282629TableInfo.Table.push_back(MCD::OPC_Fail);26302631// Print the table to the output stream.2632emitTable(OS, TableInfo.Table, 0, FC.getBitWidth(), Opc.first.first,2633Opc.second);2634}26352636// For variable instruction, we emit a instruction length table2637// to let the decoder know how long the instructions are.2638// You can see example usage in M68k's disassembler.2639if (IsVarLenInst)2640emitInstrLenTable(OS, InstrLen);2641// Emit the predicate function.2642emitPredicateFunction(OS, TableInfo.Predicates, 0);26432644// Emit the decoder function.2645emitDecoderFunction(OS, TableInfo.Decoders, 0);26462647// Emit the main entry point for the decoder, decodeInstruction().2648emitDecodeInstruction(OS, IsVarLenInst);26492650OS << "\n} // end namespace llvm\n";2651}26522653namespace llvm {26542655void EmitDecoder(RecordKeeper &RK, raw_ostream &OS,2656const std::string &PredicateNamespace) {2657DecoderEmitter(RK, PredicateNamespace).run(OS);2658}26592660} // end namespace llvm266126622663