Path: blob/main/contrib/llvm-project/llvm/utils/TableGen/DAGISelMatcherGen.cpp
35258 views
//===- DAGISelMatcherGen.cpp - Matcher 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//===----------------------------------------------------------------------===//78#include "Basic/SDNodeProperties.h"9#include "Common/CodeGenDAGPatterns.h"10#include "Common/CodeGenInstruction.h"11#include "Common/CodeGenRegisters.h"12#include "Common/CodeGenTarget.h"13#include "Common/DAGISelMatcher.h"14#include "Common/InfoByHwMode.h"15#include "llvm/ADT/SmallVector.h"16#include "llvm/ADT/StringMap.h"17#include "llvm/TableGen/Error.h"18#include "llvm/TableGen/Record.h"19#include <utility>20using namespace llvm;2122/// getRegisterValueType - Look up and return the ValueType of the specified23/// register. If the register is a member of multiple register classes, they24/// must all have the same type.25static MVT::SimpleValueType getRegisterValueType(Record *R,26const CodeGenTarget &T) {27bool FoundRC = false;28MVT::SimpleValueType VT = MVT::Other;29const CodeGenRegister *Reg = T.getRegBank().getReg(R);3031for (const auto &RC : T.getRegBank().getRegClasses()) {32if (!RC.contains(Reg))33continue;3435if (!FoundRC) {36FoundRC = true;37const ValueTypeByHwMode &VVT = RC.getValueTypeNum(0);38assert(VVT.isSimple());39VT = VVT.getSimple().SimpleTy;40continue;41}4243#ifndef NDEBUG44// If this occurs in multiple register classes, they all have to agree.45const ValueTypeByHwMode &VVT = RC.getValueTypeNum(0);46assert(VVT.isSimple() && VVT.getSimple().SimpleTy == VT &&47"ValueType mismatch between register classes for this register");48#endif49}50return VT;51}5253namespace {54class MatcherGen {55const PatternToMatch &Pattern;56const CodeGenDAGPatterns &CGP;5758/// PatWithNoTypes - This is a clone of Pattern.getSrcPattern() that starts59/// out with all of the types removed. This allows us to insert type checks60/// as we scan the tree.61TreePatternNodePtr PatWithNoTypes;6263/// VariableMap - A map from variable names ('$dst') to the recorded operand64/// number that they were captured as. These are biased by 1 to make65/// insertion easier.66StringMap<unsigned> VariableMap;6768/// This maintains the recorded operand number that OPC_CheckComplexPattern69/// drops each sub-operand into. We don't want to insert these into70/// VariableMap because that leads to identity checking if they are71/// encountered multiple times. Biased by 1 like VariableMap for72/// consistency.73StringMap<unsigned> NamedComplexPatternOperands;7475/// NextRecordedOperandNo - As we emit opcodes to record matched values in76/// the RecordedNodes array, this keeps track of which slot will be next to77/// record into.78unsigned NextRecordedOperandNo;7980/// MatchedChainNodes - This maintains the position in the recorded nodes81/// array of all of the recorded input nodes that have chains.82SmallVector<unsigned, 2> MatchedChainNodes;8384/// MatchedComplexPatterns - This maintains a list of all of the85/// ComplexPatterns that we need to check. The second element of each pair86/// is the recorded operand number of the input node.87SmallVector<std::pair<const TreePatternNode *, unsigned>, 2>88MatchedComplexPatterns;8990/// PhysRegInputs - List list has an entry for each explicitly specified91/// physreg input to the pattern. The first elt is the Register node, the92/// second is the recorded slot number the input pattern match saved it in.93SmallVector<std::pair<Record *, unsigned>, 2> PhysRegInputs;9495/// Matcher - This is the top level of the generated matcher, the result.96Matcher *TheMatcher;9798/// CurPredicate - As we emit matcher nodes, this points to the latest check99/// which should have future checks stuck into its Next position.100Matcher *CurPredicate;101102public:103MatcherGen(const PatternToMatch &pattern, const CodeGenDAGPatterns &cgp);104105bool EmitMatcherCode(unsigned Variant);106void EmitResultCode();107108Matcher *GetMatcher() const { return TheMatcher; }109110private:111void AddMatcher(Matcher *NewNode);112void InferPossibleTypes();113114// Matcher Generation.115void EmitMatchCode(const TreePatternNode &N, TreePatternNode &NodeNoTypes);116void EmitLeafMatchCode(const TreePatternNode &N);117void EmitOperatorMatchCode(const TreePatternNode &N,118TreePatternNode &NodeNoTypes);119120/// If this is the first time a node with unique identifier Name has been121/// seen, record it. Otherwise, emit a check to make sure this is the same122/// node. Returns true if this is the first encounter.123bool recordUniqueNode(ArrayRef<std::string> Names);124125// Result Code Generation.126unsigned getNamedArgumentSlot(StringRef Name) {127unsigned VarMapEntry = VariableMap[Name];128assert(VarMapEntry != 0 &&129"Variable referenced but not defined and not caught earlier!");130return VarMapEntry - 1;131}132133void EmitResultOperand(const TreePatternNode &N,134SmallVectorImpl<unsigned> &ResultOps);135void EmitResultOfNamedOperand(const TreePatternNode &N,136SmallVectorImpl<unsigned> &ResultOps);137void EmitResultLeafAsOperand(const TreePatternNode &N,138SmallVectorImpl<unsigned> &ResultOps);139void EmitResultInstructionAsOperand(const TreePatternNode &N,140SmallVectorImpl<unsigned> &ResultOps);141void EmitResultSDNodeXFormAsOperand(const TreePatternNode &N,142SmallVectorImpl<unsigned> &ResultOps);143};144145} // end anonymous namespace146147MatcherGen::MatcherGen(const PatternToMatch &pattern,148const CodeGenDAGPatterns &cgp)149: Pattern(pattern), CGP(cgp), NextRecordedOperandNo(0), TheMatcher(nullptr),150CurPredicate(nullptr) {151// We need to produce the matcher tree for the patterns source pattern. To152// do this we need to match the structure as well as the types. To do the153// type matching, we want to figure out the fewest number of type checks we154// need to emit. For example, if there is only one integer type supported155// by a target, there should be no type comparisons at all for integer156// patterns!157//158// To figure out the fewest number of type checks needed, clone the pattern,159// remove the types, then perform type inference on the pattern as a whole.160// If there are unresolved types, emit an explicit check for those types,161// apply the type to the tree, then rerun type inference. Iterate until all162// types are resolved.163//164PatWithNoTypes = Pattern.getSrcPattern().clone();165PatWithNoTypes->RemoveAllTypes();166167// If there are types that are manifestly known, infer them.168InferPossibleTypes();169}170171/// InferPossibleTypes - As we emit the pattern, we end up generating type172/// checks and applying them to the 'PatWithNoTypes' tree. As we do this, we173/// want to propagate implied types as far throughout the tree as possible so174/// that we avoid doing redundant type checks. This does the type propagation.175void MatcherGen::InferPossibleTypes() {176// TP - Get *SOME* tree pattern, we don't care which. It is only used for177// diagnostics, which we know are impossible at this point.178TreePattern &TP = *CGP.pf_begin()->second;179180bool MadeChange = true;181while (MadeChange)182MadeChange = PatWithNoTypes->ApplyTypeConstraints(183TP, true /*Ignore reg constraints*/);184}185186/// AddMatcher - Add a matcher node to the current graph we're building.187void MatcherGen::AddMatcher(Matcher *NewNode) {188if (CurPredicate)189CurPredicate->setNext(NewNode);190else191TheMatcher = NewNode;192CurPredicate = NewNode;193}194195//===----------------------------------------------------------------------===//196// Pattern Match Generation197//===----------------------------------------------------------------------===//198199/// EmitLeafMatchCode - Generate matching code for leaf nodes.200void MatcherGen::EmitLeafMatchCode(const TreePatternNode &N) {201assert(N.isLeaf() && "Not a leaf?");202203// Direct match against an integer constant.204if (IntInit *II = dyn_cast<IntInit>(N.getLeafValue())) {205// If this is the root of the dag we're matching, we emit a redundant opcode206// check to ensure that this gets folded into the normal top-level207// OpcodeSwitch.208if (&N == &Pattern.getSrcPattern()) {209const SDNodeInfo &NI = CGP.getSDNodeInfo(CGP.getSDNodeNamed("imm"));210AddMatcher(new CheckOpcodeMatcher(NI));211}212213return AddMatcher(new CheckIntegerMatcher(II->getValue()));214}215216// An UnsetInit represents a named node without any constraints.217if (isa<UnsetInit>(N.getLeafValue())) {218assert(N.hasName() && "Unnamed ? leaf");219return;220}221222DefInit *DI = dyn_cast<DefInit>(N.getLeafValue());223if (!DI) {224errs() << "Unknown leaf kind: " << N << "\n";225abort();226}227228Record *LeafRec = DI->getDef();229230// A ValueType leaf node can represent a register when named, or itself when231// unnamed.232if (LeafRec->isSubClassOf("ValueType")) {233// A named ValueType leaf always matches: (add i32:$a, i32:$b).234if (N.hasName())235return;236// An unnamed ValueType as in (sext_inreg GPR:$foo, i8).237return AddMatcher(new CheckValueTypeMatcher(llvm::getValueType(LeafRec)));238}239240if ( // Handle register references. Nothing to do here, they always match.241LeafRec->isSubClassOf("RegisterClass") ||242LeafRec->isSubClassOf("RegisterOperand") ||243LeafRec->isSubClassOf("PointerLikeRegClass") ||244LeafRec->isSubClassOf("SubRegIndex") ||245// Place holder for SRCVALUE nodes. Nothing to do here.246LeafRec->getName() == "srcvalue")247return;248249// If we have a physreg reference like (mul gpr:$src, EAX) then we need to250// record the register251if (LeafRec->isSubClassOf("Register")) {252AddMatcher(new RecordMatcher("physreg input " + LeafRec->getName().str(),253NextRecordedOperandNo));254PhysRegInputs.push_back(std::pair(LeafRec, NextRecordedOperandNo++));255return;256}257258if (LeafRec->isSubClassOf("CondCode"))259return AddMatcher(new CheckCondCodeMatcher(LeafRec->getName()));260261if (LeafRec->isSubClassOf("ComplexPattern")) {262// We can't model ComplexPattern uses that don't have their name taken yet.263// The OPC_CheckComplexPattern operation implicitly records the results.264if (N.getName().empty()) {265std::string S;266raw_string_ostream OS(S);267OS << "We expect complex pattern uses to have names: " << N;268PrintFatalError(S);269}270271// Remember this ComplexPattern so that we can emit it after all the other272// structural matches are done.273unsigned InputOperand = VariableMap[N.getName()] - 1;274MatchedComplexPatterns.push_back(std::pair(&N, InputOperand));275return;276}277278if (LeafRec->getName() == "immAllOnesV" ||279LeafRec->getName() == "immAllZerosV") {280// If this is the root of the dag we're matching, we emit a redundant opcode281// check to ensure that this gets folded into the normal top-level282// OpcodeSwitch.283if (&N == &Pattern.getSrcPattern()) {284MVT VT = N.getSimpleType(0);285StringRef Name = VT.isScalableVector() ? "splat_vector" : "build_vector";286const SDNodeInfo &NI = CGP.getSDNodeInfo(CGP.getSDNodeNamed(Name));287AddMatcher(new CheckOpcodeMatcher(NI));288}289if (LeafRec->getName() == "immAllOnesV")290AddMatcher(new CheckImmAllOnesVMatcher());291else292AddMatcher(new CheckImmAllZerosVMatcher());293return;294}295296errs() << "Unknown leaf kind: " << N << "\n";297abort();298}299300void MatcherGen::EmitOperatorMatchCode(const TreePatternNode &N,301TreePatternNode &NodeNoTypes) {302assert(!N.isLeaf() && "Not an operator?");303304if (N.getOperator()->isSubClassOf("ComplexPattern")) {305// The "name" of a non-leaf complex pattern (MY_PAT $op1, $op2) is306// "MY_PAT:op1:op2". We should already have validated that the uses are307// consistent.308std::string PatternName = std::string(N.getOperator()->getName());309for (unsigned i = 0; i < N.getNumChildren(); ++i) {310PatternName += ":";311PatternName += N.getChild(i).getName();312}313314if (recordUniqueNode(PatternName)) {315auto NodeAndOpNum = std::pair(&N, NextRecordedOperandNo - 1);316MatchedComplexPatterns.push_back(NodeAndOpNum);317}318319return;320}321322const SDNodeInfo &CInfo = CGP.getSDNodeInfo(N.getOperator());323324// If this is an 'and R, 1234' where the operation is AND/OR and the RHS is325// a constant without a predicate fn that has more than one bit set, handle326// this as a special case. This is usually for targets that have special327// handling of certain large constants (e.g. alpha with it's 8/16/32-bit328// handling stuff). Using these instructions is often far more efficient329// than materializing the constant. Unfortunately, both the instcombiner330// and the dag combiner can often infer that bits are dead, and thus drop331// them from the mask in the dag. For example, it might turn 'AND X, 255'332// into 'AND X, 254' if it knows the low bit is set. Emit code that checks333// to handle this.334if ((N.getOperator()->getName() == "and" ||335N.getOperator()->getName() == "or") &&336N.getChild(1).isLeaf() && N.getChild(1).getPredicateCalls().empty() &&337N.getPredicateCalls().empty()) {338if (IntInit *II = dyn_cast<IntInit>(N.getChild(1).getLeafValue())) {339if (!llvm::has_single_bit<uint32_t>(340II->getValue())) { // Don't bother with single bits.341// If this is at the root of the pattern, we emit a redundant342// CheckOpcode so that the following checks get factored properly under343// a single opcode check.344if (&N == &Pattern.getSrcPattern())345AddMatcher(new CheckOpcodeMatcher(CInfo));346347// Emit the CheckAndImm/CheckOrImm node.348if (N.getOperator()->getName() == "and")349AddMatcher(new CheckAndImmMatcher(II->getValue()));350else351AddMatcher(new CheckOrImmMatcher(II->getValue()));352353// Match the LHS of the AND as appropriate.354AddMatcher(new MoveChildMatcher(0));355EmitMatchCode(N.getChild(0), NodeNoTypes.getChild(0));356AddMatcher(new MoveParentMatcher());357return;358}359}360}361362// Check that the current opcode lines up.363AddMatcher(new CheckOpcodeMatcher(CInfo));364365// If this node has memory references (i.e. is a load or store), tell the366// interpreter to capture them in the memref array.367if (N.NodeHasProperty(SDNPMemOperand, CGP))368AddMatcher(new RecordMemRefMatcher());369370// If this node has a chain, then the chain is operand #0 is the SDNode, and371// the child numbers of the node are all offset by one.372unsigned OpNo = 0;373if (N.NodeHasProperty(SDNPHasChain, CGP)) {374// Record the node and remember it in our chained nodes list.375AddMatcher(new RecordMatcher("'" + N.getOperator()->getName().str() +376"' chained node",377NextRecordedOperandNo));378// Remember all of the input chains our pattern will match.379MatchedChainNodes.push_back(NextRecordedOperandNo++);380381// Don't look at the input chain when matching the tree pattern to the382// SDNode.383OpNo = 1;384385// If this node is not the root and the subtree underneath it produces a386// chain, then the result of matching the node is also produce a chain.387// Beyond that, this means that we're also folding (at least) the root node388// into the node that produce the chain (for example, matching389// "(add reg, (load ptr))" as a add_with_memory on X86). This is390// problematic, if the 'reg' node also uses the load (say, its chain).391// Graphically:392//393// [LD]394// ^ ^395// | \ DAG's like cheese.396// / |397// / [YY]398// | ^399// [XX]--/400//401// It would be invalid to fold XX and LD. In this case, folding the two402// nodes together would induce a cycle in the DAG, making it a 'cyclic DAG'403// To prevent this, we emit a dynamic check for legality before allowing404// this to be folded.405//406const TreePatternNode &Root = Pattern.getSrcPattern();407if (&N != &Root) { // Not the root of the pattern.408// If there is a node between the root and this node, then we definitely409// need to emit the check.410bool NeedCheck = !Root.hasChild(&N);411412// If it *is* an immediate child of the root, we can still need a check if413// the root SDNode has multiple inputs. For us, this means that it is an414// intrinsic, has multiple operands, or has other inputs like chain or415// glue).416if (!NeedCheck) {417const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Root.getOperator());418NeedCheck =419Root.getOperator() == CGP.get_intrinsic_void_sdnode() ||420Root.getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||421Root.getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||422PInfo.getNumOperands() > 1 || PInfo.hasProperty(SDNPHasChain) ||423PInfo.hasProperty(SDNPInGlue) || PInfo.hasProperty(SDNPOptInGlue);424}425426if (NeedCheck)427AddMatcher(new CheckFoldableChainNodeMatcher());428}429}430431// If this node has an output glue and isn't the root, remember it.432if (N.NodeHasProperty(SDNPOutGlue, CGP) && &N != &Pattern.getSrcPattern()) {433// TODO: This redundantly records nodes with both glues and chains.434435// Record the node and remember it in our chained nodes list.436AddMatcher(new RecordMatcher("'" + N.getOperator()->getName().str() +437"' glue output node",438NextRecordedOperandNo));439}440441// If this node is known to have an input glue or if it *might* have an input442// glue, capture it as the glue input of the pattern.443if (N.NodeHasProperty(SDNPOptInGlue, CGP) ||444N.NodeHasProperty(SDNPInGlue, CGP))445AddMatcher(new CaptureGlueInputMatcher());446447for (unsigned i = 0, e = N.getNumChildren(); i != e; ++i, ++OpNo) {448// Get the code suitable for matching this child. Move to the child, check449// it then move back to the parent.450AddMatcher(new MoveChildMatcher(OpNo));451EmitMatchCode(N.getChild(i), NodeNoTypes.getChild(i));452AddMatcher(new MoveParentMatcher());453}454}455456bool MatcherGen::recordUniqueNode(ArrayRef<std::string> Names) {457unsigned Entry = 0;458for (const std::string &Name : Names) {459unsigned &VarMapEntry = VariableMap[Name];460if (!Entry)461Entry = VarMapEntry;462assert(Entry == VarMapEntry);463}464465bool NewRecord = false;466if (Entry == 0) {467// If it is a named node, we must emit a 'Record' opcode.468std::string WhatFor;469for (const std::string &Name : Names) {470if (!WhatFor.empty())471WhatFor += ',';472WhatFor += "$" + Name;473}474AddMatcher(new RecordMatcher(WhatFor, NextRecordedOperandNo));475Entry = ++NextRecordedOperandNo;476NewRecord = true;477} else {478// If we get here, this is a second reference to a specific name. Since479// we already have checked that the first reference is valid, we don't480// have to recursively match it, just check that it's the same as the481// previously named thing.482AddMatcher(new CheckSameMatcher(Entry - 1));483}484485for (const std::string &Name : Names)486VariableMap[Name] = Entry;487488return NewRecord;489}490491void MatcherGen::EmitMatchCode(const TreePatternNode &N,492TreePatternNode &NodeNoTypes) {493// If N and NodeNoTypes don't agree on a type, then this is a case where we494// need to do a type check. Emit the check, apply the type to NodeNoTypes and495// reinfer any correlated types.496SmallVector<unsigned, 2> ResultsToTypeCheck;497498for (unsigned i = 0, e = NodeNoTypes.getNumTypes(); i != e; ++i) {499if (NodeNoTypes.getExtType(i) == N.getExtType(i))500continue;501NodeNoTypes.setType(i, N.getExtType(i));502InferPossibleTypes();503ResultsToTypeCheck.push_back(i);504}505506// If this node has a name associated with it, capture it in VariableMap. If507// we already saw this in the pattern, emit code to verify dagness.508SmallVector<std::string, 4> Names;509if (!N.getName().empty())510Names.push_back(N.getName());511512for (const ScopedName &Name : N.getNamesAsPredicateArg()) {513Names.push_back(514("pred:" + Twine(Name.getScope()) + ":" + Name.getIdentifier()).str());515}516517if (!Names.empty()) {518if (!recordUniqueNode(Names))519return;520}521522if (N.isLeaf())523EmitLeafMatchCode(N);524else525EmitOperatorMatchCode(N, NodeNoTypes);526527// If there are node predicates for this node, generate their checks.528for (unsigned i = 0, e = N.getPredicateCalls().size(); i != e; ++i) {529const TreePredicateCall &Pred = N.getPredicateCalls()[i];530SmallVector<unsigned, 4> Operands;531if (Pred.Fn.usesOperands()) {532TreePattern *TP = Pred.Fn.getOrigPatFragRecord();533for (unsigned i = 0; i < TP->getNumArgs(); ++i) {534std::string Name =535("pred:" + Twine(Pred.Scope) + ":" + TP->getArgName(i)).str();536Operands.push_back(getNamedArgumentSlot(Name));537}538}539AddMatcher(new CheckPredicateMatcher(Pred.Fn, Operands));540}541542for (unsigned i = 0, e = ResultsToTypeCheck.size(); i != e; ++i)543AddMatcher(new CheckTypeMatcher(N.getSimpleType(ResultsToTypeCheck[i]),544ResultsToTypeCheck[i]));545}546547/// EmitMatcherCode - Generate the code that matches the predicate of this548/// pattern for the specified Variant. If the variant is invalid this returns549/// true and does not generate code, if it is valid, it returns false.550bool MatcherGen::EmitMatcherCode(unsigned Variant) {551// If the root of the pattern is a ComplexPattern and if it is specified to552// match some number of root opcodes, these are considered to be our variants.553// Depending on which variant we're generating code for, emit the root opcode554// check.555if (const ComplexPattern *CP =556Pattern.getSrcPattern().getComplexPatternInfo(CGP)) {557const std::vector<Record *> &OpNodes = CP->getRootNodes();558assert(!OpNodes.empty() &&559"Complex Pattern must specify what it can match");560if (Variant >= OpNodes.size())561return true;562563AddMatcher(new CheckOpcodeMatcher(CGP.getSDNodeInfo(OpNodes[Variant])));564} else {565if (Variant != 0)566return true;567}568569// Emit the matcher for the pattern structure and types.570EmitMatchCode(Pattern.getSrcPattern(), *PatWithNoTypes);571572// If the pattern has a predicate on it (e.g. only enabled when a subtarget573// feature is around, do the check).574std::string PredicateCheck = Pattern.getPredicateCheck();575if (!PredicateCheck.empty())576AddMatcher(new CheckPatternPredicateMatcher(PredicateCheck));577578// Now that we've completed the structural type match, emit any ComplexPattern579// checks (e.g. addrmode matches). We emit this after the structural match580// because they are generally more expensive to evaluate and more difficult to581// factor.582for (unsigned i = 0, e = MatchedComplexPatterns.size(); i != e; ++i) {583auto &N = *MatchedComplexPatterns[i].first;584585// Remember where the results of this match get stuck.586if (N.isLeaf()) {587NamedComplexPatternOperands[N.getName()] = NextRecordedOperandNo + 1;588} else {589unsigned CurOp = NextRecordedOperandNo;590for (unsigned i = 0; i < N.getNumChildren(); ++i) {591NamedComplexPatternOperands[N.getChild(i).getName()] = CurOp + 1;592CurOp += N.getChild(i).getNumMIResults(CGP);593}594}595596// Get the slot we recorded the value in from the name on the node.597unsigned RecNodeEntry = MatchedComplexPatterns[i].second;598599const ComplexPattern *CP = N.getComplexPatternInfo(CGP);600assert(CP && "Not a valid ComplexPattern!");601602// Emit a CheckComplexPat operation, which does the match (aborting if it603// fails) and pushes the matched operands onto the recorded nodes list.604AddMatcher(new CheckComplexPatMatcher(*CP, RecNodeEntry, N.getName(),605NextRecordedOperandNo));606607// Record the right number of operands.608NextRecordedOperandNo += CP->getNumOperands();609if (CP->hasProperty(SDNPHasChain)) {610// If the complex pattern has a chain, then we need to keep track of the611// fact that we just recorded a chain input. The chain input will be612// matched as the last operand of the predicate if it was successful.613++NextRecordedOperandNo; // Chained node operand.614615// It is the last operand recorded.616assert(NextRecordedOperandNo > 1 &&617"Should have recorded input/result chains at least!");618MatchedChainNodes.push_back(NextRecordedOperandNo - 1);619}620621// TODO: Complex patterns can't have output glues, if they did, we'd want622// to record them.623}624625return false;626}627628//===----------------------------------------------------------------------===//629// Node Result Generation630//===----------------------------------------------------------------------===//631632void MatcherGen::EmitResultOfNamedOperand(633const TreePatternNode &N, SmallVectorImpl<unsigned> &ResultOps) {634assert(!N.getName().empty() && "Operand not named!");635636if (unsigned SlotNo = NamedComplexPatternOperands[N.getName()]) {637// Complex operands have already been completely selected, just find the638// right slot ant add the arguments directly.639for (unsigned i = 0; i < N.getNumMIResults(CGP); ++i)640ResultOps.push_back(SlotNo - 1 + i);641642return;643}644645unsigned SlotNo = getNamedArgumentSlot(N.getName());646647// If this is an 'imm' or 'fpimm' node, make sure to convert it to the target648// version of the immediate so that it doesn't get selected due to some other649// node use.650if (!N.isLeaf()) {651StringRef OperatorName = N.getOperator()->getName();652if (OperatorName == "imm" || OperatorName == "fpimm") {653AddMatcher(new EmitConvertToTargetMatcher(SlotNo));654ResultOps.push_back(NextRecordedOperandNo++);655return;656}657}658659for (unsigned i = 0; i < N.getNumMIResults(CGP); ++i)660ResultOps.push_back(SlotNo + i);661}662663void MatcherGen::EmitResultLeafAsOperand(const TreePatternNode &N,664SmallVectorImpl<unsigned> &ResultOps) {665assert(N.isLeaf() && "Must be a leaf");666667if (IntInit *II = dyn_cast<IntInit>(N.getLeafValue())) {668AddMatcher(new EmitIntegerMatcher(II->getValue(), N.getSimpleType(0)));669ResultOps.push_back(NextRecordedOperandNo++);670return;671}672673// If this is an explicit register reference, handle it.674if (DefInit *DI = dyn_cast<DefInit>(N.getLeafValue())) {675Record *Def = DI->getDef();676if (Def->isSubClassOf("Register")) {677const CodeGenRegister *Reg = CGP.getTargetInfo().getRegBank().getReg(Def);678AddMatcher(new EmitRegisterMatcher(Reg, N.getSimpleType(0)));679ResultOps.push_back(NextRecordedOperandNo++);680return;681}682683if (Def->getName() == "zero_reg") {684AddMatcher(new EmitRegisterMatcher(nullptr, N.getSimpleType(0)));685ResultOps.push_back(NextRecordedOperandNo++);686return;687}688689if (Def->getName() == "undef_tied_input") {690MVT::SimpleValueType ResultVT = N.getSimpleType(0);691auto IDOperandNo = NextRecordedOperandNo++;692Record *ImpDef = Def->getRecords().getDef("IMPLICIT_DEF");693CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(ImpDef);694AddMatcher(new EmitNodeMatcher(II, ResultVT, std::nullopt, false, false,695false, false, -1, IDOperandNo));696ResultOps.push_back(IDOperandNo);697return;698}699700// Handle a reference to a register class. This is used701// in COPY_TO_SUBREG instructions.702if (Def->isSubClassOf("RegisterOperand"))703Def = Def->getValueAsDef("RegClass");704if (Def->isSubClassOf("RegisterClass")) {705// If the register class has an enum integer value greater than 127, the706// encoding overflows the limit of 7 bits, which precludes the use of707// StringIntegerMatcher. In this case, fallback to using IntegerMatcher.708const CodeGenRegisterClass &RC =709CGP.getTargetInfo().getRegisterClass(Def);710if (RC.EnumValue <= 127) {711std::string Value = RC.getQualifiedIdName();712AddMatcher(new EmitStringIntegerMatcher(Value, MVT::i32));713ResultOps.push_back(NextRecordedOperandNo++);714} else {715AddMatcher(new EmitIntegerMatcher(RC.EnumValue, MVT::i32));716ResultOps.push_back(NextRecordedOperandNo++);717}718return;719}720721// Handle a subregister index. This is used for INSERT_SUBREG etc.722if (Def->isSubClassOf("SubRegIndex")) {723const CodeGenRegBank &RB = CGP.getTargetInfo().getRegBank();724// If we have more than 127 subreg indices the encoding can overflow725// 7 bit and we cannot use StringInteger.726if (RB.getSubRegIndices().size() > 127) {727const CodeGenSubRegIndex *I = RB.findSubRegIdx(Def);728assert(I && "Cannot find subreg index by name!");729if (I->EnumValue > 127) {730AddMatcher(new EmitIntegerMatcher(I->EnumValue, MVT::i32));731ResultOps.push_back(NextRecordedOperandNo++);732return;733}734}735std::string Value = getQualifiedName(Def);736AddMatcher(new EmitStringIntegerMatcher(Value, MVT::i32));737ResultOps.push_back(NextRecordedOperandNo++);738return;739}740}741742errs() << "unhandled leaf node:\n";743N.dump();744}745746static bool mayInstNodeLoadOrStore(const TreePatternNode &N,747const CodeGenDAGPatterns &CGP) {748Record *Op = N.getOperator();749const CodeGenTarget &CGT = CGP.getTargetInfo();750CodeGenInstruction &II = CGT.getInstruction(Op);751return II.mayLoad || II.mayStore;752}753754static unsigned numNodesThatMayLoadOrStore(const TreePatternNode &N,755const CodeGenDAGPatterns &CGP) {756if (N.isLeaf())757return 0;758759Record *OpRec = N.getOperator();760if (!OpRec->isSubClassOf("Instruction"))761return 0;762763unsigned Count = 0;764if (mayInstNodeLoadOrStore(N, CGP))765++Count;766767for (unsigned i = 0, e = N.getNumChildren(); i != e; ++i)768Count += numNodesThatMayLoadOrStore(N.getChild(i), CGP);769770return Count;771}772773void MatcherGen::EmitResultInstructionAsOperand(774const TreePatternNode &N, SmallVectorImpl<unsigned> &OutputOps) {775Record *Op = N.getOperator();776const CodeGenTarget &CGT = CGP.getTargetInfo();777CodeGenInstruction &II = CGT.getInstruction(Op);778const DAGInstruction &Inst = CGP.getInstruction(Op);779780bool isRoot = &N == &Pattern.getDstPattern();781782// TreeHasOutGlue - True if this tree has glue.783bool TreeHasInGlue = false, TreeHasOutGlue = false;784if (isRoot) {785const TreePatternNode &SrcPat = Pattern.getSrcPattern();786TreeHasInGlue = SrcPat.TreeHasProperty(SDNPOptInGlue, CGP) ||787SrcPat.TreeHasProperty(SDNPInGlue, CGP);788789// FIXME2: this is checking the entire pattern, not just the node in790// question, doing this just for the root seems like a total hack.791TreeHasOutGlue = SrcPat.TreeHasProperty(SDNPOutGlue, CGP);792}793794// NumResults - This is the number of results produced by the instruction in795// the "outs" list.796unsigned NumResults = Inst.getNumResults();797798// Number of operands we know the output instruction must have. If it is799// variadic, we could have more operands.800unsigned NumFixedOperands = II.Operands.size();801802SmallVector<unsigned, 8> InstOps;803804// Loop over all of the fixed operands of the instruction pattern, emitting805// code to fill them all in. The node 'N' usually has number children equal to806// the number of input operands of the instruction. However, in cases where807// there are predicate operands for an instruction, we need to fill in the808// 'execute always' values. Match up the node operands to the instruction809// operands to do this.810unsigned ChildNo = 0;811812// Similarly to the code in TreePatternNode::ApplyTypeConstraints, count the813// number of operands at the end of the list which have default values.814// Those can come from the pattern if it provides enough arguments, or be815// filled in with the default if the pattern hasn't provided them. But any816// operand with a default value _before_ the last mandatory one will be817// filled in with their defaults unconditionally.818unsigned NonOverridableOperands = NumFixedOperands;819while (NonOverridableOperands > NumResults &&820CGP.operandHasDefault(II.Operands[NonOverridableOperands - 1].Rec))821--NonOverridableOperands;822823for (unsigned InstOpNo = NumResults, e = NumFixedOperands; InstOpNo != e;824++InstOpNo) {825// Determine what to emit for this operand.826Record *OperandNode = II.Operands[InstOpNo].Rec;827if (CGP.operandHasDefault(OperandNode) &&828(InstOpNo < NonOverridableOperands || ChildNo >= N.getNumChildren())) {829// This is a predicate or optional def operand which the pattern has not830// overridden, or which we aren't letting it override; emit the 'default831// ops' operands.832const DAGDefaultOperand &DefaultOp = CGP.getDefaultOperand(OperandNode);833for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i)834EmitResultOperand(*DefaultOp.DefaultOps[i], InstOps);835continue;836}837838// Otherwise this is a normal operand or a predicate operand without839// 'execute always'; emit it.840841// For operands with multiple sub-operands we may need to emit842// multiple child patterns to cover them all. However, ComplexPattern843// children may themselves emit multiple MI operands.844unsigned NumSubOps = 1;845if (OperandNode->isSubClassOf("Operand")) {846DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");847if (unsigned NumArgs = MIOpInfo->getNumArgs())848NumSubOps = NumArgs;849}850851unsigned FinalNumOps = InstOps.size() + NumSubOps;852while (InstOps.size() < FinalNumOps) {853const TreePatternNode &Child = N.getChild(ChildNo);854unsigned BeforeAddingNumOps = InstOps.size();855EmitResultOperand(Child, InstOps);856assert(InstOps.size() > BeforeAddingNumOps && "Didn't add any operands");857858// If the operand is an instruction and it produced multiple results, just859// take the first one.860if (!Child.isLeaf() && Child.getOperator()->isSubClassOf("Instruction"))861InstOps.resize(BeforeAddingNumOps + 1);862863++ChildNo;864}865}866867// If this is a variadic output instruction (i.e. REG_SEQUENCE), we can't868// expand suboperands, use default operands, or other features determined from869// the CodeGenInstruction after the fixed operands, which were handled870// above. Emit the remaining instructions implicitly added by the use for871// variable_ops.872if (II.Operands.isVariadic) {873for (unsigned I = ChildNo, E = N.getNumChildren(); I < E; ++I)874EmitResultOperand(N.getChild(I), InstOps);875}876877// If this node has input glue or explicitly specified input physregs, we878// need to add chained and glued copyfromreg nodes and materialize the glue879// input.880if (isRoot && !PhysRegInputs.empty()) {881// Emit all of the CopyToReg nodes for the input physical registers. These882// occur in patterns like (mul:i8 AL:i8, GR8:i8:$src).883for (unsigned i = 0, e = PhysRegInputs.size(); i != e; ++i) {884const CodeGenRegister *Reg =885CGP.getTargetInfo().getRegBank().getReg(PhysRegInputs[i].first);886AddMatcher(new EmitCopyToRegMatcher(PhysRegInputs[i].second, Reg));887}888889// Even if the node has no other glue inputs, the resultant node must be890// glued to the CopyFromReg nodes we just generated.891TreeHasInGlue = true;892}893894// Result order: node results, chain, glue895896// Determine the result types.897SmallVector<MVT::SimpleValueType, 4> ResultVTs;898for (unsigned i = 0, e = N.getNumTypes(); i != e; ++i)899ResultVTs.push_back(N.getSimpleType(i));900901// If this is the root instruction of a pattern that has physical registers in902// its result pattern, add output VTs for them. For example, X86 has:903// (set AL, (mul ...))904// This also handles implicit results like:905// (implicit EFLAGS)906if (isRoot && !Pattern.getDstRegs().empty()) {907// If the root came from an implicit def in the instruction handling stuff,908// don't re-add it.909Record *HandledReg = nullptr;910if (II.HasOneImplicitDefWithKnownVT(CGT) != MVT::Other)911HandledReg = II.ImplicitDefs[0];912913for (Record *Reg : Pattern.getDstRegs()) {914if (!Reg->isSubClassOf("Register") || Reg == HandledReg)915continue;916ResultVTs.push_back(getRegisterValueType(Reg, CGT));917}918}919920// If this is the root of the pattern and the pattern we're matching includes921// a node that is variadic, mark the generated node as variadic so that it922// gets the excess operands from the input DAG.923int NumFixedArityOperands = -1;924if (isRoot && Pattern.getSrcPattern().NodeHasProperty(SDNPVariadic, CGP))925NumFixedArityOperands = Pattern.getSrcPattern().getNumChildren();926927// If this is the root node and multiple matched nodes in the input pattern928// have MemRefs in them, have the interpreter collect them and plop them onto929// this node. If there is just one node with MemRefs, leave them on that node930// even if it is not the root.931//932// FIXME3: This is actively incorrect for result patterns with multiple933// memory-referencing instructions.934bool PatternHasMemOperands =935Pattern.getSrcPattern().TreeHasProperty(SDNPMemOperand, CGP);936937bool NodeHasMemRefs = false;938if (PatternHasMemOperands) {939unsigned NumNodesThatLoadOrStore =940numNodesThatMayLoadOrStore(Pattern.getDstPattern(), CGP);941bool NodeIsUniqueLoadOrStore =942mayInstNodeLoadOrStore(N, CGP) && NumNodesThatLoadOrStore == 1;943NodeHasMemRefs =944NodeIsUniqueLoadOrStore || (isRoot && (mayInstNodeLoadOrStore(N, CGP) ||945NumNodesThatLoadOrStore != 1));946}947948// Determine whether we need to attach a chain to this node.949bool NodeHasChain = false;950if (Pattern.getSrcPattern().TreeHasProperty(SDNPHasChain, CGP)) {951// For some instructions, we were able to infer from the pattern whether952// they should have a chain. Otherwise, attach the chain to the root.953//954// FIXME2: This is extremely dubious for several reasons, not the least of955// which it gives special status to instructions with patterns that Pat<>956// nodes can't duplicate.957if (II.hasChain_Inferred)958NodeHasChain = II.hasChain;959else960NodeHasChain = isRoot;961// Instructions which load and store from memory should have a chain,962// regardless of whether they happen to have a pattern saying so.963if (II.hasCtrlDep || II.mayLoad || II.mayStore || II.canFoldAsLoad ||964II.hasSideEffects)965NodeHasChain = true;966}967968assert((!ResultVTs.empty() || TreeHasOutGlue || NodeHasChain) &&969"Node has no result");970971AddMatcher(new EmitNodeMatcher(II, ResultVTs, InstOps, NodeHasChain,972TreeHasInGlue, TreeHasOutGlue, NodeHasMemRefs,973NumFixedArityOperands, NextRecordedOperandNo));974975// The non-chain and non-glue results of the newly emitted node get recorded.976for (unsigned i = 0, e = ResultVTs.size(); i != e; ++i) {977if (ResultVTs[i] == MVT::Other || ResultVTs[i] == MVT::Glue)978break;979OutputOps.push_back(NextRecordedOperandNo++);980}981}982983void MatcherGen::EmitResultSDNodeXFormAsOperand(984const TreePatternNode &N, SmallVectorImpl<unsigned> &ResultOps) {985assert(N.getOperator()->isSubClassOf("SDNodeXForm") && "Not SDNodeXForm?");986987// Emit the operand.988SmallVector<unsigned, 8> InputOps;989990// FIXME2: Could easily generalize this to support multiple inputs and outputs991// to the SDNodeXForm. For now we just support one input and one output like992// the old instruction selector.993assert(N.getNumChildren() == 1);994EmitResultOperand(N.getChild(0), InputOps);995996// The input currently must have produced exactly one result.997assert(InputOps.size() == 1 && "Unexpected input to SDNodeXForm");998999AddMatcher(new EmitNodeXFormMatcher(InputOps[0], N.getOperator()));1000ResultOps.push_back(NextRecordedOperandNo++);1001}10021003void MatcherGen::EmitResultOperand(const TreePatternNode &N,1004SmallVectorImpl<unsigned> &ResultOps) {1005// This is something selected from the pattern we matched.1006if (!N.getName().empty())1007return EmitResultOfNamedOperand(N, ResultOps);10081009if (N.isLeaf())1010return EmitResultLeafAsOperand(N, ResultOps);10111012Record *OpRec = N.getOperator();1013if (OpRec->isSubClassOf("Instruction"))1014return EmitResultInstructionAsOperand(N, ResultOps);1015if (OpRec->isSubClassOf("SDNodeXForm"))1016return EmitResultSDNodeXFormAsOperand(N, ResultOps);1017errs() << "Unknown result node to emit code for: " << N << '\n';1018PrintFatalError("Unknown node in result pattern!");1019}10201021void MatcherGen::EmitResultCode() {1022// Patterns that match nodes with (potentially multiple) chain inputs have to1023// merge them together into a token factor. This informs the generated code1024// what all the chained nodes are.1025if (!MatchedChainNodes.empty())1026AddMatcher(new EmitMergeInputChainsMatcher(MatchedChainNodes));10271028// Codegen the root of the result pattern, capturing the resulting values.1029SmallVector<unsigned, 8> Ops;1030EmitResultOperand(Pattern.getDstPattern(), Ops);10311032// At this point, we have however many values the result pattern produces.1033// However, the input pattern might not need all of these. If there are1034// excess values at the end (such as implicit defs of condition codes etc)1035// just lop them off. This doesn't need to worry about glue or chains, just1036// explicit results.1037//1038unsigned NumSrcResults = Pattern.getSrcPattern().getNumTypes();10391040// If the pattern also has (implicit) results, count them as well.1041if (!Pattern.getDstRegs().empty()) {1042// If the root came from an implicit def in the instruction handling stuff,1043// don't re-add it.1044Record *HandledReg = nullptr;1045const TreePatternNode &DstPat = Pattern.getDstPattern();1046if (!DstPat.isLeaf() && DstPat.getOperator()->isSubClassOf("Instruction")) {1047const CodeGenTarget &CGT = CGP.getTargetInfo();1048CodeGenInstruction &II = CGT.getInstruction(DstPat.getOperator());10491050if (II.HasOneImplicitDefWithKnownVT(CGT) != MVT::Other)1051HandledReg = II.ImplicitDefs[0];1052}10531054for (Record *Reg : Pattern.getDstRegs()) {1055if (!Reg->isSubClassOf("Register") || Reg == HandledReg)1056continue;1057++NumSrcResults;1058}1059}10601061SmallVector<unsigned, 8> Results(Ops);10621063// Apply result permutation.1064for (unsigned ResNo = 0; ResNo < Pattern.getDstPattern().getNumResults();1065++ResNo) {1066Results[ResNo] = Ops[Pattern.getDstPattern().getResultIndex(ResNo)];1067}10681069Results.resize(NumSrcResults);1070AddMatcher(new CompleteMatchMatcher(Results, Pattern));1071}10721073/// ConvertPatternToMatcher - Create the matcher for the specified pattern with1074/// the specified variant. If the variant number is invalid, this returns null.1075Matcher *llvm::ConvertPatternToMatcher(const PatternToMatch &Pattern,1076unsigned Variant,1077const CodeGenDAGPatterns &CGP) {1078MatcherGen Gen(Pattern, CGP);10791080// Generate the code for the matcher.1081if (Gen.EmitMatcherCode(Variant))1082return nullptr;10831084// FIXME2: Kill extra MoveParent commands at the end of the matcher sequence.1085// FIXME2: Split result code out to another table, and make the matcher end1086// with an "Emit <index>" command. This allows result generation stuff to be1087// shared and factored?10881089// If the match succeeds, then we generate Pattern.1090Gen.EmitResultCode();10911092// Unconditional match.1093return Gen.GetMatcher();1094}109510961097