Path: blob/main/contrib/llvm-project/llvm/utils/TableGen/DAGISelMatcherOpt.cpp
35258 views
//===- DAGISelMatcherOpt.cpp - Optimize a DAG Matcher ---------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements the DAG Matcher optimizer.9//10//===----------------------------------------------------------------------===//1112#include "Basic/SDNodeProperties.h"13#include "Common/CodeGenDAGPatterns.h"14#include "Common/DAGISelMatcher.h"15#include "llvm/ADT/StringSet.h"16#include "llvm/Support/Debug.h"17#include "llvm/Support/raw_ostream.h"18using namespace llvm;1920#define DEBUG_TYPE "isel-opt"2122/// ContractNodes - Turn multiple matcher node patterns like 'MoveChild+Record'23/// into single compound nodes like RecordChild.24static void ContractNodes(std::unique_ptr<Matcher> &MatcherPtr,25const CodeGenDAGPatterns &CGP) {26// If we reached the end of the chain, we're done.27Matcher *N = MatcherPtr.get();28if (!N)29return;3031// If we have a scope node, walk down all of the children.32if (ScopeMatcher *Scope = dyn_cast<ScopeMatcher>(N)) {33for (unsigned i = 0, e = Scope->getNumChildren(); i != e; ++i) {34std::unique_ptr<Matcher> Child(Scope->takeChild(i));35ContractNodes(Child, CGP);36Scope->resetChild(i, Child.release());37}38return;39}4041// If we found a movechild node with a node that comes in a 'foochild' form,42// transform it.43if (MoveChildMatcher *MC = dyn_cast<MoveChildMatcher>(N)) {44Matcher *New = nullptr;45if (RecordMatcher *RM = dyn_cast<RecordMatcher>(MC->getNext()))46if (MC->getChildNo() < 8) // Only have RecordChild0...747New = new RecordChildMatcher(MC->getChildNo(), RM->getWhatFor(),48RM->getResultNo());4950if (CheckTypeMatcher *CT = dyn_cast<CheckTypeMatcher>(MC->getNext()))51if (MC->getChildNo() < 8 && // Only have CheckChildType0...752CT->getResNo() == 0) // CheckChildType checks res #053New = new CheckChildTypeMatcher(MC->getChildNo(), CT->getType());5455if (CheckSameMatcher *CS = dyn_cast<CheckSameMatcher>(MC->getNext()))56if (MC->getChildNo() < 4) // Only have CheckChildSame0...357New = new CheckChildSameMatcher(MC->getChildNo(), CS->getMatchNumber());5859if (CheckIntegerMatcher *CI = dyn_cast<CheckIntegerMatcher>(MC->getNext()))60if (MC->getChildNo() < 5) // Only have CheckChildInteger0...461New = new CheckChildIntegerMatcher(MC->getChildNo(), CI->getValue());6263if (auto *CCC = dyn_cast<CheckCondCodeMatcher>(MC->getNext()))64if (MC->getChildNo() == 2) // Only have CheckChild2CondCode65New = new CheckChild2CondCodeMatcher(CCC->getCondCodeName());6667if (New) {68// Insert the new node.69New->setNext(MatcherPtr.release());70MatcherPtr.reset(New);71// Remove the old one.72MC->setNext(MC->getNext()->takeNext());73return ContractNodes(MatcherPtr, CGP);74}75}7677// Zap movechild -> moveparent.78if (MoveChildMatcher *MC = dyn_cast<MoveChildMatcher>(N))79if (MoveParentMatcher *MP = dyn_cast<MoveParentMatcher>(MC->getNext())) {80MatcherPtr.reset(MP->takeNext());81return ContractNodes(MatcherPtr, CGP);82}8384// Turn EmitNode->CompleteMatch into MorphNodeTo if we can.85if (EmitNodeMatcher *EN = dyn_cast<EmitNodeMatcher>(N))86if (CompleteMatchMatcher *CM =87dyn_cast<CompleteMatchMatcher>(EN->getNext())) {88// We can only use MorphNodeTo if the result values match up.89unsigned RootResultFirst = EN->getFirstResultSlot();90bool ResultsMatch = true;91for (unsigned i = 0, e = CM->getNumResults(); i != e; ++i)92if (CM->getResult(i) != RootResultFirst + i)93ResultsMatch = false;9495// If the selected node defines a subset of the glue/chain results, we96// can't use MorphNodeTo. For example, we can't use MorphNodeTo if the97// matched pattern has a chain but the root node doesn't.98const PatternToMatch &Pattern = CM->getPattern();99100if (!EN->hasChain() &&101Pattern.getSrcPattern().NodeHasProperty(SDNPHasChain, CGP))102ResultsMatch = false;103104// If the matched node has glue and the output root doesn't, we can't105// use MorphNodeTo.106//107// NOTE: Strictly speaking, we don't have to check for glue here108// because the code in the pattern generator doesn't handle it right. We109// do it anyway for thoroughness.110if (!EN->hasOutGlue() &&111Pattern.getSrcPattern().NodeHasProperty(SDNPOutGlue, CGP))112ResultsMatch = false;113114#if 0115// If the root result node defines more results than the source root node116// *and* has a chain or glue input, then we can't match it because it117// would end up replacing the extra result with the chain/glue.118if ((EN->hasGlue() || EN->hasChain()) &&119EN->getNumNonChainGlueVTs() > ... need to get no results reliably ...)120ResultMatch = false;121#endif122123if (ResultsMatch) {124const SmallVectorImpl<MVT::SimpleValueType> &VTs = EN->getVTList();125const SmallVectorImpl<unsigned> &Operands = EN->getOperandList();126MatcherPtr.reset(new MorphNodeToMatcher(127EN->getInstruction(), VTs, Operands, EN->hasChain(),128EN->hasInGlue(), EN->hasOutGlue(), EN->hasMemRefs(),129EN->getNumFixedArityOperands(), Pattern));130return;131}132133// FIXME2: Kill off all the SelectionDAG::SelectNodeTo and getMachineNode134// variants.135}136137ContractNodes(N->getNextPtr(), CGP);138139// If we have a CheckType/CheckChildType/Record node followed by a140// CheckOpcode, invert the two nodes. We prefer to do structural checks141// before type checks, as this opens opportunities for factoring on targets142// like X86 where many operations are valid on multiple types.143if ((isa<CheckTypeMatcher>(N) || isa<CheckChildTypeMatcher>(N) ||144isa<RecordMatcher>(N)) &&145isa<CheckOpcodeMatcher>(N->getNext())) {146// Unlink the two nodes from the list.147Matcher *CheckType = MatcherPtr.release();148Matcher *CheckOpcode = CheckType->takeNext();149Matcher *Tail = CheckOpcode->takeNext();150151// Relink them.152MatcherPtr.reset(CheckOpcode);153CheckOpcode->setNext(CheckType);154CheckType->setNext(Tail);155return ContractNodes(MatcherPtr, CGP);156}157158// If we have a MoveParent followed by a MoveChild, we convert it to159// MoveSibling.160if (auto *MP = dyn_cast<MoveParentMatcher>(N)) {161if (auto *MC = dyn_cast<MoveChildMatcher>(MP->getNext())) {162auto *MS = new MoveSiblingMatcher(MC->getChildNo());163MS->setNext(MC->takeNext());164MatcherPtr.reset(MS);165return ContractNodes(MatcherPtr, CGP);166}167if (auto *RC = dyn_cast<RecordChildMatcher>(MP->getNext())) {168if (auto *MC = dyn_cast<MoveChildMatcher>(RC->getNext())) {169if (RC->getChildNo() == MC->getChildNo()) {170auto *MS = new MoveSiblingMatcher(MC->getChildNo());171auto *RM = new RecordMatcher(RC->getWhatFor(), RC->getResultNo());172// Insert the new node.173RM->setNext(MC->takeNext());174MS->setNext(RM);175MatcherPtr.reset(MS);176return ContractNodes(MatcherPtr, CGP);177}178}179}180}181}182183/// FindNodeWithKind - Scan a series of matchers looking for a matcher with a184/// specified kind. Return null if we didn't find one otherwise return the185/// matcher.186static Matcher *FindNodeWithKind(Matcher *M, Matcher::KindTy Kind) {187for (; M; M = M->getNext())188if (M->getKind() == Kind)189return M;190return nullptr;191}192193/// FactorNodes - Turn matches like this:194/// Scope195/// OPC_CheckType i32196/// ABC197/// OPC_CheckType i32198/// XYZ199/// into:200/// OPC_CheckType i32201/// Scope202/// ABC203/// XYZ204///205static void FactorNodes(std::unique_ptr<Matcher> &InputMatcherPtr) {206// Look for a push node. Iterates instead of recurses to reduce stack usage.207ScopeMatcher *Scope = nullptr;208std::unique_ptr<Matcher> *RebindableMatcherPtr = &InputMatcherPtr;209while (!Scope) {210// If we reached the end of the chain, we're done.211Matcher *N = RebindableMatcherPtr->get();212if (!N)213return;214215// If this is not a push node, just scan for one.216Scope = dyn_cast<ScopeMatcher>(N);217if (!Scope)218RebindableMatcherPtr = &(N->getNextPtr());219}220std::unique_ptr<Matcher> &MatcherPtr = *RebindableMatcherPtr;221222// Okay, pull together the children of the scope node into a vector so we can223// inspect it more easily.224SmallVector<Matcher *, 32> OptionsToMatch;225226for (unsigned i = 0, e = Scope->getNumChildren(); i != e; ++i) {227// Factor the subexpression.228std::unique_ptr<Matcher> Child(Scope->takeChild(i));229FactorNodes(Child);230231// If the child is a ScopeMatcher we can just merge its contents.232if (auto *SM = dyn_cast<ScopeMatcher>(Child.get())) {233for (unsigned j = 0, e = SM->getNumChildren(); j != e; ++j)234OptionsToMatch.push_back(SM->takeChild(j));235} else {236OptionsToMatch.push_back(Child.release());237}238}239240// Loop over options to match, merging neighboring patterns with identical241// starting nodes into a shared matcher.242auto E = OptionsToMatch.end();243for (auto I = OptionsToMatch.begin(); I != E; ++I) {244// If there are no other matchers left, there's nothing to merge with.245auto J = std::next(I);246if (J == E)247break;248249// Remember where we started. We'll use this to move non-equal elements.250auto K = J;251252// Find the set of matchers that start with this node.253Matcher *Optn = *I;254255// See if the next option starts with the same matcher. If the two256// neighbors *do* start with the same matcher, we can factor the matcher out257// of at least these two patterns. See what the maximal set we can merge258// together is.259SmallVector<Matcher *, 8> EqualMatchers;260EqualMatchers.push_back(Optn);261262// Factor all of the known-equal matchers after this one into the same263// group.264while (J != E && (*J)->isEqual(Optn))265EqualMatchers.push_back(*J++);266267// If we found a non-equal matcher, see if it is contradictory with the268// current node. If so, we know that the ordering relation between the269// current sets of nodes and this node don't matter. Look past it to see if270// we can merge anything else into this matching group.271while (J != E) {272Matcher *ScanMatcher = *J;273274// If we found an entry that matches out matcher, merge it into the set to275// handle.276if (Optn->isEqual(ScanMatcher)) {277// It is equal after all, add the option to EqualMatchers.278EqualMatchers.push_back(ScanMatcher);279++J;280continue;281}282283// If the option we're checking for contradicts the start of the list,284// move it earlier in OptionsToMatch for the next iteration of the outer285// loop. Then continue searching for equal or contradictory matchers.286if (Optn->isContradictory(ScanMatcher)) {287*K++ = *J++;288continue;289}290291// If we're scanning for a simple node, see if it occurs later in the292// sequence. If so, and if we can move it up, it might be contradictory293// or the same as what we're looking for. If so, reorder it.294if (Optn->isSimplePredicateOrRecordNode()) {295Matcher *M2 = FindNodeWithKind(ScanMatcher, Optn->getKind());296if (M2 && M2 != ScanMatcher && M2->canMoveBefore(ScanMatcher) &&297(M2->isEqual(Optn) || M2->isContradictory(Optn))) {298Matcher *MatcherWithoutM2 = ScanMatcher->unlinkNode(M2);299M2->setNext(MatcherWithoutM2);300*J = M2;301continue;302}303}304305// Otherwise, we don't know how to handle this entry, we have to bail.306break;307}308309if (J != E &&310// Don't print if it's obvious nothing extract could be merged anyway.311std::next(J) != E) {312LLVM_DEBUG(errs() << "Couldn't merge this:\n"; Optn->print(errs(), 4);313errs() << "into this:\n"; (*J)->print(errs(), 4);314(*std::next(J))->printOne(errs());315if (std::next(J, 2) != E)(*std::next(J, 2))->printOne(errs());316errs() << "\n");317}318319// If we removed any equal matchers, we may need to slide the rest of the320// elements down for the next iteration of the outer loop.321if (J != K) {322while (J != E)323*K++ = *J++;324325// Update end pointer for outer loop.326E = K;327}328329// If we only found one option starting with this matcher, no factoring is330// possible. Put the Matcher back in OptionsToMatch.331if (EqualMatchers.size() == 1) {332*I = EqualMatchers[0];333continue;334}335336// Factor these checks by pulling the first node off each entry and337// discarding it. Take the first one off the first entry to reuse.338Matcher *Shared = Optn;339Optn = Optn->takeNext();340EqualMatchers[0] = Optn;341342// Remove and delete the first node from the other matchers we're factoring.343for (unsigned i = 1, e = EqualMatchers.size(); i != e; ++i) {344Matcher *Tmp = EqualMatchers[i]->takeNext();345delete EqualMatchers[i];346EqualMatchers[i] = Tmp;347assert(!Optn == !Tmp && "Expected all to be null if any are null");348}349350if (EqualMatchers[0]) {351Shared->setNext(new ScopeMatcher(std::move(EqualMatchers)));352353// Recursively factor the newly created node.354FactorNodes(Shared->getNextPtr());355}356357// Put the new Matcher where we started in OptionsToMatch.358*I = Shared;359}360361// Trim the array to match the updated end.362if (E != OptionsToMatch.end())363OptionsToMatch.erase(E, OptionsToMatch.end());364365// If we're down to a single pattern to match, then we don't need this scope366// anymore.367if (OptionsToMatch.size() == 1) {368MatcherPtr.reset(OptionsToMatch[0]);369return;370}371372if (OptionsToMatch.empty()) {373MatcherPtr.reset();374return;375}376377// If our factoring failed (didn't achieve anything) see if we can simplify in378// other ways.379380// Check to see if all of the leading entries are now opcode checks. If so,381// we can convert this Scope to be a OpcodeSwitch instead.382bool AllOpcodeChecks = true, AllTypeChecks = true;383for (unsigned i = 0, e = OptionsToMatch.size(); i != e; ++i) {384// Check to see if this breaks a series of CheckOpcodeMatchers.385if (AllOpcodeChecks && !isa<CheckOpcodeMatcher>(OptionsToMatch[i])) {386#if 0387if (i > 3) {388errs() << "FAILING OPC #" << i << "\n";389OptionsToMatch[i]->dump();390}391#endif392AllOpcodeChecks = false;393}394395// Check to see if this breaks a series of CheckTypeMatcher's.396if (AllTypeChecks) {397CheckTypeMatcher *CTM = cast_or_null<CheckTypeMatcher>(398FindNodeWithKind(OptionsToMatch[i], Matcher::CheckType));399if (!CTM ||400// iPTR checks could alias any other case without us knowing, don't401// bother with them.402CTM->getType() == MVT::iPTR ||403// SwitchType only works for result #0.404CTM->getResNo() != 0 ||405// If the CheckType isn't at the start of the list, see if we can move406// it there.407!CTM->canMoveBefore(OptionsToMatch[i])) {408#if 0409if (i > 3 && AllTypeChecks) {410errs() << "FAILING TYPE #" << i << "\n";411OptionsToMatch[i]->dump();412}413#endif414AllTypeChecks = false;415}416}417}418419// If all the options are CheckOpcode's, we can form the SwitchOpcode, woot.420if (AllOpcodeChecks) {421StringSet<> Opcodes;422SmallVector<std::pair<const SDNodeInfo *, Matcher *>, 8> Cases;423for (unsigned i = 0, e = OptionsToMatch.size(); i != e; ++i) {424CheckOpcodeMatcher *COM = cast<CheckOpcodeMatcher>(OptionsToMatch[i]);425assert(Opcodes.insert(COM->getOpcode().getEnumName()).second &&426"Duplicate opcodes not factored?");427Cases.push_back(std::pair(&COM->getOpcode(), COM->takeNext()));428delete COM;429}430431MatcherPtr.reset(new SwitchOpcodeMatcher(std::move(Cases)));432return;433}434435// If all the options are CheckType's, we can form the SwitchType, woot.436if (AllTypeChecks) {437DenseMap<unsigned, unsigned> TypeEntry;438SmallVector<std::pair<MVT::SimpleValueType, Matcher *>, 8> Cases;439for (unsigned i = 0, e = OptionsToMatch.size(); i != e; ++i) {440Matcher *M = FindNodeWithKind(OptionsToMatch[i], Matcher::CheckType);441assert(M && isa<CheckTypeMatcher>(M) && "Unknown Matcher type");442443auto *CTM = cast<CheckTypeMatcher>(M);444Matcher *MatcherWithoutCTM = OptionsToMatch[i]->unlinkNode(CTM);445MVT::SimpleValueType CTMTy = CTM->getType();446delete CTM;447448unsigned &Entry = TypeEntry[CTMTy];449if (Entry != 0) {450// If we have unfactored duplicate types, then we should factor them.451Matcher *PrevMatcher = Cases[Entry - 1].second;452if (ScopeMatcher *SM = dyn_cast<ScopeMatcher>(PrevMatcher)) {453SM->setNumChildren(SM->getNumChildren() + 1);454SM->resetChild(SM->getNumChildren() - 1, MatcherWithoutCTM);455continue;456}457458SmallVector<Matcher *, 2> Entries = {PrevMatcher, MatcherWithoutCTM};459Cases[Entry - 1].second = new ScopeMatcher(std::move(Entries));460continue;461}462463Entry = Cases.size() + 1;464Cases.push_back(std::pair(CTMTy, MatcherWithoutCTM));465}466467// Make sure we recursively factor any scopes we may have created.468for (auto &M : Cases) {469if (ScopeMatcher *SM = dyn_cast<ScopeMatcher>(M.second)) {470std::unique_ptr<Matcher> Scope(SM);471FactorNodes(Scope);472M.second = Scope.release();473assert(M.second && "null matcher");474}475}476477if (Cases.size() != 1) {478MatcherPtr.reset(new SwitchTypeMatcher(std::move(Cases)));479} else {480// If we factored and ended up with one case, create it now.481MatcherPtr.reset(new CheckTypeMatcher(Cases[0].first, 0));482MatcherPtr->setNext(Cases[0].second);483}484return;485}486487// Reassemble the Scope node with the adjusted children.488Scope->setNumChildren(OptionsToMatch.size());489for (unsigned i = 0, e = OptionsToMatch.size(); i != e; ++i)490Scope->resetChild(i, OptionsToMatch[i]);491}492493void llvm::OptimizeMatcher(std::unique_ptr<Matcher> &MatcherPtr,494const CodeGenDAGPatterns &CGP) {495ContractNodes(MatcherPtr, CGP);496FactorNodes(MatcherPtr);497}498499500