#include "CodeGenDAGPatterns.h"
#include "CodeGenInstruction.h"
#include "CodeGenRegisters.h"
#include "DAGISelMatcher.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/TableGen/Error.h"
#include "llvm/TableGen/Record.h"
#include <utility>
using namespace llvm;
static MVT::SimpleValueType getRegisterValueType(Record *R,
const CodeGenTarget &T) {
bool FoundRC = false;
MVT::SimpleValueType VT = MVT::Other;
const CodeGenRegister *Reg = T.getRegBank().getReg(R);
for (const auto &RC : T.getRegBank().getRegClasses()) {
if (!RC.contains(Reg))
continue;
if (!FoundRC) {
FoundRC = true;
const ValueTypeByHwMode &VVT = RC.getValueTypeNum(0);
if (VVT.isSimple())
VT = VVT.getSimple().SimpleTy;
continue;
}
#ifndef NDEBUG
const ValueTypeByHwMode &T = RC.getValueTypeNum(0);
assert((!T.isSimple() || T.getSimple().SimpleTy == VT) &&
"ValueType mismatch between register classes for this register");
#endif
}
return VT;
}
namespace {
class MatcherGen {
const PatternToMatch &Pattern;
const CodeGenDAGPatterns &CGP;
TreePatternNodePtr PatWithNoTypes;
StringMap<unsigned> VariableMap;
StringMap<unsigned> NamedComplexPatternOperands;
unsigned NextRecordedOperandNo;
SmallVector<unsigned, 2> MatchedChainNodes;
SmallVector<std::pair<const TreePatternNode*,
unsigned>, 2> MatchedComplexPatterns;
SmallVector<std::pair<Record*, unsigned>, 2> PhysRegInputs;
Matcher *TheMatcher;
Matcher *CurPredicate;
public:
MatcherGen(const PatternToMatch &pattern, const CodeGenDAGPatterns &cgp);
bool EmitMatcherCode(unsigned Variant);
void EmitResultCode();
Matcher *GetMatcher() const { return TheMatcher; }
private:
void AddMatcher(Matcher *NewNode);
void InferPossibleTypes(unsigned ForceMode);
void EmitMatchCode(const TreePatternNode *N, TreePatternNode *NodeNoTypes,
unsigned ForceMode);
void EmitLeafMatchCode(const TreePatternNode *N);
void EmitOperatorMatchCode(const TreePatternNode *N,
TreePatternNode *NodeNoTypes,
unsigned ForceMode);
bool recordUniqueNode(ArrayRef<std::string> Names);
unsigned getNamedArgumentSlot(StringRef Name) {
unsigned VarMapEntry = VariableMap[Name];
assert(VarMapEntry != 0 &&
"Variable referenced but not defined and not caught earlier!");
return VarMapEntry-1;
}
void EmitResultOperand(const TreePatternNode *N,
SmallVectorImpl<unsigned> &ResultOps);
void EmitResultOfNamedOperand(const TreePatternNode *N,
SmallVectorImpl<unsigned> &ResultOps);
void EmitResultLeafAsOperand(const TreePatternNode *N,
SmallVectorImpl<unsigned> &ResultOps);
void EmitResultInstructionAsOperand(const TreePatternNode *N,
SmallVectorImpl<unsigned> &ResultOps);
void EmitResultSDNodeXFormAsOperand(const TreePatternNode *N,
SmallVectorImpl<unsigned> &ResultOps);
};
}
MatcherGen::MatcherGen(const PatternToMatch &pattern,
const CodeGenDAGPatterns &cgp)
: Pattern(pattern), CGP(cgp), NextRecordedOperandNo(0),
TheMatcher(nullptr), CurPredicate(nullptr) {
PatWithNoTypes = Pattern.getSrcPattern()->clone();
PatWithNoTypes->RemoveAllTypes();
InferPossibleTypes(Pattern.getForceMode());
}
void MatcherGen::InferPossibleTypes(unsigned ForceMode) {
TreePattern &TP = *CGP.pf_begin()->second;
TP.getInfer().CodeGen = true;
TP.getInfer().ForceMode = ForceMode;
bool MadeChange = true;
while (MadeChange)
MadeChange = PatWithNoTypes->ApplyTypeConstraints(TP,
true);
}
void MatcherGen::AddMatcher(Matcher *NewNode) {
if (CurPredicate)
CurPredicate->setNext(NewNode);
else
TheMatcher = NewNode;
CurPredicate = NewNode;
}
void MatcherGen::EmitLeafMatchCode(const TreePatternNode *N) {
assert(N->isLeaf() && "Not a leaf?");
if (IntInit *II = dyn_cast<IntInit>(N->getLeafValue())) {
if (N == Pattern.getSrcPattern()) {
const SDNodeInfo &NI = CGP.getSDNodeInfo(CGP.getSDNodeNamed("imm"));
AddMatcher(new CheckOpcodeMatcher(NI));
}
return AddMatcher(new CheckIntegerMatcher(II->getValue()));
}
if (isa<UnsetInit>(N->getLeafValue())) {
assert(N->hasName() && "Unnamed ? leaf");
return;
}
DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
if (!DI) {
errs() << "Unknown leaf kind: " << *N << "\n";
abort();
}
Record *LeafRec = DI->getDef();
if (LeafRec->isSubClassOf("ValueType")) {
if (N->hasName())
return;
return AddMatcher(new CheckValueTypeMatcher(LeafRec->getName()));
}
if ( LeafRec->isSubClassOf("RegisterClass") ||
LeafRec->isSubClassOf("RegisterOperand") ||
LeafRec->isSubClassOf("PointerLikeRegClass") ||
LeafRec->isSubClassOf("SubRegIndex") ||
LeafRec->getName() == "srcvalue")
return;
if (LeafRec->isSubClassOf("Register")) {
AddMatcher(new RecordMatcher("physreg input "+LeafRec->getName().str(),
NextRecordedOperandNo));
PhysRegInputs.push_back(std::make_pair(LeafRec, NextRecordedOperandNo++));
return;
}
if (LeafRec->isSubClassOf("CondCode"))
return AddMatcher(new CheckCondCodeMatcher(LeafRec->getName()));
if (LeafRec->isSubClassOf("ComplexPattern")) {
if (N->getName().empty()) {
std::string S;
raw_string_ostream OS(S);
OS << "We expect complex pattern uses to have names: " << *N;
PrintFatalError(S);
}
unsigned InputOperand = VariableMap[N->getName()] - 1;
MatchedComplexPatterns.push_back(std::make_pair(N, InputOperand));
return;
}
if (LeafRec->getName() == "immAllOnesV") {
if (N == Pattern.getSrcPattern()) {
MVT VT = N->getSimpleType(0);
StringRef Name = VT.isScalableVector() ? "splat_vector" : "build_vector";
const SDNodeInfo &NI = CGP.getSDNodeInfo(CGP.getSDNodeNamed(Name));
AddMatcher(new CheckOpcodeMatcher(NI));
}
return AddMatcher(new CheckImmAllOnesVMatcher());
}
if (LeafRec->getName() == "immAllZerosV") {
if (N == Pattern.getSrcPattern()) {
MVT VT = N->getSimpleType(0);
StringRef Name = VT.isScalableVector() ? "splat_vector" : "build_vector";
const SDNodeInfo &NI = CGP.getSDNodeInfo(CGP.getSDNodeNamed(Name));
AddMatcher(new CheckOpcodeMatcher(NI));
}
return AddMatcher(new CheckImmAllZerosVMatcher());
}
errs() << "Unknown leaf kind: " << *N << "\n";
abort();
}
void MatcherGen::EmitOperatorMatchCode(const TreePatternNode *N,
TreePatternNode *NodeNoTypes,
unsigned ForceMode) {
assert(!N->isLeaf() && "Not an operator?");
if (N->getOperator()->isSubClassOf("ComplexPattern")) {
std::string PatternName = std::string(N->getOperator()->getName());
for (unsigned i = 0; i < N->getNumChildren(); ++i) {
PatternName += ":";
PatternName += N->getChild(i)->getName();
}
if (recordUniqueNode(PatternName)) {
auto NodeAndOpNum = std::make_pair(N, NextRecordedOperandNo - 1);
MatchedComplexPatterns.push_back(NodeAndOpNum);
}
return;
}
const SDNodeInfo &CInfo = CGP.getSDNodeInfo(N->getOperator());
if ((N->getOperator()->getName() == "and" ||
N->getOperator()->getName() == "or") &&
N->getChild(1)->isLeaf() && N->getChild(1)->getPredicateCalls().empty() &&
N->getPredicateCalls().empty()) {
if (IntInit *II = dyn_cast<IntInit>(N->getChild(1)->getLeafValue())) {
if (!isPowerOf2_32(II->getValue())) { if (N == Pattern.getSrcPattern())
AddMatcher(new CheckOpcodeMatcher(CInfo));
if (N->getOperator()->getName() == "and")
AddMatcher(new CheckAndImmMatcher(II->getValue()));
else
AddMatcher(new CheckOrImmMatcher(II->getValue()));
AddMatcher(new MoveChildMatcher(0));
EmitMatchCode(N->getChild(0), NodeNoTypes->getChild(0), ForceMode);
AddMatcher(new MoveParentMatcher());
return;
}
}
}
AddMatcher(new CheckOpcodeMatcher(CInfo));
if (N->NodeHasProperty(SDNPMemOperand, CGP))
AddMatcher(new RecordMemRefMatcher());
unsigned OpNo = 0;
if (N->NodeHasProperty(SDNPHasChain, CGP)) {
AddMatcher(new RecordMatcher("'" + N->getOperator()->getName().str() +
"' chained node",
NextRecordedOperandNo));
MatchedChainNodes.push_back(NextRecordedOperandNo++);
OpNo = 1;
const TreePatternNode *Root = Pattern.getSrcPattern();
if (N != Root) { bool NeedCheck = !Root->hasChild(N);
if (!NeedCheck) {
const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Root->getOperator());
NeedCheck =
Root->getOperator() == CGP.get_intrinsic_void_sdnode() ||
Root->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
Root->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
PInfo.getNumOperands() > 1 ||
PInfo.hasProperty(SDNPHasChain) ||
PInfo.hasProperty(SDNPInGlue) ||
PInfo.hasProperty(SDNPOptInGlue);
}
if (NeedCheck)
AddMatcher(new CheckFoldableChainNodeMatcher());
}
}
if (N->NodeHasProperty(SDNPOutGlue, CGP) &&
N != Pattern.getSrcPattern()) {
AddMatcher(new RecordMatcher("'" + N->getOperator()->getName().str() +
"' glue output node",
NextRecordedOperandNo));
}
if (N->NodeHasProperty(SDNPOptInGlue, CGP) ||
N->NodeHasProperty(SDNPInGlue, CGP))
AddMatcher(new CaptureGlueInputMatcher());
for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
AddMatcher(new MoveChildMatcher(OpNo));
EmitMatchCode(N->getChild(i), NodeNoTypes->getChild(i), ForceMode);
AddMatcher(new MoveParentMatcher());
}
}
bool MatcherGen::recordUniqueNode(ArrayRef<std::string> Names) {
unsigned Entry = 0;
for (const std::string &Name : Names) {
unsigned &VarMapEntry = VariableMap[Name];
if (!Entry)
Entry = VarMapEntry;
assert(Entry == VarMapEntry);
}
bool NewRecord = false;
if (Entry == 0) {
std::string WhatFor;
for (const std::string &Name : Names) {
if (!WhatFor.empty())
WhatFor += ',';
WhatFor += "$" + Name;
}
AddMatcher(new RecordMatcher(WhatFor, NextRecordedOperandNo));
Entry = ++NextRecordedOperandNo;
NewRecord = true;
} else {
AddMatcher(new CheckSameMatcher(Entry-1));
}
for (const std::string &Name : Names)
VariableMap[Name] = Entry;
return NewRecord;
}
void MatcherGen::EmitMatchCode(const TreePatternNode *N,
TreePatternNode *NodeNoTypes,
unsigned ForceMode) {
SmallVector<unsigned, 2> ResultsToTypeCheck;
for (unsigned i = 0, e = NodeNoTypes->getNumTypes(); i != e; ++i) {
if (NodeNoTypes->getExtType(i) == N->getExtType(i)) continue;
NodeNoTypes->setType(i, N->getExtType(i));
InferPossibleTypes(ForceMode);
ResultsToTypeCheck.push_back(i);
}
SmallVector<std::string, 4> Names;
if (!N->getName().empty())
Names.push_back(N->getName());
for (const ScopedName &Name : N->getNamesAsPredicateArg()) {
Names.push_back(("pred:" + Twine(Name.getScope()) + ":" + Name.getIdentifier()).str());
}
if (!Names.empty()) {
if (!recordUniqueNode(Names))
return;
}
if (N->isLeaf())
EmitLeafMatchCode(N);
else
EmitOperatorMatchCode(N, NodeNoTypes, ForceMode);
for (unsigned i = 0, e = N->getPredicateCalls().size(); i != e; ++i) {
const TreePredicateCall &Pred = N->getPredicateCalls()[i];
SmallVector<unsigned, 4> Operands;
if (Pred.Fn.usesOperands()) {
TreePattern *TP = Pred.Fn.getOrigPatFragRecord();
for (unsigned i = 0; i < TP->getNumArgs(); ++i) {
std::string Name =
("pred:" + Twine(Pred.Scope) + ":" + TP->getArgName(i)).str();
Operands.push_back(getNamedArgumentSlot(Name));
}
}
AddMatcher(new CheckPredicateMatcher(Pred.Fn, Operands));
}
for (unsigned i = 0, e = ResultsToTypeCheck.size(); i != e; ++i)
AddMatcher(new CheckTypeMatcher(N->getSimpleType(ResultsToTypeCheck[i]),
ResultsToTypeCheck[i]));
}
bool MatcherGen::EmitMatcherCode(unsigned Variant) {
if (const ComplexPattern *CP =
Pattern.getSrcPattern()->getComplexPatternInfo(CGP)) {
const std::vector<Record*> &OpNodes = CP->getRootNodes();
assert(!OpNodes.empty() &&"Complex Pattern must specify what it can match");
if (Variant >= OpNodes.size()) return true;
AddMatcher(new CheckOpcodeMatcher(CGP.getSDNodeInfo(OpNodes[Variant])));
} else {
if (Variant != 0) return true;
}
EmitMatchCode(Pattern.getSrcPattern(), PatWithNoTypes.get(),
Pattern.getForceMode());
if (!Pattern.getPredicateCheck().empty())
AddMatcher(new CheckPatternPredicateMatcher(Pattern.getPredicateCheck()));
for (unsigned i = 0, e = MatchedComplexPatterns.size(); i != e; ++i) {
auto N = MatchedComplexPatterns[i].first;
if (N->isLeaf()) {
NamedComplexPatternOperands[N->getName()] = NextRecordedOperandNo + 1;
} else {
unsigned CurOp = NextRecordedOperandNo;
for (unsigned i = 0; i < N->getNumChildren(); ++i) {
NamedComplexPatternOperands[N->getChild(i)->getName()] = CurOp + 1;
CurOp += N->getChild(i)->getNumMIResults(CGP);
}
}
unsigned RecNodeEntry = MatchedComplexPatterns[i].second;
const ComplexPattern &CP = *N->getComplexPatternInfo(CGP);
AddMatcher(new CheckComplexPatMatcher(CP, RecNodeEntry,
N->getName(), NextRecordedOperandNo));
NextRecordedOperandNo += CP.getNumOperands();
if (CP.hasProperty(SDNPHasChain)) {
++NextRecordedOperandNo;
assert(NextRecordedOperandNo > 1 &&
"Should have recorded input/result chains at least!");
MatchedChainNodes.push_back(NextRecordedOperandNo-1);
}
}
return false;
}
void MatcherGen::EmitResultOfNamedOperand(const TreePatternNode *N,
SmallVectorImpl<unsigned> &ResultOps){
assert(!N->getName().empty() && "Operand not named!");
if (unsigned SlotNo = NamedComplexPatternOperands[N->getName()]) {
for (unsigned i = 0; i < N->getNumMIResults(CGP); ++i)
ResultOps.push_back(SlotNo - 1 + i);
return;
}
unsigned SlotNo = getNamedArgumentSlot(N->getName());
if (!N->isLeaf()) {
StringRef OperatorName = N->getOperator()->getName();
if (OperatorName == "imm" || OperatorName == "fpimm") {
AddMatcher(new EmitConvertToTargetMatcher(SlotNo));
ResultOps.push_back(NextRecordedOperandNo++);
return;
}
}
for (unsigned i = 0; i < N->getNumMIResults(CGP); ++i)
ResultOps.push_back(SlotNo + i);
}
void MatcherGen::EmitResultLeafAsOperand(const TreePatternNode *N,
SmallVectorImpl<unsigned> &ResultOps) {
assert(N->isLeaf() && "Must be a leaf");
if (IntInit *II = dyn_cast<IntInit>(N->getLeafValue())) {
AddMatcher(new EmitIntegerMatcher(II->getValue(), N->getSimpleType(0)));
ResultOps.push_back(NextRecordedOperandNo++);
return;
}
if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
Record *Def = DI->getDef();
if (Def->isSubClassOf("Register")) {
const CodeGenRegister *Reg =
CGP.getTargetInfo().getRegBank().getReg(Def);
AddMatcher(new EmitRegisterMatcher(Reg, N->getSimpleType(0)));
ResultOps.push_back(NextRecordedOperandNo++);
return;
}
if (Def->getName() == "zero_reg") {
AddMatcher(new EmitRegisterMatcher(nullptr, N->getSimpleType(0)));
ResultOps.push_back(NextRecordedOperandNo++);
return;
}
if (Def->getName() == "undef_tied_input") {
std::array<MVT::SimpleValueType, 1> ResultVTs = {{ N->getSimpleType(0) }};
std::array<unsigned, 0> InstOps;
auto IDOperandNo = NextRecordedOperandNo++;
AddMatcher(new EmitNodeMatcher("TargetOpcode::IMPLICIT_DEF",
ResultVTs, InstOps, false, false, false,
false, -1, IDOperandNo));
ResultOps.push_back(IDOperandNo);
return;
}
if (Def->isSubClassOf("RegisterOperand"))
Def = Def->getValueAsDef("RegClass");
if (Def->isSubClassOf("RegisterClass")) {
const CodeGenRegisterClass &RC =
CGP.getTargetInfo().getRegisterClass(Def);
if (RC.EnumValue <= 127) {
std::string Value = getQualifiedName(Def) + "RegClassID";
AddMatcher(new EmitStringIntegerMatcher(Value, MVT::i32));
ResultOps.push_back(NextRecordedOperandNo++);
} else {
AddMatcher(new EmitIntegerMatcher(RC.EnumValue, MVT::i32));
ResultOps.push_back(NextRecordedOperandNo++);
}
return;
}
if (Def->isSubClassOf("SubRegIndex")) {
const CodeGenRegBank &RB = CGP.getTargetInfo().getRegBank();
if (RB.getSubRegIndices().size() > 127) {
const CodeGenSubRegIndex *I = RB.findSubRegIdx(Def);
assert(I && "Cannot find subreg index by name!");
if (I->EnumValue > 127) {
AddMatcher(new EmitIntegerMatcher(I->EnumValue, MVT::i32));
ResultOps.push_back(NextRecordedOperandNo++);
return;
}
}
std::string Value = getQualifiedName(Def);
AddMatcher(new EmitStringIntegerMatcher(Value, MVT::i32));
ResultOps.push_back(NextRecordedOperandNo++);
return;
}
}
errs() << "unhandled leaf node:\n";
N->dump();
}
static bool
mayInstNodeLoadOrStore(const TreePatternNode *N,
const CodeGenDAGPatterns &CGP) {
Record *Op = N->getOperator();
const CodeGenTarget &CGT = CGP.getTargetInfo();
CodeGenInstruction &II = CGT.getInstruction(Op);
return II.mayLoad || II.mayStore;
}
static unsigned
numNodesThatMayLoadOrStore(const TreePatternNode *N,
const CodeGenDAGPatterns &CGP) {
if (N->isLeaf())
return 0;
Record *OpRec = N->getOperator();
if (!OpRec->isSubClassOf("Instruction"))
return 0;
unsigned Count = 0;
if (mayInstNodeLoadOrStore(N, CGP))
++Count;
for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Count += numNodesThatMayLoadOrStore(N->getChild(i), CGP);
return Count;
}
void MatcherGen::
EmitResultInstructionAsOperand(const TreePatternNode *N,
SmallVectorImpl<unsigned> &OutputOps) {
Record *Op = N->getOperator();
const CodeGenTarget &CGT = CGP.getTargetInfo();
CodeGenInstruction &II = CGT.getInstruction(Op);
const DAGInstruction &Inst = CGP.getInstruction(Op);
bool isRoot = N == Pattern.getDstPattern();
bool TreeHasInGlue = false, TreeHasOutGlue = false;
if (isRoot) {
const TreePatternNode *SrcPat = Pattern.getSrcPattern();
TreeHasInGlue = SrcPat->TreeHasProperty(SDNPOptInGlue, CGP) ||
SrcPat->TreeHasProperty(SDNPInGlue, CGP);
TreeHasOutGlue = SrcPat->TreeHasProperty(SDNPOutGlue, CGP);
}
unsigned NumResults = Inst.getNumResults();
unsigned NumFixedOperands = II.Operands.size();
SmallVector<unsigned, 8> InstOps;
unsigned ChildNo = 0;
unsigned NonOverridableOperands = NumFixedOperands;
while (NonOverridableOperands > NumResults &&
CGP.operandHasDefault(II.Operands[NonOverridableOperands-1].Rec))
--NonOverridableOperands;
for (unsigned InstOpNo = NumResults, e = NumFixedOperands;
InstOpNo != e; ++InstOpNo) {
Record *OperandNode = II.Operands[InstOpNo].Rec;
if (CGP.operandHasDefault(OperandNode) &&
(InstOpNo < NonOverridableOperands || ChildNo >= N->getNumChildren())) {
const DAGDefaultOperand &DefaultOp
= CGP.getDefaultOperand(OperandNode);
for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i)
EmitResultOperand(DefaultOp.DefaultOps[i].get(), InstOps);
continue;
}
unsigned NumSubOps = 1;
if (OperandNode->isSubClassOf("Operand")) {
DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
if (unsigned NumArgs = MIOpInfo->getNumArgs())
NumSubOps = NumArgs;
}
unsigned FinalNumOps = InstOps.size() + NumSubOps;
while (InstOps.size() < FinalNumOps) {
const TreePatternNode *Child = N->getChild(ChildNo);
unsigned BeforeAddingNumOps = InstOps.size();
EmitResultOperand(Child, InstOps);
assert(InstOps.size() > BeforeAddingNumOps && "Didn't add any operands");
if (!Child->isLeaf() && Child->getOperator()->isSubClassOf("Instruction"))
InstOps.resize(BeforeAddingNumOps+1);
++ChildNo;
}
}
if (II.Operands.isVariadic) {
for (unsigned I = ChildNo, E = N->getNumChildren(); I < E; ++I)
EmitResultOperand(N->getChild(I), InstOps);
}
if (isRoot && !PhysRegInputs.empty()) {
for (unsigned i = 0, e = PhysRegInputs.size(); i != e; ++i) {
const CodeGenRegister *Reg =
CGP.getTargetInfo().getRegBank().getReg(PhysRegInputs[i].first);
AddMatcher(new EmitCopyToRegMatcher(PhysRegInputs[i].second,
Reg));
}
TreeHasInGlue = true;
}
SmallVector<MVT::SimpleValueType, 4> ResultVTs;
for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i)
ResultVTs.push_back(N->getSimpleType(i));
if (isRoot && !Pattern.getDstRegs().empty()) {
Record *HandledReg = nullptr;
if (II.HasOneImplicitDefWithKnownVT(CGT) != MVT::Other)
HandledReg = II.ImplicitDefs[0];
for (Record *Reg : Pattern.getDstRegs()) {
if (!Reg->isSubClassOf("Register") || Reg == HandledReg) continue;
ResultVTs.push_back(getRegisterValueType(Reg, CGT));
}
}
int NumFixedArityOperands = -1;
if (isRoot &&
Pattern.getSrcPattern()->NodeHasProperty(SDNPVariadic, CGP))
NumFixedArityOperands = Pattern.getSrcPattern()->getNumChildren();
bool PatternHasMemOperands =
Pattern.getSrcPattern()->TreeHasProperty(SDNPMemOperand, CGP);
bool NodeHasMemRefs = false;
if (PatternHasMemOperands) {
unsigned NumNodesThatLoadOrStore =
numNodesThatMayLoadOrStore(Pattern.getDstPattern(), CGP);
bool NodeIsUniqueLoadOrStore = mayInstNodeLoadOrStore(N, CGP) &&
NumNodesThatLoadOrStore == 1;
NodeHasMemRefs =
NodeIsUniqueLoadOrStore || (isRoot && (mayInstNodeLoadOrStore(N, CGP) ||
NumNodesThatLoadOrStore != 1));
}
bool NodeHasChain = false;
if (Pattern.getSrcPattern()->TreeHasProperty(SDNPHasChain, CGP)) {
if (II.hasChain_Inferred)
NodeHasChain = II.hasChain;
else
NodeHasChain = isRoot;
if (II.hasCtrlDep || II.mayLoad || II.mayStore || II.canFoldAsLoad ||
II.hasSideEffects)
NodeHasChain = true;
}
assert((!ResultVTs.empty() || TreeHasOutGlue || NodeHasChain) &&
"Node has no result");
AddMatcher(new EmitNodeMatcher(II.Namespace.str()+"::"+II.TheDef->getName().str(),
ResultVTs, InstOps,
NodeHasChain, TreeHasInGlue, TreeHasOutGlue,
NodeHasMemRefs, NumFixedArityOperands,
NextRecordedOperandNo));
for (unsigned i = 0, e = ResultVTs.size(); i != e; ++i) {
if (ResultVTs[i] == MVT::Other || ResultVTs[i] == MVT::Glue) break;
OutputOps.push_back(NextRecordedOperandNo++);
}
}
void MatcherGen::
EmitResultSDNodeXFormAsOperand(const TreePatternNode *N,
SmallVectorImpl<unsigned> &ResultOps) {
assert(N->getOperator()->isSubClassOf("SDNodeXForm") && "Not SDNodeXForm?");
SmallVector<unsigned, 8> InputOps;
assert(N->getNumChildren() == 1);
EmitResultOperand(N->getChild(0), InputOps);
assert(InputOps.size() == 1 && "Unexpected input to SDNodeXForm");
AddMatcher(new EmitNodeXFormMatcher(InputOps[0], N->getOperator()));
ResultOps.push_back(NextRecordedOperandNo++);
}
void MatcherGen::EmitResultOperand(const TreePatternNode *N,
SmallVectorImpl<unsigned> &ResultOps) {
if (!N->getName().empty())
return EmitResultOfNamedOperand(N, ResultOps);
if (N->isLeaf())
return EmitResultLeafAsOperand(N, ResultOps);
Record *OpRec = N->getOperator();
if (OpRec->isSubClassOf("Instruction"))
return EmitResultInstructionAsOperand(N, ResultOps);
if (OpRec->isSubClassOf("SDNodeXForm"))
return EmitResultSDNodeXFormAsOperand(N, ResultOps);
errs() << "Unknown result node to emit code for: " << *N << '\n';
PrintFatalError("Unknown node in result pattern!");
}
void MatcherGen::EmitResultCode() {
if (!MatchedChainNodes.empty())
AddMatcher(new EmitMergeInputChainsMatcher(MatchedChainNodes));
SmallVector<unsigned, 8> Ops;
EmitResultOperand(Pattern.getDstPattern(), Ops);
unsigned NumSrcResults = Pattern.getSrcPattern()->getNumTypes();
if (!Pattern.getDstRegs().empty()) {
Record *HandledReg = nullptr;
const TreePatternNode *DstPat = Pattern.getDstPattern();
if (!DstPat->isLeaf() &&DstPat->getOperator()->isSubClassOf("Instruction")){
const CodeGenTarget &CGT = CGP.getTargetInfo();
CodeGenInstruction &II = CGT.getInstruction(DstPat->getOperator());
if (II.HasOneImplicitDefWithKnownVT(CGT) != MVT::Other)
HandledReg = II.ImplicitDefs[0];
}
for (Record *Reg : Pattern.getDstRegs()) {
if (!Reg->isSubClassOf("Register") || Reg == HandledReg) continue;
++NumSrcResults;
}
}
SmallVector<unsigned, 8> Results(Ops);
for (unsigned ResNo = 0; ResNo < Pattern.getDstPattern()->getNumResults();
++ResNo) {
Results[ResNo] = Ops[Pattern.getDstPattern()->getResultIndex(ResNo)];
}
Results.resize(NumSrcResults);
AddMatcher(new CompleteMatchMatcher(Results, Pattern));
}
Matcher *llvm::ConvertPatternToMatcher(const PatternToMatch &Pattern,
unsigned Variant,
const CodeGenDAGPatterns &CGP) {
MatcherGen Gen(Pattern, CGP);
if (Gen.EmitMatcherCode(Variant))
return nullptr;
Gen.EmitResultCode();
return Gen.GetMatcher();
}