1 //===- DAGISelMatcherOpt.cpp - Optimize a DAG Matcher ---------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements the DAG Matcher optimizer.
11 //===----------------------------------------------------------------------===//
13 #include "CodeGenDAGPatterns.h"
14 #include "DAGISelMatcher.h"
15 #include "SDNodeProperties.h"
16 #include "llvm/ADT/StringSet.h"
17 #include "llvm/Support/Debug.h"
18 #include "llvm/Support/raw_ostream.h"
21 #define DEBUG_TYPE "isel-opt"
23 /// ContractNodes - Turn multiple matcher node patterns like 'MoveChild+Record'
24 /// into single compound nodes like RecordChild.
25 static void ContractNodes(std::unique_ptr
<Matcher
> &MatcherPtr
,
26 const CodeGenDAGPatterns
&CGP
) {
27 // If we reached the end of the chain, we're done.
28 Matcher
*N
= MatcherPtr
.get();
32 // If we have a scope node, walk down all of the children.
33 if (ScopeMatcher
*Scope
= dyn_cast
<ScopeMatcher
>(N
)) {
34 for (unsigned i
= 0, e
= Scope
->getNumChildren(); i
!= e
; ++i
) {
35 std::unique_ptr
<Matcher
> Child(Scope
->takeChild(i
));
36 ContractNodes(Child
, CGP
);
37 Scope
->resetChild(i
, Child
.release());
42 // If we found a movechild node with a node that comes in a 'foochild' form,
44 if (MoveChildMatcher
*MC
= dyn_cast
<MoveChildMatcher
>(N
)) {
45 Matcher
*New
= nullptr;
46 if (RecordMatcher
*RM
= dyn_cast
<RecordMatcher
>(MC
->getNext()))
47 if (MC
->getChildNo() < 8) // Only have RecordChild0...7
48 New
= new RecordChildMatcher(MC
->getChildNo(), RM
->getWhatFor(),
51 if (CheckTypeMatcher
*CT
= dyn_cast
<CheckTypeMatcher
>(MC
->getNext()))
52 if (MC
->getChildNo() < 8 && // Only have CheckChildType0...7
53 CT
->getResNo() == 0) // CheckChildType checks res #0
54 New
= new CheckChildTypeMatcher(MC
->getChildNo(), CT
->getType());
56 if (CheckSameMatcher
*CS
= dyn_cast
<CheckSameMatcher
>(MC
->getNext()))
57 if (MC
->getChildNo() < 4) // Only have CheckChildSame0...3
58 New
= new CheckChildSameMatcher(MC
->getChildNo(), CS
->getMatchNumber());
60 if (CheckIntegerMatcher
*CI
= dyn_cast
<CheckIntegerMatcher
>(MC
->getNext()))
61 if (MC
->getChildNo() < 5) // Only have CheckChildInteger0...4
62 New
= new CheckChildIntegerMatcher(MC
->getChildNo(), CI
->getValue());
64 if (auto *CCC
= dyn_cast
<CheckCondCodeMatcher
>(MC
->getNext()))
65 if (MC
->getChildNo() == 2) // Only have CheckChild2CondCode
66 New
= new CheckChild2CondCodeMatcher(CCC
->getCondCodeName());
69 // Insert the new node.
70 New
->setNext(MatcherPtr
.release());
71 MatcherPtr
.reset(New
);
72 // Remove the old one.
73 MC
->setNext(MC
->getNext()->takeNext());
74 return ContractNodes(MatcherPtr
, CGP
);
78 // Zap movechild -> moveparent.
79 if (MoveChildMatcher
*MC
= dyn_cast
<MoveChildMatcher
>(N
))
80 if (MoveParentMatcher
*MP
= dyn_cast
<MoveParentMatcher
>(MC
->getNext())) {
81 MatcherPtr
.reset(MP
->takeNext());
82 return ContractNodes(MatcherPtr
, CGP
);
85 // Turn EmitNode->CompleteMatch into MorphNodeTo if we can.
86 if (EmitNodeMatcher
*EN
= dyn_cast
<EmitNodeMatcher
>(N
))
87 if (CompleteMatchMatcher
*CM
=
88 dyn_cast
<CompleteMatchMatcher
>(EN
->getNext())) {
89 // We can only use MorphNodeTo if the result values match up.
90 unsigned RootResultFirst
= EN
->getFirstResultSlot();
91 bool ResultsMatch
= true;
92 for (unsigned i
= 0, e
= CM
->getNumResults(); i
!= e
; ++i
)
93 if (CM
->getResult(i
) != RootResultFirst
+ i
)
96 // If the selected node defines a subset of the glue/chain results, we
97 // can't use MorphNodeTo. For example, we can't use MorphNodeTo if the
98 // matched pattern has a chain but the root node doesn't.
99 const PatternToMatch
&Pattern
= CM
->getPattern();
101 if (!EN
->hasChain() &&
102 Pattern
.getSrcPattern()->NodeHasProperty(SDNPHasChain
, CGP
))
103 ResultsMatch
= false;
105 // If the matched node has glue and the output root doesn't, we can't
108 // NOTE: Strictly speaking, we don't have to check for glue here
109 // because the code in the pattern generator doesn't handle it right. We
110 // do it anyway for thoroughness.
111 if (!EN
->hasOutGlue() &&
112 Pattern
.getSrcPattern()->NodeHasProperty(SDNPOutGlue
, CGP
))
113 ResultsMatch
= false;
116 // If the root result node defines more results than the source root node
117 // *and* has a chain or glue input, then we can't match it because it
118 // would end up replacing the extra result with the chain/glue.
119 if ((EN
->hasGlue() || EN
->hasChain()) &&
120 EN
->getNumNonChainGlueVTs() > ... need to get no results reliably
...)
125 const SmallVectorImpl
<MVT::SimpleValueType
> &VTs
= EN
->getVTList();
126 const SmallVectorImpl
<unsigned> &Operands
= EN
->getOperandList();
127 MatcherPtr
.reset(new MorphNodeToMatcher(
128 EN
->getInstruction(), VTs
, Operands
, EN
->hasChain(),
129 EN
->hasInGlue(), EN
->hasOutGlue(), EN
->hasMemRefs(),
130 EN
->getNumFixedArityOperands(), Pattern
));
134 // FIXME2: Kill off all the SelectionDAG::SelectNodeTo and getMachineNode
138 ContractNodes(N
->getNextPtr(), CGP
);
140 // If we have a CheckType/CheckChildType/Record node followed by a
141 // CheckOpcode, invert the two nodes. We prefer to do structural checks
142 // before type checks, as this opens opportunities for factoring on targets
143 // like X86 where many operations are valid on multiple types.
144 if ((isa
<CheckTypeMatcher
>(N
) || isa
<CheckChildTypeMatcher
>(N
) ||
145 isa
<RecordMatcher
>(N
)) &&
146 isa
<CheckOpcodeMatcher
>(N
->getNext())) {
147 // Unlink the two nodes from the list.
148 Matcher
*CheckType
= MatcherPtr
.release();
149 Matcher
*CheckOpcode
= CheckType
->takeNext();
150 Matcher
*Tail
= CheckOpcode
->takeNext();
153 MatcherPtr
.reset(CheckOpcode
);
154 CheckOpcode
->setNext(CheckType
);
155 CheckType
->setNext(Tail
);
156 return ContractNodes(MatcherPtr
, CGP
);
160 /// FindNodeWithKind - Scan a series of matchers looking for a matcher with a
161 /// specified kind. Return null if we didn't find one otherwise return the
163 static Matcher
*FindNodeWithKind(Matcher
*M
, Matcher::KindTy Kind
) {
164 for (; M
; M
= M
->getNext())
165 if (M
->getKind() == Kind
)
170 /// FactorNodes - Turn matches like this:
172 /// OPC_CheckType i32
174 /// OPC_CheckType i32
177 /// OPC_CheckType i32
182 static void FactorNodes(std::unique_ptr
<Matcher
> &InputMatcherPtr
) {
183 // Look for a push node. Iterates instead of recurses to reduce stack usage.
184 ScopeMatcher
*Scope
= nullptr;
185 std::unique_ptr
<Matcher
> *RebindableMatcherPtr
= &InputMatcherPtr
;
187 // If we reached the end of the chain, we're done.
188 Matcher
*N
= RebindableMatcherPtr
->get();
192 // If this is not a push node, just scan for one.
193 Scope
= dyn_cast
<ScopeMatcher
>(N
);
195 RebindableMatcherPtr
= &(N
->getNextPtr());
197 std::unique_ptr
<Matcher
> &MatcherPtr
= *RebindableMatcherPtr
;
199 // Okay, pull together the children of the scope node into a vector so we can
200 // inspect it more easily.
201 SmallVector
<Matcher
*, 32> OptionsToMatch
;
203 for (unsigned i
= 0, e
= Scope
->getNumChildren(); i
!= e
; ++i
) {
204 // Factor the subexpression.
205 std::unique_ptr
<Matcher
> Child(Scope
->takeChild(i
));
208 // If the child is a ScopeMatcher we can just merge its contents.
209 if (auto *SM
= dyn_cast
<ScopeMatcher
>(Child
.get())) {
210 for (unsigned j
= 0, e
= SM
->getNumChildren(); j
!= e
; ++j
)
211 OptionsToMatch
.push_back(SM
->takeChild(j
));
213 OptionsToMatch
.push_back(Child
.release());
217 // Loop over options to match, merging neighboring patterns with identical
218 // starting nodes into a shared matcher.
219 auto E
= OptionsToMatch
.end();
220 for (auto I
= OptionsToMatch
.begin(); I
!= E
; ++I
) {
221 // If there are no other matchers left, there's nothing to merge with.
222 auto J
= std::next(I
);
226 // Remember where we started. We'll use this to move non-equal elements.
229 // Find the set of matchers that start with this node.
232 // See if the next option starts with the same matcher. If the two
233 // neighbors *do* start with the same matcher, we can factor the matcher out
234 // of at least these two patterns. See what the maximal set we can merge
236 SmallVector
<Matcher
*, 8> EqualMatchers
;
237 EqualMatchers
.push_back(Optn
);
239 // Factor all of the known-equal matchers after this one into the same
241 while (J
!= E
&& (*J
)->isEqual(Optn
))
242 EqualMatchers
.push_back(*J
++);
244 // If we found a non-equal matcher, see if it is contradictory with the
245 // current node. If so, we know that the ordering relation between the
246 // current sets of nodes and this node don't matter. Look past it to see if
247 // we can merge anything else into this matching group.
249 Matcher
*ScanMatcher
= *J
;
251 // If we found an entry that matches out matcher, merge it into the set to
253 if (Optn
->isEqual(ScanMatcher
)) {
254 // It is equal after all, add the option to EqualMatchers.
255 EqualMatchers
.push_back(ScanMatcher
);
260 // If the option we're checking for contradicts the start of the list,
261 // move it earlier in OptionsToMatch for the next iteration of the outer
262 // loop. Then continue searching for equal or contradictory matchers.
263 if (Optn
->isContradictory(ScanMatcher
)) {
268 // If we're scanning for a simple node, see if it occurs later in the
269 // sequence. If so, and if we can move it up, it might be contradictory
270 // or the same as what we're looking for. If so, reorder it.
271 if (Optn
->isSimplePredicateOrRecordNode()) {
272 Matcher
*M2
= FindNodeWithKind(ScanMatcher
, Optn
->getKind());
273 if (M2
&& M2
!= ScanMatcher
&& M2
->canMoveBefore(ScanMatcher
) &&
274 (M2
->isEqual(Optn
) || M2
->isContradictory(Optn
))) {
275 Matcher
*MatcherWithoutM2
= ScanMatcher
->unlinkNode(M2
);
276 M2
->setNext(MatcherWithoutM2
);
282 // Otherwise, we don't know how to handle this entry, we have to bail.
287 // Don't print if it's obvious nothing extract could be merged anyway.
289 LLVM_DEBUG(errs() << "Couldn't merge this:\n"; Optn
->print(errs(), 4);
290 errs() << "into this:\n";
291 (*J
)->print(errs(), 4);
292 (*std::next(J
))->printOne(errs());
293 if (std::next(J
, 2) != E
) (*std::next(J
, 2))->printOne(errs());
297 // If we removed any equal matchers, we may need to slide the rest of the
298 // elements down for the next iteration of the outer loop.
303 // Update end pointer for outer loop.
307 // If we only found one option starting with this matcher, no factoring is
308 // possible. Put the Matcher back in OptionsToMatch.
309 if (EqualMatchers
.size() == 1) {
310 *I
= EqualMatchers
[0];
314 // Factor these checks by pulling the first node off each entry and
315 // discarding it. Take the first one off the first entry to reuse.
316 Matcher
*Shared
= Optn
;
317 Optn
= Optn
->takeNext();
318 EqualMatchers
[0] = Optn
;
320 // Remove and delete the first node from the other matchers we're factoring.
321 for (unsigned i
= 1, e
= EqualMatchers
.size(); i
!= e
; ++i
) {
322 Matcher
*Tmp
= EqualMatchers
[i
]->takeNext();
323 delete EqualMatchers
[i
];
324 EqualMatchers
[i
] = Tmp
;
325 assert(!Optn
== !Tmp
&& "Expected all to be null if any are null");
328 if (EqualMatchers
[0]) {
329 Shared
->setNext(new ScopeMatcher(std::move(EqualMatchers
)));
331 // Recursively factor the newly created node.
332 FactorNodes(Shared
->getNextPtr());
335 // Put the new Matcher where we started in OptionsToMatch.
339 // Trim the array to match the updated end.
340 if (E
!= OptionsToMatch
.end())
341 OptionsToMatch
.erase(E
, OptionsToMatch
.end());
343 // If we're down to a single pattern to match, then we don't need this scope
345 if (OptionsToMatch
.size() == 1) {
346 MatcherPtr
.reset(OptionsToMatch
[0]);
350 if (OptionsToMatch
.empty()) {
355 // If our factoring failed (didn't achieve anything) see if we can simplify in
358 // Check to see if all of the leading entries are now opcode checks. If so,
359 // we can convert this Scope to be a OpcodeSwitch instead.
360 bool AllOpcodeChecks
= true, AllTypeChecks
= true;
361 for (unsigned i
= 0, e
= OptionsToMatch
.size(); i
!= e
; ++i
) {
362 // Check to see if this breaks a series of CheckOpcodeMatchers.
363 if (AllOpcodeChecks
&& !isa
<CheckOpcodeMatcher
>(OptionsToMatch
[i
])) {
366 errs() << "FAILING OPC #" << i
<< "\n";
367 OptionsToMatch
[i
]->dump();
370 AllOpcodeChecks
= false;
373 // Check to see if this breaks a series of CheckTypeMatcher's.
375 CheckTypeMatcher
*CTM
= cast_or_null
<CheckTypeMatcher
>(
376 FindNodeWithKind(OptionsToMatch
[i
], Matcher::CheckType
));
378 // iPTR checks could alias any other case without us knowing, don't
380 CTM
->getType() == MVT::iPTR
||
381 // SwitchType only works for result #0.
382 CTM
->getResNo() != 0 ||
383 // If the CheckType isn't at the start of the list, see if we can move
385 !CTM
->canMoveBefore(OptionsToMatch
[i
])) {
387 if (i
> 3 && AllTypeChecks
) {
388 errs() << "FAILING TYPE #" << i
<< "\n";
389 OptionsToMatch
[i
]->dump();
392 AllTypeChecks
= false;
397 // If all the options are CheckOpcode's, we can form the SwitchOpcode, woot.
398 if (AllOpcodeChecks
) {
400 SmallVector
<std::pair
<const SDNodeInfo
*, Matcher
*>, 8> Cases
;
401 for (unsigned i
= 0, e
= OptionsToMatch
.size(); i
!= e
; ++i
) {
402 CheckOpcodeMatcher
*COM
= cast
<CheckOpcodeMatcher
>(OptionsToMatch
[i
]);
403 assert(Opcodes
.insert(COM
->getOpcode().getEnumName()).second
&&
404 "Duplicate opcodes not factored?");
405 Cases
.push_back(std::make_pair(&COM
->getOpcode(), COM
->takeNext()));
409 MatcherPtr
.reset(new SwitchOpcodeMatcher(std::move(Cases
)));
413 // If all the options are CheckType's, we can form the SwitchType, woot.
415 DenseMap
<unsigned, unsigned> TypeEntry
;
416 SmallVector
<std::pair
<MVT::SimpleValueType
, Matcher
*>, 8> Cases
;
417 for (unsigned i
= 0, e
= OptionsToMatch
.size(); i
!= e
; ++i
) {
418 Matcher
*M
= FindNodeWithKind(OptionsToMatch
[i
], Matcher::CheckType
);
419 assert(M
&& isa
<CheckTypeMatcher
>(M
) && "Unknown Matcher type");
421 auto *CTM
= cast
<CheckTypeMatcher
>(M
);
422 Matcher
*MatcherWithoutCTM
= OptionsToMatch
[i
]->unlinkNode(CTM
);
423 MVT::SimpleValueType CTMTy
= CTM
->getType();
426 unsigned &Entry
= TypeEntry
[CTMTy
];
428 // If we have unfactored duplicate types, then we should factor them.
429 Matcher
*PrevMatcher
= Cases
[Entry
- 1].second
;
430 if (ScopeMatcher
*SM
= dyn_cast
<ScopeMatcher
>(PrevMatcher
)) {
431 SM
->setNumChildren(SM
->getNumChildren() + 1);
432 SM
->resetChild(SM
->getNumChildren() - 1, MatcherWithoutCTM
);
436 SmallVector
<Matcher
*, 2> Entries
= {PrevMatcher
, MatcherWithoutCTM
};
437 Cases
[Entry
- 1].second
= new ScopeMatcher(std::move(Entries
));
441 Entry
= Cases
.size() + 1;
442 Cases
.push_back(std::make_pair(CTMTy
, MatcherWithoutCTM
));
445 // Make sure we recursively factor any scopes we may have created.
446 for (auto &M
: Cases
) {
447 if (ScopeMatcher
*SM
= dyn_cast
<ScopeMatcher
>(M
.second
)) {
448 std::unique_ptr
<Matcher
> Scope(SM
);
450 M
.second
= Scope
.release();
451 assert(M
.second
&& "null matcher");
455 if (Cases
.size() != 1) {
456 MatcherPtr
.reset(new SwitchTypeMatcher(std::move(Cases
)));
458 // If we factored and ended up with one case, create it now.
459 MatcherPtr
.reset(new CheckTypeMatcher(Cases
[0].first
, 0));
460 MatcherPtr
->setNext(Cases
[0].second
);
465 // Reassemble the Scope node with the adjusted children.
466 Scope
->setNumChildren(OptionsToMatch
.size());
467 for (unsigned i
= 0, e
= OptionsToMatch
.size(); i
!= e
; ++i
)
468 Scope
->resetChild(i
, OptionsToMatch
[i
]);
471 void llvm::OptimizeMatcher(std::unique_ptr
<Matcher
> &MatcherPtr
,
472 const CodeGenDAGPatterns
&CGP
) {
473 ContractNodes(MatcherPtr
, CGP
);
474 FactorNodes(MatcherPtr
);