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 "Basic/SDNodeProperties.h"
14 #include "Common/CodeGenDAGPatterns.h"
15 #include "Common/DAGISelMatcher.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
);
159 // If we have a MoveParent followed by a MoveChild, we convert it to
161 if (auto *MP
= dyn_cast
<MoveParentMatcher
>(N
)) {
162 if (auto *MC
= dyn_cast
<MoveChildMatcher
>(MP
->getNext())) {
163 auto *MS
= new MoveSiblingMatcher(MC
->getChildNo());
164 MS
->setNext(MC
->takeNext());
165 MatcherPtr
.reset(MS
);
166 return ContractNodes(MatcherPtr
, CGP
);
168 if (auto *RC
= dyn_cast
<RecordChildMatcher
>(MP
->getNext())) {
169 if (auto *MC
= dyn_cast
<MoveChildMatcher
>(RC
->getNext())) {
170 if (RC
->getChildNo() == MC
->getChildNo()) {
171 auto *MS
= new MoveSiblingMatcher(MC
->getChildNo());
172 auto *RM
= new RecordMatcher(RC
->getWhatFor(), RC
->getResultNo());
173 // Insert the new node.
174 RM
->setNext(MC
->takeNext());
176 MatcherPtr
.reset(MS
);
177 return ContractNodes(MatcherPtr
, CGP
);
184 /// FindNodeWithKind - Scan a series of matchers looking for a matcher with a
185 /// specified kind. Return null if we didn't find one otherwise return the
187 static Matcher
*FindNodeWithKind(Matcher
*M
, Matcher::KindTy Kind
) {
188 for (; M
; M
= M
->getNext())
189 if (M
->getKind() == Kind
)
194 /// FactorNodes - Turn matches like this:
196 /// OPC_CheckType i32
198 /// OPC_CheckType i32
201 /// OPC_CheckType i32
206 static void FactorNodes(std::unique_ptr
<Matcher
> &InputMatcherPtr
) {
207 // Look for a push node. Iterates instead of recurses to reduce stack usage.
208 ScopeMatcher
*Scope
= nullptr;
209 std::unique_ptr
<Matcher
> *RebindableMatcherPtr
= &InputMatcherPtr
;
211 // If we reached the end of the chain, we're done.
212 Matcher
*N
= RebindableMatcherPtr
->get();
216 // If this is not a push node, just scan for one.
217 Scope
= dyn_cast
<ScopeMatcher
>(N
);
219 RebindableMatcherPtr
= &(N
->getNextPtr());
221 std::unique_ptr
<Matcher
> &MatcherPtr
= *RebindableMatcherPtr
;
223 // Okay, pull together the children of the scope node into a vector so we can
224 // inspect it more easily.
225 SmallVector
<Matcher
*, 32> OptionsToMatch
;
227 for (unsigned i
= 0, e
= Scope
->getNumChildren(); i
!= e
; ++i
) {
228 // Factor the subexpression.
229 std::unique_ptr
<Matcher
> Child(Scope
->takeChild(i
));
232 // If the child is a ScopeMatcher we can just merge its contents.
233 if (auto *SM
= dyn_cast
<ScopeMatcher
>(Child
.get())) {
234 for (unsigned j
= 0, e
= SM
->getNumChildren(); j
!= e
; ++j
)
235 OptionsToMatch
.push_back(SM
->takeChild(j
));
237 OptionsToMatch
.push_back(Child
.release());
241 // Loop over options to match, merging neighboring patterns with identical
242 // starting nodes into a shared matcher.
243 auto E
= OptionsToMatch
.end();
244 for (auto I
= OptionsToMatch
.begin(); I
!= E
; ++I
) {
245 // If there are no other matchers left, there's nothing to merge with.
246 auto J
= std::next(I
);
250 // Remember where we started. We'll use this to move non-equal elements.
253 // Find the set of matchers that start with this node.
256 // See if the next option starts with the same matcher. If the two
257 // neighbors *do* start with the same matcher, we can factor the matcher out
258 // of at least these two patterns. See what the maximal set we can merge
260 SmallVector
<Matcher
*, 8> EqualMatchers
;
261 EqualMatchers
.push_back(Optn
);
263 // Factor all of the known-equal matchers after this one into the same
265 while (J
!= E
&& (*J
)->isEqual(Optn
))
266 EqualMatchers
.push_back(*J
++);
268 // If we found a non-equal matcher, see if it is contradictory with the
269 // current node. If so, we know that the ordering relation between the
270 // current sets of nodes and this node don't matter. Look past it to see if
271 // we can merge anything else into this matching group.
273 Matcher
*ScanMatcher
= *J
;
275 // If we found an entry that matches out matcher, merge it into the set to
277 if (Optn
->isEqual(ScanMatcher
)) {
278 // It is equal after all, add the option to EqualMatchers.
279 EqualMatchers
.push_back(ScanMatcher
);
284 // If the option we're checking for contradicts the start of the list,
285 // move it earlier in OptionsToMatch for the next iteration of the outer
286 // loop. Then continue searching for equal or contradictory matchers.
287 if (Optn
->isContradictory(ScanMatcher
)) {
292 // If we're scanning for a simple node, see if it occurs later in the
293 // sequence. If so, and if we can move it up, it might be contradictory
294 // or the same as what we're looking for. If so, reorder it.
295 if (Optn
->isSimplePredicateOrRecordNode()) {
296 Matcher
*M2
= FindNodeWithKind(ScanMatcher
, Optn
->getKind());
297 if (M2
&& M2
!= ScanMatcher
&& M2
->canMoveBefore(ScanMatcher
) &&
298 (M2
->isEqual(Optn
) || M2
->isContradictory(Optn
))) {
299 Matcher
*MatcherWithoutM2
= ScanMatcher
->unlinkNode(M2
);
300 M2
->setNext(MatcherWithoutM2
);
306 // Otherwise, we don't know how to handle this entry, we have to bail.
311 // Don't print if it's obvious nothing extract could be merged anyway.
313 LLVM_DEBUG(errs() << "Couldn't merge this:\n";
314 Optn
->print(errs(), indent(4)); errs() << "into this:\n";
315 (*J
)->print(errs(), indent(4));
316 (*std::next(J
))->printOne(errs());
317 if (std::next(J
, 2) != E
)(*std::next(J
, 2))->printOne(errs());
321 // If we removed any equal matchers, we may need to slide the rest of the
322 // elements down for the next iteration of the outer loop.
327 // Update end pointer for outer loop.
331 // If we only found one option starting with this matcher, no factoring is
332 // possible. Put the Matcher back in OptionsToMatch.
333 if (EqualMatchers
.size() == 1) {
334 *I
= EqualMatchers
[0];
338 // Factor these checks by pulling the first node off each entry and
339 // discarding it. Take the first one off the first entry to reuse.
340 Matcher
*Shared
= Optn
;
341 Optn
= Optn
->takeNext();
342 EqualMatchers
[0] = Optn
;
344 // Remove and delete the first node from the other matchers we're factoring.
345 for (unsigned i
= 1, e
= EqualMatchers
.size(); i
!= e
; ++i
) {
346 Matcher
*Tmp
= EqualMatchers
[i
]->takeNext();
347 delete EqualMatchers
[i
];
348 EqualMatchers
[i
] = Tmp
;
349 assert(!Optn
== !Tmp
&& "Expected all to be null if any are null");
352 if (EqualMatchers
[0]) {
353 Shared
->setNext(new ScopeMatcher(std::move(EqualMatchers
)));
355 // Recursively factor the newly created node.
356 FactorNodes(Shared
->getNextPtr());
359 // Put the new Matcher where we started in OptionsToMatch.
363 // Trim the array to match the updated end.
364 if (E
!= OptionsToMatch
.end())
365 OptionsToMatch
.erase(E
, OptionsToMatch
.end());
367 // If we're down to a single pattern to match, then we don't need this scope
369 if (OptionsToMatch
.size() == 1) {
370 MatcherPtr
.reset(OptionsToMatch
[0]);
374 if (OptionsToMatch
.empty()) {
379 // If our factoring failed (didn't achieve anything) see if we can simplify in
382 // Check to see if all of the leading entries are now opcode checks. If so,
383 // we can convert this Scope to be a OpcodeSwitch instead.
384 bool AllOpcodeChecks
= true, AllTypeChecks
= true;
385 for (unsigned i
= 0, e
= OptionsToMatch
.size(); i
!= e
; ++i
) {
386 // Check to see if this breaks a series of CheckOpcodeMatchers.
387 if (AllOpcodeChecks
&& !isa
<CheckOpcodeMatcher
>(OptionsToMatch
[i
])) {
390 errs() << "FAILING OPC #" << i
<< "\n";
391 OptionsToMatch
[i
]->dump();
394 AllOpcodeChecks
= false;
397 // Check to see if this breaks a series of CheckTypeMatcher's.
399 CheckTypeMatcher
*CTM
= cast_or_null
<CheckTypeMatcher
>(
400 FindNodeWithKind(OptionsToMatch
[i
], Matcher::CheckType
));
402 // iPTR checks could alias any other case without us knowing, don't
404 CTM
->getType() == MVT::iPTR
||
405 // SwitchType only works for result #0.
406 CTM
->getResNo() != 0 ||
407 // If the CheckType isn't at the start of the list, see if we can move
409 !CTM
->canMoveBefore(OptionsToMatch
[i
])) {
411 if (i
> 3 && AllTypeChecks
) {
412 errs() << "FAILING TYPE #" << i
<< "\n";
413 OptionsToMatch
[i
]->dump();
416 AllTypeChecks
= false;
421 // If all the options are CheckOpcode's, we can form the SwitchOpcode, woot.
422 if (AllOpcodeChecks
) {
424 SmallVector
<std::pair
<const SDNodeInfo
*, Matcher
*>, 8> Cases
;
425 for (unsigned i
= 0, e
= OptionsToMatch
.size(); i
!= e
; ++i
) {
426 CheckOpcodeMatcher
*COM
= cast
<CheckOpcodeMatcher
>(OptionsToMatch
[i
]);
427 assert(Opcodes
.insert(COM
->getOpcode().getEnumName()).second
&&
428 "Duplicate opcodes not factored?");
429 Cases
.push_back(std::pair(&COM
->getOpcode(), COM
->takeNext()));
433 MatcherPtr
.reset(new SwitchOpcodeMatcher(std::move(Cases
)));
437 // If all the options are CheckType's, we can form the SwitchType, woot.
439 DenseMap
<unsigned, unsigned> TypeEntry
;
440 SmallVector
<std::pair
<MVT::SimpleValueType
, Matcher
*>, 8> Cases
;
441 for (unsigned i
= 0, e
= OptionsToMatch
.size(); i
!= e
; ++i
) {
442 Matcher
*M
= FindNodeWithKind(OptionsToMatch
[i
], Matcher::CheckType
);
443 assert(M
&& isa
<CheckTypeMatcher
>(M
) && "Unknown Matcher type");
445 auto *CTM
= cast
<CheckTypeMatcher
>(M
);
446 Matcher
*MatcherWithoutCTM
= OptionsToMatch
[i
]->unlinkNode(CTM
);
447 MVT::SimpleValueType CTMTy
= CTM
->getType();
450 unsigned &Entry
= TypeEntry
[CTMTy
];
452 // If we have unfactored duplicate types, then we should factor them.
453 Matcher
*PrevMatcher
= Cases
[Entry
- 1].second
;
454 if (ScopeMatcher
*SM
= dyn_cast
<ScopeMatcher
>(PrevMatcher
)) {
455 SM
->setNumChildren(SM
->getNumChildren() + 1);
456 SM
->resetChild(SM
->getNumChildren() - 1, MatcherWithoutCTM
);
460 SmallVector
<Matcher
*, 2> Entries
= {PrevMatcher
, MatcherWithoutCTM
};
461 Cases
[Entry
- 1].second
= new ScopeMatcher(std::move(Entries
));
465 Entry
= Cases
.size() + 1;
466 Cases
.push_back(std::pair(CTMTy
, MatcherWithoutCTM
));
469 // Make sure we recursively factor any scopes we may have created.
470 for (auto &M
: Cases
) {
471 if (ScopeMatcher
*SM
= dyn_cast
<ScopeMatcher
>(M
.second
)) {
472 std::unique_ptr
<Matcher
> Scope(SM
);
474 M
.second
= Scope
.release();
475 assert(M
.second
&& "null matcher");
479 if (Cases
.size() != 1) {
480 MatcherPtr
.reset(new SwitchTypeMatcher(std::move(Cases
)));
482 // If we factored and ended up with one case, create it now.
483 MatcherPtr
.reset(new CheckTypeMatcher(Cases
[0].first
, 0));
484 MatcherPtr
->setNext(Cases
[0].second
);
489 // Reassemble the Scope node with the adjusted children.
490 Scope
->setNumChildren(OptionsToMatch
.size());
491 for (unsigned i
= 0, e
= OptionsToMatch
.size(); i
!= e
; ++i
)
492 Scope
->resetChild(i
, OptionsToMatch
[i
]);
495 void llvm::OptimizeMatcher(std::unique_ptr
<Matcher
> &MatcherPtr
,
496 const CodeGenDAGPatterns
&CGP
) {
497 ContractNodes(MatcherPtr
, CGP
);
498 FactorNodes(MatcherPtr
);