Path: blob/main/contrib/llvm-project/llvm/utils/TableGen/CompressInstEmitter.cpp
35258 views
//===-------- CompressInstEmitter.cpp - Generator for Compression ---------===//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// CompressInstEmitter implements a tablegen-driven CompressPat based7// Instruction Compression mechanism.8//9//===----------------------------------------------------------------------===//10//11// CompressInstEmitter implements a tablegen-driven CompressPat Instruction12// Compression mechanism for generating compressed instructions from the13// expanded instruction form.1415// This tablegen backend processes CompressPat declarations in a16// td file and generates all the required checks to validate the pattern17// declarations; validate the input and output operands to generate the correct18// compressed instructions. The checks include validating different types of19// operands; register operands, immediate operands, fixed register and fixed20// immediate inputs.21//22// Example:23// /// Defines a Pat match between compressed and uncompressed instruction.24// /// The relationship and helper function generation are handled by25// /// CompressInstEmitter backend.26// class CompressPat<dag input, dag output, list<Predicate> predicates = []> {27// /// Uncompressed instruction description.28// dag Input = input;29// /// Compressed instruction description.30// dag Output = output;31// /// Predicates that must be true for this to match.32// list<Predicate> Predicates = predicates;33// /// Duplicate match when tied operand is just different.34// bit isCompressOnly = false;35// }36//37// let Predicates = [HasStdExtC] in {38// def : CompressPat<(ADD GPRNoX0:$rs1, GPRNoX0:$rs1, GPRNoX0:$rs2),39// (C_ADD GPRNoX0:$rs1, GPRNoX0:$rs2)>;40// }41//42// The <TargetName>GenCompressInstEmitter.inc is an auto-generated header43// file which exports two functions for compressing/uncompressing MCInst44// instructions, plus some helper functions:45//46// bool compressInst(MCInst &OutInst, const MCInst &MI,47// const MCSubtargetInfo &STI);48//49// bool uncompressInst(MCInst &OutInst, const MCInst &MI,50// const MCSubtargetInfo &STI);51//52// In addition, it exports a function for checking whether53// an instruction is compressable:54//55// bool isCompressibleInst(const MachineInstr& MI,56// const <TargetName>Subtarget &STI);57//58// The clients that include this auto-generated header file and59// invoke these functions can compress an instruction before emitting60// it in the target-specific ASM or ELF streamer or can uncompress61// an instruction before printing it when the expanded instruction62// format aliases is favored.6364//===----------------------------------------------------------------------===//6566#include "Common/CodeGenInstruction.h"67#include "Common/CodeGenRegisters.h"68#include "Common/CodeGenTarget.h"69#include "llvm/ADT/IndexedMap.h"70#include "llvm/ADT/SmallVector.h"71#include "llvm/ADT/StringMap.h"72#include "llvm/Support/Debug.h"73#include "llvm/Support/ErrorHandling.h"74#include "llvm/TableGen/Error.h"75#include "llvm/TableGen/Record.h"76#include "llvm/TableGen/TableGenBackend.h"77#include <set>78#include <vector>79using namespace llvm;8081#define DEBUG_TYPE "compress-inst-emitter"8283namespace {84class CompressInstEmitter {85struct OpData {86enum MapKind { Operand, Imm, Reg };87MapKind Kind;88union {89// Operand number mapped to.90unsigned Operand;91// Integer immediate value.92int64_t Imm;93// Physical register.94Record *Reg;95} Data;96// Tied operand index within the instruction.97int TiedOpIdx = -1;98};99struct CompressPat {100// The source instruction definition.101CodeGenInstruction Source;102// The destination instruction to transform to.103CodeGenInstruction Dest;104// Required target features to enable pattern.105std::vector<Record *> PatReqFeatures;106// Maps operands in the Source Instruction to107// the corresponding Dest instruction operand.108IndexedMap<OpData> SourceOperandMap;109// Maps operands in the Dest Instruction110// to the corresponding Source instruction operand.111IndexedMap<OpData> DestOperandMap;112113bool IsCompressOnly;114CompressPat(CodeGenInstruction &S, CodeGenInstruction &D,115std::vector<Record *> RF, IndexedMap<OpData> &SourceMap,116IndexedMap<OpData> &DestMap, bool IsCompressOnly)117: Source(S), Dest(D), PatReqFeatures(RF), SourceOperandMap(SourceMap),118DestOperandMap(DestMap), IsCompressOnly(IsCompressOnly) {}119};120enum EmitterType { Compress, Uncompress, CheckCompress };121RecordKeeper &Records;122CodeGenTarget Target;123SmallVector<CompressPat, 4> CompressPatterns;124125void addDagOperandMapping(Record *Rec, DagInit *Dag, CodeGenInstruction &Inst,126IndexedMap<OpData> &OperandMap, bool IsSourceInst);127void evaluateCompressPat(Record *Compress);128void emitCompressInstEmitter(raw_ostream &OS, EmitterType EType);129bool validateTypes(Record *SubType, Record *Type, bool IsSourceInst);130bool validateRegister(Record *Reg, Record *RegClass);131void createDagOperandMapping(Record *Rec, StringMap<unsigned> &SourceOperands,132StringMap<unsigned> &DestOperands,133DagInit *SourceDag, DagInit *DestDag,134IndexedMap<OpData> &SourceOperandMap);135136void createInstOperandMapping(Record *Rec, DagInit *SourceDag,137DagInit *DestDag,138IndexedMap<OpData> &SourceOperandMap,139IndexedMap<OpData> &DestOperandMap,140StringMap<unsigned> &SourceOperands,141CodeGenInstruction &DestInst);142143public:144CompressInstEmitter(RecordKeeper &R) : Records(R), Target(R) {}145146void run(raw_ostream &OS);147};148} // End anonymous namespace.149150bool CompressInstEmitter::validateRegister(Record *Reg, Record *RegClass) {151assert(Reg->isSubClassOf("Register") && "Reg record should be a Register");152assert(RegClass->isSubClassOf("RegisterClass") &&153"RegClass record should be a RegisterClass");154const CodeGenRegisterClass &RC = Target.getRegisterClass(RegClass);155const CodeGenRegister *R = Target.getRegisterByName(Reg->getName().lower());156assert((R != nullptr) && "Register not defined!!");157return RC.contains(R);158}159160bool CompressInstEmitter::validateTypes(Record *DagOpType, Record *InstOpType,161bool IsSourceInst) {162if (DagOpType == InstOpType)163return true;164// Only source instruction operands are allowed to not match Input Dag165// operands.166if (!IsSourceInst)167return false;168169if (DagOpType->isSubClassOf("RegisterClass") &&170InstOpType->isSubClassOf("RegisterClass")) {171const CodeGenRegisterClass &RC = Target.getRegisterClass(InstOpType);172const CodeGenRegisterClass &SubRC = Target.getRegisterClass(DagOpType);173return RC.hasSubClass(&SubRC);174}175176// At this point either or both types are not registers, reject the pattern.177if (DagOpType->isSubClassOf("RegisterClass") ||178InstOpType->isSubClassOf("RegisterClass"))179return false;180181// Let further validation happen when compress()/uncompress() functions are182// invoked.183LLVM_DEBUG(dbgs() << (IsSourceInst ? "Input" : "Output")184<< " Dag Operand Type: '" << DagOpType->getName()185<< "' and "186<< "Instruction Operand Type: '" << InstOpType->getName()187<< "' can't be checked at pattern validation time!\n");188return true;189}190191/// The patterns in the Dag contain different types of operands:192/// Register operands, e.g.: GPRC:$rs1; Fixed registers, e.g: X1; Immediate193/// operands, e.g.: simm6:$imm; Fixed immediate operands, e.g.: 0. This function194/// maps Dag operands to its corresponding instruction operands. For register195/// operands and fixed registers it expects the Dag operand type to be contained196/// in the instantiated instruction operand type. For immediate operands and197/// immediates no validation checks are enforced at pattern validation time.198void CompressInstEmitter::addDagOperandMapping(Record *Rec, DagInit *Dag,199CodeGenInstruction &Inst,200IndexedMap<OpData> &OperandMap,201bool IsSourceInst) {202// TiedCount keeps track of the number of operands skipped in Inst203// operands list to get to the corresponding Dag operand. This is204// necessary because the number of operands in Inst might be greater205// than number of operands in the Dag due to how tied operands206// are represented.207unsigned TiedCount = 0;208for (unsigned I = 0, E = Inst.Operands.size(); I != E; ++I) {209int TiedOpIdx = Inst.Operands[I].getTiedRegister();210if (-1 != TiedOpIdx) {211// Set the entry in OperandMap for the tied operand we're skipping.212OperandMap[I].Kind = OperandMap[TiedOpIdx].Kind;213OperandMap[I].Data = OperandMap[TiedOpIdx].Data;214TiedCount++;215continue;216}217if (DefInit *DI = dyn_cast<DefInit>(Dag->getArg(I - TiedCount))) {218if (DI->getDef()->isSubClassOf("Register")) {219// Check if the fixed register belongs to the Register class.220if (!validateRegister(DI->getDef(), Inst.Operands[I].Rec))221PrintFatalError(Rec->getLoc(),222"Error in Dag '" + Dag->getAsString() +223"'Register: '" + DI->getDef()->getName() +224"' is not in register class '" +225Inst.Operands[I].Rec->getName() + "'");226OperandMap[I].Kind = OpData::Reg;227OperandMap[I].Data.Reg = DI->getDef();228continue;229}230// Validate that Dag operand type matches the type defined in the231// corresponding instruction. Operands in the input Dag pattern are232// allowed to be a subclass of the type specified in corresponding233// instruction operand instead of being an exact match.234if (!validateTypes(DI->getDef(), Inst.Operands[I].Rec, IsSourceInst))235PrintFatalError(Rec->getLoc(),236"Error in Dag '" + Dag->getAsString() + "'. Operand '" +237Dag->getArgNameStr(I - TiedCount) + "' has type '" +238DI->getDef()->getName() +239"' which does not match the type '" +240Inst.Operands[I].Rec->getName() +241"' in the corresponding instruction operand!");242243OperandMap[I].Kind = OpData::Operand;244} else if (IntInit *II = dyn_cast<IntInit>(Dag->getArg(I - TiedCount))) {245// Validate that corresponding instruction operand expects an immediate.246if (Inst.Operands[I].Rec->isSubClassOf("RegisterClass"))247PrintFatalError(248Rec->getLoc(),249"Error in Dag '" + Dag->getAsString() + "' Found immediate: '" +250II->getAsString() +251"' but corresponding instruction operand expected a register!");252// No pattern validation check possible for values of fixed immediate.253OperandMap[I].Kind = OpData::Imm;254OperandMap[I].Data.Imm = II->getValue();255LLVM_DEBUG(256dbgs() << " Found immediate '" << II->getValue() << "' at "257<< (IsSourceInst ? "input " : "output ")258<< "Dag. No validation time check possible for values of "259"fixed immediate.\n");260} else261llvm_unreachable("Unhandled CompressPat argument type!");262}263}264265// Verify the Dag operand count is enough to build an instruction.266static bool verifyDagOpCount(CodeGenInstruction &Inst, DagInit *Dag,267bool IsSource) {268if (Dag->getNumArgs() == Inst.Operands.size())269return true;270// Source instructions are non compressed instructions and don't have tied271// operands.272if (IsSource)273PrintFatalError(Inst.TheDef->getLoc(),274"Input operands for Inst '" + Inst.TheDef->getName() +275"' and input Dag operand count mismatch");276// The Dag can't have more arguments than the Instruction.277if (Dag->getNumArgs() > Inst.Operands.size())278PrintFatalError(Inst.TheDef->getLoc(),279"Inst '" + Inst.TheDef->getName() +280"' and Dag operand count mismatch");281282// The Instruction might have tied operands so the Dag might have283// a fewer operand count.284unsigned RealCount = Inst.Operands.size();285for (const auto &Operand : Inst.Operands)286if (Operand.getTiedRegister() != -1)287--RealCount;288289if (Dag->getNumArgs() != RealCount)290PrintFatalError(Inst.TheDef->getLoc(),291"Inst '" + Inst.TheDef->getName() +292"' and Dag operand count mismatch");293return true;294}295296static bool validateArgsTypes(Init *Arg1, Init *Arg2) {297return cast<DefInit>(Arg1)->getDef() == cast<DefInit>(Arg2)->getDef();298}299300// Creates a mapping between the operand name in the Dag (e.g. $rs1) and301// its index in the list of Dag operands and checks that operands with the same302// name have the same types. For example in 'C_ADD $rs1, $rs2' we generate the303// mapping $rs1 --> 0, $rs2 ---> 1. If the operand appears twice in the (tied)304// same Dag we use the last occurrence for indexing.305void CompressInstEmitter::createDagOperandMapping(306Record *Rec, StringMap<unsigned> &SourceOperands,307StringMap<unsigned> &DestOperands, DagInit *SourceDag, DagInit *DestDag,308IndexedMap<OpData> &SourceOperandMap) {309for (unsigned I = 0; I < DestDag->getNumArgs(); ++I) {310// Skip fixed immediates and registers, they were handled in311// addDagOperandMapping.312if ("" == DestDag->getArgNameStr(I))313continue;314DestOperands[DestDag->getArgNameStr(I)] = I;315}316317for (unsigned I = 0; I < SourceDag->getNumArgs(); ++I) {318// Skip fixed immediates and registers, they were handled in319// addDagOperandMapping.320if ("" == SourceDag->getArgNameStr(I))321continue;322323StringMap<unsigned>::iterator It =324SourceOperands.find(SourceDag->getArgNameStr(I));325if (It != SourceOperands.end()) {326// Operand sharing the same name in the Dag should be mapped as tied.327SourceOperandMap[I].TiedOpIdx = It->getValue();328if (!validateArgsTypes(SourceDag->getArg(It->getValue()),329SourceDag->getArg(I)))330PrintFatalError(Rec->getLoc(),331"Input Operand '" + SourceDag->getArgNameStr(I) +332"' has a mismatched tied operand!\n");333}334It = DestOperands.find(SourceDag->getArgNameStr(I));335if (It == DestOperands.end())336PrintFatalError(Rec->getLoc(), "Operand " + SourceDag->getArgNameStr(I) +337" defined in Input Dag but not used in"338" Output Dag!\n");339// Input Dag operand types must match output Dag operand type.340if (!validateArgsTypes(DestDag->getArg(It->getValue()),341SourceDag->getArg(I)))342PrintFatalError(Rec->getLoc(), "Type mismatch between Input and "343"Output Dag operand '" +344SourceDag->getArgNameStr(I) + "'!");345SourceOperands[SourceDag->getArgNameStr(I)] = I;346}347}348349/// Map operand names in the Dag to their index in both corresponding input and350/// output instructions. Validate that operands defined in the input are351/// used in the output pattern while populating the maps.352void CompressInstEmitter::createInstOperandMapping(353Record *Rec, DagInit *SourceDag, DagInit *DestDag,354IndexedMap<OpData> &SourceOperandMap, IndexedMap<OpData> &DestOperandMap,355StringMap<unsigned> &SourceOperands, CodeGenInstruction &DestInst) {356// TiedCount keeps track of the number of operands skipped in Inst357// operands list to get to the corresponding Dag operand.358unsigned TiedCount = 0;359LLVM_DEBUG(dbgs() << " Operand mapping:\n Source Dest\n");360for (unsigned I = 0, E = DestInst.Operands.size(); I != E; ++I) {361int TiedInstOpIdx = DestInst.Operands[I].getTiedRegister();362if (TiedInstOpIdx != -1) {363++TiedCount;364DestOperandMap[I].Data = DestOperandMap[TiedInstOpIdx].Data;365DestOperandMap[I].Kind = DestOperandMap[TiedInstOpIdx].Kind;366if (DestOperandMap[I].Kind == OpData::Operand)367// No need to fill the SourceOperandMap here since it was mapped to368// destination operand 'TiedInstOpIdx' in a previous iteration.369LLVM_DEBUG(dbgs() << " " << DestOperandMap[I].Data.Operand370<< " ====> " << I371<< " Dest operand tied with operand '"372<< TiedInstOpIdx << "'\n");373continue;374}375// Skip fixed immediates and registers, they were handled in376// addDagOperandMapping.377if (DestOperandMap[I].Kind != OpData::Operand)378continue;379380unsigned DagArgIdx = I - TiedCount;381StringMap<unsigned>::iterator SourceOp =382SourceOperands.find(DestDag->getArgNameStr(DagArgIdx));383if (SourceOp == SourceOperands.end())384PrintFatalError(Rec->getLoc(),385"Output Dag operand '" +386DestDag->getArgNameStr(DagArgIdx) +387"' has no matching input Dag operand.");388389assert(DestDag->getArgNameStr(DagArgIdx) ==390SourceDag->getArgNameStr(SourceOp->getValue()) &&391"Incorrect operand mapping detected!\n");392DestOperandMap[I].Data.Operand = SourceOp->getValue();393SourceOperandMap[SourceOp->getValue()].Data.Operand = I;394LLVM_DEBUG(dbgs() << " " << SourceOp->getValue() << " ====> " << I395<< "\n");396}397}398399/// Validates the CompressPattern and create operand mapping.400/// These are the checks to validate a CompressPat pattern declarations.401/// Error out with message under these conditions:402/// - Dag Input opcode is an expanded instruction and Dag Output opcode is a403/// compressed instruction.404/// - Operands in Dag Input must be all used in Dag Output.405/// Register Operand type in Dag Input Type must be contained in the406/// corresponding Source Instruction type.407/// - Register Operand type in Dag Input must be the same as in Dag Ouput.408/// - Register Operand type in Dag Output must be the same as the409/// corresponding Destination Inst type.410/// - Immediate Operand type in Dag Input must be the same as in Dag Ouput.411/// - Immediate Operand type in Dag Ouput must be the same as the corresponding412/// Destination Instruction type.413/// - Fixed register must be contained in the corresponding Source Instruction414/// type.415/// - Fixed register must be contained in the corresponding Destination416/// Instruction type.417/// Warning message printed under these conditions:418/// - Fixed immediate in Dag Input or Dag Ouput cannot be checked at this time419/// and generate warning.420/// - Immediate operand type in Dag Input differs from the corresponding Source421/// Instruction type and generate a warning.422void CompressInstEmitter::evaluateCompressPat(Record *Rec) {423// Validate input Dag operands.424DagInit *SourceDag = Rec->getValueAsDag("Input");425assert(SourceDag && "Missing 'Input' in compress pattern!");426LLVM_DEBUG(dbgs() << "Input: " << *SourceDag << "\n");427428// Checking we are transforming from compressed to uncompressed instructions.429Record *SourceOperator = SourceDag->getOperatorAsDef(Rec->getLoc());430CodeGenInstruction SourceInst(SourceOperator);431verifyDagOpCount(SourceInst, SourceDag, true);432433// Validate output Dag operands.434DagInit *DestDag = Rec->getValueAsDag("Output");435assert(DestDag && "Missing 'Output' in compress pattern!");436LLVM_DEBUG(dbgs() << "Output: " << *DestDag << "\n");437438Record *DestOperator = DestDag->getOperatorAsDef(Rec->getLoc());439CodeGenInstruction DestInst(DestOperator);440verifyDagOpCount(DestInst, DestDag, false);441442if (SourceOperator->getValueAsInt("Size") <=443DestOperator->getValueAsInt("Size"))444PrintFatalError(445Rec->getLoc(),446"Compressed instruction '" + DestOperator->getName() +447"'is not strictly smaller than the uncompressed instruction '" +448SourceOperator->getName() + "' !");449450// Fill the mapping from the source to destination instructions.451452IndexedMap<OpData> SourceOperandMap;453SourceOperandMap.grow(SourceInst.Operands.size());454// Create a mapping between source Dag operands and source Inst operands.455addDagOperandMapping(Rec, SourceDag, SourceInst, SourceOperandMap,456/*IsSourceInst*/ true);457458IndexedMap<OpData> DestOperandMap;459DestOperandMap.grow(DestInst.Operands.size());460// Create a mapping between destination Dag operands and destination Inst461// operands.462addDagOperandMapping(Rec, DestDag, DestInst, DestOperandMap,463/*IsSourceInst*/ false);464465StringMap<unsigned> SourceOperands;466StringMap<unsigned> DestOperands;467createDagOperandMapping(Rec, SourceOperands, DestOperands, SourceDag, DestDag,468SourceOperandMap);469// Create operand mapping between the source and destination instructions.470createInstOperandMapping(Rec, SourceDag, DestDag, SourceOperandMap,471DestOperandMap, SourceOperands, DestInst);472473// Get the target features for the CompressPat.474std::vector<Record *> PatReqFeatures;475std::vector<Record *> RF = Rec->getValueAsListOfDefs("Predicates");476copy_if(RF, std::back_inserter(PatReqFeatures), [](Record *R) {477return R->getValueAsBit("AssemblerMatcherPredicate");478});479480CompressPatterns.push_back(CompressPat(SourceInst, DestInst, PatReqFeatures,481SourceOperandMap, DestOperandMap,482Rec->getValueAsBit("isCompressOnly")));483}484485static void486getReqFeatures(std::set<std::pair<bool, StringRef>> &FeaturesSet,487std::set<std::set<std::pair<bool, StringRef>>> &AnyOfFeatureSets,488const std::vector<Record *> &ReqFeatures) {489for (auto &R : ReqFeatures) {490const DagInit *D = R->getValueAsDag("AssemblerCondDag");491std::string CombineType = D->getOperator()->getAsString();492if (CombineType != "any_of" && CombineType != "all_of")493PrintFatalError(R->getLoc(), "Invalid AssemblerCondDag!");494if (D->getNumArgs() == 0)495PrintFatalError(R->getLoc(), "Invalid AssemblerCondDag!");496bool IsOr = CombineType == "any_of";497std::set<std::pair<bool, StringRef>> AnyOfSet;498499for (auto *Arg : D->getArgs()) {500bool IsNot = false;501if (auto *NotArg = dyn_cast<DagInit>(Arg)) {502if (NotArg->getOperator()->getAsString() != "not" ||503NotArg->getNumArgs() != 1)504PrintFatalError(R->getLoc(), "Invalid AssemblerCondDag!");505Arg = NotArg->getArg(0);506IsNot = true;507}508if (!isa<DefInit>(Arg) ||509!cast<DefInit>(Arg)->getDef()->isSubClassOf("SubtargetFeature"))510PrintFatalError(R->getLoc(), "Invalid AssemblerCondDag!");511if (IsOr)512AnyOfSet.insert({IsNot, cast<DefInit>(Arg)->getDef()->getName()});513else514FeaturesSet.insert({IsNot, cast<DefInit>(Arg)->getDef()->getName()});515}516517if (IsOr)518AnyOfFeatureSets.insert(AnyOfSet);519}520}521522static unsigned getPredicates(DenseMap<const Record *, unsigned> &PredicateMap,523std::vector<const Record *> &Predicates,524Record *Rec, StringRef Name) {525unsigned &Entry = PredicateMap[Rec];526if (Entry)527return Entry;528529if (!Rec->isValueUnset(Name)) {530Predicates.push_back(Rec);531Entry = Predicates.size();532return Entry;533}534535PrintFatalError(Rec->getLoc(), "No " + Name +536" predicate on this operand at all: '" +537Rec->getName() + "'");538return 0;539}540541static void printPredicates(const std::vector<const Record *> &Predicates,542StringRef Name, raw_ostream &OS) {543for (unsigned I = 0; I < Predicates.size(); ++I) {544StringRef Pred = Predicates[I]->getValueAsString(Name);545OS << " case " << I + 1 << ": {\n"546<< " // " << Predicates[I]->getName() << "\n"547<< " " << Pred << "\n"548<< " }\n";549}550}551552static void mergeCondAndCode(raw_ostream &CombinedStream, StringRef CondStr,553StringRef CodeStr) {554// Remove first indentation and last '&&'.555CondStr = CondStr.drop_front(6).drop_back(4);556CombinedStream.indent(4) << "if (" << CondStr << ") {\n";557CombinedStream << CodeStr;558CombinedStream.indent(4) << " return true;\n";559CombinedStream.indent(4) << "} // if\n";560}561562void CompressInstEmitter::emitCompressInstEmitter(raw_ostream &OS,563EmitterType EType) {564Record *AsmWriter = Target.getAsmWriter();565if (!AsmWriter->getValueAsInt("PassSubtarget"))566PrintFatalError(AsmWriter->getLoc(),567"'PassSubtarget' is false. SubTargetInfo object is needed "568"for target features.\n");569570StringRef TargetName = Target.getName();571572// Sort entries in CompressPatterns to handle instructions that can have more573// than one candidate for compression\uncompression, e.g ADD can be574// transformed to a C_ADD or a C_MV. When emitting 'uncompress()' function the575// source and destination are flipped and the sort key needs to change576// accordingly.577llvm::stable_sort(CompressPatterns, [EType](const CompressPat &LHS,578const CompressPat &RHS) {579if (EType == EmitterType::Compress || EType == EmitterType::CheckCompress)580return (LHS.Source.TheDef->getName() < RHS.Source.TheDef->getName());581return (LHS.Dest.TheDef->getName() < RHS.Dest.TheDef->getName());582});583584// A list of MCOperandPredicates for all operands in use, and the reverse map.585std::vector<const Record *> MCOpPredicates;586DenseMap<const Record *, unsigned> MCOpPredicateMap;587// A list of ImmLeaf Predicates for all operands in use, and the reverse map.588std::vector<const Record *> ImmLeafPredicates;589DenseMap<const Record *, unsigned> ImmLeafPredicateMap;590591std::string F;592std::string FH;593raw_string_ostream Func(F);594raw_string_ostream FuncH(FH);595596if (EType == EmitterType::Compress)597OS << "\n#ifdef GEN_COMPRESS_INSTR\n"598<< "#undef GEN_COMPRESS_INSTR\n\n";599else if (EType == EmitterType::Uncompress)600OS << "\n#ifdef GEN_UNCOMPRESS_INSTR\n"601<< "#undef GEN_UNCOMPRESS_INSTR\n\n";602else if (EType == EmitterType::CheckCompress)603OS << "\n#ifdef GEN_CHECK_COMPRESS_INSTR\n"604<< "#undef GEN_CHECK_COMPRESS_INSTR\n\n";605606if (EType == EmitterType::Compress) {607FuncH << "static bool compressInst(MCInst &OutInst,\n";608FuncH.indent(25) << "const MCInst &MI,\n";609FuncH.indent(25) << "const MCSubtargetInfo &STI) {\n";610} else if (EType == EmitterType::Uncompress) {611FuncH << "static bool uncompressInst(MCInst &OutInst,\n";612FuncH.indent(27) << "const MCInst &MI,\n";613FuncH.indent(27) << "const MCSubtargetInfo &STI) {\n";614} else if (EType == EmitterType::CheckCompress) {615FuncH << "static bool isCompressibleInst(const MachineInstr &MI,\n";616FuncH.indent(31) << "const " << TargetName << "Subtarget &STI) {\n";617}618619if (CompressPatterns.empty()) {620OS << FH;621OS.indent(2) << "return false;\n}\n";622if (EType == EmitterType::Compress)623OS << "\n#endif //GEN_COMPRESS_INSTR\n";624else if (EType == EmitterType::Uncompress)625OS << "\n#endif //GEN_UNCOMPRESS_INSTR\n\n";626else if (EType == EmitterType::CheckCompress)627OS << "\n#endif //GEN_CHECK_COMPRESS_INSTR\n\n";628return;629}630631std::string CaseString;632raw_string_ostream CaseStream(CaseString);633StringRef PrevOp;634StringRef CurOp;635CaseStream << " switch (MI.getOpcode()) {\n";636CaseStream << " default: return false;\n";637638bool CompressOrCheck =639EType == EmitterType::Compress || EType == EmitterType::CheckCompress;640bool CompressOrUncompress =641EType == EmitterType::Compress || EType == EmitterType::Uncompress;642std::string ValidatorName =643CompressOrUncompress644? (TargetName + "ValidateMCOperandFor" +645(EType == EmitterType::Compress ? "Compress" : "Uncompress"))646.str()647: "";648649for (auto &CompressPat : CompressPatterns) {650if (EType == EmitterType::Uncompress && CompressPat.IsCompressOnly)651continue;652653std::string CondString;654std::string CodeString;655raw_string_ostream CondStream(CondString);656raw_string_ostream CodeStream(CodeString);657CodeGenInstruction &Source =658CompressOrCheck ? CompressPat.Source : CompressPat.Dest;659CodeGenInstruction &Dest =660CompressOrCheck ? CompressPat.Dest : CompressPat.Source;661IndexedMap<OpData> SourceOperandMap = CompressOrCheck662? CompressPat.SourceOperandMap663: CompressPat.DestOperandMap;664IndexedMap<OpData> &DestOperandMap = CompressOrCheck665? CompressPat.DestOperandMap666: CompressPat.SourceOperandMap;667668CurOp = Source.TheDef->getName();669// Check current and previous opcode to decide to continue or end a case.670if (CurOp != PrevOp) {671if (!PrevOp.empty())672CaseStream.indent(6) << "break;\n } // case " + PrevOp + "\n";673CaseStream.indent(4) << "case " + TargetName + "::" + CurOp + ": {\n";674}675676std::set<std::pair<bool, StringRef>> FeaturesSet;677std::set<std::set<std::pair<bool, StringRef>>> AnyOfFeatureSets;678// Add CompressPat required features.679getReqFeatures(FeaturesSet, AnyOfFeatureSets, CompressPat.PatReqFeatures);680681// Add Dest instruction required features.682std::vector<Record *> ReqFeatures;683std::vector<Record *> RF = Dest.TheDef->getValueAsListOfDefs("Predicates");684copy_if(RF, std::back_inserter(ReqFeatures), [](Record *R) {685return R->getValueAsBit("AssemblerMatcherPredicate");686});687getReqFeatures(FeaturesSet, AnyOfFeatureSets, ReqFeatures);688689// Emit checks for all required features.690for (auto &Op : FeaturesSet) {691StringRef Not = Op.first ? "!" : "";692CondStream.indent(6) << Not << "STI.getFeatureBits()[" << TargetName693<< "::" << Op.second << "]"694<< " &&\n";695}696697// Emit checks for all required feature groups.698for (auto &Set : AnyOfFeatureSets) {699CondStream.indent(6) << "(";700for (auto &Op : Set) {701bool IsLast = &Op == &*Set.rbegin();702StringRef Not = Op.first ? "!" : "";703CondStream << Not << "STI.getFeatureBits()[" << TargetName704<< "::" << Op.second << "]";705if (!IsLast)706CondStream << " || ";707}708CondStream << ") &&\n";709}710711// Start Source Inst operands validation.712unsigned OpNo = 0;713for (OpNo = 0; OpNo < Source.Operands.size(); ++OpNo) {714if (SourceOperandMap[OpNo].TiedOpIdx != -1) {715if (Source.Operands[OpNo].Rec->isSubClassOf("RegisterClass"))716CondStream.indent(6)717<< "(MI.getOperand(" << OpNo << ").isReg()) && (MI.getOperand("718<< SourceOperandMap[OpNo].TiedOpIdx << ").isReg()) &&\n"719<< " (MI.getOperand(" << OpNo720<< ").getReg() == MI.getOperand("721<< SourceOperandMap[OpNo].TiedOpIdx << ").getReg()) &&\n";722else723PrintFatalError("Unexpected tied operand types!\n");724}725// Check for fixed immediates\registers in the source instruction.726switch (SourceOperandMap[OpNo].Kind) {727case OpData::Operand:728// We don't need to do anything for source instruction operand checks.729break;730case OpData::Imm:731CondStream.indent(6)732<< "(MI.getOperand(" << OpNo << ").isImm()) &&\n"733<< " (MI.getOperand(" << OpNo734<< ").getImm() == " << SourceOperandMap[OpNo].Data.Imm << ") &&\n";735break;736case OpData::Reg: {737Record *Reg = SourceOperandMap[OpNo].Data.Reg;738CondStream.indent(6)739<< "(MI.getOperand(" << OpNo << ").isReg()) &&\n"740<< " (MI.getOperand(" << OpNo << ").getReg() == " << TargetName741<< "::" << Reg->getName() << ") &&\n";742break;743}744}745}746CodeStream.indent(6) << "// " << Dest.AsmString << "\n";747if (CompressOrUncompress)748CodeStream.indent(6) << "OutInst.setOpcode(" << TargetName749<< "::" << Dest.TheDef->getName() << ");\n";750OpNo = 0;751for (const auto &DestOperand : Dest.Operands) {752CodeStream.indent(6) << "// Operand: " << DestOperand.Name << "\n";753switch (DestOperandMap[OpNo].Kind) {754case OpData::Operand: {755unsigned OpIdx = DestOperandMap[OpNo].Data.Operand;756// Check that the operand in the Source instruction fits757// the type for the Dest instruction.758if (DestOperand.Rec->isSubClassOf("RegisterClass") ||759DestOperand.Rec->isSubClassOf("RegisterOperand")) {760auto *ClassRec = DestOperand.Rec->isSubClassOf("RegisterClass")761? DestOperand.Rec762: DestOperand.Rec->getValueAsDef("RegClass");763// This is a register operand. Check the register class.764// Don't check register class if this is a tied operand, it was done765// for the operand its tied to.766if (DestOperand.getTiedRegister() == -1)767CondStream.indent(6)768<< "(MI.getOperand(" << OpIdx << ").isReg()) &&\n"769<< " (" << TargetName << "MCRegisterClasses[" << TargetName770<< "::" << ClassRec->getName()771<< "RegClassID].contains(MI.getOperand(" << OpIdx772<< ").getReg())) &&\n";773774if (CompressOrUncompress)775CodeStream.indent(6)776<< "OutInst.addOperand(MI.getOperand(" << OpIdx << "));\n";777} else {778// Handling immediate operands.779if (CompressOrUncompress) {780unsigned Entry =781getPredicates(MCOpPredicateMap, MCOpPredicates, DestOperand.Rec,782"MCOperandPredicate");783CondStream.indent(6)784<< ValidatorName << "("785<< "MI.getOperand(" << OpIdx << "), STI, " << Entry << ") &&\n";786} else {787unsigned Entry =788getPredicates(ImmLeafPredicateMap, ImmLeafPredicates,789DestOperand.Rec, "ImmediateCode");790CondStream.indent(6)791<< "MI.getOperand(" << OpIdx << ").isImm() &&\n";792CondStream.indent(6) << TargetName << "ValidateMachineOperand("793<< "MI.getOperand(" << OpIdx << "), &STI, "794<< Entry << ") &&\n";795}796if (CompressOrUncompress)797CodeStream.indent(6)798<< "OutInst.addOperand(MI.getOperand(" << OpIdx << "));\n";799}800break;801}802case OpData::Imm: {803if (CompressOrUncompress) {804unsigned Entry = getPredicates(MCOpPredicateMap, MCOpPredicates,805DestOperand.Rec, "MCOperandPredicate");806CondStream.indent(6)807<< ValidatorName << "("808<< "MCOperand::createImm(" << DestOperandMap[OpNo].Data.Imm809<< "), STI, " << Entry << ") &&\n";810} else {811unsigned Entry = getPredicates(ImmLeafPredicateMap, ImmLeafPredicates,812DestOperand.Rec, "ImmediateCode");813CondStream.indent(6)814<< TargetName815<< "ValidateMachineOperand(MachineOperand::CreateImm("816<< DestOperandMap[OpNo].Data.Imm << "), &STI, " << Entry817<< ") &&\n";818}819if (CompressOrUncompress)820CodeStream.indent(6) << "OutInst.addOperand(MCOperand::createImm("821<< DestOperandMap[OpNo].Data.Imm << "));\n";822} break;823case OpData::Reg: {824if (CompressOrUncompress) {825// Fixed register has been validated at pattern validation time.826Record *Reg = DestOperandMap[OpNo].Data.Reg;827CodeStream.indent(6)828<< "OutInst.addOperand(MCOperand::createReg(" << TargetName829<< "::" << Reg->getName() << "));\n";830}831} break;832}833++OpNo;834}835if (CompressOrUncompress)836CodeStream.indent(6) << "OutInst.setLoc(MI.getLoc());\n";837mergeCondAndCode(CaseStream, CondString, CodeString);838PrevOp = CurOp;839}840Func << CaseString << "\n";841// Close brace for the last case.842Func.indent(4) << "} // case " << CurOp << "\n";843Func.indent(2) << "} // switch\n";844Func.indent(2) << "return false;\n}\n";845846if (!MCOpPredicates.empty()) {847OS << "static bool " << ValidatorName << "(const MCOperand &MCOp,\n"848<< " const MCSubtargetInfo &STI,\n"849<< " unsigned PredicateIndex) {\n"850<< " switch (PredicateIndex) {\n"851<< " default:\n"852<< " llvm_unreachable(\"Unknown MCOperandPredicate kind\");\n"853<< " break;\n";854855printPredicates(MCOpPredicates, "MCOperandPredicate", OS);856857OS << " }\n"858<< "}\n\n";859}860861if (!ImmLeafPredicates.empty()) {862OS << "static bool " << TargetName863<< "ValidateMachineOperand(const MachineOperand &MO,\n"864<< " const " << TargetName << "Subtarget *Subtarget,\n"865<< " unsigned PredicateIndex) {\n"866<< " int64_t Imm = MO.getImm();\n"867<< " switch (PredicateIndex) {\n"868<< " default:\n"869<< " llvm_unreachable(\"Unknown ImmLeaf Predicate kind\");\n"870<< " break;\n";871872printPredicates(ImmLeafPredicates, "ImmediateCode", OS);873874OS << " }\n"875<< "}\n\n";876}877878OS << FH;879OS << F;880881if (EType == EmitterType::Compress)882OS << "\n#endif //GEN_COMPRESS_INSTR\n";883else if (EType == EmitterType::Uncompress)884OS << "\n#endif //GEN_UNCOMPRESS_INSTR\n\n";885else if (EType == EmitterType::CheckCompress)886OS << "\n#endif //GEN_CHECK_COMPRESS_INSTR\n\n";887}888889void CompressInstEmitter::run(raw_ostream &OS) {890std::vector<Record *> Insts = Records.getAllDerivedDefinitions("CompressPat");891892// Process the CompressPat definitions, validating them as we do so.893for (unsigned I = 0, E = Insts.size(); I != E; ++I)894evaluateCompressPat(Insts[I]);895896// Emit file header.897emitSourceFileHeader("Compress instruction Source Fragment", OS, Records);898// Generate compressInst() function.899emitCompressInstEmitter(OS, EmitterType::Compress);900// Generate uncompressInst() function.901emitCompressInstEmitter(OS, EmitterType::Uncompress);902// Generate isCompressibleInst() function.903emitCompressInstEmitter(OS, EmitterType::CheckCompress);904}905906static TableGen::Emitter::OptClass<CompressInstEmitter>907X("gen-compress-inst-emitter", "Generate compressed instructions.");908909910