File: | llvm/lib/Transforms/Scalar/LoopFlatten.cpp |
Warning: | line 185, column 5 Called C++ object pointer is null |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===- LoopFlatten.cpp - Loop flattening pass------------------------------===// | ||||||
2 | // | ||||||
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 | ||||||
6 | // | ||||||
7 | //===----------------------------------------------------------------------===// | ||||||
8 | // | ||||||
9 | // This pass flattens pairs nested loops into a single loop. | ||||||
10 | // | ||||||
11 | // The intention is to optimise loop nests like this, which together access an | ||||||
12 | // array linearly: | ||||||
13 | // for (int i = 0; i < N; ++i) | ||||||
14 | // for (int j = 0; j < M; ++j) | ||||||
15 | // f(A[i*M+j]); | ||||||
16 | // into one loop: | ||||||
17 | // for (int i = 0; i < (N*M); ++i) | ||||||
18 | // f(A[i]); | ||||||
19 | // | ||||||
20 | // It can also flatten loops where the induction variables are not used in the | ||||||
21 | // loop. This is only worth doing if the induction variables are only used in an | ||||||
22 | // expression like i*M+j. If they had any other uses, we would have to insert a | ||||||
23 | // div/mod to reconstruct the original values, so this wouldn't be profitable. | ||||||
24 | // | ||||||
25 | // We also need to prove that N*M will not overflow. | ||||||
26 | // | ||||||
27 | //===----------------------------------------------------------------------===// | ||||||
28 | |||||||
29 | #include "llvm/Transforms/Scalar/LoopFlatten.h" | ||||||
30 | #include "llvm/Analysis/AssumptionCache.h" | ||||||
31 | #include "llvm/Analysis/LoopInfo.h" | ||||||
32 | #include "llvm/Analysis/OptimizationRemarkEmitter.h" | ||||||
33 | #include "llvm/Analysis/ScalarEvolution.h" | ||||||
34 | #include "llvm/Analysis/TargetTransformInfo.h" | ||||||
35 | #include "llvm/Analysis/ValueTracking.h" | ||||||
36 | #include "llvm/IR/Dominators.h" | ||||||
37 | #include "llvm/IR/Function.h" | ||||||
38 | #include "llvm/IR/IRBuilder.h" | ||||||
39 | #include "llvm/IR/Module.h" | ||||||
40 | #include "llvm/IR/PatternMatch.h" | ||||||
41 | #include "llvm/IR/Verifier.h" | ||||||
42 | #include "llvm/InitializePasses.h" | ||||||
43 | #include "llvm/Pass.h" | ||||||
44 | #include "llvm/Support/Debug.h" | ||||||
45 | #include "llvm/Support/raw_ostream.h" | ||||||
46 | #include "llvm/Transforms/Scalar.h" | ||||||
47 | #include "llvm/Transforms/Utils/Local.h" | ||||||
48 | #include "llvm/Transforms/Utils/LoopUtils.h" | ||||||
49 | #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h" | ||||||
50 | #include "llvm/Transforms/Utils/SimplifyIndVar.h" | ||||||
51 | |||||||
52 | #define DEBUG_TYPE"loop-flatten" "loop-flatten" | ||||||
53 | |||||||
54 | using namespace llvm; | ||||||
55 | using namespace llvm::PatternMatch; | ||||||
56 | |||||||
57 | static cl::opt<unsigned> RepeatedInstructionThreshold( | ||||||
58 | "loop-flatten-cost-threshold", cl::Hidden, cl::init(2), | ||||||
59 | cl::desc("Limit on the cost of instructions that can be repeated due to " | ||||||
60 | "loop flattening")); | ||||||
61 | |||||||
62 | static cl::opt<bool> | ||||||
63 | AssumeNoOverflow("loop-flatten-assume-no-overflow", cl::Hidden, | ||||||
64 | cl::init(false), | ||||||
65 | cl::desc("Assume that the product of the two iteration " | ||||||
66 | "limits will never overflow")); | ||||||
67 | |||||||
68 | static cl::opt<bool> | ||||||
69 | WidenIV("loop-flatten-widen-iv", cl::Hidden, | ||||||
70 | cl::init(true), | ||||||
71 | cl::desc("Widen the loop induction variables, if possible, so " | ||||||
72 | "overflow checks won't reject flattening")); | ||||||
73 | |||||||
74 | struct FlattenInfo { | ||||||
75 | Loop *OuterLoop = nullptr; | ||||||
76 | Loop *InnerLoop = nullptr; | ||||||
77 | PHINode *InnerInductionPHI = nullptr; | ||||||
78 | PHINode *OuterInductionPHI = nullptr; | ||||||
79 | Value *InnerLimit = nullptr; | ||||||
80 | Value *OuterLimit = nullptr; | ||||||
81 | BinaryOperator *InnerIncrement = nullptr; | ||||||
82 | BinaryOperator *OuterIncrement = nullptr; | ||||||
83 | BranchInst *InnerBranch = nullptr; | ||||||
84 | BranchInst *OuterBranch = nullptr; | ||||||
85 | SmallPtrSet<Value *, 4> LinearIVUses; | ||||||
86 | SmallPtrSet<PHINode *, 4> InnerPHIsToTransform; | ||||||
87 | |||||||
88 | // Whether this holds the flatten info before or after widening. | ||||||
89 | bool Widened = false; | ||||||
90 | |||||||
91 | FlattenInfo(Loop *OL, Loop *IL) : OuterLoop(OL), InnerLoop(IL) {}; | ||||||
92 | }; | ||||||
93 | |||||||
94 | // Finds the induction variable, increment and limit for a simple loop that we | ||||||
95 | // can flatten. | ||||||
96 | static bool findLoopComponents( | ||||||
97 | Loop *L, SmallPtrSetImpl<Instruction *> &IterationInstructions, | ||||||
98 | PHINode *&InductionPHI, Value *&Limit, BinaryOperator *&Increment, | ||||||
99 | BranchInst *&BackBranch, ScalarEvolution *SE) { | ||||||
100 | LLVM_DEBUG(dbgs() << "Finding components of loop: " << L->getName() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Finding components of loop: " << L->getName() << "\n"; } } while (false); | ||||||
| |||||||
101 | |||||||
102 | if (!L->isLoopSimplifyForm()) { | ||||||
103 | LLVM_DEBUG(dbgs() << "Loop is not in normal form\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Loop is not in normal form\n" ; } } while (false); | ||||||
104 | return false; | ||||||
105 | } | ||||||
106 | |||||||
107 | // There must be exactly one exiting block, and it must be the same at the | ||||||
108 | // latch. | ||||||
109 | BasicBlock *Latch = L->getLoopLatch(); | ||||||
110 | if (L->getExitingBlock() != Latch) { | ||||||
111 | LLVM_DEBUG(dbgs() << "Exiting and latch block are different\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Exiting and latch block are different\n" ; } } while (false); | ||||||
112 | return false; | ||||||
113 | } | ||||||
114 | // Latch block must end in a conditional branch. | ||||||
115 | BackBranch = dyn_cast<BranchInst>(Latch->getTerminator()); | ||||||
116 | if (!BackBranch
| ||||||
117 | LLVM_DEBUG(dbgs() << "Could not find back-branch\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Could not find back-branch\n" ; } } while (false); | ||||||
118 | return false; | ||||||
119 | } | ||||||
120 | IterationInstructions.insert(BackBranch); | ||||||
121 | LLVM_DEBUG(dbgs() << "Found back branch: "; BackBranch->dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Found back branch: "; BackBranch ->dump(); } } while (false); | ||||||
122 | bool ContinueOnTrue = L->contains(BackBranch->getSuccessor(0)); | ||||||
123 | |||||||
124 | // Find the induction PHI. If there is no induction PHI, we can't do the | ||||||
125 | // transformation. TODO: could other variables trigger this? Do we have to | ||||||
126 | // search for the best one? | ||||||
127 | InductionPHI = nullptr; | ||||||
128 | for (PHINode &PHI : L->getHeader()->phis()) { | ||||||
129 | InductionDescriptor ID; | ||||||
130 | if (InductionDescriptor::isInductionPHI(&PHI, L, SE, ID)) { | ||||||
131 | InductionPHI = &PHI; | ||||||
132 | LLVM_DEBUG(dbgs() << "Found induction PHI: "; InductionPHI->dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Found induction PHI: "; InductionPHI ->dump(); } } while (false); | ||||||
133 | break; | ||||||
134 | } | ||||||
135 | } | ||||||
136 | if (!InductionPHI
| ||||||
137 | LLVM_DEBUG(dbgs() << "Could not find induction PHI\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Could not find induction PHI\n" ; } } while (false); | ||||||
138 | return false; | ||||||
139 | } | ||||||
140 | |||||||
141 | auto IsValidPredicate = [&](ICmpInst::Predicate Pred) { | ||||||
142 | if (ContinueOnTrue) | ||||||
143 | return Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_ULT; | ||||||
144 | else | ||||||
145 | return Pred == CmpInst::ICMP_EQ; | ||||||
146 | }; | ||||||
147 | |||||||
148 | // Find Compare and make sure it is valid | ||||||
149 | ICmpInst *Compare = dyn_cast<ICmpInst>(BackBranch->getCondition()); | ||||||
150 | if (!Compare
| ||||||
151 | Compare->hasNUsesOrMore(2)) { | ||||||
152 | LLVM_DEBUG(dbgs() << "Could not find valid comparison\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Could not find valid comparison\n" ; } } while (false); | ||||||
153 | return false; | ||||||
154 | } | ||||||
155 | IterationInstructions.insert(Compare); | ||||||
156 | LLVM_DEBUG(dbgs() << "Found comparison: "; Compare->dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Found comparison: "; Compare ->dump(); } } while (false); | ||||||
157 | |||||||
158 | // Find increment and limit from the compare | ||||||
159 | Increment = nullptr; | ||||||
160 | if (match(Compare->getOperand(0), | ||||||
161 | m_c_Add(m_Specific(InductionPHI), m_ConstantInt<1>()))) { | ||||||
162 | Increment = dyn_cast<BinaryOperator>(Compare->getOperand(0)); | ||||||
163 | Limit = Compare->getOperand(1); | ||||||
164 | } else if (Compare->getUnsignedPredicate() == CmpInst::ICMP_NE && | ||||||
165 | match(Compare->getOperand(1), | ||||||
166 | m_c_Add(m_Specific(InductionPHI), m_ConstantInt<1>()))) { | ||||||
167 | Increment = dyn_cast<BinaryOperator>(Compare->getOperand(1)); | ||||||
168 | Limit = Compare->getOperand(0); | ||||||
169 | } | ||||||
170 | if (!Increment
| ||||||
171 | LLVM_DEBUG(dbgs() << "Cound not find valid increment\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Cound not find valid increment\n" ; } } while (false); | ||||||
172 | return false; | ||||||
173 | } | ||||||
174 | IterationInstructions.insert(Increment); | ||||||
175 | LLVM_DEBUG(dbgs() << "Found increment: "; Increment->dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Found increment: "; Increment ->dump(); } } while (false); | ||||||
176 | LLVM_DEBUG(dbgs() << "Found limit: "; Limit->dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Found limit: "; Limit-> dump(); } } while (false); | ||||||
177 | |||||||
178 | assert(InductionPHI->getNumIncomingValues() == 2)((InductionPHI->getNumIncomingValues() == 2) ? static_cast <void> (0) : __assert_fail ("InductionPHI->getNumIncomingValues() == 2" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/lib/Transforms/Scalar/LoopFlatten.cpp" , 178, __PRETTY_FUNCTION__)); | ||||||
179 | assert(InductionPHI->getIncomingValueForBlock(Latch) == Increment &&((InductionPHI->getIncomingValueForBlock(Latch) == Increment && "PHI value is not increment inst") ? static_cast< void> (0) : __assert_fail ("InductionPHI->getIncomingValueForBlock(Latch) == Increment && \"PHI value is not increment inst\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/lib/Transforms/Scalar/LoopFlatten.cpp" , 180, __PRETTY_FUNCTION__)) | ||||||
180 | "PHI value is not increment inst")((InductionPHI->getIncomingValueForBlock(Latch) == Increment && "PHI value is not increment inst") ? static_cast< void> (0) : __assert_fail ("InductionPHI->getIncomingValueForBlock(Latch) == Increment && \"PHI value is not increment inst\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/lib/Transforms/Scalar/LoopFlatten.cpp" , 180, __PRETTY_FUNCTION__)); | ||||||
181 | |||||||
182 | auto *CI = dyn_cast<ConstantInt>( | ||||||
183 | InductionPHI->getIncomingValueForBlock(L->getLoopPreheader())); | ||||||
184 | if (!CI
| ||||||
185 | LLVM_DEBUG(dbgs() << "PHI value is not zero: "; CI->dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "PHI value is not zero: " ; CI->dump(); } } while (false); | ||||||
| |||||||
186 | return false; | ||||||
187 | } | ||||||
188 | |||||||
189 | LLVM_DEBUG(dbgs() << "Successfully found all loop components\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Successfully found all loop components\n" ; } } while (false); | ||||||
190 | return true; | ||||||
191 | } | ||||||
192 | |||||||
193 | static bool checkPHIs(struct FlattenInfo &FI, | ||||||
194 | const TargetTransformInfo *TTI) { | ||||||
195 | // All PHIs in the inner and outer headers must either be: | ||||||
196 | // - The induction PHI, which we are going to rewrite as one induction in | ||||||
197 | // the new loop. This is already checked by findLoopComponents. | ||||||
198 | // - An outer header PHI with all incoming values from outside the loop. | ||||||
199 | // LoopSimplify guarantees we have a pre-header, so we don't need to | ||||||
200 | // worry about that here. | ||||||
201 | // - Pairs of PHIs in the inner and outer headers, which implement a | ||||||
202 | // loop-carried dependency that will still be valid in the new loop. To | ||||||
203 | // be valid, this variable must be modified only in the inner loop. | ||||||
204 | |||||||
205 | // The set of PHI nodes in the outer loop header that we know will still be | ||||||
206 | // valid after the transformation. These will not need to be modified (with | ||||||
207 | // the exception of the induction variable), but we do need to check that | ||||||
208 | // there are no unsafe PHI nodes. | ||||||
209 | SmallPtrSet<PHINode *, 4> SafeOuterPHIs; | ||||||
210 | SafeOuterPHIs.insert(FI.OuterInductionPHI); | ||||||
211 | |||||||
212 | // Check that all PHI nodes in the inner loop header match one of the valid | ||||||
213 | // patterns. | ||||||
214 | for (PHINode &InnerPHI : FI.InnerLoop->getHeader()->phis()) { | ||||||
215 | // The induction PHIs break these rules, and that's OK because we treat | ||||||
216 | // them specially when doing the transformation. | ||||||
217 | if (&InnerPHI == FI.InnerInductionPHI) | ||||||
218 | continue; | ||||||
219 | |||||||
220 | // Each inner loop PHI node must have two incoming values/blocks - one | ||||||
221 | // from the pre-header, and one from the latch. | ||||||
222 | assert(InnerPHI.getNumIncomingValues() == 2)((InnerPHI.getNumIncomingValues() == 2) ? static_cast<void > (0) : __assert_fail ("InnerPHI.getNumIncomingValues() == 2" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/lib/Transforms/Scalar/LoopFlatten.cpp" , 222, __PRETTY_FUNCTION__)); | ||||||
223 | Value *PreHeaderValue = | ||||||
224 | InnerPHI.getIncomingValueForBlock(FI.InnerLoop->getLoopPreheader()); | ||||||
225 | Value *LatchValue = | ||||||
226 | InnerPHI.getIncomingValueForBlock(FI.InnerLoop->getLoopLatch()); | ||||||
227 | |||||||
228 | // The incoming value from the outer loop must be the PHI node in the | ||||||
229 | // outer loop header, with no modifications made in the top of the outer | ||||||
230 | // loop. | ||||||
231 | PHINode *OuterPHI = dyn_cast<PHINode>(PreHeaderValue); | ||||||
232 | if (!OuterPHI || OuterPHI->getParent() != FI.OuterLoop->getHeader()) { | ||||||
233 | LLVM_DEBUG(dbgs() << "value modified in top of outer loop\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "value modified in top of outer loop\n" ; } } while (false); | ||||||
234 | return false; | ||||||
235 | } | ||||||
236 | |||||||
237 | // The other incoming value must come from the inner loop, without any | ||||||
238 | // modifications in the tail end of the outer loop. We are in LCSSA form, | ||||||
239 | // so this will actually be a PHI in the inner loop's exit block, which | ||||||
240 | // only uses values from inside the inner loop. | ||||||
241 | PHINode *LCSSAPHI = dyn_cast<PHINode>( | ||||||
242 | OuterPHI->getIncomingValueForBlock(FI.OuterLoop->getLoopLatch())); | ||||||
243 | if (!LCSSAPHI) { | ||||||
244 | LLVM_DEBUG(dbgs() << "could not find LCSSA PHI\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "could not find LCSSA PHI\n" ; } } while (false); | ||||||
245 | return false; | ||||||
246 | } | ||||||
247 | |||||||
248 | // The value used by the LCSSA PHI must be the same one that the inner | ||||||
249 | // loop's PHI uses. | ||||||
250 | if (LCSSAPHI->hasConstantValue() != LatchValue) { | ||||||
251 | LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "LCSSA PHI incoming value does not match latch value\n" ; } } while (false) | ||||||
252 | dbgs() << "LCSSA PHI incoming value does not match latch value\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "LCSSA PHI incoming value does not match latch value\n" ; } } while (false); | ||||||
253 | return false; | ||||||
254 | } | ||||||
255 | |||||||
256 | LLVM_DEBUG(dbgs() << "PHI pair is safe:\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "PHI pair is safe:\n"; } } while (false); | ||||||
257 | LLVM_DEBUG(dbgs() << " Inner: "; InnerPHI.dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << " Inner: "; InnerPHI.dump (); } } while (false); | ||||||
258 | LLVM_DEBUG(dbgs() << " Outer: "; OuterPHI->dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << " Outer: "; OuterPHI-> dump(); } } while (false); | ||||||
259 | SafeOuterPHIs.insert(OuterPHI); | ||||||
260 | FI.InnerPHIsToTransform.insert(&InnerPHI); | ||||||
261 | } | ||||||
262 | |||||||
263 | for (PHINode &OuterPHI : FI.OuterLoop->getHeader()->phis()) { | ||||||
264 | if (!SafeOuterPHIs.count(&OuterPHI)) { | ||||||
265 | LLVM_DEBUG(dbgs() << "found unsafe PHI in outer loop: "; OuterPHI.dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "found unsafe PHI in outer loop: " ; OuterPHI.dump(); } } while (false); | ||||||
266 | return false; | ||||||
267 | } | ||||||
268 | } | ||||||
269 | |||||||
270 | LLVM_DEBUG(dbgs() << "checkPHIs: OK\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "checkPHIs: OK\n"; } } while (false); | ||||||
271 | return true; | ||||||
272 | } | ||||||
273 | |||||||
274 | static bool | ||||||
275 | checkOuterLoopInsts(struct FlattenInfo &FI, | ||||||
276 | SmallPtrSetImpl<Instruction *> &IterationInstructions, | ||||||
277 | const TargetTransformInfo *TTI) { | ||||||
278 | // Check for instructions in the outer but not inner loop. If any of these | ||||||
279 | // have side-effects then this transformation is not legal, and if there is | ||||||
280 | // a significant amount of code here which can't be optimised out that it's | ||||||
281 | // not profitable (as these instructions would get executed for each | ||||||
282 | // iteration of the inner loop). | ||||||
283 | InstructionCost RepeatedInstrCost = 0; | ||||||
284 | for (auto *B : FI.OuterLoop->getBlocks()) { | ||||||
285 | if (FI.InnerLoop->contains(B)) | ||||||
286 | continue; | ||||||
287 | |||||||
288 | for (auto &I : *B) { | ||||||
289 | if (!isa<PHINode>(&I) && !I.isTerminator() && | ||||||
290 | !isSafeToSpeculativelyExecute(&I)) { | ||||||
291 | LLVM_DEBUG(dbgs() << "Cannot flatten because instruction may have "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Cannot flatten because instruction may have " "side effects: "; I.dump(); } } while (false) | ||||||
292 | "side effects: ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Cannot flatten because instruction may have " "side effects: "; I.dump(); } } while (false) | ||||||
293 | I.dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Cannot flatten because instruction may have " "side effects: "; I.dump(); } } while (false); | ||||||
294 | return false; | ||||||
295 | } | ||||||
296 | // The execution count of the outer loop's iteration instructions | ||||||
297 | // (increment, compare and branch) will be increased, but the | ||||||
298 | // equivalent instructions will be removed from the inner loop, so | ||||||
299 | // they make a net difference of zero. | ||||||
300 | if (IterationInstructions.count(&I)) | ||||||
301 | continue; | ||||||
302 | // The uncoditional branch to the inner loop's header will turn into | ||||||
303 | // a fall-through, so adds no cost. | ||||||
304 | BranchInst *Br = dyn_cast<BranchInst>(&I); | ||||||
305 | if (Br && Br->isUnconditional() && | ||||||
306 | Br->getSuccessor(0) == FI.InnerLoop->getHeader()) | ||||||
307 | continue; | ||||||
308 | // Multiplies of the outer iteration variable and inner iteration | ||||||
309 | // count will be optimised out. | ||||||
310 | if (match(&I, m_c_Mul(m_Specific(FI.OuterInductionPHI), | ||||||
311 | m_Specific(FI.InnerLimit)))) | ||||||
312 | continue; | ||||||
313 | InstructionCost Cost = | ||||||
314 | TTI->getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency); | ||||||
315 | LLVM_DEBUG(dbgs() << "Cost " << Cost << ": "; I.dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Cost " << Cost << ": "; I.dump(); } } while (false); | ||||||
316 | RepeatedInstrCost += Cost; | ||||||
317 | } | ||||||
318 | } | ||||||
319 | |||||||
320 | LLVM_DEBUG(dbgs() << "Cost of instructions that will be repeated: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Cost of instructions that will be repeated: " << RepeatedInstrCost << "\n"; } } while (false) | ||||||
321 | << RepeatedInstrCost << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Cost of instructions that will be repeated: " << RepeatedInstrCost << "\n"; } } while (false); | ||||||
322 | // Bail out if flattening the loops would cause instructions in the outer | ||||||
323 | // loop but not in the inner loop to be executed extra times. | ||||||
324 | if (RepeatedInstrCost > RepeatedInstructionThreshold) { | ||||||
325 | LLVM_DEBUG(dbgs() << "checkOuterLoopInsts: not profitable, bailing.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "checkOuterLoopInsts: not profitable, bailing.\n" ; } } while (false); | ||||||
326 | return false; | ||||||
327 | } | ||||||
328 | |||||||
329 | LLVM_DEBUG(dbgs() << "checkOuterLoopInsts: OK\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "checkOuterLoopInsts: OK\n" ; } } while (false); | ||||||
330 | return true; | ||||||
331 | } | ||||||
332 | |||||||
333 | static bool checkIVUsers(struct FlattenInfo &FI) { | ||||||
334 | // We require all uses of both induction variables to match this pattern: | ||||||
335 | // | ||||||
336 | // (OuterPHI * InnerLimit) + InnerPHI | ||||||
337 | // | ||||||
338 | // Any uses of the induction variables not matching that pattern would | ||||||
339 | // require a div/mod to reconstruct in the flattened loop, so the | ||||||
340 | // transformation wouldn't be profitable. | ||||||
341 | |||||||
342 | Value *InnerLimit = FI.InnerLimit; | ||||||
343 | if (FI.Widened && | ||||||
344 | (isa<SExtInst>(InnerLimit) || isa<ZExtInst>(InnerLimit))) | ||||||
345 | InnerLimit = cast<Instruction>(InnerLimit)->getOperand(0); | ||||||
346 | |||||||
347 | // Check that all uses of the inner loop's induction variable match the | ||||||
348 | // expected pattern, recording the uses of the outer IV. | ||||||
349 | SmallPtrSet<Value *, 4> ValidOuterPHIUses; | ||||||
350 | for (User *U : FI.InnerInductionPHI->users()) { | ||||||
351 | if (U == FI.InnerIncrement) | ||||||
352 | continue; | ||||||
353 | |||||||
354 | // After widening the IVs, a trunc instruction might have been introduced, so | ||||||
355 | // look through truncs. | ||||||
356 | if (isa<TruncInst>(U)) { | ||||||
357 | if (!U->hasOneUse()) | ||||||
358 | return false; | ||||||
359 | U = *U->user_begin(); | ||||||
360 | } | ||||||
361 | |||||||
362 | LLVM_DEBUG(dbgs() << "Found use of inner induction variable: "; U->dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Found use of inner induction variable: " ; U->dump(); } } while (false); | ||||||
363 | |||||||
364 | Value *MatchedMul; | ||||||
365 | Value *MatchedItCount; | ||||||
366 | bool IsAdd = match(U, m_c_Add(m_Specific(FI.InnerInductionPHI), | ||||||
367 | m_Value(MatchedMul))) && | ||||||
368 | match(MatchedMul, m_c_Mul(m_Specific(FI.OuterInductionPHI), | ||||||
369 | m_Value(MatchedItCount))); | ||||||
370 | |||||||
371 | // Matches the same pattern as above, except it also looks for truncs | ||||||
372 | // on the phi, which can be the result of widening the induction variables. | ||||||
373 | bool IsAddTrunc = match(U, m_c_Add(m_Trunc(m_Specific(FI.InnerInductionPHI)), | ||||||
374 | m_Value(MatchedMul))) && | ||||||
375 | match(MatchedMul, | ||||||
376 | m_c_Mul(m_Trunc(m_Specific(FI.OuterInductionPHI)), | ||||||
377 | m_Value(MatchedItCount))); | ||||||
378 | |||||||
379 | if ((IsAdd || IsAddTrunc) && MatchedItCount == InnerLimit) { | ||||||
380 | LLVM_DEBUG(dbgs() << "Use is optimisable\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Use is optimisable\n"; } } while (false); | ||||||
381 | ValidOuterPHIUses.insert(MatchedMul); | ||||||
382 | FI.LinearIVUses.insert(U); | ||||||
383 | } else { | ||||||
384 | LLVM_DEBUG(dbgs() << "Did not match expected pattern, bailing\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Did not match expected pattern, bailing\n" ; } } while (false); | ||||||
385 | return false; | ||||||
386 | } | ||||||
387 | } | ||||||
388 | |||||||
389 | // Check that there are no uses of the outer IV other than the ones found | ||||||
390 | // as part of the pattern above. | ||||||
391 | for (User *U : FI.OuterInductionPHI->users()) { | ||||||
392 | if (U == FI.OuterIncrement) | ||||||
393 | continue; | ||||||
394 | |||||||
395 | auto IsValidOuterPHIUses = [&] (User *U) -> bool { | ||||||
396 | LLVM_DEBUG(dbgs() << "Found use of outer induction variable: "; U->dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Found use of outer induction variable: " ; U->dump(); } } while (false); | ||||||
397 | if (!ValidOuterPHIUses.count(U)) { | ||||||
398 | LLVM_DEBUG(dbgs() << "Did not match expected pattern, bailing\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Did not match expected pattern, bailing\n" ; } } while (false); | ||||||
399 | return false; | ||||||
400 | } | ||||||
401 | LLVM_DEBUG(dbgs() << "Use is optimisable\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Use is optimisable\n"; } } while (false); | ||||||
402 | return true; | ||||||
403 | }; | ||||||
404 | |||||||
405 | if (auto *V = dyn_cast<TruncInst>(U)) { | ||||||
406 | for (auto *K : V->users()) { | ||||||
407 | if (!IsValidOuterPHIUses(K)) | ||||||
408 | return false; | ||||||
409 | } | ||||||
410 | continue; | ||||||
411 | } | ||||||
412 | |||||||
413 | if (!IsValidOuterPHIUses(U)) | ||||||
414 | return false; | ||||||
415 | } | ||||||
416 | |||||||
417 | LLVM_DEBUG(dbgs() << "checkIVUsers: OK\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "checkIVUsers: OK\n"; dbgs () << "Found " << FI.LinearIVUses.size() << " value(s) that can be replaced:\n"; for (Value *V : FI.LinearIVUses ) { dbgs() << " "; V->dump(); }; } } while (false) | ||||||
418 | dbgs() << "Found " << FI.LinearIVUses.size()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "checkIVUsers: OK\n"; dbgs () << "Found " << FI.LinearIVUses.size() << " value(s) that can be replaced:\n"; for (Value *V : FI.LinearIVUses ) { dbgs() << " "; V->dump(); }; } } while (false) | ||||||
419 | << " value(s) that can be replaced:\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "checkIVUsers: OK\n"; dbgs () << "Found " << FI.LinearIVUses.size() << " value(s) that can be replaced:\n"; for (Value *V : FI.LinearIVUses ) { dbgs() << " "; V->dump(); }; } } while (false) | ||||||
420 | for (Value *V : FI.LinearIVUses) {do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "checkIVUsers: OK\n"; dbgs () << "Found " << FI.LinearIVUses.size() << " value(s) that can be replaced:\n"; for (Value *V : FI.LinearIVUses ) { dbgs() << " "; V->dump(); }; } } while (false) | ||||||
421 | dbgs() << " ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "checkIVUsers: OK\n"; dbgs () << "Found " << FI.LinearIVUses.size() << " value(s) that can be replaced:\n"; for (Value *V : FI.LinearIVUses ) { dbgs() << " "; V->dump(); }; } } while (false) | ||||||
422 | V->dump();do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "checkIVUsers: OK\n"; dbgs () << "Found " << FI.LinearIVUses.size() << " value(s) that can be replaced:\n"; for (Value *V : FI.LinearIVUses ) { dbgs() << " "; V->dump(); }; } } while (false) | ||||||
423 | })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "checkIVUsers: OK\n"; dbgs () << "Found " << FI.LinearIVUses.size() << " value(s) that can be replaced:\n"; for (Value *V : FI.LinearIVUses ) { dbgs() << " "; V->dump(); }; } } while (false); | ||||||
424 | return true; | ||||||
425 | } | ||||||
426 | |||||||
427 | // Return an OverflowResult dependant on if overflow of the multiplication of | ||||||
428 | // InnerLimit and OuterLimit can be assumed not to happen. | ||||||
429 | static OverflowResult checkOverflow(struct FlattenInfo &FI, | ||||||
430 | DominatorTree *DT, AssumptionCache *AC) { | ||||||
431 | Function *F = FI.OuterLoop->getHeader()->getParent(); | ||||||
432 | const DataLayout &DL = F->getParent()->getDataLayout(); | ||||||
433 | |||||||
434 | // For debugging/testing. | ||||||
435 | if (AssumeNoOverflow) | ||||||
436 | return OverflowResult::NeverOverflows; | ||||||
437 | |||||||
438 | // Check if the multiply could not overflow due to known ranges of the | ||||||
439 | // input values. | ||||||
440 | OverflowResult OR = computeOverflowForUnsignedMul( | ||||||
441 | FI.InnerLimit, FI.OuterLimit, DL, AC, | ||||||
442 | FI.OuterLoop->getLoopPreheader()->getTerminator(), DT); | ||||||
443 | if (OR != OverflowResult::MayOverflow) | ||||||
444 | return OR; | ||||||
445 | |||||||
446 | for (Value *V : FI.LinearIVUses) { | ||||||
447 | for (Value *U : V->users()) { | ||||||
448 | if (auto *GEP = dyn_cast<GetElementPtrInst>(U)) { | ||||||
449 | // The IV is used as the operand of a GEP, and the IV is at least as | ||||||
450 | // wide as the address space of the GEP. In this case, the GEP would | ||||||
451 | // wrap around the address space before the IV increment wraps, which | ||||||
452 | // would be UB. | ||||||
453 | if (GEP->isInBounds() && | ||||||
454 | V->getType()->getIntegerBitWidth() >= | ||||||
455 | DL.getPointerTypeSizeInBits(GEP->getType())) { | ||||||
456 | LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "use of linear IV would be UB if overflow occurred: " ; GEP->dump(); } } while (false) | ||||||
457 | dbgs() << "use of linear IV would be UB if overflow occurred: ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "use of linear IV would be UB if overflow occurred: " ; GEP->dump(); } } while (false) | ||||||
458 | GEP->dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "use of linear IV would be UB if overflow occurred: " ; GEP->dump(); } } while (false); | ||||||
459 | return OverflowResult::NeverOverflows; | ||||||
460 | } | ||||||
461 | } | ||||||
462 | } | ||||||
463 | } | ||||||
464 | |||||||
465 | return OverflowResult::MayOverflow; | ||||||
466 | } | ||||||
467 | |||||||
468 | static bool CanFlattenLoopPair(struct FlattenInfo &FI, DominatorTree *DT, | ||||||
469 | LoopInfo *LI, ScalarEvolution *SE, | ||||||
470 | AssumptionCache *AC, const TargetTransformInfo *TTI) { | ||||||
471 | SmallPtrSet<Instruction *, 8> IterationInstructions; | ||||||
472 | if (!findLoopComponents(FI.InnerLoop, IterationInstructions, FI.InnerInductionPHI, | ||||||
473 | FI.InnerLimit, FI.InnerIncrement, FI.InnerBranch, SE)) | ||||||
474 | return false; | ||||||
475 | if (!findLoopComponents(FI.OuterLoop, IterationInstructions, FI.OuterInductionPHI, | ||||||
476 | FI.OuterLimit, FI.OuterIncrement, FI.OuterBranch, SE)) | ||||||
477 | return false; | ||||||
478 | |||||||
479 | // Both of the loop limit values must be invariant in the outer loop | ||||||
480 | // (non-instructions are all inherently invariant). | ||||||
481 | if (!FI.OuterLoop->isLoopInvariant(FI.InnerLimit)) { | ||||||
482 | LLVM_DEBUG(dbgs() << "inner loop limit not invariant\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "inner loop limit not invariant\n" ; } } while (false); | ||||||
483 | return false; | ||||||
484 | } | ||||||
485 | if (!FI.OuterLoop->isLoopInvariant(FI.OuterLimit)) { | ||||||
486 | LLVM_DEBUG(dbgs() << "outer loop limit not invariant\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "outer loop limit not invariant\n" ; } } while (false); | ||||||
487 | return false; | ||||||
488 | } | ||||||
489 | |||||||
490 | if (!checkPHIs(FI, TTI)) | ||||||
491 | return false; | ||||||
492 | |||||||
493 | // FIXME: it should be possible to handle different types correctly. | ||||||
494 | if (FI.InnerInductionPHI->getType() != FI.OuterInductionPHI->getType()) | ||||||
495 | return false; | ||||||
496 | |||||||
497 | if (!checkOuterLoopInsts(FI, IterationInstructions, TTI)) | ||||||
498 | return false; | ||||||
499 | |||||||
500 | // Find the values in the loop that can be replaced with the linearized | ||||||
501 | // induction variable, and check that there are no other uses of the inner | ||||||
502 | // or outer induction variable. If there were, we could still do this | ||||||
503 | // transformation, but we'd have to insert a div/mod to calculate the | ||||||
504 | // original IVs, so it wouldn't be profitable. | ||||||
505 | if (!checkIVUsers(FI)) | ||||||
506 | return false; | ||||||
507 | |||||||
508 | LLVM_DEBUG(dbgs() << "CanFlattenLoopPair: OK\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "CanFlattenLoopPair: OK\n" ; } } while (false); | ||||||
509 | return true; | ||||||
510 | } | ||||||
511 | |||||||
512 | static bool DoFlattenLoopPair(struct FlattenInfo &FI, DominatorTree *DT, | ||||||
513 | LoopInfo *LI, ScalarEvolution *SE, | ||||||
514 | AssumptionCache *AC, | ||||||
515 | const TargetTransformInfo *TTI) { | ||||||
516 | Function *F = FI.OuterLoop->getHeader()->getParent(); | ||||||
517 | LLVM_DEBUG(dbgs() << "Checks all passed, doing the transformation\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Checks all passed, doing the transformation\n" ; } } while (false); | ||||||
518 | { | ||||||
519 | using namespace ore; | ||||||
520 | OptimizationRemark Remark(DEBUG_TYPE"loop-flatten", "Flattened", FI.InnerLoop->getStartLoc(), | ||||||
521 | FI.InnerLoop->getHeader()); | ||||||
522 | OptimizationRemarkEmitter ORE(F); | ||||||
523 | Remark << "Flattened into outer loop"; | ||||||
524 | ORE.emit(Remark); | ||||||
525 | } | ||||||
526 | |||||||
527 | Value *NewTripCount = | ||||||
528 | BinaryOperator::CreateMul(FI.InnerLimit, FI.OuterLimit, "flatten.tripcount", | ||||||
529 | FI.OuterLoop->getLoopPreheader()->getTerminator()); | ||||||
530 | LLVM_DEBUG(dbgs() << "Created new trip count in preheader: ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Created new trip count in preheader: " ; NewTripCount->dump(); } } while (false) | ||||||
531 | NewTripCount->dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Created new trip count in preheader: " ; NewTripCount->dump(); } } while (false); | ||||||
532 | |||||||
533 | // Fix up PHI nodes that take values from the inner loop back-edge, which | ||||||
534 | // we are about to remove. | ||||||
535 | FI.InnerInductionPHI->removeIncomingValue(FI.InnerLoop->getLoopLatch()); | ||||||
536 | |||||||
537 | // The old Phi will be optimised away later, but for now we can't leave | ||||||
538 | // leave it in an invalid state, so are updating them too. | ||||||
539 | for (PHINode *PHI : FI.InnerPHIsToTransform) | ||||||
540 | PHI->removeIncomingValue(FI.InnerLoop->getLoopLatch()); | ||||||
541 | |||||||
542 | // Modify the trip count of the outer loop to be the product of the two | ||||||
543 | // trip counts. | ||||||
544 | cast<User>(FI.OuterBranch->getCondition())->setOperand(1, NewTripCount); | ||||||
545 | |||||||
546 | // Replace the inner loop backedge with an unconditional branch to the exit. | ||||||
547 | BasicBlock *InnerExitBlock = FI.InnerLoop->getExitBlock(); | ||||||
548 | BasicBlock *InnerExitingBlock = FI.InnerLoop->getExitingBlock(); | ||||||
549 | InnerExitingBlock->getTerminator()->eraseFromParent(); | ||||||
550 | BranchInst::Create(InnerExitBlock, InnerExitingBlock); | ||||||
551 | DT->deleteEdge(InnerExitingBlock, FI.InnerLoop->getHeader()); | ||||||
552 | |||||||
553 | // Replace all uses of the polynomial calculated from the two induction | ||||||
554 | // variables with the one new one. | ||||||
555 | IRBuilder<> Builder(FI.OuterInductionPHI->getParent()->getTerminator()); | ||||||
556 | for (Value *V : FI.LinearIVUses) { | ||||||
557 | Value *OuterValue = FI.OuterInductionPHI; | ||||||
558 | if (FI.Widened) | ||||||
559 | OuterValue = Builder.CreateTrunc(FI.OuterInductionPHI, V->getType(), | ||||||
560 | "flatten.trunciv"); | ||||||
561 | |||||||
562 | LLVM_DEBUG(dbgs() << "Replacing: "; V->dump();do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Replacing: "; V->dump (); dbgs() << "with: "; OuterValue->dump(); } } while (false) | ||||||
563 | dbgs() << "with: "; OuterValue->dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Replacing: "; V->dump (); dbgs() << "with: "; OuterValue->dump(); } } while (false); | ||||||
564 | V->replaceAllUsesWith(OuterValue); | ||||||
565 | } | ||||||
566 | |||||||
567 | // Tell LoopInfo, SCEV and the pass manager that the inner loop has been | ||||||
568 | // deleted, and any information that have about the outer loop invalidated. | ||||||
569 | SE->forgetLoop(FI.OuterLoop); | ||||||
570 | SE->forgetLoop(FI.InnerLoop); | ||||||
571 | LI->erase(FI.InnerLoop); | ||||||
572 | return true; | ||||||
573 | } | ||||||
574 | |||||||
575 | static bool CanWidenIV(struct FlattenInfo &FI, DominatorTree *DT, | ||||||
576 | LoopInfo *LI, ScalarEvolution *SE, | ||||||
577 | AssumptionCache *AC, const TargetTransformInfo *TTI) { | ||||||
578 | if (!WidenIV) { | ||||||
579 | LLVM_DEBUG(dbgs() << "Widening the IVs is disabled\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Widening the IVs is disabled\n" ; } } while (false); | ||||||
580 | return false; | ||||||
581 | } | ||||||
582 | |||||||
583 | LLVM_DEBUG(dbgs() << "Try widening the IVs\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Try widening the IVs\n"; } } while (false); | ||||||
584 | Module *M = FI.InnerLoop->getHeader()->getParent()->getParent(); | ||||||
585 | auto &DL = M->getDataLayout(); | ||||||
586 | auto *InnerType = FI.InnerInductionPHI->getType(); | ||||||
587 | auto *OuterType = FI.OuterInductionPHI->getType(); | ||||||
588 | unsigned MaxLegalSize = DL.getLargestLegalIntTypeSizeInBits(); | ||||||
589 | auto *MaxLegalType = DL.getLargestLegalIntType(M->getContext()); | ||||||
590 | |||||||
591 | // If both induction types are less than the maximum legal integer width, | ||||||
592 | // promote both to the widest type available so we know calculating | ||||||
593 | // (OuterLimit * InnerLimit) as the new trip count is safe. | ||||||
594 | if (InnerType != OuterType || | ||||||
595 | InnerType->getScalarSizeInBits() >= MaxLegalSize || | ||||||
596 | MaxLegalType->getScalarSizeInBits() < InnerType->getScalarSizeInBits() * 2) { | ||||||
597 | LLVM_DEBUG(dbgs() << "Can't widen the IV\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Can't widen the IV\n"; } } while (false); | ||||||
598 | return false; | ||||||
599 | } | ||||||
600 | |||||||
601 | SCEVExpander Rewriter(*SE, DL, "loopflatten"); | ||||||
602 | SmallVector<WideIVInfo, 2> WideIVs; | ||||||
603 | SmallVector<WeakTrackingVH, 4> DeadInsts; | ||||||
604 | WideIVs.push_back( {FI.InnerInductionPHI, MaxLegalType, false }); | ||||||
605 | WideIVs.push_back( {FI.OuterInductionPHI, MaxLegalType, false }); | ||||||
606 | unsigned ElimExt; | ||||||
607 | unsigned Widened; | ||||||
608 | |||||||
609 | for (unsigned i = 0; i < WideIVs.size(); i++) { | ||||||
610 | PHINode *WidePhi = createWideIV(WideIVs[i], LI, SE, Rewriter, DT, DeadInsts, | ||||||
611 | ElimExt, Widened, true /* HasGuards */, | ||||||
612 | true /* UsePostIncrementRanges */); | ||||||
613 | if (!WidePhi) | ||||||
614 | return false; | ||||||
615 | LLVM_DEBUG(dbgs() << "Created wide phi: "; WidePhi->dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Created wide phi: "; WidePhi ->dump(); } } while (false); | ||||||
616 | LLVM_DEBUG(dbgs() << "Deleting old phi: "; WideIVs[i].NarrowIV->dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Deleting old phi: "; WideIVs [i].NarrowIV->dump(); } } while (false); | ||||||
617 | RecursivelyDeleteDeadPHINode(WideIVs[i].NarrowIV); | ||||||
618 | } | ||||||
619 | // After widening, rediscover all the loop components. | ||||||
620 | assert(Widened && "Widenend IV expected")((Widened && "Widenend IV expected") ? static_cast< void> (0) : __assert_fail ("Widened && \"Widenend IV expected\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/lib/Transforms/Scalar/LoopFlatten.cpp" , 620, __PRETTY_FUNCTION__)); | ||||||
621 | FI.Widened = true; | ||||||
622 | return CanFlattenLoopPair(FI, DT, LI, SE, AC, TTI); | ||||||
623 | } | ||||||
624 | |||||||
625 | static bool FlattenLoopPair(struct FlattenInfo &FI, DominatorTree *DT, | ||||||
626 | LoopInfo *LI, ScalarEvolution *SE, | ||||||
627 | AssumptionCache *AC, | ||||||
628 | const TargetTransformInfo *TTI) { | ||||||
629 | LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Loop flattening running on outer loop " << FI.OuterLoop->getHeader()->getName() << " and inner loop " << FI.InnerLoop->getHeader()-> getName() << " in " << FI.OuterLoop->getHeader ()->getParent()->getName() << "\n"; } } while (false ) | ||||||
630 | dbgs() << "Loop flattening running on outer loop "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Loop flattening running on outer loop " << FI.OuterLoop->getHeader()->getName() << " and inner loop " << FI.InnerLoop->getHeader()-> getName() << " in " << FI.OuterLoop->getHeader ()->getParent()->getName() << "\n"; } } while (false ) | ||||||
631 | << FI.OuterLoop->getHeader()->getName() << " and inner loop "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Loop flattening running on outer loop " << FI.OuterLoop->getHeader()->getName() << " and inner loop " << FI.InnerLoop->getHeader()-> getName() << " in " << FI.OuterLoop->getHeader ()->getParent()->getName() << "\n"; } } while (false ) | ||||||
632 | << FI.InnerLoop->getHeader()->getName() << " in "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Loop flattening running on outer loop " << FI.OuterLoop->getHeader()->getName() << " and inner loop " << FI.InnerLoop->getHeader()-> getName() << " in " << FI.OuterLoop->getHeader ()->getParent()->getName() << "\n"; } } while (false ) | ||||||
633 | << FI.OuterLoop->getHeader()->getParent()->getName() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Loop flattening running on outer loop " << FI.OuterLoop->getHeader()->getName() << " and inner loop " << FI.InnerLoop->getHeader()-> getName() << " in " << FI.OuterLoop->getHeader ()->getParent()->getName() << "\n"; } } while (false ); | ||||||
634 | |||||||
635 | if (!CanFlattenLoopPair(FI, DT, LI, SE, AC, TTI)) | ||||||
636 | return false; | ||||||
637 | |||||||
638 | // Check if we can widen the induction variables to avoid overflow checks. | ||||||
639 | if (CanWidenIV(FI, DT, LI, SE, AC, TTI)) | ||||||
640 | return DoFlattenLoopPair(FI, DT, LI, SE, AC, TTI); | ||||||
641 | |||||||
642 | // Check if the new iteration variable might overflow. In this case, we | ||||||
643 | // need to version the loop, and select the original version at runtime if | ||||||
644 | // the iteration space is too large. | ||||||
645 | // TODO: We currently don't version the loop. | ||||||
646 | OverflowResult OR = checkOverflow(FI, DT, AC); | ||||||
647 | if (OR == OverflowResult::AlwaysOverflowsHigh || | ||||||
648 | OR == OverflowResult::AlwaysOverflowsLow) { | ||||||
649 | LLVM_DEBUG(dbgs() << "Multiply would always overflow, so not profitable\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Multiply would always overflow, so not profitable\n" ; } } while (false); | ||||||
650 | return false; | ||||||
651 | } else if (OR == OverflowResult::MayOverflow) { | ||||||
652 | LLVM_DEBUG(dbgs() << "Multiply might overflow, not flattening\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Multiply might overflow, not flattening\n" ; } } while (false); | ||||||
653 | return false; | ||||||
654 | } | ||||||
655 | |||||||
656 | LLVM_DEBUG(dbgs() << "Multiply cannot overflow, modifying loop in-place\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-flatten")) { dbgs() << "Multiply cannot overflow, modifying loop in-place\n" ; } } while (false); | ||||||
657 | return DoFlattenLoopPair(FI, DT, LI, SE, AC, TTI); | ||||||
658 | } | ||||||
659 | |||||||
660 | bool Flatten(DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, | ||||||
661 | AssumptionCache *AC, TargetTransformInfo *TTI) { | ||||||
662 | bool Changed = false; | ||||||
663 | for (auto *InnerLoop : LI->getLoopsInPreorder()) { | ||||||
664 | auto *OuterLoop = InnerLoop->getParentLoop(); | ||||||
665 | if (!OuterLoop) | ||||||
666 | continue; | ||||||
667 | struct FlattenInfo FI(OuterLoop, InnerLoop); | ||||||
668 | Changed |= FlattenLoopPair(FI, DT, LI, SE, AC, TTI); | ||||||
669 | } | ||||||
670 | return Changed; | ||||||
671 | } | ||||||
672 | |||||||
673 | PreservedAnalyses LoopFlattenPass::run(Function &F, | ||||||
674 | FunctionAnalysisManager &AM) { | ||||||
675 | auto *DT = &AM.getResult<DominatorTreeAnalysis>(F); | ||||||
676 | auto *LI = &AM.getResult<LoopAnalysis>(F); | ||||||
677 | auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F); | ||||||
678 | auto *AC = &AM.getResult<AssumptionAnalysis>(F); | ||||||
679 | auto *TTI = &AM.getResult<TargetIRAnalysis>(F); | ||||||
680 | |||||||
681 | if (!Flatten(DT, LI, SE, AC, TTI)) | ||||||
682 | return PreservedAnalyses::all(); | ||||||
683 | |||||||
684 | PreservedAnalyses PA; | ||||||
685 | PA.preserveSet<CFGAnalyses>(); | ||||||
686 | return PA; | ||||||
687 | } | ||||||
688 | |||||||
689 | namespace { | ||||||
690 | class LoopFlattenLegacyPass : public FunctionPass { | ||||||
691 | public: | ||||||
692 | static char ID; // Pass ID, replacement for typeid | ||||||
693 | LoopFlattenLegacyPass() : FunctionPass(ID) { | ||||||
694 | initializeLoopFlattenLegacyPassPass(*PassRegistry::getPassRegistry()); | ||||||
695 | } | ||||||
696 | |||||||
697 | // Possibly flatten loop L into its child. | ||||||
698 | bool runOnFunction(Function &F) override; | ||||||
699 | |||||||
700 | void getAnalysisUsage(AnalysisUsage &AU) const override { | ||||||
701 | getLoopAnalysisUsage(AU); | ||||||
702 | AU.addRequired<TargetTransformInfoWrapperPass>(); | ||||||
703 | AU.addPreserved<TargetTransformInfoWrapperPass>(); | ||||||
704 | AU.addRequired<AssumptionCacheTracker>(); | ||||||
705 | AU.addPreserved<AssumptionCacheTracker>(); | ||||||
706 | } | ||||||
707 | }; | ||||||
708 | } // namespace | ||||||
709 | |||||||
710 | char LoopFlattenLegacyPass::ID = 0; | ||||||
711 | INITIALIZE_PASS_BEGIN(LoopFlattenLegacyPass, "loop-flatten", "Flattens loops",static void *initializeLoopFlattenLegacyPassPassOnce(PassRegistry &Registry) { | ||||||
712 | false, false)static void *initializeLoopFlattenLegacyPassPassOnce(PassRegistry &Registry) { | ||||||
713 | INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)initializeTargetTransformInfoWrapperPassPass(Registry); | ||||||
714 | INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)initializeAssumptionCacheTrackerPass(Registry); | ||||||
715 | INITIALIZE_PASS_END(LoopFlattenLegacyPass, "loop-flatten", "Flattens loops",PassInfo *PI = new PassInfo( "Flattens loops", "loop-flatten" , &LoopFlattenLegacyPass::ID, PassInfo::NormalCtor_t(callDefaultCtor <LoopFlattenLegacyPass>), false, false); Registry.registerPass (*PI, true); return PI; } static llvm::once_flag InitializeLoopFlattenLegacyPassPassFlag ; void llvm::initializeLoopFlattenLegacyPassPass(PassRegistry &Registry) { llvm::call_once(InitializeLoopFlattenLegacyPassPassFlag , initializeLoopFlattenLegacyPassPassOnce, std::ref(Registry) ); } | ||||||
716 | false, false)PassInfo *PI = new PassInfo( "Flattens loops", "loop-flatten" , &LoopFlattenLegacyPass::ID, PassInfo::NormalCtor_t(callDefaultCtor <LoopFlattenLegacyPass>), false, false); Registry.registerPass (*PI, true); return PI; } static llvm::once_flag InitializeLoopFlattenLegacyPassPassFlag ; void llvm::initializeLoopFlattenLegacyPassPass(PassRegistry &Registry) { llvm::call_once(InitializeLoopFlattenLegacyPassPassFlag , initializeLoopFlattenLegacyPassPassOnce, std::ref(Registry) ); } | ||||||
717 | |||||||
718 | FunctionPass *llvm::createLoopFlattenPass() { return new LoopFlattenLegacyPass(); } | ||||||
719 | |||||||
720 | bool LoopFlattenLegacyPass::runOnFunction(Function &F) { | ||||||
721 | ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); | ||||||
722 | LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); | ||||||
723 | auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>(); | ||||||
724 | DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr; | ||||||
725 | auto &TTIP = getAnalysis<TargetTransformInfoWrapperPass>(); | ||||||
726 | auto *TTI = &TTIP.getTTI(F); | ||||||
727 | auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); | ||||||
728 | return Flatten(DT, LI, SE, AC, TTI); | ||||||
729 | } |
1 | //===- llvm/Instructions.h - Instruction subclass definitions ---*- C++ -*-===// |
2 | // |
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 |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | // |
9 | // This file exposes the class definitions of all of the subclasses of the |
10 | // Instruction class. This is meant to be an easy way to get access to all |
11 | // instruction subclasses. |
12 | // |
13 | //===----------------------------------------------------------------------===// |
14 | |
15 | #ifndef LLVM_IR_INSTRUCTIONS_H |
16 | #define LLVM_IR_INSTRUCTIONS_H |
17 | |
18 | #include "llvm/ADT/ArrayRef.h" |
19 | #include "llvm/ADT/Bitfields.h" |
20 | #include "llvm/ADT/None.h" |
21 | #include "llvm/ADT/STLExtras.h" |
22 | #include "llvm/ADT/SmallVector.h" |
23 | #include "llvm/ADT/StringRef.h" |
24 | #include "llvm/ADT/Twine.h" |
25 | #include "llvm/ADT/iterator.h" |
26 | #include "llvm/ADT/iterator_range.h" |
27 | #include "llvm/IR/Attributes.h" |
28 | #include "llvm/IR/BasicBlock.h" |
29 | #include "llvm/IR/CallingConv.h" |
30 | #include "llvm/IR/CFG.h" |
31 | #include "llvm/IR/Constant.h" |
32 | #include "llvm/IR/DerivedTypes.h" |
33 | #include "llvm/IR/Function.h" |
34 | #include "llvm/IR/InstrTypes.h" |
35 | #include "llvm/IR/Instruction.h" |
36 | #include "llvm/IR/OperandTraits.h" |
37 | #include "llvm/IR/Type.h" |
38 | #include "llvm/IR/Use.h" |
39 | #include "llvm/IR/User.h" |
40 | #include "llvm/IR/Value.h" |
41 | #include "llvm/Support/AtomicOrdering.h" |
42 | #include "llvm/Support/Casting.h" |
43 | #include "llvm/Support/ErrorHandling.h" |
44 | #include <cassert> |
45 | #include <cstddef> |
46 | #include <cstdint> |
47 | #include <iterator> |
48 | |
49 | namespace llvm { |
50 | |
51 | class APInt; |
52 | class ConstantInt; |
53 | class DataLayout; |
54 | class LLVMContext; |
55 | |
56 | //===----------------------------------------------------------------------===// |
57 | // AllocaInst Class |
58 | //===----------------------------------------------------------------------===// |
59 | |
60 | /// an instruction to allocate memory on the stack |
61 | class AllocaInst : public UnaryInstruction { |
62 | Type *AllocatedType; |
63 | |
64 | using AlignmentField = AlignmentBitfieldElementT<0>; |
65 | using UsedWithInAllocaField = BoolBitfieldElementT<AlignmentField::NextBit>; |
66 | using SwiftErrorField = BoolBitfieldElementT<UsedWithInAllocaField::NextBit>; |
67 | static_assert(Bitfield::areContiguous<AlignmentField, UsedWithInAllocaField, |
68 | SwiftErrorField>(), |
69 | "Bitfields must be contiguous"); |
70 | |
71 | protected: |
72 | // Note: Instruction needs to be a friend here to call cloneImpl. |
73 | friend class Instruction; |
74 | |
75 | AllocaInst *cloneImpl() const; |
76 | |
77 | public: |
78 | explicit AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, |
79 | const Twine &Name, Instruction *InsertBefore); |
80 | AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, |
81 | const Twine &Name, BasicBlock *InsertAtEnd); |
82 | |
83 | AllocaInst(Type *Ty, unsigned AddrSpace, const Twine &Name, |
84 | Instruction *InsertBefore); |
85 | AllocaInst(Type *Ty, unsigned AddrSpace, |
86 | const Twine &Name, BasicBlock *InsertAtEnd); |
87 | |
88 | AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, Align Align, |
89 | const Twine &Name = "", Instruction *InsertBefore = nullptr); |
90 | AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, Align Align, |
91 | const Twine &Name, BasicBlock *InsertAtEnd); |
92 | |
93 | /// Return true if there is an allocation size parameter to the allocation |
94 | /// instruction that is not 1. |
95 | bool isArrayAllocation() const; |
96 | |
97 | /// Get the number of elements allocated. For a simple allocation of a single |
98 | /// element, this will return a constant 1 value. |
99 | const Value *getArraySize() const { return getOperand(0); } |
100 | Value *getArraySize() { return getOperand(0); } |
101 | |
102 | /// Overload to return most specific pointer type. |
103 | PointerType *getType() const { |
104 | return cast<PointerType>(Instruction::getType()); |
105 | } |
106 | |
107 | /// Get allocation size in bits. Returns None if size can't be determined, |
108 | /// e.g. in case of a VLA. |
109 | Optional<TypeSize> getAllocationSizeInBits(const DataLayout &DL) const; |
110 | |
111 | /// Return the type that is being allocated by the instruction. |
112 | Type *getAllocatedType() const { return AllocatedType; } |
113 | /// for use only in special circumstances that need to generically |
114 | /// transform a whole instruction (eg: IR linking and vectorization). |
115 | void setAllocatedType(Type *Ty) { AllocatedType = Ty; } |
116 | |
117 | /// Return the alignment of the memory that is being allocated by the |
118 | /// instruction. |
119 | Align getAlign() const { |
120 | return Align(1ULL << getSubclassData<AlignmentField>()); |
121 | } |
122 | |
123 | void setAlignment(Align Align) { |
124 | setSubclassData<AlignmentField>(Log2(Align)); |
125 | } |
126 | |
127 | // FIXME: Remove this one transition to Align is over. |
128 | unsigned getAlignment() const { return getAlign().value(); } |
129 | |
130 | /// Return true if this alloca is in the entry block of the function and is a |
131 | /// constant size. If so, the code generator will fold it into the |
132 | /// prolog/epilog code, so it is basically free. |
133 | bool isStaticAlloca() const; |
134 | |
135 | /// Return true if this alloca is used as an inalloca argument to a call. Such |
136 | /// allocas are never considered static even if they are in the entry block. |
137 | bool isUsedWithInAlloca() const { |
138 | return getSubclassData<UsedWithInAllocaField>(); |
139 | } |
140 | |
141 | /// Specify whether this alloca is used to represent the arguments to a call. |
142 | void setUsedWithInAlloca(bool V) { |
143 | setSubclassData<UsedWithInAllocaField>(V); |
144 | } |
145 | |
146 | /// Return true if this alloca is used as a swifterror argument to a call. |
147 | bool isSwiftError() const { return getSubclassData<SwiftErrorField>(); } |
148 | /// Specify whether this alloca is used to represent a swifterror. |
149 | void setSwiftError(bool V) { setSubclassData<SwiftErrorField>(V); } |
150 | |
151 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
152 | static bool classof(const Instruction *I) { |
153 | return (I->getOpcode() == Instruction::Alloca); |
154 | } |
155 | static bool classof(const Value *V) { |
156 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
157 | } |
158 | |
159 | private: |
160 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
161 | // method so that subclasses cannot accidentally use it. |
162 | template <typename Bitfield> |
163 | void setSubclassData(typename Bitfield::Type Value) { |
164 | Instruction::setSubclassData<Bitfield>(Value); |
165 | } |
166 | }; |
167 | |
168 | //===----------------------------------------------------------------------===// |
169 | // LoadInst Class |
170 | //===----------------------------------------------------------------------===// |
171 | |
172 | /// An instruction for reading from memory. This uses the SubclassData field in |
173 | /// Value to store whether or not the load is volatile. |
174 | class LoadInst : public UnaryInstruction { |
175 | using VolatileField = BoolBitfieldElementT<0>; |
176 | using AlignmentField = AlignmentBitfieldElementT<VolatileField::NextBit>; |
177 | using OrderingField = AtomicOrderingBitfieldElementT<AlignmentField::NextBit>; |
178 | static_assert( |
179 | Bitfield::areContiguous<VolatileField, AlignmentField, OrderingField>(), |
180 | "Bitfields must be contiguous"); |
181 | |
182 | void AssertOK(); |
183 | |
184 | protected: |
185 | // Note: Instruction needs to be a friend here to call cloneImpl. |
186 | friend class Instruction; |
187 | |
188 | LoadInst *cloneImpl() const; |
189 | |
190 | public: |
191 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, |
192 | Instruction *InsertBefore); |
193 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd); |
194 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile, |
195 | Instruction *InsertBefore); |
196 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile, |
197 | BasicBlock *InsertAtEnd); |
198 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile, |
199 | Align Align, Instruction *InsertBefore = nullptr); |
200 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile, |
201 | Align Align, BasicBlock *InsertAtEnd); |
202 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile, |
203 | Align Align, AtomicOrdering Order, |
204 | SyncScope::ID SSID = SyncScope::System, |
205 | Instruction *InsertBefore = nullptr); |
206 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile, |
207 | Align Align, AtomicOrdering Order, SyncScope::ID SSID, |
208 | BasicBlock *InsertAtEnd); |
209 | |
210 | /// Return true if this is a load from a volatile memory location. |
211 | bool isVolatile() const { return getSubclassData<VolatileField>(); } |
212 | |
213 | /// Specify whether this is a volatile load or not. |
214 | void setVolatile(bool V) { setSubclassData<VolatileField>(V); } |
215 | |
216 | /// Return the alignment of the access that is being performed. |
217 | /// FIXME: Remove this function once transition to Align is over. |
218 | /// Use getAlign() instead. |
219 | unsigned getAlignment() const { return getAlign().value(); } |
220 | |
221 | /// Return the alignment of the access that is being performed. |
222 | Align getAlign() const { |
223 | return Align(1ULL << (getSubclassData<AlignmentField>())); |
224 | } |
225 | |
226 | void setAlignment(Align Align) { |
227 | setSubclassData<AlignmentField>(Log2(Align)); |
228 | } |
229 | |
230 | /// Returns the ordering constraint of this load instruction. |
231 | AtomicOrdering getOrdering() const { |
232 | return getSubclassData<OrderingField>(); |
233 | } |
234 | /// Sets the ordering constraint of this load instruction. May not be Release |
235 | /// or AcquireRelease. |
236 | void setOrdering(AtomicOrdering Ordering) { |
237 | setSubclassData<OrderingField>(Ordering); |
238 | } |
239 | |
240 | /// Returns the synchronization scope ID of this load instruction. |
241 | SyncScope::ID getSyncScopeID() const { |
242 | return SSID; |
243 | } |
244 | |
245 | /// Sets the synchronization scope ID of this load instruction. |
246 | void setSyncScopeID(SyncScope::ID SSID) { |
247 | this->SSID = SSID; |
248 | } |
249 | |
250 | /// Sets the ordering constraint and the synchronization scope ID of this load |
251 | /// instruction. |
252 | void setAtomic(AtomicOrdering Ordering, |
253 | SyncScope::ID SSID = SyncScope::System) { |
254 | setOrdering(Ordering); |
255 | setSyncScopeID(SSID); |
256 | } |
257 | |
258 | bool isSimple() const { return !isAtomic() && !isVolatile(); } |
259 | |
260 | bool isUnordered() const { |
261 | return (getOrdering() == AtomicOrdering::NotAtomic || |
262 | getOrdering() == AtomicOrdering::Unordered) && |
263 | !isVolatile(); |
264 | } |
265 | |
266 | Value *getPointerOperand() { return getOperand(0); } |
267 | const Value *getPointerOperand() const { return getOperand(0); } |
268 | static unsigned getPointerOperandIndex() { return 0U; } |
269 | Type *getPointerOperandType() const { return getPointerOperand()->getType(); } |
270 | |
271 | /// Returns the address space of the pointer operand. |
272 | unsigned getPointerAddressSpace() const { |
273 | return getPointerOperandType()->getPointerAddressSpace(); |
274 | } |
275 | |
276 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
277 | static bool classof(const Instruction *I) { |
278 | return I->getOpcode() == Instruction::Load; |
279 | } |
280 | static bool classof(const Value *V) { |
281 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
282 | } |
283 | |
284 | private: |
285 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
286 | // method so that subclasses cannot accidentally use it. |
287 | template <typename Bitfield> |
288 | void setSubclassData(typename Bitfield::Type Value) { |
289 | Instruction::setSubclassData<Bitfield>(Value); |
290 | } |
291 | |
292 | /// The synchronization scope ID of this load instruction. Not quite enough |
293 | /// room in SubClassData for everything, so synchronization scope ID gets its |
294 | /// own field. |
295 | SyncScope::ID SSID; |
296 | }; |
297 | |
298 | //===----------------------------------------------------------------------===// |
299 | // StoreInst Class |
300 | //===----------------------------------------------------------------------===// |
301 | |
302 | /// An instruction for storing to memory. |
303 | class StoreInst : public Instruction { |
304 | using VolatileField = BoolBitfieldElementT<0>; |
305 | using AlignmentField = AlignmentBitfieldElementT<VolatileField::NextBit>; |
306 | using OrderingField = AtomicOrderingBitfieldElementT<AlignmentField::NextBit>; |
307 | static_assert( |
308 | Bitfield::areContiguous<VolatileField, AlignmentField, OrderingField>(), |
309 | "Bitfields must be contiguous"); |
310 | |
311 | void AssertOK(); |
312 | |
313 | protected: |
314 | // Note: Instruction needs to be a friend here to call cloneImpl. |
315 | friend class Instruction; |
316 | |
317 | StoreInst *cloneImpl() const; |
318 | |
319 | public: |
320 | StoreInst(Value *Val, Value *Ptr, Instruction *InsertBefore); |
321 | StoreInst(Value *Val, Value *Ptr, BasicBlock *InsertAtEnd); |
322 | StoreInst(Value *Val, Value *Ptr, bool isVolatile, Instruction *InsertBefore); |
323 | StoreInst(Value *Val, Value *Ptr, bool isVolatile, BasicBlock *InsertAtEnd); |
324 | StoreInst(Value *Val, Value *Ptr, bool isVolatile, Align Align, |
325 | Instruction *InsertBefore = nullptr); |
326 | StoreInst(Value *Val, Value *Ptr, bool isVolatile, Align Align, |
327 | BasicBlock *InsertAtEnd); |
328 | StoreInst(Value *Val, Value *Ptr, bool isVolatile, Align Align, |
329 | AtomicOrdering Order, SyncScope::ID SSID = SyncScope::System, |
330 | Instruction *InsertBefore = nullptr); |
331 | StoreInst(Value *Val, Value *Ptr, bool isVolatile, Align Align, |
332 | AtomicOrdering Order, SyncScope::ID SSID, BasicBlock *InsertAtEnd); |
333 | |
334 | // allocate space for exactly two operands |
335 | void *operator new(size_t s) { |
336 | return User::operator new(s, 2); |
337 | } |
338 | |
339 | /// Return true if this is a store to a volatile memory location. |
340 | bool isVolatile() const { return getSubclassData<VolatileField>(); } |
341 | |
342 | /// Specify whether this is a volatile store or not. |
343 | void setVolatile(bool V) { setSubclassData<VolatileField>(V); } |
344 | |
345 | /// Transparently provide more efficient getOperand methods. |
346 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
347 | |
348 | /// Return the alignment of the access that is being performed |
349 | /// FIXME: Remove this function once transition to Align is over. |
350 | /// Use getAlign() instead. |
351 | unsigned getAlignment() const { return getAlign().value(); } |
352 | |
353 | Align getAlign() const { |
354 | return Align(1ULL << (getSubclassData<AlignmentField>())); |
355 | } |
356 | |
357 | void setAlignment(Align Align) { |
358 | setSubclassData<AlignmentField>(Log2(Align)); |
359 | } |
360 | |
361 | /// Returns the ordering constraint of this store instruction. |
362 | AtomicOrdering getOrdering() const { |
363 | return getSubclassData<OrderingField>(); |
364 | } |
365 | |
366 | /// Sets the ordering constraint of this store instruction. May not be |
367 | /// Acquire or AcquireRelease. |
368 | void setOrdering(AtomicOrdering Ordering) { |
369 | setSubclassData<OrderingField>(Ordering); |
370 | } |
371 | |
372 | /// Returns the synchronization scope ID of this store instruction. |
373 | SyncScope::ID getSyncScopeID() const { |
374 | return SSID; |
375 | } |
376 | |
377 | /// Sets the synchronization scope ID of this store instruction. |
378 | void setSyncScopeID(SyncScope::ID SSID) { |
379 | this->SSID = SSID; |
380 | } |
381 | |
382 | /// Sets the ordering constraint and the synchronization scope ID of this |
383 | /// store instruction. |
384 | void setAtomic(AtomicOrdering Ordering, |
385 | SyncScope::ID SSID = SyncScope::System) { |
386 | setOrdering(Ordering); |
387 | setSyncScopeID(SSID); |
388 | } |
389 | |
390 | bool isSimple() const { return !isAtomic() && !isVolatile(); } |
391 | |
392 | bool isUnordered() const { |
393 | return (getOrdering() == AtomicOrdering::NotAtomic || |
394 | getOrdering() == AtomicOrdering::Unordered) && |
395 | !isVolatile(); |
396 | } |
397 | |
398 | Value *getValueOperand() { return getOperand(0); } |
399 | const Value *getValueOperand() const { return getOperand(0); } |
400 | |
401 | Value *getPointerOperand() { return getOperand(1); } |
402 | const Value *getPointerOperand() const { return getOperand(1); } |
403 | static unsigned getPointerOperandIndex() { return 1U; } |
404 | Type *getPointerOperandType() const { return getPointerOperand()->getType(); } |
405 | |
406 | /// Returns the address space of the pointer operand. |
407 | unsigned getPointerAddressSpace() const { |
408 | return getPointerOperandType()->getPointerAddressSpace(); |
409 | } |
410 | |
411 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
412 | static bool classof(const Instruction *I) { |
413 | return I->getOpcode() == Instruction::Store; |
414 | } |
415 | static bool classof(const Value *V) { |
416 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
417 | } |
418 | |
419 | private: |
420 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
421 | // method so that subclasses cannot accidentally use it. |
422 | template <typename Bitfield> |
423 | void setSubclassData(typename Bitfield::Type Value) { |
424 | Instruction::setSubclassData<Bitfield>(Value); |
425 | } |
426 | |
427 | /// The synchronization scope ID of this store instruction. Not quite enough |
428 | /// room in SubClassData for everything, so synchronization scope ID gets its |
429 | /// own field. |
430 | SyncScope::ID SSID; |
431 | }; |
432 | |
433 | template <> |
434 | struct OperandTraits<StoreInst> : public FixedNumOperandTraits<StoreInst, 2> { |
435 | }; |
436 | |
437 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(StoreInst, Value)StoreInst::op_iterator StoreInst::op_begin() { return OperandTraits <StoreInst>::op_begin(this); } StoreInst::const_op_iterator StoreInst::op_begin() const { return OperandTraits<StoreInst >::op_begin(const_cast<StoreInst*>(this)); } StoreInst ::op_iterator StoreInst::op_end() { return OperandTraits<StoreInst >::op_end(this); } StoreInst::const_op_iterator StoreInst:: op_end() const { return OperandTraits<StoreInst>::op_end (const_cast<StoreInst*>(this)); } Value *StoreInst::getOperand (unsigned i_nocapture) const { ((i_nocapture < OperandTraits <StoreInst>::operands(this) && "getOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<StoreInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 437, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<StoreInst>::op_begin(const_cast<StoreInst *>(this))[i_nocapture].get()); } void StoreInst::setOperand (unsigned i_nocapture, Value *Val_nocapture) { ((i_nocapture < OperandTraits<StoreInst>::operands(this) && "setOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<StoreInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 437, __PRETTY_FUNCTION__)); OperandTraits<StoreInst>:: op_begin(this)[i_nocapture] = Val_nocapture; } unsigned StoreInst ::getNumOperands() const { return OperandTraits<StoreInst> ::operands(this); } template <int Idx_nocapture> Use & StoreInst::Op() { return this->OpFrom<Idx_nocapture> (this); } template <int Idx_nocapture> const Use &StoreInst ::Op() const { return this->OpFrom<Idx_nocapture>(this ); } |
438 | |
439 | //===----------------------------------------------------------------------===// |
440 | // FenceInst Class |
441 | //===----------------------------------------------------------------------===// |
442 | |
443 | /// An instruction for ordering other memory operations. |
444 | class FenceInst : public Instruction { |
445 | using OrderingField = AtomicOrderingBitfieldElementT<0>; |
446 | |
447 | void Init(AtomicOrdering Ordering, SyncScope::ID SSID); |
448 | |
449 | protected: |
450 | // Note: Instruction needs to be a friend here to call cloneImpl. |
451 | friend class Instruction; |
452 | |
453 | FenceInst *cloneImpl() const; |
454 | |
455 | public: |
456 | // Ordering may only be Acquire, Release, AcquireRelease, or |
457 | // SequentiallyConsistent. |
458 | FenceInst(LLVMContext &C, AtomicOrdering Ordering, |
459 | SyncScope::ID SSID = SyncScope::System, |
460 | Instruction *InsertBefore = nullptr); |
461 | FenceInst(LLVMContext &C, AtomicOrdering Ordering, SyncScope::ID SSID, |
462 | BasicBlock *InsertAtEnd); |
463 | |
464 | // allocate space for exactly zero operands |
465 | void *operator new(size_t s) { |
466 | return User::operator new(s, 0); |
467 | } |
468 | |
469 | /// Returns the ordering constraint of this fence instruction. |
470 | AtomicOrdering getOrdering() const { |
471 | return getSubclassData<OrderingField>(); |
472 | } |
473 | |
474 | /// Sets the ordering constraint of this fence instruction. May only be |
475 | /// Acquire, Release, AcquireRelease, or SequentiallyConsistent. |
476 | void setOrdering(AtomicOrdering Ordering) { |
477 | setSubclassData<OrderingField>(Ordering); |
478 | } |
479 | |
480 | /// Returns the synchronization scope ID of this fence instruction. |
481 | SyncScope::ID getSyncScopeID() const { |
482 | return SSID; |
483 | } |
484 | |
485 | /// Sets the synchronization scope ID of this fence instruction. |
486 | void setSyncScopeID(SyncScope::ID SSID) { |
487 | this->SSID = SSID; |
488 | } |
489 | |
490 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
491 | static bool classof(const Instruction *I) { |
492 | return I->getOpcode() == Instruction::Fence; |
493 | } |
494 | static bool classof(const Value *V) { |
495 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
496 | } |
497 | |
498 | private: |
499 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
500 | // method so that subclasses cannot accidentally use it. |
501 | template <typename Bitfield> |
502 | void setSubclassData(typename Bitfield::Type Value) { |
503 | Instruction::setSubclassData<Bitfield>(Value); |
504 | } |
505 | |
506 | /// The synchronization scope ID of this fence instruction. Not quite enough |
507 | /// room in SubClassData for everything, so synchronization scope ID gets its |
508 | /// own field. |
509 | SyncScope::ID SSID; |
510 | }; |
511 | |
512 | //===----------------------------------------------------------------------===// |
513 | // AtomicCmpXchgInst Class |
514 | //===----------------------------------------------------------------------===// |
515 | |
516 | /// An instruction that atomically checks whether a |
517 | /// specified value is in a memory location, and, if it is, stores a new value |
518 | /// there. The value returned by this instruction is a pair containing the |
519 | /// original value as first element, and an i1 indicating success (true) or |
520 | /// failure (false) as second element. |
521 | /// |
522 | class AtomicCmpXchgInst : public Instruction { |
523 | void Init(Value *Ptr, Value *Cmp, Value *NewVal, Align Align, |
524 | AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering, |
525 | SyncScope::ID SSID); |
526 | |
527 | template <unsigned Offset> |
528 | using AtomicOrderingBitfieldElement = |
529 | typename Bitfield::Element<AtomicOrdering, Offset, 3, |
530 | AtomicOrdering::LAST>; |
531 | |
532 | protected: |
533 | // Note: Instruction needs to be a friend here to call cloneImpl. |
534 | friend class Instruction; |
535 | |
536 | AtomicCmpXchgInst *cloneImpl() const; |
537 | |
538 | public: |
539 | AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal, Align Alignment, |
540 | AtomicOrdering SuccessOrdering, |
541 | AtomicOrdering FailureOrdering, SyncScope::ID SSID, |
542 | Instruction *InsertBefore = nullptr); |
543 | AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal, Align Alignment, |
544 | AtomicOrdering SuccessOrdering, |
545 | AtomicOrdering FailureOrdering, SyncScope::ID SSID, |
546 | BasicBlock *InsertAtEnd); |
547 | |
548 | // allocate space for exactly three operands |
549 | void *operator new(size_t s) { |
550 | return User::operator new(s, 3); |
551 | } |
552 | |
553 | using VolatileField = BoolBitfieldElementT<0>; |
554 | using WeakField = BoolBitfieldElementT<VolatileField::NextBit>; |
555 | using SuccessOrderingField = |
556 | AtomicOrderingBitfieldElementT<WeakField::NextBit>; |
557 | using FailureOrderingField = |
558 | AtomicOrderingBitfieldElementT<SuccessOrderingField::NextBit>; |
559 | using AlignmentField = |
560 | AlignmentBitfieldElementT<FailureOrderingField::NextBit>; |
561 | static_assert( |
562 | Bitfield::areContiguous<VolatileField, WeakField, SuccessOrderingField, |
563 | FailureOrderingField, AlignmentField>(), |
564 | "Bitfields must be contiguous"); |
565 | |
566 | /// Return the alignment of the memory that is being allocated by the |
567 | /// instruction. |
568 | Align getAlign() const { |
569 | return Align(1ULL << getSubclassData<AlignmentField>()); |
570 | } |
571 | |
572 | void setAlignment(Align Align) { |
573 | setSubclassData<AlignmentField>(Log2(Align)); |
574 | } |
575 | |
576 | /// Return true if this is a cmpxchg from a volatile memory |
577 | /// location. |
578 | /// |
579 | bool isVolatile() const { return getSubclassData<VolatileField>(); } |
580 | |
581 | /// Specify whether this is a volatile cmpxchg. |
582 | /// |
583 | void setVolatile(bool V) { setSubclassData<VolatileField>(V); } |
584 | |
585 | /// Return true if this cmpxchg may spuriously fail. |
586 | bool isWeak() const { return getSubclassData<WeakField>(); } |
587 | |
588 | void setWeak(bool IsWeak) { setSubclassData<WeakField>(IsWeak); } |
589 | |
590 | /// Transparently provide more efficient getOperand methods. |
591 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
592 | |
593 | /// Returns the success ordering constraint of this cmpxchg instruction. |
594 | AtomicOrdering getSuccessOrdering() const { |
595 | return getSubclassData<SuccessOrderingField>(); |
596 | } |
597 | |
598 | /// Sets the success ordering constraint of this cmpxchg instruction. |
599 | void setSuccessOrdering(AtomicOrdering Ordering) { |
600 | assert(Ordering != AtomicOrdering::NotAtomic &&((Ordering != AtomicOrdering::NotAtomic && "CmpXchg instructions can only be atomic." ) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"CmpXchg instructions can only be atomic.\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 601, __PRETTY_FUNCTION__)) |
601 | "CmpXchg instructions can only be atomic.")((Ordering != AtomicOrdering::NotAtomic && "CmpXchg instructions can only be atomic." ) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"CmpXchg instructions can only be atomic.\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 601, __PRETTY_FUNCTION__)); |
602 | setSubclassData<SuccessOrderingField>(Ordering); |
603 | } |
604 | |
605 | /// Returns the failure ordering constraint of this cmpxchg instruction. |
606 | AtomicOrdering getFailureOrdering() const { |
607 | return getSubclassData<FailureOrderingField>(); |
608 | } |
609 | |
610 | /// Sets the failure ordering constraint of this cmpxchg instruction. |
611 | void setFailureOrdering(AtomicOrdering Ordering) { |
612 | assert(Ordering != AtomicOrdering::NotAtomic &&((Ordering != AtomicOrdering::NotAtomic && "CmpXchg instructions can only be atomic." ) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"CmpXchg instructions can only be atomic.\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 613, __PRETTY_FUNCTION__)) |
613 | "CmpXchg instructions can only be atomic.")((Ordering != AtomicOrdering::NotAtomic && "CmpXchg instructions can only be atomic." ) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"CmpXchg instructions can only be atomic.\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 613, __PRETTY_FUNCTION__)); |
614 | setSubclassData<FailureOrderingField>(Ordering); |
615 | } |
616 | |
617 | /// Returns the synchronization scope ID of this cmpxchg instruction. |
618 | SyncScope::ID getSyncScopeID() const { |
619 | return SSID; |
620 | } |
621 | |
622 | /// Sets the synchronization scope ID of this cmpxchg instruction. |
623 | void setSyncScopeID(SyncScope::ID SSID) { |
624 | this->SSID = SSID; |
625 | } |
626 | |
627 | Value *getPointerOperand() { return getOperand(0); } |
628 | const Value *getPointerOperand() const { return getOperand(0); } |
629 | static unsigned getPointerOperandIndex() { return 0U; } |
630 | |
631 | Value *getCompareOperand() { return getOperand(1); } |
632 | const Value *getCompareOperand() const { return getOperand(1); } |
633 | |
634 | Value *getNewValOperand() { return getOperand(2); } |
635 | const Value *getNewValOperand() const { return getOperand(2); } |
636 | |
637 | /// Returns the address space of the pointer operand. |
638 | unsigned getPointerAddressSpace() const { |
639 | return getPointerOperand()->getType()->getPointerAddressSpace(); |
640 | } |
641 | |
642 | /// Returns the strongest permitted ordering on failure, given the |
643 | /// desired ordering on success. |
644 | /// |
645 | /// If the comparison in a cmpxchg operation fails, there is no atomic store |
646 | /// so release semantics cannot be provided. So this function drops explicit |
647 | /// Release requests from the AtomicOrdering. A SequentiallyConsistent |
648 | /// operation would remain SequentiallyConsistent. |
649 | static AtomicOrdering |
650 | getStrongestFailureOrdering(AtomicOrdering SuccessOrdering) { |
651 | switch (SuccessOrdering) { |
652 | default: |
653 | llvm_unreachable("invalid cmpxchg success ordering")::llvm::llvm_unreachable_internal("invalid cmpxchg success ordering" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 653); |
654 | case AtomicOrdering::Release: |
655 | case AtomicOrdering::Monotonic: |
656 | return AtomicOrdering::Monotonic; |
657 | case AtomicOrdering::AcquireRelease: |
658 | case AtomicOrdering::Acquire: |
659 | return AtomicOrdering::Acquire; |
660 | case AtomicOrdering::SequentiallyConsistent: |
661 | return AtomicOrdering::SequentiallyConsistent; |
662 | } |
663 | } |
664 | |
665 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
666 | static bool classof(const Instruction *I) { |
667 | return I->getOpcode() == Instruction::AtomicCmpXchg; |
668 | } |
669 | static bool classof(const Value *V) { |
670 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
671 | } |
672 | |
673 | private: |
674 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
675 | // method so that subclasses cannot accidentally use it. |
676 | template <typename Bitfield> |
677 | void setSubclassData(typename Bitfield::Type Value) { |
678 | Instruction::setSubclassData<Bitfield>(Value); |
679 | } |
680 | |
681 | /// The synchronization scope ID of this cmpxchg instruction. Not quite |
682 | /// enough room in SubClassData for everything, so synchronization scope ID |
683 | /// gets its own field. |
684 | SyncScope::ID SSID; |
685 | }; |
686 | |
687 | template <> |
688 | struct OperandTraits<AtomicCmpXchgInst> : |
689 | public FixedNumOperandTraits<AtomicCmpXchgInst, 3> { |
690 | }; |
691 | |
692 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicCmpXchgInst, Value)AtomicCmpXchgInst::op_iterator AtomicCmpXchgInst::op_begin() { return OperandTraits<AtomicCmpXchgInst>::op_begin(this ); } AtomicCmpXchgInst::const_op_iterator AtomicCmpXchgInst:: op_begin() const { return OperandTraits<AtomicCmpXchgInst> ::op_begin(const_cast<AtomicCmpXchgInst*>(this)); } AtomicCmpXchgInst ::op_iterator AtomicCmpXchgInst::op_end() { return OperandTraits <AtomicCmpXchgInst>::op_end(this); } AtomicCmpXchgInst:: const_op_iterator AtomicCmpXchgInst::op_end() const { return OperandTraits <AtomicCmpXchgInst>::op_end(const_cast<AtomicCmpXchgInst *>(this)); } Value *AtomicCmpXchgInst::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<AtomicCmpXchgInst >::operands(this) && "getOperand() out of range!") ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicCmpXchgInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 692, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<AtomicCmpXchgInst>::op_begin(const_cast <AtomicCmpXchgInst*>(this))[i_nocapture].get()); } void AtomicCmpXchgInst::setOperand(unsigned i_nocapture, Value *Val_nocapture ) { ((i_nocapture < OperandTraits<AtomicCmpXchgInst> ::operands(this) && "setOperand() out of range!") ? static_cast <void> (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicCmpXchgInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 692, __PRETTY_FUNCTION__)); OperandTraits<AtomicCmpXchgInst >::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned AtomicCmpXchgInst::getNumOperands() const { return OperandTraits <AtomicCmpXchgInst>::operands(this); } template <int Idx_nocapture> Use &AtomicCmpXchgInst::Op() { return this ->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture > const Use &AtomicCmpXchgInst::Op() const { return this ->OpFrom<Idx_nocapture>(this); } |
693 | |
694 | //===----------------------------------------------------------------------===// |
695 | // AtomicRMWInst Class |
696 | //===----------------------------------------------------------------------===// |
697 | |
698 | /// an instruction that atomically reads a memory location, |
699 | /// combines it with another value, and then stores the result back. Returns |
700 | /// the old value. |
701 | /// |
702 | class AtomicRMWInst : public Instruction { |
703 | protected: |
704 | // Note: Instruction needs to be a friend here to call cloneImpl. |
705 | friend class Instruction; |
706 | |
707 | AtomicRMWInst *cloneImpl() const; |
708 | |
709 | public: |
710 | /// This enumeration lists the possible modifications atomicrmw can make. In |
711 | /// the descriptions, 'p' is the pointer to the instruction's memory location, |
712 | /// 'old' is the initial value of *p, and 'v' is the other value passed to the |
713 | /// instruction. These instructions always return 'old'. |
714 | enum BinOp : unsigned { |
715 | /// *p = v |
716 | Xchg, |
717 | /// *p = old + v |
718 | Add, |
719 | /// *p = old - v |
720 | Sub, |
721 | /// *p = old & v |
722 | And, |
723 | /// *p = ~(old & v) |
724 | Nand, |
725 | /// *p = old | v |
726 | Or, |
727 | /// *p = old ^ v |
728 | Xor, |
729 | /// *p = old >signed v ? old : v |
730 | Max, |
731 | /// *p = old <signed v ? old : v |
732 | Min, |
733 | /// *p = old >unsigned v ? old : v |
734 | UMax, |
735 | /// *p = old <unsigned v ? old : v |
736 | UMin, |
737 | |
738 | /// *p = old + v |
739 | FAdd, |
740 | |
741 | /// *p = old - v |
742 | FSub, |
743 | |
744 | FIRST_BINOP = Xchg, |
745 | LAST_BINOP = FSub, |
746 | BAD_BINOP |
747 | }; |
748 | |
749 | private: |
750 | template <unsigned Offset> |
751 | using AtomicOrderingBitfieldElement = |
752 | typename Bitfield::Element<AtomicOrdering, Offset, 3, |
753 | AtomicOrdering::LAST>; |
754 | |
755 | template <unsigned Offset> |
756 | using BinOpBitfieldElement = |
757 | typename Bitfield::Element<BinOp, Offset, 4, BinOp::LAST_BINOP>; |
758 | |
759 | public: |
760 | AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val, Align Alignment, |
761 | AtomicOrdering Ordering, SyncScope::ID SSID, |
762 | Instruction *InsertBefore = nullptr); |
763 | AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val, Align Alignment, |
764 | AtomicOrdering Ordering, SyncScope::ID SSID, |
765 | BasicBlock *InsertAtEnd); |
766 | |
767 | // allocate space for exactly two operands |
768 | void *operator new(size_t s) { |
769 | return User::operator new(s, 2); |
770 | } |
771 | |
772 | using VolatileField = BoolBitfieldElementT<0>; |
773 | using AtomicOrderingField = |
774 | AtomicOrderingBitfieldElementT<VolatileField::NextBit>; |
775 | using OperationField = BinOpBitfieldElement<AtomicOrderingField::NextBit>; |
776 | using AlignmentField = AlignmentBitfieldElementT<OperationField::NextBit>; |
777 | static_assert(Bitfield::areContiguous<VolatileField, AtomicOrderingField, |
778 | OperationField, AlignmentField>(), |
779 | "Bitfields must be contiguous"); |
780 | |
781 | BinOp getOperation() const { return getSubclassData<OperationField>(); } |
782 | |
783 | static StringRef getOperationName(BinOp Op); |
784 | |
785 | static bool isFPOperation(BinOp Op) { |
786 | switch (Op) { |
787 | case AtomicRMWInst::FAdd: |
788 | case AtomicRMWInst::FSub: |
789 | return true; |
790 | default: |
791 | return false; |
792 | } |
793 | } |
794 | |
795 | void setOperation(BinOp Operation) { |
796 | setSubclassData<OperationField>(Operation); |
797 | } |
798 | |
799 | /// Return the alignment of the memory that is being allocated by the |
800 | /// instruction. |
801 | Align getAlign() const { |
802 | return Align(1ULL << getSubclassData<AlignmentField>()); |
803 | } |
804 | |
805 | void setAlignment(Align Align) { |
806 | setSubclassData<AlignmentField>(Log2(Align)); |
807 | } |
808 | |
809 | /// Return true if this is a RMW on a volatile memory location. |
810 | /// |
811 | bool isVolatile() const { return getSubclassData<VolatileField>(); } |
812 | |
813 | /// Specify whether this is a volatile RMW or not. |
814 | /// |
815 | void setVolatile(bool V) { setSubclassData<VolatileField>(V); } |
816 | |
817 | /// Transparently provide more efficient getOperand methods. |
818 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
819 | |
820 | /// Returns the ordering constraint of this rmw instruction. |
821 | AtomicOrdering getOrdering() const { |
822 | return getSubclassData<AtomicOrderingField>(); |
823 | } |
824 | |
825 | /// Sets the ordering constraint of this rmw instruction. |
826 | void setOrdering(AtomicOrdering Ordering) { |
827 | assert(Ordering != AtomicOrdering::NotAtomic &&((Ordering != AtomicOrdering::NotAtomic && "atomicrmw instructions can only be atomic." ) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"atomicrmw instructions can only be atomic.\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 828, __PRETTY_FUNCTION__)) |
828 | "atomicrmw instructions can only be atomic.")((Ordering != AtomicOrdering::NotAtomic && "atomicrmw instructions can only be atomic." ) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"atomicrmw instructions can only be atomic.\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 828, __PRETTY_FUNCTION__)); |
829 | setSubclassData<AtomicOrderingField>(Ordering); |
830 | } |
831 | |
832 | /// Returns the synchronization scope ID of this rmw instruction. |
833 | SyncScope::ID getSyncScopeID() const { |
834 | return SSID; |
835 | } |
836 | |
837 | /// Sets the synchronization scope ID of this rmw instruction. |
838 | void setSyncScopeID(SyncScope::ID SSID) { |
839 | this->SSID = SSID; |
840 | } |
841 | |
842 | Value *getPointerOperand() { return getOperand(0); } |
843 | const Value *getPointerOperand() const { return getOperand(0); } |
844 | static unsigned getPointerOperandIndex() { return 0U; } |
845 | |
846 | Value *getValOperand() { return getOperand(1); } |
847 | const Value *getValOperand() const { return getOperand(1); } |
848 | |
849 | /// Returns the address space of the pointer operand. |
850 | unsigned getPointerAddressSpace() const { |
851 | return getPointerOperand()->getType()->getPointerAddressSpace(); |
852 | } |
853 | |
854 | bool isFloatingPointOperation() const { |
855 | return isFPOperation(getOperation()); |
856 | } |
857 | |
858 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
859 | static bool classof(const Instruction *I) { |
860 | return I->getOpcode() == Instruction::AtomicRMW; |
861 | } |
862 | static bool classof(const Value *V) { |
863 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
864 | } |
865 | |
866 | private: |
867 | void Init(BinOp Operation, Value *Ptr, Value *Val, Align Align, |
868 | AtomicOrdering Ordering, SyncScope::ID SSID); |
869 | |
870 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
871 | // method so that subclasses cannot accidentally use it. |
872 | template <typename Bitfield> |
873 | void setSubclassData(typename Bitfield::Type Value) { |
874 | Instruction::setSubclassData<Bitfield>(Value); |
875 | } |
876 | |
877 | /// The synchronization scope ID of this rmw instruction. Not quite enough |
878 | /// room in SubClassData for everything, so synchronization scope ID gets its |
879 | /// own field. |
880 | SyncScope::ID SSID; |
881 | }; |
882 | |
883 | template <> |
884 | struct OperandTraits<AtomicRMWInst> |
885 | : public FixedNumOperandTraits<AtomicRMWInst,2> { |
886 | }; |
887 | |
888 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicRMWInst, Value)AtomicRMWInst::op_iterator AtomicRMWInst::op_begin() { return OperandTraits<AtomicRMWInst>::op_begin(this); } AtomicRMWInst ::const_op_iterator AtomicRMWInst::op_begin() const { return OperandTraits <AtomicRMWInst>::op_begin(const_cast<AtomicRMWInst*> (this)); } AtomicRMWInst::op_iterator AtomicRMWInst::op_end() { return OperandTraits<AtomicRMWInst>::op_end(this); } AtomicRMWInst::const_op_iterator AtomicRMWInst::op_end() const { return OperandTraits<AtomicRMWInst>::op_end(const_cast <AtomicRMWInst*>(this)); } Value *AtomicRMWInst::getOperand (unsigned i_nocapture) const { ((i_nocapture < OperandTraits <AtomicRMWInst>::operands(this) && "getOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicRMWInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 888, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<AtomicRMWInst>::op_begin(const_cast< AtomicRMWInst*>(this))[i_nocapture].get()); } void AtomicRMWInst ::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (( i_nocapture < OperandTraits<AtomicRMWInst>::operands (this) && "setOperand() out of range!") ? static_cast <void> (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicRMWInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 888, __PRETTY_FUNCTION__)); OperandTraits<AtomicRMWInst> ::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned AtomicRMWInst ::getNumOperands() const { return OperandTraits<AtomicRMWInst >::operands(this); } template <int Idx_nocapture> Use &AtomicRMWInst::Op() { return this->OpFrom<Idx_nocapture >(this); } template <int Idx_nocapture> const Use & AtomicRMWInst::Op() const { return this->OpFrom<Idx_nocapture >(this); } |
889 | |
890 | //===----------------------------------------------------------------------===// |
891 | // GetElementPtrInst Class |
892 | //===----------------------------------------------------------------------===// |
893 | |
894 | // checkGEPType - Simple wrapper function to give a better assertion failure |
895 | // message on bad indexes for a gep instruction. |
896 | // |
897 | inline Type *checkGEPType(Type *Ty) { |
898 | assert(Ty && "Invalid GetElementPtrInst indices for type!")((Ty && "Invalid GetElementPtrInst indices for type!" ) ? static_cast<void> (0) : __assert_fail ("Ty && \"Invalid GetElementPtrInst indices for type!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 898, __PRETTY_FUNCTION__)); |
899 | return Ty; |
900 | } |
901 | |
902 | /// an instruction for type-safe pointer arithmetic to |
903 | /// access elements of arrays and structs |
904 | /// |
905 | class GetElementPtrInst : public Instruction { |
906 | Type *SourceElementType; |
907 | Type *ResultElementType; |
908 | |
909 | GetElementPtrInst(const GetElementPtrInst &GEPI); |
910 | |
911 | /// Constructors - Create a getelementptr instruction with a base pointer an |
912 | /// list of indices. The first ctor can optionally insert before an existing |
913 | /// instruction, the second appends the new instruction to the specified |
914 | /// BasicBlock. |
915 | inline GetElementPtrInst(Type *PointeeType, Value *Ptr, |
916 | ArrayRef<Value *> IdxList, unsigned Values, |
917 | const Twine &NameStr, Instruction *InsertBefore); |
918 | inline GetElementPtrInst(Type *PointeeType, Value *Ptr, |
919 | ArrayRef<Value *> IdxList, unsigned Values, |
920 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
921 | |
922 | void init(Value *Ptr, ArrayRef<Value *> IdxList, const Twine &NameStr); |
923 | |
924 | protected: |
925 | // Note: Instruction needs to be a friend here to call cloneImpl. |
926 | friend class Instruction; |
927 | |
928 | GetElementPtrInst *cloneImpl() const; |
929 | |
930 | public: |
931 | static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr, |
932 | ArrayRef<Value *> IdxList, |
933 | const Twine &NameStr = "", |
934 | Instruction *InsertBefore = nullptr) { |
935 | unsigned Values = 1 + unsigned(IdxList.size()); |
936 | if (!PointeeType) |
937 | PointeeType = |
938 | cast<PointerType>(Ptr->getType()->getScalarType())->getElementType(); |
939 | else |
940 | assert(((PointeeType == cast<PointerType>(Ptr->getType()-> getScalarType())->getElementType()) ? static_cast<void> (0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 942, __PRETTY_FUNCTION__)) |
941 | PointeeType ==((PointeeType == cast<PointerType>(Ptr->getType()-> getScalarType())->getElementType()) ? static_cast<void> (0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 942, __PRETTY_FUNCTION__)) |
942 | cast<PointerType>(Ptr->getType()->getScalarType())->getElementType())((PointeeType == cast<PointerType>(Ptr->getType()-> getScalarType())->getElementType()) ? static_cast<void> (0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 942, __PRETTY_FUNCTION__)); |
943 | return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values, |
944 | NameStr, InsertBefore); |
945 | } |
946 | |
947 | static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr, |
948 | ArrayRef<Value *> IdxList, |
949 | const Twine &NameStr, |
950 | BasicBlock *InsertAtEnd) { |
951 | unsigned Values = 1 + unsigned(IdxList.size()); |
952 | if (!PointeeType) |
953 | PointeeType = |
954 | cast<PointerType>(Ptr->getType()->getScalarType())->getElementType(); |
955 | else |
956 | assert(((PointeeType == cast<PointerType>(Ptr->getType()-> getScalarType())->getElementType()) ? static_cast<void> (0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 958, __PRETTY_FUNCTION__)) |
957 | PointeeType ==((PointeeType == cast<PointerType>(Ptr->getType()-> getScalarType())->getElementType()) ? static_cast<void> (0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 958, __PRETTY_FUNCTION__)) |
958 | cast<PointerType>(Ptr->getType()->getScalarType())->getElementType())((PointeeType == cast<PointerType>(Ptr->getType()-> getScalarType())->getElementType()) ? static_cast<void> (0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 958, __PRETTY_FUNCTION__)); |
959 | return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values, |
960 | NameStr, InsertAtEnd); |
961 | } |
962 | |
963 | /// Create an "inbounds" getelementptr. See the documentation for the |
964 | /// "inbounds" flag in LangRef.html for details. |
965 | static GetElementPtrInst *CreateInBounds(Value *Ptr, |
966 | ArrayRef<Value *> IdxList, |
967 | const Twine &NameStr = "", |
968 | Instruction *InsertBefore = nullptr){ |
969 | return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertBefore); |
970 | } |
971 | |
972 | static GetElementPtrInst * |
973 | CreateInBounds(Type *PointeeType, Value *Ptr, ArrayRef<Value *> IdxList, |
974 | const Twine &NameStr = "", |
975 | Instruction *InsertBefore = nullptr) { |
976 | GetElementPtrInst *GEP = |
977 | Create(PointeeType, Ptr, IdxList, NameStr, InsertBefore); |
978 | GEP->setIsInBounds(true); |
979 | return GEP; |
980 | } |
981 | |
982 | static GetElementPtrInst *CreateInBounds(Value *Ptr, |
983 | ArrayRef<Value *> IdxList, |
984 | const Twine &NameStr, |
985 | BasicBlock *InsertAtEnd) { |
986 | return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertAtEnd); |
987 | } |
988 | |
989 | static GetElementPtrInst *CreateInBounds(Type *PointeeType, Value *Ptr, |
990 | ArrayRef<Value *> IdxList, |
991 | const Twine &NameStr, |
992 | BasicBlock *InsertAtEnd) { |
993 | GetElementPtrInst *GEP = |
994 | Create(PointeeType, Ptr, IdxList, NameStr, InsertAtEnd); |
995 | GEP->setIsInBounds(true); |
996 | return GEP; |
997 | } |
998 | |
999 | /// Transparently provide more efficient getOperand methods. |
1000 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
1001 | |
1002 | Type *getSourceElementType() const { return SourceElementType; } |
1003 | |
1004 | void setSourceElementType(Type *Ty) { SourceElementType = Ty; } |
1005 | void setResultElementType(Type *Ty) { ResultElementType = Ty; } |
1006 | |
1007 | Type *getResultElementType() const { |
1008 | assert(ResultElementType ==((ResultElementType == cast<PointerType>(getType()-> getScalarType())->getElementType()) ? static_cast<void> (0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 1009, __PRETTY_FUNCTION__)) |
1009 | cast<PointerType>(getType()->getScalarType())->getElementType())((ResultElementType == cast<PointerType>(getType()-> getScalarType())->getElementType()) ? static_cast<void> (0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 1009, __PRETTY_FUNCTION__)); |
1010 | return ResultElementType; |
1011 | } |
1012 | |
1013 | /// Returns the address space of this instruction's pointer type. |
1014 | unsigned getAddressSpace() const { |
1015 | // Note that this is always the same as the pointer operand's address space |
1016 | // and that is cheaper to compute, so cheat here. |
1017 | return getPointerAddressSpace(); |
1018 | } |
1019 | |
1020 | /// Returns the result type of a getelementptr with the given source |
1021 | /// element type and indexes. |
1022 | /// |
1023 | /// Null is returned if the indices are invalid for the specified |
1024 | /// source element type. |
1025 | static Type *getIndexedType(Type *Ty, ArrayRef<Value *> IdxList); |
1026 | static Type *getIndexedType(Type *Ty, ArrayRef<Constant *> IdxList); |
1027 | static Type *getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList); |
1028 | |
1029 | /// Return the type of the element at the given index of an indexable |
1030 | /// type. This is equivalent to "getIndexedType(Agg, {Zero, Idx})". |
1031 | /// |
1032 | /// Returns null if the type can't be indexed, or the given index is not |
1033 | /// legal for the given type. |
1034 | static Type *getTypeAtIndex(Type *Ty, Value *Idx); |
1035 | static Type *getTypeAtIndex(Type *Ty, uint64_t Idx); |
1036 | |
1037 | inline op_iterator idx_begin() { return op_begin()+1; } |
1038 | inline const_op_iterator idx_begin() const { return op_begin()+1; } |
1039 | inline op_iterator idx_end() { return op_end(); } |
1040 | inline const_op_iterator idx_end() const { return op_end(); } |
1041 | |
1042 | inline iterator_range<op_iterator> indices() { |
1043 | return make_range(idx_begin(), idx_end()); |
1044 | } |
1045 | |
1046 | inline iterator_range<const_op_iterator> indices() const { |
1047 | return make_range(idx_begin(), idx_end()); |
1048 | } |
1049 | |
1050 | Value *getPointerOperand() { |
1051 | return getOperand(0); |
1052 | } |
1053 | const Value *getPointerOperand() const { |
1054 | return getOperand(0); |
1055 | } |
1056 | static unsigned getPointerOperandIndex() { |
1057 | return 0U; // get index for modifying correct operand. |
1058 | } |
1059 | |
1060 | /// Method to return the pointer operand as a |
1061 | /// PointerType. |
1062 | Type *getPointerOperandType() const { |
1063 | return getPointerOperand()->getType(); |
1064 | } |
1065 | |
1066 | /// Returns the address space of the pointer operand. |
1067 | unsigned getPointerAddressSpace() const { |
1068 | return getPointerOperandType()->getPointerAddressSpace(); |
1069 | } |
1070 | |
1071 | /// Returns the pointer type returned by the GEP |
1072 | /// instruction, which may be a vector of pointers. |
1073 | static Type *getGEPReturnType(Type *ElTy, Value *Ptr, |
1074 | ArrayRef<Value *> IdxList) { |
1075 | Type *PtrTy = PointerType::get(checkGEPType(getIndexedType(ElTy, IdxList)), |
1076 | Ptr->getType()->getPointerAddressSpace()); |
1077 | // Vector GEP |
1078 | if (auto *PtrVTy = dyn_cast<VectorType>(Ptr->getType())) { |
1079 | ElementCount EltCount = PtrVTy->getElementCount(); |
1080 | return VectorType::get(PtrTy, EltCount); |
1081 | } |
1082 | for (Value *Index : IdxList) |
1083 | if (auto *IndexVTy = dyn_cast<VectorType>(Index->getType())) { |
1084 | ElementCount EltCount = IndexVTy->getElementCount(); |
1085 | return VectorType::get(PtrTy, EltCount); |
1086 | } |
1087 | // Scalar GEP |
1088 | return PtrTy; |
1089 | } |
1090 | |
1091 | unsigned getNumIndices() const { // Note: always non-negative |
1092 | return getNumOperands() - 1; |
1093 | } |
1094 | |
1095 | bool hasIndices() const { |
1096 | return getNumOperands() > 1; |
1097 | } |
1098 | |
1099 | /// Return true if all of the indices of this GEP are |
1100 | /// zeros. If so, the result pointer and the first operand have the same |
1101 | /// value, just potentially different types. |
1102 | bool hasAllZeroIndices() const; |
1103 | |
1104 | /// Return true if all of the indices of this GEP are |
1105 | /// constant integers. If so, the result pointer and the first operand have |
1106 | /// a constant offset between them. |
1107 | bool hasAllConstantIndices() const; |
1108 | |
1109 | /// Set or clear the inbounds flag on this GEP instruction. |
1110 | /// See LangRef.html for the meaning of inbounds on a getelementptr. |
1111 | void setIsInBounds(bool b = true); |
1112 | |
1113 | /// Determine whether the GEP has the inbounds flag. |
1114 | bool isInBounds() const; |
1115 | |
1116 | /// Accumulate the constant address offset of this GEP if possible. |
1117 | /// |
1118 | /// This routine accepts an APInt into which it will accumulate the constant |
1119 | /// offset of this GEP if the GEP is in fact constant. If the GEP is not |
1120 | /// all-constant, it returns false and the value of the offset APInt is |
1121 | /// undefined (it is *not* preserved!). The APInt passed into this routine |
1122 | /// must be at least as wide as the IntPtr type for the address space of |
1123 | /// the base GEP pointer. |
1124 | bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const; |
1125 | |
1126 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
1127 | static bool classof(const Instruction *I) { |
1128 | return (I->getOpcode() == Instruction::GetElementPtr); |
1129 | } |
1130 | static bool classof(const Value *V) { |
1131 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
1132 | } |
1133 | }; |
1134 | |
1135 | template <> |
1136 | struct OperandTraits<GetElementPtrInst> : |
1137 | public VariadicOperandTraits<GetElementPtrInst, 1> { |
1138 | }; |
1139 | |
1140 | GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr, |
1141 | ArrayRef<Value *> IdxList, unsigned Values, |
1142 | const Twine &NameStr, |
1143 | Instruction *InsertBefore) |
1144 | : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr, |
1145 | OperandTraits<GetElementPtrInst>::op_end(this) - Values, |
1146 | Values, InsertBefore), |
1147 | SourceElementType(PointeeType), |
1148 | ResultElementType(getIndexedType(PointeeType, IdxList)) { |
1149 | assert(ResultElementType ==((ResultElementType == cast<PointerType>(getType()-> getScalarType())->getElementType()) ? static_cast<void> (0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 1150, __PRETTY_FUNCTION__)) |
1150 | cast<PointerType>(getType()->getScalarType())->getElementType())((ResultElementType == cast<PointerType>(getType()-> getScalarType())->getElementType()) ? static_cast<void> (0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 1150, __PRETTY_FUNCTION__)); |
1151 | init(Ptr, IdxList, NameStr); |
1152 | } |
1153 | |
1154 | GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr, |
1155 | ArrayRef<Value *> IdxList, unsigned Values, |
1156 | const Twine &NameStr, |
1157 | BasicBlock *InsertAtEnd) |
1158 | : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr, |
1159 | OperandTraits<GetElementPtrInst>::op_end(this) - Values, |
1160 | Values, InsertAtEnd), |
1161 | SourceElementType(PointeeType), |
1162 | ResultElementType(getIndexedType(PointeeType, IdxList)) { |
1163 | assert(ResultElementType ==((ResultElementType == cast<PointerType>(getType()-> getScalarType())->getElementType()) ? static_cast<void> (0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 1164, __PRETTY_FUNCTION__)) |
1164 | cast<PointerType>(getType()->getScalarType())->getElementType())((ResultElementType == cast<PointerType>(getType()-> getScalarType())->getElementType()) ? static_cast<void> (0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 1164, __PRETTY_FUNCTION__)); |
1165 | init(Ptr, IdxList, NameStr); |
1166 | } |
1167 | |
1168 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrInst, Value)GetElementPtrInst::op_iterator GetElementPtrInst::op_begin() { return OperandTraits<GetElementPtrInst>::op_begin(this ); } GetElementPtrInst::const_op_iterator GetElementPtrInst:: op_begin() const { return OperandTraits<GetElementPtrInst> ::op_begin(const_cast<GetElementPtrInst*>(this)); } GetElementPtrInst ::op_iterator GetElementPtrInst::op_end() { return OperandTraits <GetElementPtrInst>::op_end(this); } GetElementPtrInst:: const_op_iterator GetElementPtrInst::op_end() const { return OperandTraits <GetElementPtrInst>::op_end(const_cast<GetElementPtrInst *>(this)); } Value *GetElementPtrInst::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<GetElementPtrInst >::operands(this) && "getOperand() out of range!") ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<GetElementPtrInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 1168, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<GetElementPtrInst>::op_begin(const_cast <GetElementPtrInst*>(this))[i_nocapture].get()); } void GetElementPtrInst::setOperand(unsigned i_nocapture, Value *Val_nocapture ) { ((i_nocapture < OperandTraits<GetElementPtrInst> ::operands(this) && "setOperand() out of range!") ? static_cast <void> (0) : __assert_fail ("i_nocapture < OperandTraits<GetElementPtrInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 1168, __PRETTY_FUNCTION__)); OperandTraits<GetElementPtrInst >::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned GetElementPtrInst::getNumOperands() const { return OperandTraits <GetElementPtrInst>::operands(this); } template <int Idx_nocapture> Use &GetElementPtrInst::Op() { return this ->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture > const Use &GetElementPtrInst::Op() const { return this ->OpFrom<Idx_nocapture>(this); } |
1169 | |
1170 | //===----------------------------------------------------------------------===// |
1171 | // ICmpInst Class |
1172 | //===----------------------------------------------------------------------===// |
1173 | |
1174 | /// This instruction compares its operands according to the predicate given |
1175 | /// to the constructor. It only operates on integers or pointers. The operands |
1176 | /// must be identical types. |
1177 | /// Represent an integer comparison operator. |
1178 | class ICmpInst: public CmpInst { |
1179 | void AssertOK() { |
1180 | assert(isIntPredicate() &&((isIntPredicate() && "Invalid ICmp predicate value") ? static_cast<void> (0) : __assert_fail ("isIntPredicate() && \"Invalid ICmp predicate value\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 1181, __PRETTY_FUNCTION__)) |
1181 | "Invalid ICmp predicate value")((isIntPredicate() && "Invalid ICmp predicate value") ? static_cast<void> (0) : __assert_fail ("isIntPredicate() && \"Invalid ICmp predicate value\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 1181, __PRETTY_FUNCTION__)); |
1182 | assert(getOperand(0)->getType() == getOperand(1)->getType() &&((getOperand(0)->getType() == getOperand(1)->getType() && "Both operands to ICmp instruction are not of the same type!" ) ? static_cast<void> (0) : __assert_fail ("getOperand(0)->getType() == getOperand(1)->getType() && \"Both operands to ICmp instruction are not of the same type!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 1183, __PRETTY_FUNCTION__)) |
1183 | "Both operands to ICmp instruction are not of the same type!")((getOperand(0)->getType() == getOperand(1)->getType() && "Both operands to ICmp instruction are not of the same type!" ) ? static_cast<void> (0) : __assert_fail ("getOperand(0)->getType() == getOperand(1)->getType() && \"Both operands to ICmp instruction are not of the same type!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 1183, __PRETTY_FUNCTION__)); |
1184 | // Check that the operands are the right type |
1185 | assert((getOperand(0)->getType()->isIntOrIntVectorTy() ||(((getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand (0)->getType()->isPtrOrPtrVectorTy()) && "Invalid operand types for ICmp instruction" ) ? static_cast<void> (0) : __assert_fail ("(getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand(0)->getType()->isPtrOrPtrVectorTy()) && \"Invalid operand types for ICmp instruction\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 1187, __PRETTY_FUNCTION__)) |
1186 | getOperand(0)->getType()->isPtrOrPtrVectorTy()) &&(((getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand (0)->getType()->isPtrOrPtrVectorTy()) && "Invalid operand types for ICmp instruction" ) ? static_cast<void> (0) : __assert_fail ("(getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand(0)->getType()->isPtrOrPtrVectorTy()) && \"Invalid operand types for ICmp instruction\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 1187, __PRETTY_FUNCTION__)) |
1187 | "Invalid operand types for ICmp instruction")(((getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand (0)->getType()->isPtrOrPtrVectorTy()) && "Invalid operand types for ICmp instruction" ) ? static_cast<void> (0) : __assert_fail ("(getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand(0)->getType()->isPtrOrPtrVectorTy()) && \"Invalid operand types for ICmp instruction\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 1187, __PRETTY_FUNCTION__)); |
1188 | } |
1189 | |
1190 | protected: |
1191 | // Note: Instruction needs to be a friend here to call cloneImpl. |
1192 | friend class Instruction; |
1193 | |
1194 | /// Clone an identical ICmpInst |
1195 | ICmpInst *cloneImpl() const; |
1196 | |
1197 | public: |
1198 | /// Constructor with insert-before-instruction semantics. |
1199 | ICmpInst( |
1200 | Instruction *InsertBefore, ///< Where to insert |
1201 | Predicate pred, ///< The predicate to use for the comparison |
1202 | Value *LHS, ///< The left-hand-side of the expression |
1203 | Value *RHS, ///< The right-hand-side of the expression |
1204 | const Twine &NameStr = "" ///< Name of the instruction |
1205 | ) : CmpInst(makeCmpResultType(LHS->getType()), |
1206 | Instruction::ICmp, pred, LHS, RHS, NameStr, |
1207 | InsertBefore) { |
1208 | #ifndef NDEBUG |
1209 | AssertOK(); |
1210 | #endif |
1211 | } |
1212 | |
1213 | /// Constructor with insert-at-end semantics. |
1214 | ICmpInst( |
1215 | BasicBlock &InsertAtEnd, ///< Block to insert into. |
1216 | Predicate pred, ///< The predicate to use for the comparison |
1217 | Value *LHS, ///< The left-hand-side of the expression |
1218 | Value *RHS, ///< The right-hand-side of the expression |
1219 | const Twine &NameStr = "" ///< Name of the instruction |
1220 | ) : CmpInst(makeCmpResultType(LHS->getType()), |
1221 | Instruction::ICmp, pred, LHS, RHS, NameStr, |
1222 | &InsertAtEnd) { |
1223 | #ifndef NDEBUG |
1224 | AssertOK(); |
1225 | #endif |
1226 | } |
1227 | |
1228 | /// Constructor with no-insertion semantics |
1229 | ICmpInst( |
1230 | Predicate pred, ///< The predicate to use for the comparison |
1231 | Value *LHS, ///< The left-hand-side of the expression |
1232 | Value *RHS, ///< The right-hand-side of the expression |
1233 | const Twine &NameStr = "" ///< Name of the instruction |
1234 | ) : CmpInst(makeCmpResultType(LHS->getType()), |
1235 | Instruction::ICmp, pred, LHS, RHS, NameStr) { |
1236 | #ifndef NDEBUG |
1237 | AssertOK(); |
1238 | #endif |
1239 | } |
1240 | |
1241 | /// For example, EQ->EQ, SLE->SLE, UGT->SGT, etc. |
1242 | /// @returns the predicate that would be the result if the operand were |
1243 | /// regarded as signed. |
1244 | /// Return the signed version of the predicate |
1245 | Predicate getSignedPredicate() const { |
1246 | return getSignedPredicate(getPredicate()); |
1247 | } |
1248 | |
1249 | /// This is a static version that you can use without an instruction. |
1250 | /// Return the signed version of the predicate. |
1251 | static Predicate getSignedPredicate(Predicate pred); |
1252 | |
1253 | /// For example, EQ->EQ, SLE->ULE, UGT->UGT, etc. |
1254 | /// @returns the predicate that would be the result if the operand were |
1255 | /// regarded as unsigned. |
1256 | /// Return the unsigned version of the predicate |
1257 | Predicate getUnsignedPredicate() const { |
1258 | return getUnsignedPredicate(getPredicate()); |
1259 | } |
1260 | |
1261 | /// This is a static version that you can use without an instruction. |
1262 | /// Return the unsigned version of the predicate. |
1263 | static Predicate getUnsignedPredicate(Predicate pred); |
1264 | |
1265 | /// Return true if this predicate is either EQ or NE. This also |
1266 | /// tests for commutativity. |
1267 | static bool isEquality(Predicate P) { |
1268 | return P == ICMP_EQ || P == ICMP_NE; |
1269 | } |
1270 | |
1271 | /// Return true if this predicate is either EQ or NE. This also |
1272 | /// tests for commutativity. |
1273 | bool isEquality() const { |
1274 | return isEquality(getPredicate()); |
1275 | } |
1276 | |
1277 | /// @returns true if the predicate of this ICmpInst is commutative |
1278 | /// Determine if this relation is commutative. |
1279 | bool isCommutative() const { return isEquality(); } |
1280 | |
1281 | /// Return true if the predicate is relational (not EQ or NE). |
1282 | /// |
1283 | bool isRelational() const { |
1284 | return !isEquality(); |
1285 | } |
1286 | |
1287 | /// Return true if the predicate is relational (not EQ or NE). |
1288 | /// |
1289 | static bool isRelational(Predicate P) { |
1290 | return !isEquality(P); |
1291 | } |
1292 | |
1293 | /// Return true if the predicate is SGT or UGT. |
1294 | /// |
1295 | static bool isGT(Predicate P) { |
1296 | return P == ICMP_SGT || P == ICMP_UGT; |
1297 | } |
1298 | |
1299 | /// Return true if the predicate is SLT or ULT. |
1300 | /// |
1301 | static bool isLT(Predicate P) { |
1302 | return P == ICMP_SLT || P == ICMP_ULT; |
1303 | } |
1304 | |
1305 | /// Return true if the predicate is SGE or UGE. |
1306 | /// |
1307 | static bool isGE(Predicate P) { |
1308 | return P == ICMP_SGE || P == ICMP_UGE; |
1309 | } |
1310 | |
1311 | /// Return true if the predicate is SLE or ULE. |
1312 | /// |
1313 | static bool isLE(Predicate P) { |
1314 | return P == ICMP_SLE || P == ICMP_ULE; |
1315 | } |
1316 | |
1317 | /// Exchange the two operands to this instruction in such a way that it does |
1318 | /// not modify the semantics of the instruction. The predicate value may be |
1319 | /// changed to retain the same result if the predicate is order dependent |
1320 | /// (e.g. ult). |
1321 | /// Swap operands and adjust predicate. |
1322 | void swapOperands() { |
1323 | setPredicate(getSwappedPredicate()); |
1324 | Op<0>().swap(Op<1>()); |
1325 | } |
1326 | |
1327 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
1328 | static bool classof(const Instruction *I) { |
1329 | return I->getOpcode() == Instruction::ICmp; |
1330 | } |
1331 | static bool classof(const Value *V) { |
1332 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
1333 | } |
1334 | }; |
1335 | |
1336 | //===----------------------------------------------------------------------===// |
1337 | // FCmpInst Class |
1338 | //===----------------------------------------------------------------------===// |
1339 | |
1340 | /// This instruction compares its operands according to the predicate given |
1341 | /// to the constructor. It only operates on floating point values or packed |
1342 | /// vectors of floating point values. The operands must be identical types. |
1343 | /// Represents a floating point comparison operator. |
1344 | class FCmpInst: public CmpInst { |
1345 | void AssertOK() { |
1346 | assert(isFPPredicate() && "Invalid FCmp predicate value")((isFPPredicate() && "Invalid FCmp predicate value") ? static_cast<void> (0) : __assert_fail ("isFPPredicate() && \"Invalid FCmp predicate value\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 1346, __PRETTY_FUNCTION__)); |
1347 | assert(getOperand(0)->getType() == getOperand(1)->getType() &&((getOperand(0)->getType() == getOperand(1)->getType() && "Both operands to FCmp instruction are not of the same type!" ) ? static_cast<void> (0) : __assert_fail ("getOperand(0)->getType() == getOperand(1)->getType() && \"Both operands to FCmp instruction are not of the same type!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 1348, __PRETTY_FUNCTION__)) |
1348 | "Both operands to FCmp instruction are not of the same type!")((getOperand(0)->getType() == getOperand(1)->getType() && "Both operands to FCmp instruction are not of the same type!" ) ? static_cast<void> (0) : __assert_fail ("getOperand(0)->getType() == getOperand(1)->getType() && \"Both operands to FCmp instruction are not of the same type!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 1348, __PRETTY_FUNCTION__)); |
1349 | // Check that the operands are the right type |
1350 | assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&((getOperand(0)->getType()->isFPOrFPVectorTy() && "Invalid operand types for FCmp instruction") ? static_cast< void> (0) : __assert_fail ("getOperand(0)->getType()->isFPOrFPVectorTy() && \"Invalid operand types for FCmp instruction\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 1351, __PRETTY_FUNCTION__)) |
1351 | "Invalid operand types for FCmp instruction")((getOperand(0)->getType()->isFPOrFPVectorTy() && "Invalid operand types for FCmp instruction") ? static_cast< void> (0) : __assert_fail ("getOperand(0)->getType()->isFPOrFPVectorTy() && \"Invalid operand types for FCmp instruction\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 1351, __PRETTY_FUNCTION__)); |
1352 | } |
1353 | |
1354 | protected: |
1355 | // Note: Instruction needs to be a friend here to call cloneImpl. |
1356 | friend class Instruction; |
1357 | |
1358 | /// Clone an identical FCmpInst |
1359 | FCmpInst *cloneImpl() const; |
1360 | |
1361 | public: |
1362 | /// Constructor with insert-before-instruction semantics. |
1363 | FCmpInst( |
1364 | Instruction *InsertBefore, ///< Where to insert |
1365 | Predicate pred, ///< The predicate to use for the comparison |
1366 | Value *LHS, ///< The left-hand-side of the expression |
1367 | Value *RHS, ///< The right-hand-side of the expression |
1368 | const Twine &NameStr = "" ///< Name of the instruction |
1369 | ) : CmpInst(makeCmpResultType(LHS->getType()), |
1370 | Instruction::FCmp, pred, LHS, RHS, NameStr, |
1371 | InsertBefore) { |
1372 | AssertOK(); |
1373 | } |
1374 | |
1375 | /// Constructor with insert-at-end semantics. |
1376 | FCmpInst( |
1377 | BasicBlock &InsertAtEnd, ///< Block to insert into. |
1378 | Predicate pred, ///< The predicate to use for the comparison |
1379 | Value *LHS, ///< The left-hand-side of the expression |
1380 | Value *RHS, ///< The right-hand-side of the expression |
1381 | const Twine &NameStr = "" ///< Name of the instruction |
1382 | ) : CmpInst(makeCmpResultType(LHS->getType()), |
1383 | Instruction::FCmp, pred, LHS, RHS, NameStr, |
1384 | &InsertAtEnd) { |
1385 | AssertOK(); |
1386 | } |
1387 | |
1388 | /// Constructor with no-insertion semantics |
1389 | FCmpInst( |
1390 | Predicate Pred, ///< The predicate to use for the comparison |
1391 | Value *LHS, ///< The left-hand-side of the expression |
1392 | Value *RHS, ///< The right-hand-side of the expression |
1393 | const Twine &NameStr = "", ///< Name of the instruction |
1394 | Instruction *FlagsSource = nullptr |
1395 | ) : CmpInst(makeCmpResultType(LHS->getType()), Instruction::FCmp, Pred, LHS, |
1396 | RHS, NameStr, nullptr, FlagsSource) { |
1397 | AssertOK(); |
1398 | } |
1399 | |
1400 | /// @returns true if the predicate of this instruction is EQ or NE. |
1401 | /// Determine if this is an equality predicate. |
1402 | static bool isEquality(Predicate Pred) { |
1403 | return Pred == FCMP_OEQ || Pred == FCMP_ONE || Pred == FCMP_UEQ || |
1404 | Pred == FCMP_UNE; |
1405 | } |
1406 | |
1407 | /// @returns true if the predicate of this instruction is EQ or NE. |
1408 | /// Determine if this is an equality predicate. |
1409 | bool isEquality() const { return isEquality(getPredicate()); } |
1410 | |
1411 | /// @returns true if the predicate of this instruction is commutative. |
1412 | /// Determine if this is a commutative predicate. |
1413 | bool isCommutative() const { |
1414 | return isEquality() || |
1415 | getPredicate() == FCMP_FALSE || |
1416 | getPredicate() == FCMP_TRUE || |
1417 | getPredicate() == FCMP_ORD || |
1418 | getPredicate() == FCMP_UNO; |
1419 | } |
1420 | |
1421 | /// @returns true if the predicate is relational (not EQ or NE). |
1422 | /// Determine if this a relational predicate. |
1423 | bool isRelational() const { return !isEquality(); } |
1424 | |
1425 | /// Exchange the two operands to this instruction in such a way that it does |
1426 | /// not modify the semantics of the instruction. The predicate value may be |
1427 | /// changed to retain the same result if the predicate is order dependent |
1428 | /// (e.g. ult). |
1429 | /// Swap operands and adjust predicate. |
1430 | void swapOperands() { |
1431 | setPredicate(getSwappedPredicate()); |
1432 | Op<0>().swap(Op<1>()); |
1433 | } |
1434 | |
1435 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
1436 | static bool classof(const Instruction *I) { |
1437 | return I->getOpcode() == Instruction::FCmp; |
1438 | } |
1439 | static bool classof(const Value *V) { |
1440 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
1441 | } |
1442 | }; |
1443 | |
1444 | //===----------------------------------------------------------------------===// |
1445 | /// This class represents a function call, abstracting a target |
1446 | /// machine's calling convention. This class uses low bit of the SubClassData |
1447 | /// field to indicate whether or not this is a tail call. The rest of the bits |
1448 | /// hold the calling convention of the call. |
1449 | /// |
1450 | class CallInst : public CallBase { |
1451 | CallInst(const CallInst &CI); |
1452 | |
1453 | /// Construct a CallInst given a range of arguments. |
1454 | /// Construct a CallInst from a range of arguments |
1455 | inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1456 | ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr, |
1457 | Instruction *InsertBefore); |
1458 | |
1459 | inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1460 | const Twine &NameStr, Instruction *InsertBefore) |
1461 | : CallInst(Ty, Func, Args, None, NameStr, InsertBefore) {} |
1462 | |
1463 | /// Construct a CallInst given a range of arguments. |
1464 | /// Construct a CallInst from a range of arguments |
1465 | inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1466 | ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr, |
1467 | BasicBlock *InsertAtEnd); |
1468 | |
1469 | explicit CallInst(FunctionType *Ty, Value *F, const Twine &NameStr, |
1470 | Instruction *InsertBefore); |
1471 | |
1472 | CallInst(FunctionType *ty, Value *F, const Twine &NameStr, |
1473 | BasicBlock *InsertAtEnd); |
1474 | |
1475 | void init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args, |
1476 | ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr); |
1477 | void init(FunctionType *FTy, Value *Func, const Twine &NameStr); |
1478 | |
1479 | /// Compute the number of operands to allocate. |
1480 | static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) { |
1481 | // We need one operand for the called function, plus the input operand |
1482 | // counts provided. |
1483 | return 1 + NumArgs + NumBundleInputs; |
1484 | } |
1485 | |
1486 | protected: |
1487 | // Note: Instruction needs to be a friend here to call cloneImpl. |
1488 | friend class Instruction; |
1489 | |
1490 | CallInst *cloneImpl() const; |
1491 | |
1492 | public: |
1493 | static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr = "", |
1494 | Instruction *InsertBefore = nullptr) { |
1495 | return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertBefore); |
1496 | } |
1497 | |
1498 | static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1499 | const Twine &NameStr, |
1500 | Instruction *InsertBefore = nullptr) { |
1501 | return new (ComputeNumOperands(Args.size())) |
1502 | CallInst(Ty, Func, Args, None, NameStr, InsertBefore); |
1503 | } |
1504 | |
1505 | static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1506 | ArrayRef<OperandBundleDef> Bundles = None, |
1507 | const Twine &NameStr = "", |
1508 | Instruction *InsertBefore = nullptr) { |
1509 | const int NumOperands = |
1510 | ComputeNumOperands(Args.size(), CountBundleInputs(Bundles)); |
1511 | const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo); |
1512 | |
1513 | return new (NumOperands, DescriptorBytes) |
1514 | CallInst(Ty, Func, Args, Bundles, NameStr, InsertBefore); |
1515 | } |
1516 | |
1517 | static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr, |
1518 | BasicBlock *InsertAtEnd) { |
1519 | return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertAtEnd); |
1520 | } |
1521 | |
1522 | static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1523 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
1524 | return new (ComputeNumOperands(Args.size())) |
1525 | CallInst(Ty, Func, Args, None, NameStr, InsertAtEnd); |
1526 | } |
1527 | |
1528 | static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1529 | ArrayRef<OperandBundleDef> Bundles, |
1530 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
1531 | const int NumOperands = |
1532 | ComputeNumOperands(Args.size(), CountBundleInputs(Bundles)); |
1533 | const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo); |
1534 | |
1535 | return new (NumOperands, DescriptorBytes) |
1536 | CallInst(Ty, Func, Args, Bundles, NameStr, InsertAtEnd); |
1537 | } |
1538 | |
1539 | static CallInst *Create(FunctionCallee Func, const Twine &NameStr = "", |
1540 | Instruction *InsertBefore = nullptr) { |
1541 | return Create(Func.getFunctionType(), Func.getCallee(), NameStr, |
1542 | InsertBefore); |
1543 | } |
1544 | |
1545 | static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args, |
1546 | ArrayRef<OperandBundleDef> Bundles = None, |
1547 | const Twine &NameStr = "", |
1548 | Instruction *InsertBefore = nullptr) { |
1549 | return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles, |
1550 | NameStr, InsertBefore); |
1551 | } |
1552 | |
1553 | static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args, |
1554 | const Twine &NameStr, |
1555 | Instruction *InsertBefore = nullptr) { |
1556 | return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr, |
1557 | InsertBefore); |
1558 | } |
1559 | |
1560 | static CallInst *Create(FunctionCallee Func, const Twine &NameStr, |
1561 | BasicBlock *InsertAtEnd) { |
1562 | return Create(Func.getFunctionType(), Func.getCallee(), NameStr, |
1563 | InsertAtEnd); |
1564 | } |
1565 | |
1566 | static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args, |
1567 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
1568 | return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr, |
1569 | InsertAtEnd); |
1570 | } |
1571 | |
1572 | static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args, |
1573 | ArrayRef<OperandBundleDef> Bundles, |
1574 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
1575 | return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles, |
1576 | NameStr, InsertAtEnd); |
1577 | } |
1578 | |
1579 | /// Create a clone of \p CI with a different set of operand bundles and |
1580 | /// insert it before \p InsertPt. |
1581 | /// |
1582 | /// The returned call instruction is identical \p CI in every way except that |
1583 | /// the operand bundles for the new instruction are set to the operand bundles |
1584 | /// in \p Bundles. |
1585 | static CallInst *Create(CallInst *CI, ArrayRef<OperandBundleDef> Bundles, |
1586 | Instruction *InsertPt = nullptr); |
1587 | |
1588 | /// Generate the IR for a call to malloc: |
1589 | /// 1. Compute the malloc call's argument as the specified type's size, |
1590 | /// possibly multiplied by the array size if the array size is not |
1591 | /// constant 1. |
1592 | /// 2. Call malloc with that argument. |
1593 | /// 3. Bitcast the result of the malloc call to the specified type. |
1594 | static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy, |
1595 | Type *AllocTy, Value *AllocSize, |
1596 | Value *ArraySize = nullptr, |
1597 | Function *MallocF = nullptr, |
1598 | const Twine &Name = ""); |
1599 | static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy, |
1600 | Type *AllocTy, Value *AllocSize, |
1601 | Value *ArraySize = nullptr, |
1602 | Function *MallocF = nullptr, |
1603 | const Twine &Name = ""); |
1604 | static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy, |
1605 | Type *AllocTy, Value *AllocSize, |
1606 | Value *ArraySize = nullptr, |
1607 | ArrayRef<OperandBundleDef> Bundles = None, |
1608 | Function *MallocF = nullptr, |
1609 | const Twine &Name = ""); |
1610 | static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy, |
1611 | Type *AllocTy, Value *AllocSize, |
1612 | Value *ArraySize = nullptr, |
1613 | ArrayRef<OperandBundleDef> Bundles = None, |
1614 | Function *MallocF = nullptr, |
1615 | const Twine &Name = ""); |
1616 | /// Generate the IR for a call to the builtin free function. |
1617 | static Instruction *CreateFree(Value *Source, Instruction *InsertBefore); |
1618 | static Instruction *CreateFree(Value *Source, BasicBlock *InsertAtEnd); |
1619 | static Instruction *CreateFree(Value *Source, |
1620 | ArrayRef<OperandBundleDef> Bundles, |
1621 | Instruction *InsertBefore); |
1622 | static Instruction *CreateFree(Value *Source, |
1623 | ArrayRef<OperandBundleDef> Bundles, |
1624 | BasicBlock *InsertAtEnd); |
1625 | |
1626 | // Note that 'musttail' implies 'tail'. |
1627 | enum TailCallKind : unsigned { |
1628 | TCK_None = 0, |
1629 | TCK_Tail = 1, |
1630 | TCK_MustTail = 2, |
1631 | TCK_NoTail = 3, |
1632 | TCK_LAST = TCK_NoTail |
1633 | }; |
1634 | |
1635 | using TailCallKindField = Bitfield::Element<TailCallKind, 0, 2, TCK_LAST>; |
1636 | static_assert( |
1637 | Bitfield::areContiguous<TailCallKindField, CallBase::CallingConvField>(), |
1638 | "Bitfields must be contiguous"); |
1639 | |
1640 | TailCallKind getTailCallKind() const { |
1641 | return getSubclassData<TailCallKindField>(); |
1642 | } |
1643 | |
1644 | bool isTailCall() const { |
1645 | TailCallKind Kind = getTailCallKind(); |
1646 | return Kind == TCK_Tail || Kind == TCK_MustTail; |
1647 | } |
1648 | |
1649 | bool isMustTailCall() const { return getTailCallKind() == TCK_MustTail; } |
1650 | |
1651 | bool isNoTailCall() const { return getTailCallKind() == TCK_NoTail; } |
1652 | |
1653 | void setTailCallKind(TailCallKind TCK) { |
1654 | setSubclassData<TailCallKindField>(TCK); |
1655 | } |
1656 | |
1657 | void setTailCall(bool IsTc = true) { |
1658 | setTailCallKind(IsTc ? TCK_Tail : TCK_None); |
1659 | } |
1660 | |
1661 | /// Return true if the call can return twice |
1662 | bool canReturnTwice() const { return hasFnAttr(Attribute::ReturnsTwice); } |
1663 | void setCanReturnTwice() { |
1664 | addAttribute(AttributeList::FunctionIndex, Attribute::ReturnsTwice); |
1665 | } |
1666 | |
1667 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
1668 | static bool classof(const Instruction *I) { |
1669 | return I->getOpcode() == Instruction::Call; |
1670 | } |
1671 | static bool classof(const Value *V) { |
1672 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
1673 | } |
1674 | |
1675 | /// Updates profile metadata by scaling it by \p S / \p T. |
1676 | void updateProfWeight(uint64_t S, uint64_t T); |
1677 | |
1678 | private: |
1679 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
1680 | // method so that subclasses cannot accidentally use it. |
1681 | template <typename Bitfield> |
1682 | void setSubclassData(typename Bitfield::Type Value) { |
1683 | Instruction::setSubclassData<Bitfield>(Value); |
1684 | } |
1685 | }; |
1686 | |
1687 | CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1688 | ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr, |
1689 | BasicBlock *InsertAtEnd) |
1690 | : CallBase(Ty->getReturnType(), Instruction::Call, |
1691 | OperandTraits<CallBase>::op_end(this) - |
1692 | (Args.size() + CountBundleInputs(Bundles) + 1), |
1693 | unsigned(Args.size() + CountBundleInputs(Bundles) + 1), |
1694 | InsertAtEnd) { |
1695 | init(Ty, Func, Args, Bundles, NameStr); |
1696 | } |
1697 | |
1698 | CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1699 | ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr, |
1700 | Instruction *InsertBefore) |
1701 | : CallBase(Ty->getReturnType(), Instruction::Call, |
1702 | OperandTraits<CallBase>::op_end(this) - |
1703 | (Args.size() + CountBundleInputs(Bundles) + 1), |
1704 | unsigned(Args.size() + CountBundleInputs(Bundles) + 1), |
1705 | InsertBefore) { |
1706 | init(Ty, Func, Args, Bundles, NameStr); |
1707 | } |
1708 | |
1709 | //===----------------------------------------------------------------------===// |
1710 | // SelectInst Class |
1711 | //===----------------------------------------------------------------------===// |
1712 | |
1713 | /// This class represents the LLVM 'select' instruction. |
1714 | /// |
1715 | class SelectInst : public Instruction { |
1716 | SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr, |
1717 | Instruction *InsertBefore) |
1718 | : Instruction(S1->getType(), Instruction::Select, |
1719 | &Op<0>(), 3, InsertBefore) { |
1720 | init(C, S1, S2); |
1721 | setName(NameStr); |
1722 | } |
1723 | |
1724 | SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr, |
1725 | BasicBlock *InsertAtEnd) |
1726 | : Instruction(S1->getType(), Instruction::Select, |
1727 | &Op<0>(), 3, InsertAtEnd) { |
1728 | init(C, S1, S2); |
1729 | setName(NameStr); |
1730 | } |
1731 | |
1732 | void init(Value *C, Value *S1, Value *S2) { |
1733 | assert(!areInvalidOperands(C, S1, S2) && "Invalid operands for select")((!areInvalidOperands(C, S1, S2) && "Invalid operands for select" ) ? static_cast<void> (0) : __assert_fail ("!areInvalidOperands(C, S1, S2) && \"Invalid operands for select\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 1733, __PRETTY_FUNCTION__)); |
1734 | Op<0>() = C; |
1735 | Op<1>() = S1; |
1736 | Op<2>() = S2; |
1737 | } |
1738 | |
1739 | protected: |
1740 | // Note: Instruction needs to be a friend here to call cloneImpl. |
1741 | friend class Instruction; |
1742 | |
1743 | SelectInst *cloneImpl() const; |
1744 | |
1745 | public: |
1746 | static SelectInst *Create(Value *C, Value *S1, Value *S2, |
1747 | const Twine &NameStr = "", |
1748 | Instruction *InsertBefore = nullptr, |
1749 | Instruction *MDFrom = nullptr) { |
1750 | SelectInst *Sel = new(3) SelectInst(C, S1, S2, NameStr, InsertBefore); |
1751 | if (MDFrom) |
1752 | Sel->copyMetadata(*MDFrom); |
1753 | return Sel; |
1754 | } |
1755 | |
1756 | static SelectInst *Create(Value *C, Value *S1, Value *S2, |
1757 | const Twine &NameStr, |
1758 | BasicBlock *InsertAtEnd) { |
1759 | return new(3) SelectInst(C, S1, S2, NameStr, InsertAtEnd); |
1760 | } |
1761 | |
1762 | const Value *getCondition() const { return Op<0>(); } |
1763 | const Value *getTrueValue() const { return Op<1>(); } |
1764 | const Value *getFalseValue() const { return Op<2>(); } |
1765 | Value *getCondition() { return Op<0>(); } |
1766 | Value *getTrueValue() { return Op<1>(); } |
1767 | Value *getFalseValue() { return Op<2>(); } |
1768 | |
1769 | void setCondition(Value *V) { Op<0>() = V; } |
1770 | void setTrueValue(Value *V) { Op<1>() = V; } |
1771 | void setFalseValue(Value *V) { Op<2>() = V; } |
1772 | |
1773 | /// Swap the true and false values of the select instruction. |
1774 | /// This doesn't swap prof metadata. |
1775 | void swapValues() { Op<1>().swap(Op<2>()); } |
1776 | |
1777 | /// Return a string if the specified operands are invalid |
1778 | /// for a select operation, otherwise return null. |
1779 | static const char *areInvalidOperands(Value *Cond, Value *True, Value *False); |
1780 | |
1781 | /// Transparently provide more efficient getOperand methods. |
1782 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
1783 | |
1784 | OtherOps getOpcode() const { |
1785 | return static_cast<OtherOps>(Instruction::getOpcode()); |
1786 | } |
1787 | |
1788 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
1789 | static bool classof(const Instruction *I) { |
1790 | return I->getOpcode() == Instruction::Select; |
1791 | } |
1792 | static bool classof(const Value *V) { |
1793 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
1794 | } |
1795 | }; |
1796 | |
1797 | template <> |
1798 | struct OperandTraits<SelectInst> : public FixedNumOperandTraits<SelectInst, 3> { |
1799 | }; |
1800 | |
1801 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectInst, Value)SelectInst::op_iterator SelectInst::op_begin() { return OperandTraits <SelectInst>::op_begin(this); } SelectInst::const_op_iterator SelectInst::op_begin() const { return OperandTraits<SelectInst >::op_begin(const_cast<SelectInst*>(this)); } SelectInst ::op_iterator SelectInst::op_end() { return OperandTraits< SelectInst>::op_end(this); } SelectInst::const_op_iterator SelectInst::op_end() const { return OperandTraits<SelectInst >::op_end(const_cast<SelectInst*>(this)); } Value *SelectInst ::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<SelectInst>::operands(this) && "getOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<SelectInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 1801, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<SelectInst>::op_begin(const_cast<SelectInst *>(this))[i_nocapture].get()); } void SelectInst::setOperand (unsigned i_nocapture, Value *Val_nocapture) { ((i_nocapture < OperandTraits<SelectInst>::operands(this) && "setOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<SelectInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 1801, __PRETTY_FUNCTION__)); OperandTraits<SelectInst> ::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned SelectInst ::getNumOperands() const { return OperandTraits<SelectInst >::operands(this); } template <int Idx_nocapture> Use &SelectInst::Op() { return this->OpFrom<Idx_nocapture >(this); } template <int Idx_nocapture> const Use & SelectInst::Op() const { return this->OpFrom<Idx_nocapture >(this); } |
1802 | |
1803 | //===----------------------------------------------------------------------===// |
1804 | // VAArgInst Class |
1805 | //===----------------------------------------------------------------------===// |
1806 | |
1807 | /// This class represents the va_arg llvm instruction, which returns |
1808 | /// an argument of the specified type given a va_list and increments that list |
1809 | /// |
1810 | class VAArgInst : public UnaryInstruction { |
1811 | protected: |
1812 | // Note: Instruction needs to be a friend here to call cloneImpl. |
1813 | friend class Instruction; |
1814 | |
1815 | VAArgInst *cloneImpl() const; |
1816 | |
1817 | public: |
1818 | VAArgInst(Value *List, Type *Ty, const Twine &NameStr = "", |
1819 | Instruction *InsertBefore = nullptr) |
1820 | : UnaryInstruction(Ty, VAArg, List, InsertBefore) { |
1821 | setName(NameStr); |
1822 | } |
1823 | |
1824 | VAArgInst(Value *List, Type *Ty, const Twine &NameStr, |
1825 | BasicBlock *InsertAtEnd) |
1826 | : UnaryInstruction(Ty, VAArg, List, InsertAtEnd) { |
1827 | setName(NameStr); |
1828 | } |
1829 | |
1830 | Value *getPointerOperand() { return getOperand(0); } |
1831 | const Value *getPointerOperand() const { return getOperand(0); } |
1832 | static unsigned getPointerOperandIndex() { return 0U; } |
1833 | |
1834 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
1835 | static bool classof(const Instruction *I) { |
1836 | return I->getOpcode() == VAArg; |
1837 | } |
1838 | static bool classof(const Value *V) { |
1839 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
1840 | } |
1841 | }; |
1842 | |
1843 | //===----------------------------------------------------------------------===// |
1844 | // ExtractElementInst Class |
1845 | //===----------------------------------------------------------------------===// |
1846 | |
1847 | /// This instruction extracts a single (scalar) |
1848 | /// element from a VectorType value |
1849 | /// |
1850 | class ExtractElementInst : public Instruction { |
1851 | ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr = "", |
1852 | Instruction *InsertBefore = nullptr); |
1853 | ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr, |
1854 | BasicBlock *InsertAtEnd); |
1855 | |
1856 | protected: |
1857 | // Note: Instruction needs to be a friend here to call cloneImpl. |
1858 | friend class Instruction; |
1859 | |
1860 | ExtractElementInst *cloneImpl() const; |
1861 | |
1862 | public: |
1863 | static ExtractElementInst *Create(Value *Vec, Value *Idx, |
1864 | const Twine &NameStr = "", |
1865 | Instruction *InsertBefore = nullptr) { |
1866 | return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertBefore); |
1867 | } |
1868 | |
1869 | static ExtractElementInst *Create(Value *Vec, Value *Idx, |
1870 | const Twine &NameStr, |
1871 | BasicBlock *InsertAtEnd) { |
1872 | return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertAtEnd); |
1873 | } |
1874 | |
1875 | /// Return true if an extractelement instruction can be |
1876 | /// formed with the specified operands. |
1877 | static bool isValidOperands(const Value *Vec, const Value *Idx); |
1878 | |
1879 | Value *getVectorOperand() { return Op<0>(); } |
1880 | Value *getIndexOperand() { return Op<1>(); } |
1881 | const Value *getVectorOperand() const { return Op<0>(); } |
1882 | const Value *getIndexOperand() const { return Op<1>(); } |
1883 | |
1884 | VectorType *getVectorOperandType() const { |
1885 | return cast<VectorType>(getVectorOperand()->getType()); |
1886 | } |
1887 | |
1888 | /// Transparently provide more efficient getOperand methods. |
1889 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
1890 | |
1891 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
1892 | static bool classof(const Instruction *I) { |
1893 | return I->getOpcode() == Instruction::ExtractElement; |
1894 | } |
1895 | static bool classof(const Value *V) { |
1896 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
1897 | } |
1898 | }; |
1899 | |
1900 | template <> |
1901 | struct OperandTraits<ExtractElementInst> : |
1902 | public FixedNumOperandTraits<ExtractElementInst, 2> { |
1903 | }; |
1904 | |
1905 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementInst, Value)ExtractElementInst::op_iterator ExtractElementInst::op_begin( ) { return OperandTraits<ExtractElementInst>::op_begin( this); } ExtractElementInst::const_op_iterator ExtractElementInst ::op_begin() const { return OperandTraits<ExtractElementInst >::op_begin(const_cast<ExtractElementInst*>(this)); } ExtractElementInst::op_iterator ExtractElementInst::op_end() { return OperandTraits<ExtractElementInst>::op_end(this ); } ExtractElementInst::const_op_iterator ExtractElementInst ::op_end() const { return OperandTraits<ExtractElementInst >::op_end(const_cast<ExtractElementInst*>(this)); } Value *ExtractElementInst::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<ExtractElementInst>:: operands(this) && "getOperand() out of range!") ? static_cast <void> (0) : __assert_fail ("i_nocapture < OperandTraits<ExtractElementInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 1905, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<ExtractElementInst>::op_begin(const_cast <ExtractElementInst*>(this))[i_nocapture].get()); } void ExtractElementInst::setOperand(unsigned i_nocapture, Value * Val_nocapture) { ((i_nocapture < OperandTraits<ExtractElementInst >::operands(this) && "setOperand() out of range!") ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ExtractElementInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 1905, __PRETTY_FUNCTION__)); OperandTraits<ExtractElementInst >::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned ExtractElementInst::getNumOperands() const { return OperandTraits <ExtractElementInst>::operands(this); } template <int Idx_nocapture> Use &ExtractElementInst::Op() { return this->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture> const Use &ExtractElementInst::Op() const { return this->OpFrom<Idx_nocapture>(this); } |
1906 | |
1907 | //===----------------------------------------------------------------------===// |
1908 | // InsertElementInst Class |
1909 | //===----------------------------------------------------------------------===// |
1910 | |
1911 | /// This instruction inserts a single (scalar) |
1912 | /// element into a VectorType value |
1913 | /// |
1914 | class InsertElementInst : public Instruction { |
1915 | InsertElementInst(Value *Vec, Value *NewElt, Value *Idx, |
1916 | const Twine &NameStr = "", |
1917 | Instruction *InsertBefore = nullptr); |
1918 | InsertElementInst(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr, |
1919 | BasicBlock *InsertAtEnd); |
1920 | |
1921 | protected: |
1922 | // Note: Instruction needs to be a friend here to call cloneImpl. |
1923 | friend class Instruction; |
1924 | |
1925 | InsertElementInst *cloneImpl() const; |
1926 | |
1927 | public: |
1928 | static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx, |
1929 | const Twine &NameStr = "", |
1930 | Instruction *InsertBefore = nullptr) { |
1931 | return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertBefore); |
1932 | } |
1933 | |
1934 | static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx, |
1935 | const Twine &NameStr, |
1936 | BasicBlock *InsertAtEnd) { |
1937 | return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertAtEnd); |
1938 | } |
1939 | |
1940 | /// Return true if an insertelement instruction can be |
1941 | /// formed with the specified operands. |
1942 | static bool isValidOperands(const Value *Vec, const Value *NewElt, |
1943 | const Value *Idx); |
1944 | |
1945 | /// Overload to return most specific vector type. |
1946 | /// |
1947 | VectorType *getType() const { |
1948 | return cast<VectorType>(Instruction::getType()); |
1949 | } |
1950 | |
1951 | /// Transparently provide more efficient getOperand methods. |
1952 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
1953 | |
1954 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
1955 | static bool classof(const Instruction *I) { |
1956 | return I->getOpcode() == Instruction::InsertElement; |
1957 | } |
1958 | static bool classof(const Value *V) { |
1959 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
1960 | } |
1961 | }; |
1962 | |
1963 | template <> |
1964 | struct OperandTraits<InsertElementInst> : |
1965 | public FixedNumOperandTraits<InsertElementInst, 3> { |
1966 | }; |
1967 | |
1968 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementInst, Value)InsertElementInst::op_iterator InsertElementInst::op_begin() { return OperandTraits<InsertElementInst>::op_begin(this ); } InsertElementInst::const_op_iterator InsertElementInst:: op_begin() const { return OperandTraits<InsertElementInst> ::op_begin(const_cast<InsertElementInst*>(this)); } InsertElementInst ::op_iterator InsertElementInst::op_end() { return OperandTraits <InsertElementInst>::op_end(this); } InsertElementInst:: const_op_iterator InsertElementInst::op_end() const { return OperandTraits <InsertElementInst>::op_end(const_cast<InsertElementInst *>(this)); } Value *InsertElementInst::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<InsertElementInst >::operands(this) && "getOperand() out of range!") ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<InsertElementInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 1968, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<InsertElementInst>::op_begin(const_cast <InsertElementInst*>(this))[i_nocapture].get()); } void InsertElementInst::setOperand(unsigned i_nocapture, Value *Val_nocapture ) { ((i_nocapture < OperandTraits<InsertElementInst> ::operands(this) && "setOperand() out of range!") ? static_cast <void> (0) : __assert_fail ("i_nocapture < OperandTraits<InsertElementInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 1968, __PRETTY_FUNCTION__)); OperandTraits<InsertElementInst >::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned InsertElementInst::getNumOperands() const { return OperandTraits <InsertElementInst>::operands(this); } template <int Idx_nocapture> Use &InsertElementInst::Op() { return this ->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture > const Use &InsertElementInst::Op() const { return this ->OpFrom<Idx_nocapture>(this); } |
1969 | |
1970 | //===----------------------------------------------------------------------===// |
1971 | // ShuffleVectorInst Class |
1972 | //===----------------------------------------------------------------------===// |
1973 | |
1974 | constexpr int UndefMaskElem = -1; |
1975 | |
1976 | /// This instruction constructs a fixed permutation of two |
1977 | /// input vectors. |
1978 | /// |
1979 | /// For each element of the result vector, the shuffle mask selects an element |
1980 | /// from one of the input vectors to copy to the result. Non-negative elements |
1981 | /// in the mask represent an index into the concatenated pair of input vectors. |
1982 | /// UndefMaskElem (-1) specifies that the result element is undefined. |
1983 | /// |
1984 | /// For scalable vectors, all the elements of the mask must be 0 or -1. This |
1985 | /// requirement may be relaxed in the future. |
1986 | class ShuffleVectorInst : public Instruction { |
1987 | SmallVector<int, 4> ShuffleMask; |
1988 | Constant *ShuffleMaskForBitcode; |
1989 | |
1990 | protected: |
1991 | // Note: Instruction needs to be a friend here to call cloneImpl. |
1992 | friend class Instruction; |
1993 | |
1994 | ShuffleVectorInst *cloneImpl() const; |
1995 | |
1996 | public: |
1997 | ShuffleVectorInst(Value *V1, Value *V2, Value *Mask, |
1998 | const Twine &NameStr = "", |
1999 | Instruction *InsertBefor = nullptr); |
2000 | ShuffleVectorInst(Value *V1, Value *V2, Value *Mask, |
2001 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
2002 | ShuffleVectorInst(Value *V1, Value *V2, ArrayRef<int> Mask, |
2003 | const Twine &NameStr = "", |
2004 | Instruction *InsertBefor = nullptr); |
2005 | ShuffleVectorInst(Value *V1, Value *V2, ArrayRef<int> Mask, |
2006 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
2007 | |
2008 | void *operator new(size_t s) { return User::operator new(s, 2); } |
2009 | |
2010 | /// Swap the operands and adjust the mask to preserve the semantics |
2011 | /// of the instruction. |
2012 | void commute(); |
2013 | |
2014 | /// Return true if a shufflevector instruction can be |
2015 | /// formed with the specified operands. |
2016 | static bool isValidOperands(const Value *V1, const Value *V2, |
2017 | const Value *Mask); |
2018 | static bool isValidOperands(const Value *V1, const Value *V2, |
2019 | ArrayRef<int> Mask); |
2020 | |
2021 | /// Overload to return most specific vector type. |
2022 | /// |
2023 | VectorType *getType() const { |
2024 | return cast<VectorType>(Instruction::getType()); |
2025 | } |
2026 | |
2027 | /// Transparently provide more efficient getOperand methods. |
2028 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
2029 | |
2030 | /// Return the shuffle mask value of this instruction for the given element |
2031 | /// index. Return UndefMaskElem if the element is undef. |
2032 | int getMaskValue(unsigned Elt) const { return ShuffleMask[Elt]; } |
2033 | |
2034 | /// Convert the input shuffle mask operand to a vector of integers. Undefined |
2035 | /// elements of the mask are returned as UndefMaskElem. |
2036 | static void getShuffleMask(const Constant *Mask, |
2037 | SmallVectorImpl<int> &Result); |
2038 | |
2039 | /// Return the mask for this instruction as a vector of integers. Undefined |
2040 | /// elements of the mask are returned as UndefMaskElem. |
2041 | void getShuffleMask(SmallVectorImpl<int> &Result) const { |
2042 | Result.assign(ShuffleMask.begin(), ShuffleMask.end()); |
2043 | } |
2044 | |
2045 | /// Return the mask for this instruction, for use in bitcode. |
2046 | /// |
2047 | /// TODO: This is temporary until we decide a new bitcode encoding for |
2048 | /// shufflevector. |
2049 | Constant *getShuffleMaskForBitcode() const { return ShuffleMaskForBitcode; } |
2050 | |
2051 | static Constant *convertShuffleMaskForBitcode(ArrayRef<int> Mask, |
2052 | Type *ResultTy); |
2053 | |
2054 | void setShuffleMask(ArrayRef<int> Mask); |
2055 | |
2056 | ArrayRef<int> getShuffleMask() const { return ShuffleMask; } |
2057 | |
2058 | /// Return true if this shuffle returns a vector with a different number of |
2059 | /// elements than its source vectors. |
2060 | /// Examples: shufflevector <4 x n> A, <4 x n> B, <1,2,3> |
2061 | /// shufflevector <4 x n> A, <4 x n> B, <1,2,3,4,5> |
2062 | bool changesLength() const { |
2063 | unsigned NumSourceElts = cast<VectorType>(Op<0>()->getType()) |
2064 | ->getElementCount() |
2065 | .getKnownMinValue(); |
2066 | unsigned NumMaskElts = ShuffleMask.size(); |
2067 | return NumSourceElts != NumMaskElts; |
2068 | } |
2069 | |
2070 | /// Return true if this shuffle returns a vector with a greater number of |
2071 | /// elements than its source vectors. |
2072 | /// Example: shufflevector <2 x n> A, <2 x n> B, <1,2,3> |
2073 | bool increasesLength() const { |
2074 | unsigned NumSourceElts = cast<VectorType>(Op<0>()->getType()) |
2075 | ->getElementCount() |
2076 | .getKnownMinValue(); |
2077 | unsigned NumMaskElts = ShuffleMask.size(); |
2078 | return NumSourceElts < NumMaskElts; |
2079 | } |
2080 | |
2081 | /// Return true if this shuffle mask chooses elements from exactly one source |
2082 | /// vector. |
2083 | /// Example: <7,5,undef,7> |
2084 | /// This assumes that vector operands are the same length as the mask. |
2085 | static bool isSingleSourceMask(ArrayRef<int> Mask); |
2086 | static bool isSingleSourceMask(const Constant *Mask) { |
2087 | assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant." ) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 2087, __PRETTY_FUNCTION__)); |
2088 | SmallVector<int, 16> MaskAsInts; |
2089 | getShuffleMask(Mask, MaskAsInts); |
2090 | return isSingleSourceMask(MaskAsInts); |
2091 | } |
2092 | |
2093 | /// Return true if this shuffle chooses elements from exactly one source |
2094 | /// vector without changing the length of that vector. |
2095 | /// Example: shufflevector <4 x n> A, <4 x n> B, <3,0,undef,3> |
2096 | /// TODO: Optionally allow length-changing shuffles. |
2097 | bool isSingleSource() const { |
2098 | return !changesLength() && isSingleSourceMask(ShuffleMask); |
2099 | } |
2100 | |
2101 | /// Return true if this shuffle mask chooses elements from exactly one source |
2102 | /// vector without lane crossings. A shuffle using this mask is not |
2103 | /// necessarily a no-op because it may change the number of elements from its |
2104 | /// input vectors or it may provide demanded bits knowledge via undef lanes. |
2105 | /// Example: <undef,undef,2,3> |
2106 | static bool isIdentityMask(ArrayRef<int> Mask); |
2107 | static bool isIdentityMask(const Constant *Mask) { |
2108 | assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant." ) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 2108, __PRETTY_FUNCTION__)); |
2109 | SmallVector<int, 16> MaskAsInts; |
2110 | getShuffleMask(Mask, MaskAsInts); |
2111 | return isIdentityMask(MaskAsInts); |
2112 | } |
2113 | |
2114 | /// Return true if this shuffle chooses elements from exactly one source |
2115 | /// vector without lane crossings and does not change the number of elements |
2116 | /// from its input vectors. |
2117 | /// Example: shufflevector <4 x n> A, <4 x n> B, <4,undef,6,undef> |
2118 | bool isIdentity() const { |
2119 | return !changesLength() && isIdentityMask(ShuffleMask); |
2120 | } |
2121 | |
2122 | /// Return true if this shuffle lengthens exactly one source vector with |
2123 | /// undefs in the high elements. |
2124 | bool isIdentityWithPadding() const; |
2125 | |
2126 | /// Return true if this shuffle extracts the first N elements of exactly one |
2127 | /// source vector. |
2128 | bool isIdentityWithExtract() const; |
2129 | |
2130 | /// Return true if this shuffle concatenates its 2 source vectors. This |
2131 | /// returns false if either input is undefined. In that case, the shuffle is |
2132 | /// is better classified as an identity with padding operation. |
2133 | bool isConcat() const; |
2134 | |
2135 | /// Return true if this shuffle mask chooses elements from its source vectors |
2136 | /// without lane crossings. A shuffle using this mask would be |
2137 | /// equivalent to a vector select with a constant condition operand. |
2138 | /// Example: <4,1,6,undef> |
2139 | /// This returns false if the mask does not choose from both input vectors. |
2140 | /// In that case, the shuffle is better classified as an identity shuffle. |
2141 | /// This assumes that vector operands are the same length as the mask |
2142 | /// (a length-changing shuffle can never be equivalent to a vector select). |
2143 | static bool isSelectMask(ArrayRef<int> Mask); |
2144 | static bool isSelectMask(const Constant *Mask) { |
2145 | assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant." ) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 2145, __PRETTY_FUNCTION__)); |
2146 | SmallVector<int, 16> MaskAsInts; |
2147 | getShuffleMask(Mask, MaskAsInts); |
2148 | return isSelectMask(MaskAsInts); |
2149 | } |
2150 | |
2151 | /// Return true if this shuffle chooses elements from its source vectors |
2152 | /// without lane crossings and all operands have the same number of elements. |
2153 | /// In other words, this shuffle is equivalent to a vector select with a |
2154 | /// constant condition operand. |
2155 | /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,1,6,3> |
2156 | /// This returns false if the mask does not choose from both input vectors. |
2157 | /// In that case, the shuffle is better classified as an identity shuffle. |
2158 | /// TODO: Optionally allow length-changing shuffles. |
2159 | bool isSelect() const { |
2160 | return !changesLength() && isSelectMask(ShuffleMask); |
2161 | } |
2162 | |
2163 | /// Return true if this shuffle mask swaps the order of elements from exactly |
2164 | /// one source vector. |
2165 | /// Example: <7,6,undef,4> |
2166 | /// This assumes that vector operands are the same length as the mask. |
2167 | static bool isReverseMask(ArrayRef<int> Mask); |
2168 | static bool isReverseMask(const Constant *Mask) { |
2169 | assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant." ) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 2169, __PRETTY_FUNCTION__)); |
2170 | SmallVector<int, 16> MaskAsInts; |
2171 | getShuffleMask(Mask, MaskAsInts); |
2172 | return isReverseMask(MaskAsInts); |
2173 | } |
2174 | |
2175 | /// Return true if this shuffle swaps the order of elements from exactly |
2176 | /// one source vector. |
2177 | /// Example: shufflevector <4 x n> A, <4 x n> B, <3,undef,1,undef> |
2178 | /// TODO: Optionally allow length-changing shuffles. |
2179 | bool isReverse() const { |
2180 | return !changesLength() && isReverseMask(ShuffleMask); |
2181 | } |
2182 | |
2183 | /// Return true if this shuffle mask chooses all elements with the same value |
2184 | /// as the first element of exactly one source vector. |
2185 | /// Example: <4,undef,undef,4> |
2186 | /// This assumes that vector operands are the same length as the mask. |
2187 | static bool isZeroEltSplatMask(ArrayRef<int> Mask); |
2188 | static bool isZeroEltSplatMask(const Constant *Mask) { |
2189 | assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant." ) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 2189, __PRETTY_FUNCTION__)); |
2190 | SmallVector<int, 16> MaskAsInts; |
2191 | getShuffleMask(Mask, MaskAsInts); |
2192 | return isZeroEltSplatMask(MaskAsInts); |
2193 | } |
2194 | |
2195 | /// Return true if all elements of this shuffle are the same value as the |
2196 | /// first element of exactly one source vector without changing the length |
2197 | /// of that vector. |
2198 | /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,0,undef,0> |
2199 | /// TODO: Optionally allow length-changing shuffles. |
2200 | /// TODO: Optionally allow splats from other elements. |
2201 | bool isZeroEltSplat() const { |
2202 | return !changesLength() && isZeroEltSplatMask(ShuffleMask); |
2203 | } |
2204 | |
2205 | /// Return true if this shuffle mask is a transpose mask. |
2206 | /// Transpose vector masks transpose a 2xn matrix. They read corresponding |
2207 | /// even- or odd-numbered vector elements from two n-dimensional source |
2208 | /// vectors and write each result into consecutive elements of an |
2209 | /// n-dimensional destination vector. Two shuffles are necessary to complete |
2210 | /// the transpose, one for the even elements and another for the odd elements. |
2211 | /// This description closely follows how the TRN1 and TRN2 AArch64 |
2212 | /// instructions operate. |
2213 | /// |
2214 | /// For example, a simple 2x2 matrix can be transposed with: |
2215 | /// |
2216 | /// ; Original matrix |
2217 | /// m0 = < a, b > |
2218 | /// m1 = < c, d > |
2219 | /// |
2220 | /// ; Transposed matrix |
2221 | /// t0 = < a, c > = shufflevector m0, m1, < 0, 2 > |
2222 | /// t1 = < b, d > = shufflevector m0, m1, < 1, 3 > |
2223 | /// |
2224 | /// For matrices having greater than n columns, the resulting nx2 transposed |
2225 | /// matrix is stored in two result vectors such that one vector contains |
2226 | /// interleaved elements from all the even-numbered rows and the other vector |
2227 | /// contains interleaved elements from all the odd-numbered rows. For example, |
2228 | /// a 2x4 matrix can be transposed with: |
2229 | /// |
2230 | /// ; Original matrix |
2231 | /// m0 = < a, b, c, d > |
2232 | /// m1 = < e, f, g, h > |
2233 | /// |
2234 | /// ; Transposed matrix |
2235 | /// t0 = < a, e, c, g > = shufflevector m0, m1 < 0, 4, 2, 6 > |
2236 | /// t1 = < b, f, d, h > = shufflevector m0, m1 < 1, 5, 3, 7 > |
2237 | static bool isTransposeMask(ArrayRef<int> Mask); |
2238 | static bool isTransposeMask(const Constant *Mask) { |
2239 | assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant." ) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 2239, __PRETTY_FUNCTION__)); |
2240 | SmallVector<int, 16> MaskAsInts; |
2241 | getShuffleMask(Mask, MaskAsInts); |
2242 | return isTransposeMask(MaskAsInts); |
2243 | } |
2244 | |
2245 | /// Return true if this shuffle transposes the elements of its inputs without |
2246 | /// changing the length of the vectors. This operation may also be known as a |
2247 | /// merge or interleave. See the description for isTransposeMask() for the |
2248 | /// exact specification. |
2249 | /// Example: shufflevector <4 x n> A, <4 x n> B, <0,4,2,6> |
2250 | bool isTranspose() const { |
2251 | return !changesLength() && isTransposeMask(ShuffleMask); |
2252 | } |
2253 | |
2254 | /// Return true if this shuffle mask is an extract subvector mask. |
2255 | /// A valid extract subvector mask returns a smaller vector from a single |
2256 | /// source operand. The base extraction index is returned as well. |
2257 | static bool isExtractSubvectorMask(ArrayRef<int> Mask, int NumSrcElts, |
2258 | int &Index); |
2259 | static bool isExtractSubvectorMask(const Constant *Mask, int NumSrcElts, |
2260 | int &Index) { |
2261 | assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant." ) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 2261, __PRETTY_FUNCTION__)); |
2262 | // Not possible to express a shuffle mask for a scalable vector for this |
2263 | // case. |
2264 | if (isa<ScalableVectorType>(Mask->getType())) |
2265 | return false; |
2266 | SmallVector<int, 16> MaskAsInts; |
2267 | getShuffleMask(Mask, MaskAsInts); |
2268 | return isExtractSubvectorMask(MaskAsInts, NumSrcElts, Index); |
2269 | } |
2270 | |
2271 | /// Return true if this shuffle mask is an extract subvector mask. |
2272 | bool isExtractSubvectorMask(int &Index) const { |
2273 | // Not possible to express a shuffle mask for a scalable vector for this |
2274 | // case. |
2275 | if (isa<ScalableVectorType>(getType())) |
2276 | return false; |
2277 | |
2278 | int NumSrcElts = |
2279 | cast<FixedVectorType>(Op<0>()->getType())->getNumElements(); |
2280 | return isExtractSubvectorMask(ShuffleMask, NumSrcElts, Index); |
2281 | } |
2282 | |
2283 | /// Change values in a shuffle permute mask assuming the two vector operands |
2284 | /// of length InVecNumElts have swapped position. |
2285 | static void commuteShuffleMask(MutableArrayRef<int> Mask, |
2286 | unsigned InVecNumElts) { |
2287 | for (int &Idx : Mask) { |
2288 | if (Idx == -1) |
2289 | continue; |
2290 | Idx = Idx < (int)InVecNumElts ? Idx + InVecNumElts : Idx - InVecNumElts; |
2291 | assert(Idx >= 0 && Idx < (int)InVecNumElts * 2 &&((Idx >= 0 && Idx < (int)InVecNumElts * 2 && "shufflevector mask index out of range") ? static_cast<void > (0) : __assert_fail ("Idx >= 0 && Idx < (int)InVecNumElts * 2 && \"shufflevector mask index out of range\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 2292, __PRETTY_FUNCTION__)) |
2292 | "shufflevector mask index out of range")((Idx >= 0 && Idx < (int)InVecNumElts * 2 && "shufflevector mask index out of range") ? static_cast<void > (0) : __assert_fail ("Idx >= 0 && Idx < (int)InVecNumElts * 2 && \"shufflevector mask index out of range\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 2292, __PRETTY_FUNCTION__)); |
2293 | } |
2294 | } |
2295 | |
2296 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
2297 | static bool classof(const Instruction *I) { |
2298 | return I->getOpcode() == Instruction::ShuffleVector; |
2299 | } |
2300 | static bool classof(const Value *V) { |
2301 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
2302 | } |
2303 | }; |
2304 | |
2305 | template <> |
2306 | struct OperandTraits<ShuffleVectorInst> |
2307 | : public FixedNumOperandTraits<ShuffleVectorInst, 2> {}; |
2308 | |
2309 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorInst, Value)ShuffleVectorInst::op_iterator ShuffleVectorInst::op_begin() { return OperandTraits<ShuffleVectorInst>::op_begin(this ); } ShuffleVectorInst::const_op_iterator ShuffleVectorInst:: op_begin() const { return OperandTraits<ShuffleVectorInst> ::op_begin(const_cast<ShuffleVectorInst*>(this)); } ShuffleVectorInst ::op_iterator ShuffleVectorInst::op_end() { return OperandTraits <ShuffleVectorInst>::op_end(this); } ShuffleVectorInst:: const_op_iterator ShuffleVectorInst::op_end() const { return OperandTraits <ShuffleVectorInst>::op_end(const_cast<ShuffleVectorInst *>(this)); } Value *ShuffleVectorInst::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<ShuffleVectorInst >::operands(this) && "getOperand() out of range!") ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ShuffleVectorInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 2309, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<ShuffleVectorInst>::op_begin(const_cast <ShuffleVectorInst*>(this))[i_nocapture].get()); } void ShuffleVectorInst::setOperand(unsigned i_nocapture, Value *Val_nocapture ) { ((i_nocapture < OperandTraits<ShuffleVectorInst> ::operands(this) && "setOperand() out of range!") ? static_cast <void> (0) : __assert_fail ("i_nocapture < OperandTraits<ShuffleVectorInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 2309, __PRETTY_FUNCTION__)); OperandTraits<ShuffleVectorInst >::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned ShuffleVectorInst::getNumOperands() const { return OperandTraits <ShuffleVectorInst>::operands(this); } template <int Idx_nocapture> Use &ShuffleVectorInst::Op() { return this ->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture > const Use &ShuffleVectorInst::Op() const { return this ->OpFrom<Idx_nocapture>(this); } |
2310 | |
2311 | //===----------------------------------------------------------------------===// |
2312 | // ExtractValueInst Class |
2313 | //===----------------------------------------------------------------------===// |
2314 | |
2315 | /// This instruction extracts a struct member or array |
2316 | /// element value from an aggregate value. |
2317 | /// |
2318 | class ExtractValueInst : public UnaryInstruction { |
2319 | SmallVector<unsigned, 4> Indices; |
2320 | |
2321 | ExtractValueInst(const ExtractValueInst &EVI); |
2322 | |
2323 | /// Constructors - Create a extractvalue instruction with a base aggregate |
2324 | /// value and a list of indices. The first ctor can optionally insert before |
2325 | /// an existing instruction, the second appends the new instruction to the |
2326 | /// specified BasicBlock. |
2327 | inline ExtractValueInst(Value *Agg, |
2328 | ArrayRef<unsigned> Idxs, |
2329 | const Twine &NameStr, |
2330 | Instruction *InsertBefore); |
2331 | inline ExtractValueInst(Value *Agg, |
2332 | ArrayRef<unsigned> Idxs, |
2333 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
2334 | |
2335 | void init(ArrayRef<unsigned> Idxs, const Twine &NameStr); |
2336 | |
2337 | protected: |
2338 | // Note: Instruction needs to be a friend here to call cloneImpl. |
2339 | friend class Instruction; |
2340 | |
2341 | ExtractValueInst *cloneImpl() const; |
2342 | |
2343 | public: |
2344 | static ExtractValueInst *Create(Value *Agg, |
2345 | ArrayRef<unsigned> Idxs, |
2346 | const Twine &NameStr = "", |
2347 | Instruction *InsertBefore = nullptr) { |
2348 | return new |
2349 | ExtractValueInst(Agg, Idxs, NameStr, InsertBefore); |
2350 | } |
2351 | |
2352 | static ExtractValueInst *Create(Value *Agg, |
2353 | ArrayRef<unsigned> Idxs, |
2354 | const Twine &NameStr, |
2355 | BasicBlock *InsertAtEnd) { |
2356 | return new ExtractValueInst(Agg, Idxs, NameStr, InsertAtEnd); |
2357 | } |
2358 | |
2359 | /// Returns the type of the element that would be extracted |
2360 | /// with an extractvalue instruction with the specified parameters. |
2361 | /// |
2362 | /// Null is returned if the indices are invalid for the specified type. |
2363 | static Type *getIndexedType(Type *Agg, ArrayRef<unsigned> Idxs); |
2364 | |
2365 | using idx_iterator = const unsigned*; |
2366 | |
2367 | inline idx_iterator idx_begin() const { return Indices.begin(); } |
2368 | inline idx_iterator idx_end() const { return Indices.end(); } |
2369 | inline iterator_range<idx_iterator> indices() const { |
2370 | return make_range(idx_begin(), idx_end()); |
2371 | } |
2372 | |
2373 | Value *getAggregateOperand() { |
2374 | return getOperand(0); |
2375 | } |
2376 | const Value *getAggregateOperand() const { |
2377 | return getOperand(0); |
2378 | } |
2379 | static unsigned getAggregateOperandIndex() { |
2380 | return 0U; // get index for modifying correct operand |
2381 | } |
2382 | |
2383 | ArrayRef<unsigned> getIndices() const { |
2384 | return Indices; |
2385 | } |
2386 | |
2387 | unsigned getNumIndices() const { |
2388 | return (unsigned)Indices.size(); |
2389 | } |
2390 | |
2391 | bool hasIndices() const { |
2392 | return true; |
2393 | } |
2394 | |
2395 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
2396 | static bool classof(const Instruction *I) { |
2397 | return I->getOpcode() == Instruction::ExtractValue; |
2398 | } |
2399 | static bool classof(const Value *V) { |
2400 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
2401 | } |
2402 | }; |
2403 | |
2404 | ExtractValueInst::ExtractValueInst(Value *Agg, |
2405 | ArrayRef<unsigned> Idxs, |
2406 | const Twine &NameStr, |
2407 | Instruction *InsertBefore) |
2408 | : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)), |
2409 | ExtractValue, Agg, InsertBefore) { |
2410 | init(Idxs, NameStr); |
2411 | } |
2412 | |
2413 | ExtractValueInst::ExtractValueInst(Value *Agg, |
2414 | ArrayRef<unsigned> Idxs, |
2415 | const Twine &NameStr, |
2416 | BasicBlock *InsertAtEnd) |
2417 | : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)), |
2418 | ExtractValue, Agg, InsertAtEnd) { |
2419 | init(Idxs, NameStr); |
2420 | } |
2421 | |
2422 | //===----------------------------------------------------------------------===// |
2423 | // InsertValueInst Class |
2424 | //===----------------------------------------------------------------------===// |
2425 | |
2426 | /// This instruction inserts a struct field of array element |
2427 | /// value into an aggregate value. |
2428 | /// |
2429 | class InsertValueInst : public Instruction { |
2430 | SmallVector<unsigned, 4> Indices; |
2431 | |
2432 | InsertValueInst(const InsertValueInst &IVI); |
2433 | |
2434 | /// Constructors - Create a insertvalue instruction with a base aggregate |
2435 | /// value, a value to insert, and a list of indices. The first ctor can |
2436 | /// optionally insert before an existing instruction, the second appends |
2437 | /// the new instruction to the specified BasicBlock. |
2438 | inline InsertValueInst(Value *Agg, Value *Val, |
2439 | ArrayRef<unsigned> Idxs, |
2440 | const Twine &NameStr, |
2441 | Instruction *InsertBefore); |
2442 | inline InsertValueInst(Value *Agg, Value *Val, |
2443 | ArrayRef<unsigned> Idxs, |
2444 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
2445 | |
2446 | /// Constructors - These two constructors are convenience methods because one |
2447 | /// and two index insertvalue instructions are so common. |
2448 | InsertValueInst(Value *Agg, Value *Val, unsigned Idx, |
2449 | const Twine &NameStr = "", |
2450 | Instruction *InsertBefore = nullptr); |
2451 | InsertValueInst(Value *Agg, Value *Val, unsigned Idx, const Twine &NameStr, |
2452 | BasicBlock *InsertAtEnd); |
2453 | |
2454 | void init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs, |
2455 | const Twine &NameStr); |
2456 | |
2457 | protected: |
2458 | // Note: Instruction needs to be a friend here to call cloneImpl. |
2459 | friend class Instruction; |
2460 | |
2461 | InsertValueInst *cloneImpl() const; |
2462 | |
2463 | public: |
2464 | // allocate space for exactly two operands |
2465 | void *operator new(size_t s) { |
2466 | return User::operator new(s, 2); |
2467 | } |
2468 | |
2469 | static InsertValueInst *Create(Value *Agg, Value *Val, |
2470 | ArrayRef<unsigned> Idxs, |
2471 | const Twine &NameStr = "", |
2472 | Instruction *InsertBefore = nullptr) { |
2473 | return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertBefore); |
2474 | } |
2475 | |
2476 | static InsertValueInst *Create(Value *Agg, Value *Val, |
2477 | ArrayRef<unsigned> Idxs, |
2478 | const Twine &NameStr, |
2479 | BasicBlock *InsertAtEnd) { |
2480 | return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertAtEnd); |
2481 | } |
2482 | |
2483 | /// Transparently provide more efficient getOperand methods. |
2484 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
2485 | |
2486 | using idx_iterator = const unsigned*; |
2487 | |
2488 | inline idx_iterator idx_begin() const { return Indices.begin(); } |
2489 | inline idx_iterator idx_end() const { return Indices.end(); } |
2490 | inline iterator_range<idx_iterator> indices() const { |
2491 | return make_range(idx_begin(), idx_end()); |
2492 | } |
2493 | |
2494 | Value *getAggregateOperand() { |
2495 | return getOperand(0); |
2496 | } |
2497 | const Value *getAggregateOperand() const { |
2498 | return getOperand(0); |
2499 | } |
2500 | static unsigned getAggregateOperandIndex() { |
2501 | return 0U; // get index for modifying correct operand |
2502 | } |
2503 | |
2504 | Value *getInsertedValueOperand() { |
2505 | return getOperand(1); |
2506 | } |
2507 | const Value *getInsertedValueOperand() const { |
2508 | return getOperand(1); |
2509 | } |
2510 | static unsigned getInsertedValueOperandIndex() { |
2511 | return 1U; // get index for modifying correct operand |
2512 | } |
2513 | |
2514 | ArrayRef<unsigned> getIndices() const { |
2515 | return Indices; |
2516 | } |
2517 | |
2518 | unsigned getNumIndices() const { |
2519 | return (unsigned)Indices.size(); |
2520 | } |
2521 | |
2522 | bool hasIndices() const { |
2523 | return true; |
2524 | } |
2525 | |
2526 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
2527 | static bool classof(const Instruction *I) { |
2528 | return I->getOpcode() == Instruction::InsertValue; |
2529 | } |
2530 | static bool classof(const Value *V) { |
2531 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
2532 | } |
2533 | }; |
2534 | |
2535 | template <> |
2536 | struct OperandTraits<InsertValueInst> : |
2537 | public FixedNumOperandTraits<InsertValueInst, 2> { |
2538 | }; |
2539 | |
2540 | InsertValueInst::InsertValueInst(Value *Agg, |
2541 | Value *Val, |
2542 | ArrayRef<unsigned> Idxs, |
2543 | const Twine &NameStr, |
2544 | Instruction *InsertBefore) |
2545 | : Instruction(Agg->getType(), InsertValue, |
2546 | OperandTraits<InsertValueInst>::op_begin(this), |
2547 | 2, InsertBefore) { |
2548 | init(Agg, Val, Idxs, NameStr); |
2549 | } |
2550 | |
2551 | InsertValueInst::InsertValueInst(Value *Agg, |
2552 | Value *Val, |
2553 | ArrayRef<unsigned> Idxs, |
2554 | const Twine &NameStr, |
2555 | BasicBlock *InsertAtEnd) |
2556 | : Instruction(Agg->getType(), InsertValue, |
2557 | OperandTraits<InsertValueInst>::op_begin(this), |
2558 | 2, InsertAtEnd) { |
2559 | init(Agg, Val, Idxs, NameStr); |
2560 | } |
2561 | |
2562 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueInst, Value)InsertValueInst::op_iterator InsertValueInst::op_begin() { return OperandTraits<InsertValueInst>::op_begin(this); } InsertValueInst ::const_op_iterator InsertValueInst::op_begin() const { return OperandTraits<InsertValueInst>::op_begin(const_cast< InsertValueInst*>(this)); } InsertValueInst::op_iterator InsertValueInst ::op_end() { return OperandTraits<InsertValueInst>::op_end (this); } InsertValueInst::const_op_iterator InsertValueInst:: op_end() const { return OperandTraits<InsertValueInst>:: op_end(const_cast<InsertValueInst*>(this)); } Value *InsertValueInst ::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<InsertValueInst>::operands(this) && "getOperand() out of range!") ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<InsertValueInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 2562, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<InsertValueInst>::op_begin(const_cast< InsertValueInst*>(this))[i_nocapture].get()); } void InsertValueInst ::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (( i_nocapture < OperandTraits<InsertValueInst>::operands (this) && "setOperand() out of range!") ? static_cast <void> (0) : __assert_fail ("i_nocapture < OperandTraits<InsertValueInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 2562, __PRETTY_FUNCTION__)); OperandTraits<InsertValueInst >::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned InsertValueInst::getNumOperands() const { return OperandTraits <InsertValueInst>::operands(this); } template <int Idx_nocapture > Use &InsertValueInst::Op() { return this->OpFrom< Idx_nocapture>(this); } template <int Idx_nocapture> const Use &InsertValueInst::Op() const { return this-> OpFrom<Idx_nocapture>(this); } |
2563 | |
2564 | //===----------------------------------------------------------------------===// |
2565 | // PHINode Class |
2566 | //===----------------------------------------------------------------------===// |
2567 | |
2568 | // PHINode - The PHINode class is used to represent the magical mystical PHI |
2569 | // node, that can not exist in nature, but can be synthesized in a computer |
2570 | // scientist's overactive imagination. |
2571 | // |
2572 | class PHINode : public Instruction { |
2573 | /// The number of operands actually allocated. NumOperands is |
2574 | /// the number actually in use. |
2575 | unsigned ReservedSpace; |
2576 | |
2577 | PHINode(const PHINode &PN); |
2578 | |
2579 | explicit PHINode(Type *Ty, unsigned NumReservedValues, |
2580 | const Twine &NameStr = "", |
2581 | Instruction *InsertBefore = nullptr) |
2582 | : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertBefore), |
2583 | ReservedSpace(NumReservedValues) { |
2584 | setName(NameStr); |
2585 | allocHungoffUses(ReservedSpace); |
2586 | } |
2587 | |
2588 | PHINode(Type *Ty, unsigned NumReservedValues, const Twine &NameStr, |
2589 | BasicBlock *InsertAtEnd) |
2590 | : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertAtEnd), |
2591 | ReservedSpace(NumReservedValues) { |
2592 | setName(NameStr); |
2593 | allocHungoffUses(ReservedSpace); |
2594 | } |
2595 | |
2596 | protected: |
2597 | // Note: Instruction needs to be a friend here to call cloneImpl. |
2598 | friend class Instruction; |
2599 | |
2600 | PHINode *cloneImpl() const; |
2601 | |
2602 | // allocHungoffUses - this is more complicated than the generic |
2603 | // User::allocHungoffUses, because we have to allocate Uses for the incoming |
2604 | // values and pointers to the incoming blocks, all in one allocation. |
2605 | void allocHungoffUses(unsigned N) { |
2606 | User::allocHungoffUses(N, /* IsPhi */ true); |
2607 | } |
2608 | |
2609 | public: |
2610 | /// Constructors - NumReservedValues is a hint for the number of incoming |
2611 | /// edges that this phi node will have (use 0 if you really have no idea). |
2612 | static PHINode *Create(Type *Ty, unsigned NumReservedValues, |
2613 | const Twine &NameStr = "", |
2614 | Instruction *InsertBefore = nullptr) { |
2615 | return new PHINode(Ty, NumReservedValues, NameStr, InsertBefore); |
2616 | } |
2617 | |
2618 | static PHINode *Create(Type *Ty, unsigned NumReservedValues, |
2619 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
2620 | return new PHINode(Ty, NumReservedValues, NameStr, InsertAtEnd); |
2621 | } |
2622 | |
2623 | /// Provide fast operand accessors |
2624 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
2625 | |
2626 | // Block iterator interface. This provides access to the list of incoming |
2627 | // basic blocks, which parallels the list of incoming values. |
2628 | |
2629 | using block_iterator = BasicBlock **; |
2630 | using const_block_iterator = BasicBlock * const *; |
2631 | |
2632 | block_iterator block_begin() { |
2633 | return reinterpret_cast<block_iterator>(op_begin() + ReservedSpace); |
2634 | } |
2635 | |
2636 | const_block_iterator block_begin() const { |
2637 | return reinterpret_cast<const_block_iterator>(op_begin() + ReservedSpace); |
2638 | } |
2639 | |
2640 | block_iterator block_end() { |
2641 | return block_begin() + getNumOperands(); |
2642 | } |
2643 | |
2644 | const_block_iterator block_end() const { |
2645 | return block_begin() + getNumOperands(); |
2646 | } |
2647 | |
2648 | iterator_range<block_iterator> blocks() { |
2649 | return make_range(block_begin(), block_end()); |
2650 | } |
2651 | |
2652 | iterator_range<const_block_iterator> blocks() const { |
2653 | return make_range(block_begin(), block_end()); |
2654 | } |
2655 | |
2656 | op_range incoming_values() { return operands(); } |
2657 | |
2658 | const_op_range incoming_values() const { return operands(); } |
2659 | |
2660 | /// Return the number of incoming edges |
2661 | /// |
2662 | unsigned getNumIncomingValues() const { return getNumOperands(); } |
2663 | |
2664 | /// Return incoming value number x |
2665 | /// |
2666 | Value *getIncomingValue(unsigned i) const { |
2667 | return getOperand(i); |
2668 | } |
2669 | void setIncomingValue(unsigned i, Value *V) { |
2670 | assert(V && "PHI node got a null value!")((V && "PHI node got a null value!") ? static_cast< void> (0) : __assert_fail ("V && \"PHI node got a null value!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 2670, __PRETTY_FUNCTION__)); |
2671 | assert(getType() == V->getType() &&((getType() == V->getType() && "All operands to PHI node must be the same type as the PHI node!" ) ? static_cast<void> (0) : __assert_fail ("getType() == V->getType() && \"All operands to PHI node must be the same type as the PHI node!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 2672, __PRETTY_FUNCTION__)) |
2672 | "All operands to PHI node must be the same type as the PHI node!")((getType() == V->getType() && "All operands to PHI node must be the same type as the PHI node!" ) ? static_cast<void> (0) : __assert_fail ("getType() == V->getType() && \"All operands to PHI node must be the same type as the PHI node!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 2672, __PRETTY_FUNCTION__)); |
2673 | setOperand(i, V); |
2674 | } |
2675 | |
2676 | static unsigned getOperandNumForIncomingValue(unsigned i) { |
2677 | return i; |
2678 | } |
2679 | |
2680 | static unsigned getIncomingValueNumForOperand(unsigned i) { |
2681 | return i; |
2682 | } |
2683 | |
2684 | /// Return incoming basic block number @p i. |
2685 | /// |
2686 | BasicBlock *getIncomingBlock(unsigned i) const { |
2687 | return block_begin()[i]; |
2688 | } |
2689 | |
2690 | /// Return incoming basic block corresponding |
2691 | /// to an operand of the PHI. |
2692 | /// |
2693 | BasicBlock *getIncomingBlock(const Use &U) const { |
2694 | assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?")((this == U.getUser() && "Iterator doesn't point to PHI's Uses?" ) ? static_cast<void> (0) : __assert_fail ("this == U.getUser() && \"Iterator doesn't point to PHI's Uses?\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 2694, __PRETTY_FUNCTION__)); |
2695 | return getIncomingBlock(unsigned(&U - op_begin())); |
2696 | } |
2697 | |
2698 | /// Return incoming basic block corresponding |
2699 | /// to value use iterator. |
2700 | /// |
2701 | BasicBlock *getIncomingBlock(Value::const_user_iterator I) const { |
2702 | return getIncomingBlock(I.getUse()); |
2703 | } |
2704 | |
2705 | void setIncomingBlock(unsigned i, BasicBlock *BB) { |
2706 | assert(BB && "PHI node got a null basic block!")((BB && "PHI node got a null basic block!") ? static_cast <void> (0) : __assert_fail ("BB && \"PHI node got a null basic block!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 2706, __PRETTY_FUNCTION__)); |
2707 | block_begin()[i] = BB; |
2708 | } |
2709 | |
2710 | /// Replace every incoming basic block \p Old to basic block \p New. |
2711 | void replaceIncomingBlockWith(const BasicBlock *Old, BasicBlock *New) { |
2712 | assert(New && Old && "PHI node got a null basic block!")((New && Old && "PHI node got a null basic block!" ) ? static_cast<void> (0) : __assert_fail ("New && Old && \"PHI node got a null basic block!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 2712, __PRETTY_FUNCTION__)); |
2713 | for (unsigned Op = 0, NumOps = getNumOperands(); Op != NumOps; ++Op) |
2714 | if (getIncomingBlock(Op) == Old) |
2715 | setIncomingBlock(Op, New); |
2716 | } |
2717 | |
2718 | /// Add an incoming value to the end of the PHI list |
2719 | /// |
2720 | void addIncoming(Value *V, BasicBlock *BB) { |
2721 | if (getNumOperands() == ReservedSpace) |
2722 | growOperands(); // Get more space! |
2723 | // Initialize some new operands. |
2724 | setNumHungOffUseOperands(getNumOperands() + 1); |
2725 | setIncomingValue(getNumOperands() - 1, V); |
2726 | setIncomingBlock(getNumOperands() - 1, BB); |
2727 | } |
2728 | |
2729 | /// Remove an incoming value. This is useful if a |
2730 | /// predecessor basic block is deleted. The value removed is returned. |
2731 | /// |
2732 | /// If the last incoming value for a PHI node is removed (and DeletePHIIfEmpty |
2733 | /// is true), the PHI node is destroyed and any uses of it are replaced with |
2734 | /// dummy values. The only time there should be zero incoming values to a PHI |
2735 | /// node is when the block is dead, so this strategy is sound. |
2736 | /// |
2737 | Value *removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty = true); |
2738 | |
2739 | Value *removeIncomingValue(const BasicBlock *BB, bool DeletePHIIfEmpty=true) { |
2740 | int Idx = getBasicBlockIndex(BB); |
2741 | assert(Idx >= 0 && "Invalid basic block argument to remove!")((Idx >= 0 && "Invalid basic block argument to remove!" ) ? static_cast<void> (0) : __assert_fail ("Idx >= 0 && \"Invalid basic block argument to remove!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 2741, __PRETTY_FUNCTION__)); |
2742 | return removeIncomingValue(Idx, DeletePHIIfEmpty); |
2743 | } |
2744 | |
2745 | /// Return the first index of the specified basic |
2746 | /// block in the value list for this PHI. Returns -1 if no instance. |
2747 | /// |
2748 | int getBasicBlockIndex(const BasicBlock *BB) const { |
2749 | for (unsigned i = 0, e = getNumOperands(); i != e; ++i) |
2750 | if (block_begin()[i] == BB) |
2751 | return i; |
2752 | return -1; |
2753 | } |
2754 | |
2755 | Value *getIncomingValueForBlock(const BasicBlock *BB) const { |
2756 | int Idx = getBasicBlockIndex(BB); |
2757 | assert(Idx >= 0 && "Invalid basic block argument!")((Idx >= 0 && "Invalid basic block argument!") ? static_cast <void> (0) : __assert_fail ("Idx >= 0 && \"Invalid basic block argument!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 2757, __PRETTY_FUNCTION__)); |
2758 | return getIncomingValue(Idx); |
2759 | } |
2760 | |
2761 | /// Set every incoming value(s) for block \p BB to \p V. |
2762 | void setIncomingValueForBlock(const BasicBlock *BB, Value *V) { |
2763 | assert(BB && "PHI node got a null basic block!")((BB && "PHI node got a null basic block!") ? static_cast <void> (0) : __assert_fail ("BB && \"PHI node got a null basic block!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 2763, __PRETTY_FUNCTION__)); |
2764 | bool Found = false; |
2765 | for (unsigned Op = 0, NumOps = getNumOperands(); Op != NumOps; ++Op) |
2766 | if (getIncomingBlock(Op) == BB) { |
2767 | Found = true; |
2768 | setIncomingValue(Op, V); |
2769 | } |
2770 | (void)Found; |
2771 | assert(Found && "Invalid basic block argument to set!")((Found && "Invalid basic block argument to set!") ? static_cast <void> (0) : __assert_fail ("Found && \"Invalid basic block argument to set!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 2771, __PRETTY_FUNCTION__)); |
2772 | } |
2773 | |
2774 | /// If the specified PHI node always merges together the |
2775 | /// same value, return the value, otherwise return null. |
2776 | Value *hasConstantValue() const; |
2777 | |
2778 | /// Whether the specified PHI node always merges |
2779 | /// together the same value, assuming undefs are equal to a unique |
2780 | /// non-undef value. |
2781 | bool hasConstantOrUndefValue() const; |
2782 | |
2783 | /// If the PHI node is complete which means all of its parent's predecessors |
2784 | /// have incoming value in this PHI, return true, otherwise return false. |
2785 | bool isComplete() const { |
2786 | return llvm::all_of(predecessors(getParent()), |
2787 | [this](const BasicBlock *Pred) { |
2788 | return getBasicBlockIndex(Pred) >= 0; |
2789 | }); |
2790 | } |
2791 | |
2792 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
2793 | static bool classof(const Instruction *I) { |
2794 | return I->getOpcode() == Instruction::PHI; |
2795 | } |
2796 | static bool classof(const Value *V) { |
2797 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
2798 | } |
2799 | |
2800 | private: |
2801 | void growOperands(); |
2802 | }; |
2803 | |
2804 | template <> |
2805 | struct OperandTraits<PHINode> : public HungoffOperandTraits<2> { |
2806 | }; |
2807 | |
2808 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(PHINode, Value)PHINode::op_iterator PHINode::op_begin() { return OperandTraits <PHINode>::op_begin(this); } PHINode::const_op_iterator PHINode::op_begin() const { return OperandTraits<PHINode> ::op_begin(const_cast<PHINode*>(this)); } PHINode::op_iterator PHINode::op_end() { return OperandTraits<PHINode>::op_end (this); } PHINode::const_op_iterator PHINode::op_end() const { return OperandTraits<PHINode>::op_end(const_cast<PHINode *>(this)); } Value *PHINode::getOperand(unsigned i_nocapture ) const { ((i_nocapture < OperandTraits<PHINode>::operands (this) && "getOperand() out of range!") ? static_cast <void> (0) : __assert_fail ("i_nocapture < OperandTraits<PHINode>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 2808, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<PHINode>::op_begin(const_cast<PHINode *>(this))[i_nocapture].get()); } void PHINode::setOperand( unsigned i_nocapture, Value *Val_nocapture) { ((i_nocapture < OperandTraits<PHINode>::operands(this) && "setOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<PHINode>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 2808, __PRETTY_FUNCTION__)); OperandTraits<PHINode>:: op_begin(this)[i_nocapture] = Val_nocapture; } unsigned PHINode ::getNumOperands() const { return OperandTraits<PHINode> ::operands(this); } template <int Idx_nocapture> Use & PHINode::Op() { return this->OpFrom<Idx_nocapture>(this ); } template <int Idx_nocapture> const Use &PHINode ::Op() const { return this->OpFrom<Idx_nocapture>(this ); } |
2809 | |
2810 | //===----------------------------------------------------------------------===// |
2811 | // LandingPadInst Class |
2812 | //===----------------------------------------------------------------------===// |
2813 | |
2814 | //===--------------------------------------------------------------------------- |
2815 | /// The landingpad instruction holds all of the information |
2816 | /// necessary to generate correct exception handling. The landingpad instruction |
2817 | /// cannot be moved from the top of a landing pad block, which itself is |
2818 | /// accessible only from the 'unwind' edge of an invoke. This uses the |
2819 | /// SubclassData field in Value to store whether or not the landingpad is a |
2820 | /// cleanup. |
2821 | /// |
2822 | class LandingPadInst : public Instruction { |
2823 | using CleanupField = BoolBitfieldElementT<0>; |
2824 | |
2825 | /// The number of operands actually allocated. NumOperands is |
2826 | /// the number actually in use. |
2827 | unsigned ReservedSpace; |
2828 | |
2829 | LandingPadInst(const LandingPadInst &LP); |
2830 | |
2831 | public: |
2832 | enum ClauseType { Catch, Filter }; |
2833 | |
2834 | private: |
2835 | explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues, |
2836 | const Twine &NameStr, Instruction *InsertBefore); |
2837 | explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues, |
2838 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
2839 | |
2840 | // Allocate space for exactly zero operands. |
2841 | void *operator new(size_t s) { |
2842 | return User::operator new(s); |
2843 | } |
2844 | |
2845 | void growOperands(unsigned Size); |
2846 | void init(unsigned NumReservedValues, const Twine &NameStr); |
2847 | |
2848 | protected: |
2849 | // Note: Instruction needs to be a friend here to call cloneImpl. |
2850 | friend class Instruction; |
2851 | |
2852 | LandingPadInst *cloneImpl() const; |
2853 | |
2854 | public: |
2855 | /// Constructors - NumReservedClauses is a hint for the number of incoming |
2856 | /// clauses that this landingpad will have (use 0 if you really have no idea). |
2857 | static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses, |
2858 | const Twine &NameStr = "", |
2859 | Instruction *InsertBefore = nullptr); |
2860 | static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses, |
2861 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
2862 | |
2863 | /// Provide fast operand accessors |
2864 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
2865 | |
2866 | /// Return 'true' if this landingpad instruction is a |
2867 | /// cleanup. I.e., it should be run when unwinding even if its landing pad |
2868 | /// doesn't catch the exception. |
2869 | bool isCleanup() const { return getSubclassData<CleanupField>(); } |
2870 | |
2871 | /// Indicate that this landingpad instruction is a cleanup. |
2872 | void setCleanup(bool V) { setSubclassData<CleanupField>(V); } |
2873 | |
2874 | /// Add a catch or filter clause to the landing pad. |
2875 | void addClause(Constant *ClauseVal); |
2876 | |
2877 | /// Get the value of the clause at index Idx. Use isCatch/isFilter to |
2878 | /// determine what type of clause this is. |
2879 | Constant *getClause(unsigned Idx) const { |
2880 | return cast<Constant>(getOperandList()[Idx]); |
2881 | } |
2882 | |
2883 | /// Return 'true' if the clause and index Idx is a catch clause. |
2884 | bool isCatch(unsigned Idx) const { |
2885 | return !isa<ArrayType>(getOperandList()[Idx]->getType()); |
2886 | } |
2887 | |
2888 | /// Return 'true' if the clause and index Idx is a filter clause. |
2889 | bool isFilter(unsigned Idx) const { |
2890 | return isa<ArrayType>(getOperandList()[Idx]->getType()); |
2891 | } |
2892 | |
2893 | /// Get the number of clauses for this landing pad. |
2894 | unsigned getNumClauses() const { return getNumOperands(); } |
2895 | |
2896 | /// Grow the size of the operand list to accommodate the new |
2897 | /// number of clauses. |
2898 | void reserveClauses(unsigned Size) { growOperands(Size); } |
2899 | |
2900 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
2901 | static bool classof(const Instruction *I) { |
2902 | return I->getOpcode() == Instruction::LandingPad; |
2903 | } |
2904 | static bool classof(const Value *V) { |
2905 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
2906 | } |
2907 | }; |
2908 | |
2909 | template <> |
2910 | struct OperandTraits<LandingPadInst> : public HungoffOperandTraits<1> { |
2911 | }; |
2912 | |
2913 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(LandingPadInst, Value)LandingPadInst::op_iterator LandingPadInst::op_begin() { return OperandTraits<LandingPadInst>::op_begin(this); } LandingPadInst ::const_op_iterator LandingPadInst::op_begin() const { return OperandTraits<LandingPadInst>::op_begin(const_cast< LandingPadInst*>(this)); } LandingPadInst::op_iterator LandingPadInst ::op_end() { return OperandTraits<LandingPadInst>::op_end (this); } LandingPadInst::const_op_iterator LandingPadInst::op_end () const { return OperandTraits<LandingPadInst>::op_end (const_cast<LandingPadInst*>(this)); } Value *LandingPadInst ::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<LandingPadInst>::operands(this) && "getOperand() out of range!") ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<LandingPadInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 2913, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<LandingPadInst>::op_begin(const_cast< LandingPadInst*>(this))[i_nocapture].get()); } void LandingPadInst ::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (( i_nocapture < OperandTraits<LandingPadInst>::operands (this) && "setOperand() out of range!") ? static_cast <void> (0) : __assert_fail ("i_nocapture < OperandTraits<LandingPadInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 2913, __PRETTY_FUNCTION__)); OperandTraits<LandingPadInst >::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned LandingPadInst::getNumOperands() const { return OperandTraits <LandingPadInst>::operands(this); } template <int Idx_nocapture > Use &LandingPadInst::Op() { return this->OpFrom< Idx_nocapture>(this); } template <int Idx_nocapture> const Use &LandingPadInst::Op() const { return this-> OpFrom<Idx_nocapture>(this); } |
2914 | |
2915 | //===----------------------------------------------------------------------===// |
2916 | // ReturnInst Class |
2917 | //===----------------------------------------------------------------------===// |
2918 | |
2919 | //===--------------------------------------------------------------------------- |
2920 | /// Return a value (possibly void), from a function. Execution |
2921 | /// does not continue in this function any longer. |
2922 | /// |
2923 | class ReturnInst : public Instruction { |
2924 | ReturnInst(const ReturnInst &RI); |
2925 | |
2926 | private: |
2927 | // ReturnInst constructors: |
2928 | // ReturnInst() - 'ret void' instruction |
2929 | // ReturnInst( null) - 'ret void' instruction |
2930 | // ReturnInst(Value* X) - 'ret X' instruction |
2931 | // ReturnInst( null, Inst *I) - 'ret void' instruction, insert before I |
2932 | // ReturnInst(Value* X, Inst *I) - 'ret X' instruction, insert before I |
2933 | // ReturnInst( null, BB *B) - 'ret void' instruction, insert @ end of B |
2934 | // ReturnInst(Value* X, BB *B) - 'ret X' instruction, insert @ end of B |
2935 | // |
2936 | // NOTE: If the Value* passed is of type void then the constructor behaves as |
2937 | // if it was passed NULL. |
2938 | explicit ReturnInst(LLVMContext &C, Value *retVal = nullptr, |
2939 | Instruction *InsertBefore = nullptr); |
2940 | ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd); |
2941 | explicit ReturnInst(LLVMContext &C, BasicBlock *InsertAtEnd); |
2942 | |
2943 | protected: |
2944 | // Note: Instruction needs to be a friend here to call cloneImpl. |
2945 | friend class Instruction; |
2946 | |
2947 | ReturnInst *cloneImpl() const; |
2948 | |
2949 | public: |
2950 | static ReturnInst* Create(LLVMContext &C, Value *retVal = nullptr, |
2951 | Instruction *InsertBefore = nullptr) { |
2952 | return new(!!retVal) ReturnInst(C, retVal, InsertBefore); |
2953 | } |
2954 | |
2955 | static ReturnInst* Create(LLVMContext &C, Value *retVal, |
2956 | BasicBlock *InsertAtEnd) { |
2957 | return new(!!retVal) ReturnInst(C, retVal, InsertAtEnd); |
2958 | } |
2959 | |
2960 | static ReturnInst* Create(LLVMContext &C, BasicBlock *InsertAtEnd) { |
2961 | return new(0) ReturnInst(C, InsertAtEnd); |
2962 | } |
2963 | |
2964 | /// Provide fast operand accessors |
2965 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
2966 | |
2967 | /// Convenience accessor. Returns null if there is no return value. |
2968 | Value *getReturnValue() const { |
2969 | return getNumOperands() != 0 ? getOperand(0) : nullptr; |
2970 | } |
2971 | |
2972 | unsigned getNumSuccessors() const { return 0; } |
2973 | |
2974 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
2975 | static bool classof(const Instruction *I) { |
2976 | return (I->getOpcode() == Instruction::Ret); |
2977 | } |
2978 | static bool classof(const Value *V) { |
2979 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
2980 | } |
2981 | |
2982 | private: |
2983 | BasicBlock *getSuccessor(unsigned idx) const { |
2984 | llvm_unreachable("ReturnInst has no successors!")::llvm::llvm_unreachable_internal("ReturnInst has no successors!" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 2984); |
2985 | } |
2986 | |
2987 | void setSuccessor(unsigned idx, BasicBlock *B) { |
2988 | llvm_unreachable("ReturnInst has no successors!")::llvm::llvm_unreachable_internal("ReturnInst has no successors!" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 2988); |
2989 | } |
2990 | }; |
2991 | |
2992 | template <> |
2993 | struct OperandTraits<ReturnInst> : public VariadicOperandTraits<ReturnInst> { |
2994 | }; |
2995 | |
2996 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ReturnInst, Value)ReturnInst::op_iterator ReturnInst::op_begin() { return OperandTraits <ReturnInst>::op_begin(this); } ReturnInst::const_op_iterator ReturnInst::op_begin() const { return OperandTraits<ReturnInst >::op_begin(const_cast<ReturnInst*>(this)); } ReturnInst ::op_iterator ReturnInst::op_end() { return OperandTraits< ReturnInst>::op_end(this); } ReturnInst::const_op_iterator ReturnInst::op_end() const { return OperandTraits<ReturnInst >::op_end(const_cast<ReturnInst*>(this)); } Value *ReturnInst ::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<ReturnInst>::operands(this) && "getOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ReturnInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 2996, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<ReturnInst>::op_begin(const_cast<ReturnInst *>(this))[i_nocapture].get()); } void ReturnInst::setOperand (unsigned i_nocapture, Value *Val_nocapture) { ((i_nocapture < OperandTraits<ReturnInst>::operands(this) && "setOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ReturnInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 2996, __PRETTY_FUNCTION__)); OperandTraits<ReturnInst> ::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned ReturnInst ::getNumOperands() const { return OperandTraits<ReturnInst >::operands(this); } template <int Idx_nocapture> Use &ReturnInst::Op() { return this->OpFrom<Idx_nocapture >(this); } template <int Idx_nocapture> const Use & ReturnInst::Op() const { return this->OpFrom<Idx_nocapture >(this); } |
2997 | |
2998 | //===----------------------------------------------------------------------===// |
2999 | // BranchInst Class |
3000 | //===----------------------------------------------------------------------===// |
3001 | |
3002 | //===--------------------------------------------------------------------------- |
3003 | /// Conditional or Unconditional Branch instruction. |
3004 | /// |
3005 | class BranchInst : public Instruction { |
3006 | /// Ops list - Branches are strange. The operands are ordered: |
3007 | /// [Cond, FalseDest,] TrueDest. This makes some accessors faster because |
3008 | /// they don't have to check for cond/uncond branchness. These are mostly |
3009 | /// accessed relative from op_end(). |
3010 | BranchInst(const BranchInst &BI); |
3011 | // BranchInst constructors (where {B, T, F} are blocks, and C is a condition): |
3012 | // BranchInst(BB *B) - 'br B' |
3013 | // BranchInst(BB* T, BB *F, Value *C) - 'br C, T, F' |
3014 | // BranchInst(BB* B, Inst *I) - 'br B' insert before I |
3015 | // BranchInst(BB* T, BB *F, Value *C, Inst *I) - 'br C, T, F', insert before I |
3016 | // BranchInst(BB* B, BB *I) - 'br B' insert at end |
3017 | // BranchInst(BB* T, BB *F, Value *C, BB *I) - 'br C, T, F', insert at end |
3018 | explicit BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore = nullptr); |
3019 | BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond, |
3020 | Instruction *InsertBefore = nullptr); |
3021 | BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd); |
3022 | BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond, |
3023 | BasicBlock *InsertAtEnd); |
3024 | |
3025 | void AssertOK(); |
3026 | |
3027 | protected: |
3028 | // Note: Instruction needs to be a friend here to call cloneImpl. |
3029 | friend class Instruction; |
3030 | |
3031 | BranchInst *cloneImpl() const; |
3032 | |
3033 | public: |
3034 | /// Iterator type that casts an operand to a basic block. |
3035 | /// |
3036 | /// This only makes sense because the successors are stored as adjacent |
3037 | /// operands for branch instructions. |
3038 | struct succ_op_iterator |
3039 | : iterator_adaptor_base<succ_op_iterator, value_op_iterator, |
3040 | std::random_access_iterator_tag, BasicBlock *, |
3041 | ptrdiff_t, BasicBlock *, BasicBlock *> { |
3042 | explicit succ_op_iterator(value_op_iterator I) : iterator_adaptor_base(I) {} |
3043 | |
3044 | BasicBlock *operator*() const { return cast<BasicBlock>(*I); } |
3045 | BasicBlock *operator->() const { return operator*(); } |
3046 | }; |
3047 | |
3048 | /// The const version of `succ_op_iterator`. |
3049 | struct const_succ_op_iterator |
3050 | : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator, |
3051 | std::random_access_iterator_tag, |
3052 | const BasicBlock *, ptrdiff_t, const BasicBlock *, |
3053 | const BasicBlock *> { |
3054 | explicit const_succ_op_iterator(const_value_op_iterator I) |
3055 | : iterator_adaptor_base(I) {} |
3056 | |
3057 | const BasicBlock *operator*() const { return cast<BasicBlock>(*I); } |
3058 | const BasicBlock *operator->() const { return operator*(); } |
3059 | }; |
3060 | |
3061 | static BranchInst *Create(BasicBlock *IfTrue, |
3062 | Instruction *InsertBefore = nullptr) { |
3063 | return new(1) BranchInst(IfTrue, InsertBefore); |
3064 | } |
3065 | |
3066 | static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse, |
3067 | Value *Cond, Instruction *InsertBefore = nullptr) { |
3068 | return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertBefore); |
3069 | } |
3070 | |
3071 | static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) { |
3072 | return new(1) BranchInst(IfTrue, InsertAtEnd); |
3073 | } |
3074 | |
3075 | static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse, |
3076 | Value *Cond, BasicBlock *InsertAtEnd) { |
3077 | return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertAtEnd); |
3078 | } |
3079 | |
3080 | /// Transparently provide more efficient getOperand methods. |
3081 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
3082 | |
3083 | bool isUnconditional() const { return getNumOperands() == 1; } |
3084 | bool isConditional() const { return getNumOperands() == 3; } |
3085 | |
3086 | Value *getCondition() const { |
3087 | assert(isConditional() && "Cannot get condition of an uncond branch!")((isConditional() && "Cannot get condition of an uncond branch!" ) ? static_cast<void> (0) : __assert_fail ("isConditional() && \"Cannot get condition of an uncond branch!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 3087, __PRETTY_FUNCTION__)); |
3088 | return Op<-3>(); |
3089 | } |
3090 | |
3091 | void setCondition(Value *V) { |
3092 | assert(isConditional() && "Cannot set condition of unconditional branch!")((isConditional() && "Cannot set condition of unconditional branch!" ) ? static_cast<void> (0) : __assert_fail ("isConditional() && \"Cannot set condition of unconditional branch!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 3092, __PRETTY_FUNCTION__)); |
3093 | Op<-3>() = V; |
3094 | } |
3095 | |
3096 | unsigned getNumSuccessors() const { return 1+isConditional(); } |
3097 | |
3098 | BasicBlock *getSuccessor(unsigned i) const { |
3099 | assert(i < getNumSuccessors() && "Successor # out of range for Branch!")((i < getNumSuccessors() && "Successor # out of range for Branch!" ) ? static_cast<void> (0) : __assert_fail ("i < getNumSuccessors() && \"Successor # out of range for Branch!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 3099, __PRETTY_FUNCTION__)); |
3100 | return cast_or_null<BasicBlock>((&Op<-1>() - i)->get()); |
3101 | } |
3102 | |
3103 | void setSuccessor(unsigned idx, BasicBlock *NewSucc) { |
3104 | assert(idx < getNumSuccessors() && "Successor # out of range for Branch!")((idx < getNumSuccessors() && "Successor # out of range for Branch!" ) ? static_cast<void> (0) : __assert_fail ("idx < getNumSuccessors() && \"Successor # out of range for Branch!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 3104, __PRETTY_FUNCTION__)); |
3105 | *(&Op<-1>() - idx) = NewSucc; |
3106 | } |
3107 | |
3108 | /// Swap the successors of this branch instruction. |
3109 | /// |
3110 | /// Swaps the successors of the branch instruction. This also swaps any |
3111 | /// branch weight metadata associated with the instruction so that it |
3112 | /// continues to map correctly to each operand. |
3113 | void swapSuccessors(); |
3114 | |
3115 | iterator_range<succ_op_iterator> successors() { |
3116 | return make_range( |
3117 | succ_op_iterator(std::next(value_op_begin(), isConditional() ? 1 : 0)), |
3118 | succ_op_iterator(value_op_end())); |
3119 | } |
3120 | |
3121 | iterator_range<const_succ_op_iterator> successors() const { |
3122 | return make_range(const_succ_op_iterator( |
3123 | std::next(value_op_begin(), isConditional() ? 1 : 0)), |
3124 | const_succ_op_iterator(value_op_end())); |
3125 | } |
3126 | |
3127 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
3128 | static bool classof(const Instruction *I) { |
3129 | return (I->getOpcode() == Instruction::Br); |
3130 | } |
3131 | static bool classof(const Value *V) { |
3132 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
3133 | } |
3134 | }; |
3135 | |
3136 | template <> |
3137 | struct OperandTraits<BranchInst> : public VariadicOperandTraits<BranchInst, 1> { |
3138 | }; |
3139 | |
3140 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BranchInst, Value)BranchInst::op_iterator BranchInst::op_begin() { return OperandTraits <BranchInst>::op_begin(this); } BranchInst::const_op_iterator BranchInst::op_begin() const { return OperandTraits<BranchInst >::op_begin(const_cast<BranchInst*>(this)); } BranchInst ::op_iterator BranchInst::op_end() { return OperandTraits< BranchInst>::op_end(this); } BranchInst::const_op_iterator BranchInst::op_end() const { return OperandTraits<BranchInst >::op_end(const_cast<BranchInst*>(this)); } Value *BranchInst ::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<BranchInst>::operands(this) && "getOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<BranchInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 3140, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<BranchInst>::op_begin(const_cast<BranchInst *>(this))[i_nocapture].get()); } void BranchInst::setOperand (unsigned i_nocapture, Value *Val_nocapture) { ((i_nocapture < OperandTraits<BranchInst>::operands(this) && "setOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<BranchInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 3140, __PRETTY_FUNCTION__)); OperandTraits<BranchInst> ::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned BranchInst ::getNumOperands() const { return OperandTraits<BranchInst >::operands(this); } template <int Idx_nocapture> Use &BranchInst::Op() { return this->OpFrom<Idx_nocapture >(this); } template <int Idx_nocapture> const Use & BranchInst::Op() const { return this->OpFrom<Idx_nocapture >(this); } |
3141 | |
3142 | //===----------------------------------------------------------------------===// |
3143 | // SwitchInst Class |
3144 | //===----------------------------------------------------------------------===// |
3145 | |
3146 | //===--------------------------------------------------------------------------- |
3147 | /// Multiway switch |
3148 | /// |
3149 | class SwitchInst : public Instruction { |
3150 | unsigned ReservedSpace; |
3151 | |
3152 | // Operand[0] = Value to switch on |
3153 | // Operand[1] = Default basic block destination |
3154 | // Operand[2n ] = Value to match |
3155 | // Operand[2n+1] = BasicBlock to go to on match |
3156 | SwitchInst(const SwitchInst &SI); |
3157 | |
3158 | /// Create a new switch instruction, specifying a value to switch on and a |
3159 | /// default destination. The number of additional cases can be specified here |
3160 | /// to make memory allocation more efficient. This constructor can also |
3161 | /// auto-insert before another instruction. |
3162 | SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases, |
3163 | Instruction *InsertBefore); |
3164 | |
3165 | /// Create a new switch instruction, specifying a value to switch on and a |
3166 | /// default destination. The number of additional cases can be specified here |
3167 | /// to make memory allocation more efficient. This constructor also |
3168 | /// auto-inserts at the end of the specified BasicBlock. |
3169 | SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases, |
3170 | BasicBlock *InsertAtEnd); |
3171 | |
3172 | // allocate space for exactly zero operands |
3173 | void *operator new(size_t s) { |
3174 | return User::operator new(s); |
3175 | } |
3176 | |
3177 | void init(Value *Value, BasicBlock *Default, unsigned NumReserved); |
3178 | void growOperands(); |
3179 | |
3180 | protected: |
3181 | // Note: Instruction needs to be a friend here to call cloneImpl. |
3182 | friend class Instruction; |
3183 | |
3184 | SwitchInst *cloneImpl() const; |
3185 | |
3186 | public: |
3187 | // -2 |
3188 | static const unsigned DefaultPseudoIndex = static_cast<unsigned>(~0L-1); |
3189 | |
3190 | template <typename CaseHandleT> class CaseIteratorImpl; |
3191 | |
3192 | /// A handle to a particular switch case. It exposes a convenient interface |
3193 | /// to both the case value and the successor block. |
3194 | /// |
3195 | /// We define this as a template and instantiate it to form both a const and |
3196 | /// non-const handle. |
3197 | template <typename SwitchInstT, typename ConstantIntT, typename BasicBlockT> |
3198 | class CaseHandleImpl { |
3199 | // Directly befriend both const and non-const iterators. |
3200 | friend class SwitchInst::CaseIteratorImpl< |
3201 | CaseHandleImpl<SwitchInstT, ConstantIntT, BasicBlockT>>; |
3202 | |
3203 | protected: |
3204 | // Expose the switch type we're parameterized with to the iterator. |
3205 | using SwitchInstType = SwitchInstT; |
3206 | |
3207 | SwitchInstT *SI; |
3208 | ptrdiff_t Index; |
3209 | |
3210 | CaseHandleImpl() = default; |
3211 | CaseHandleImpl(SwitchInstT *SI, ptrdiff_t Index) : SI(SI), Index(Index) {} |
3212 | |
3213 | public: |
3214 | /// Resolves case value for current case. |
3215 | ConstantIntT *getCaseValue() const { |
3216 | assert((unsigned)Index < SI->getNumCases() &&(((unsigned)Index < SI->getNumCases() && "Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("(unsigned)Index < SI->getNumCases() && \"Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 3217, __PRETTY_FUNCTION__)) |
3217 | "Index out the number of cases.")(((unsigned)Index < SI->getNumCases() && "Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("(unsigned)Index < SI->getNumCases() && \"Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 3217, __PRETTY_FUNCTION__)); |
3218 | return reinterpret_cast<ConstantIntT *>(SI->getOperand(2 + Index * 2)); |
3219 | } |
3220 | |
3221 | /// Resolves successor for current case. |
3222 | BasicBlockT *getCaseSuccessor() const { |
3223 | assert(((unsigned)Index < SI->getNumCases() ||((((unsigned)Index < SI->getNumCases() || (unsigned)Index == DefaultPseudoIndex) && "Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("((unsigned)Index < SI->getNumCases() || (unsigned)Index == DefaultPseudoIndex) && \"Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 3225, __PRETTY_FUNCTION__)) |
3224 | (unsigned)Index == DefaultPseudoIndex) &&((((unsigned)Index < SI->getNumCases() || (unsigned)Index == DefaultPseudoIndex) && "Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("((unsigned)Index < SI->getNumCases() || (unsigned)Index == DefaultPseudoIndex) && \"Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 3225, __PRETTY_FUNCTION__)) |
3225 | "Index out the number of cases.")((((unsigned)Index < SI->getNumCases() || (unsigned)Index == DefaultPseudoIndex) && "Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("((unsigned)Index < SI->getNumCases() || (unsigned)Index == DefaultPseudoIndex) && \"Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 3225, __PRETTY_FUNCTION__)); |
3226 | return SI->getSuccessor(getSuccessorIndex()); |
3227 | } |
3228 | |
3229 | /// Returns number of current case. |
3230 | unsigned getCaseIndex() const { return Index; } |
3231 | |
3232 | /// Returns successor index for current case successor. |
3233 | unsigned getSuccessorIndex() const { |
3234 | assert(((unsigned)Index == DefaultPseudoIndex ||((((unsigned)Index == DefaultPseudoIndex || (unsigned)Index < SI->getNumCases()) && "Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("((unsigned)Index == DefaultPseudoIndex || (unsigned)Index < SI->getNumCases()) && \"Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 3236, __PRETTY_FUNCTION__)) |
3235 | (unsigned)Index < SI->getNumCases()) &&((((unsigned)Index == DefaultPseudoIndex || (unsigned)Index < SI->getNumCases()) && "Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("((unsigned)Index == DefaultPseudoIndex || (unsigned)Index < SI->getNumCases()) && \"Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 3236, __PRETTY_FUNCTION__)) |
3236 | "Index out the number of cases.")((((unsigned)Index == DefaultPseudoIndex || (unsigned)Index < SI->getNumCases()) && "Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("((unsigned)Index == DefaultPseudoIndex || (unsigned)Index < SI->getNumCases()) && \"Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 3236, __PRETTY_FUNCTION__)); |
3237 | return (unsigned)Index != DefaultPseudoIndex ? Index + 1 : 0; |
3238 | } |
3239 | |
3240 | bool operator==(const CaseHandleImpl &RHS) const { |
3241 | assert(SI == RHS.SI && "Incompatible operators.")((SI == RHS.SI && "Incompatible operators.") ? static_cast <void> (0) : __assert_fail ("SI == RHS.SI && \"Incompatible operators.\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 3241, __PRETTY_FUNCTION__)); |
3242 | return Index == RHS.Index; |
3243 | } |
3244 | }; |
3245 | |
3246 | using ConstCaseHandle = |
3247 | CaseHandleImpl<const SwitchInst, const ConstantInt, const BasicBlock>; |
3248 | |
3249 | class CaseHandle |
3250 | : public CaseHandleImpl<SwitchInst, ConstantInt, BasicBlock> { |
3251 | friend class SwitchInst::CaseIteratorImpl<CaseHandle>; |
3252 | |
3253 | public: |
3254 | CaseHandle(SwitchInst *SI, ptrdiff_t Index) : CaseHandleImpl(SI, Index) {} |
3255 | |
3256 | /// Sets the new value for current case. |
3257 | void setValue(ConstantInt *V) { |
3258 | assert((unsigned)Index < SI->getNumCases() &&(((unsigned)Index < SI->getNumCases() && "Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("(unsigned)Index < SI->getNumCases() && \"Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 3259, __PRETTY_FUNCTION__)) |
3259 | "Index out the number of cases.")(((unsigned)Index < SI->getNumCases() && "Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("(unsigned)Index < SI->getNumCases() && \"Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 3259, __PRETTY_FUNCTION__)); |
3260 | SI->setOperand(2 + Index*2, reinterpret_cast<Value*>(V)); |
3261 | } |
3262 | |
3263 | /// Sets the new successor for current case. |
3264 | void setSuccessor(BasicBlock *S) { |
3265 | SI->setSuccessor(getSuccessorIndex(), S); |
3266 | } |
3267 | }; |
3268 | |
3269 | template <typename CaseHandleT> |
3270 | class CaseIteratorImpl |
3271 | : public iterator_facade_base<CaseIteratorImpl<CaseHandleT>, |
3272 | std::random_access_iterator_tag, |
3273 | CaseHandleT> { |
3274 | using SwitchInstT = typename CaseHandleT::SwitchInstType; |
3275 | |
3276 | CaseHandleT Case; |
3277 | |
3278 | public: |
3279 | /// Default constructed iterator is in an invalid state until assigned to |
3280 | /// a case for a particular switch. |
3281 | CaseIteratorImpl() = default; |
3282 | |
3283 | /// Initializes case iterator for given SwitchInst and for given |
3284 | /// case number. |
3285 | CaseIteratorImpl(SwitchInstT *SI, unsigned CaseNum) : Case(SI, CaseNum) {} |
3286 | |
3287 | /// Initializes case iterator for given SwitchInst and for given |
3288 | /// successor index. |
3289 | static CaseIteratorImpl fromSuccessorIndex(SwitchInstT *SI, |
3290 | unsigned SuccessorIndex) { |
3291 | assert(SuccessorIndex < SI->getNumSuccessors() &&((SuccessorIndex < SI->getNumSuccessors() && "Successor index # out of range!" ) ? static_cast<void> (0) : __assert_fail ("SuccessorIndex < SI->getNumSuccessors() && \"Successor index # out of range!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 3292, __PRETTY_FUNCTION__)) |
3292 | "Successor index # out of range!")((SuccessorIndex < SI->getNumSuccessors() && "Successor index # out of range!" ) ? static_cast<void> (0) : __assert_fail ("SuccessorIndex < SI->getNumSuccessors() && \"Successor index # out of range!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 3292, __PRETTY_FUNCTION__)); |
3293 | return SuccessorIndex != 0 ? CaseIteratorImpl(SI, SuccessorIndex - 1) |
3294 | : CaseIteratorImpl(SI, DefaultPseudoIndex); |
3295 | } |
3296 | |
3297 | /// Support converting to the const variant. This will be a no-op for const |
3298 | /// variant. |
3299 | operator CaseIteratorImpl<ConstCaseHandle>() const { |
3300 | return CaseIteratorImpl<ConstCaseHandle>(Case.SI, Case.Index); |
3301 | } |
3302 | |
3303 | CaseIteratorImpl &operator+=(ptrdiff_t N) { |
3304 | // Check index correctness after addition. |
3305 | // Note: Index == getNumCases() means end(). |
3306 | assert(Case.Index + N >= 0 &&((Case.Index + N >= 0 && (unsigned)(Case.Index + N ) <= Case.SI->getNumCases() && "Case.Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("Case.Index + N >= 0 && (unsigned)(Case.Index + N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 3308, __PRETTY_FUNCTION__)) |
3307 | (unsigned)(Case.Index + N) <= Case.SI->getNumCases() &&((Case.Index + N >= 0 && (unsigned)(Case.Index + N ) <= Case.SI->getNumCases() && "Case.Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("Case.Index + N >= 0 && (unsigned)(Case.Index + N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 3308, __PRETTY_FUNCTION__)) |
3308 | "Case.Index out the number of cases.")((Case.Index + N >= 0 && (unsigned)(Case.Index + N ) <= Case.SI->getNumCases() && "Case.Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("Case.Index + N >= 0 && (unsigned)(Case.Index + N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 3308, __PRETTY_FUNCTION__)); |
3309 | Case.Index += N; |
3310 | return *this; |
3311 | } |
3312 | CaseIteratorImpl &operator-=(ptrdiff_t N) { |
3313 | // Check index correctness after subtraction. |
3314 | // Note: Case.Index == getNumCases() means end(). |
3315 | assert(Case.Index - N >= 0 &&((Case.Index - N >= 0 && (unsigned)(Case.Index - N ) <= Case.SI->getNumCases() && "Case.Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("Case.Index - N >= 0 && (unsigned)(Case.Index - N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 3317, __PRETTY_FUNCTION__)) |
3316 | (unsigned)(Case.Index - N) <= Case.SI->getNumCases() &&((Case.Index - N >= 0 && (unsigned)(Case.Index - N ) <= Case.SI->getNumCases() && "Case.Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("Case.Index - N >= 0 && (unsigned)(Case.Index - N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 3317, __PRETTY_FUNCTION__)) |
3317 | "Case.Index out the number of cases.")((Case.Index - N >= 0 && (unsigned)(Case.Index - N ) <= Case.SI->getNumCases() && "Case.Index out the number of cases." ) ? static_cast<void> (0) : __assert_fail ("Case.Index - N >= 0 && (unsigned)(Case.Index - N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 3317, __PRETTY_FUNCTION__)); |
3318 | Case.Index -= N; |
3319 | return *this; |
3320 | } |
3321 | ptrdiff_t operator-(const CaseIteratorImpl &RHS) const { |
3322 | assert(Case.SI == RHS.Case.SI && "Incompatible operators.")((Case.SI == RHS.Case.SI && "Incompatible operators." ) ? static_cast<void> (0) : __assert_fail ("Case.SI == RHS.Case.SI && \"Incompatible operators.\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 3322, __PRETTY_FUNCTION__)); |
3323 | return Case.Index - RHS.Case.Index; |
3324 | } |
3325 | bool operator==(const CaseIteratorImpl &RHS) const { |
3326 | return Case == RHS.Case; |
3327 | } |
3328 | bool operator<(const CaseIteratorImpl &RHS) const { |
3329 | assert(Case.SI == RHS.Case.SI && "Incompatible operators.")((Case.SI == RHS.Case.SI && "Incompatible operators." ) ? static_cast<void> (0) : __assert_fail ("Case.SI == RHS.Case.SI && \"Incompatible operators.\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 3329, __PRETTY_FUNCTION__)); |
3330 | return Case.Index < RHS.Case.Index; |
3331 | } |
3332 | CaseHandleT &operator*() { return Case; } |
3333 | const CaseHandleT &operator*() const { return Case; } |
3334 | }; |
3335 | |
3336 | using CaseIt = CaseIteratorImpl<CaseHandle>; |
3337 | using ConstCaseIt = CaseIteratorImpl<ConstCaseHandle>; |
3338 | |
3339 | static SwitchInst *Create(Value *Value, BasicBlock *Default, |
3340 | unsigned NumCases, |
3341 | Instruction *InsertBefore = nullptr) { |
3342 | return new SwitchInst(Value, Default, NumCases, InsertBefore); |
3343 | } |
3344 | |
3345 | static SwitchInst *Create(Value *Value, BasicBlock *Default, |
3346 | unsigned NumCases, BasicBlock *InsertAtEnd) { |
3347 | return new SwitchInst(Value, Default, NumCases, InsertAtEnd); |
3348 | } |
3349 | |
3350 | /// Provide fast operand accessors |
3351 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
3352 | |
3353 | // Accessor Methods for Switch stmt |
3354 | Value *getCondition() const { return getOperand(0); } |
3355 | void setCondition(Value *V) { setOperand(0, V); } |
3356 | |
3357 | BasicBlock *getDefaultDest() const { |
3358 | return cast<BasicBlock>(getOperand(1)); |
3359 | } |
3360 | |
3361 | void setDefaultDest(BasicBlock *DefaultCase) { |
3362 | setOperand(1, reinterpret_cast<Value*>(DefaultCase)); |
3363 | } |
3364 | |
3365 | /// Return the number of 'cases' in this switch instruction, excluding the |
3366 | /// default case. |
3367 | unsigned getNumCases() const { |
3368 | return getNumOperands()/2 - 1; |
3369 | } |
3370 | |
3371 | /// Returns a read/write iterator that points to the first case in the |
3372 | /// SwitchInst. |
3373 | CaseIt case_begin() { |
3374 | return CaseIt(this, 0); |
3375 | } |
3376 | |
3377 | /// Returns a read-only iterator that points to the first case in the |
3378 | /// SwitchInst. |
3379 | ConstCaseIt case_begin() const { |
3380 | return ConstCaseIt(this, 0); |
3381 | } |
3382 | |
3383 | /// Returns a read/write iterator that points one past the last in the |
3384 | /// SwitchInst. |
3385 | CaseIt case_end() { |
3386 | return CaseIt(this, getNumCases()); |
3387 | } |
3388 | |
3389 | /// Returns a read-only iterator that points one past the last in the |
3390 | /// SwitchInst. |
3391 | ConstCaseIt case_end() const { |
3392 | return ConstCaseIt(this, getNumCases()); |
3393 | } |
3394 | |
3395 | /// Iteration adapter for range-for loops. |
3396 | iterator_range<CaseIt> cases() { |
3397 | return make_range(case_begin(), case_end()); |
3398 | } |
3399 | |
3400 | /// Constant iteration adapter for range-for loops. |
3401 | iterator_range<ConstCaseIt> cases() const { |
3402 | return make_range(case_begin(), case_end()); |
3403 | } |
3404 | |
3405 | /// Returns an iterator that points to the default case. |
3406 | /// Note: this iterator allows to resolve successor only. Attempt |
3407 | /// to resolve case value causes an assertion. |
3408 | /// Also note, that increment and decrement also causes an assertion and |
3409 | /// makes iterator invalid. |
3410 | CaseIt case_default() { |
3411 | return CaseIt(this, DefaultPseudoIndex); |
3412 | } |
3413 | ConstCaseIt case_default() const { |
3414 | return ConstCaseIt(this, DefaultPseudoIndex); |
3415 | } |
3416 | |
3417 | /// Search all of the case values for the specified constant. If it is |
3418 | /// explicitly handled, return the case iterator of it, otherwise return |
3419 | /// default case iterator to indicate that it is handled by the default |
3420 | /// handler. |
3421 | CaseIt findCaseValue(const ConstantInt *C) { |
3422 | CaseIt I = llvm::find_if( |
3423 | cases(), [C](CaseHandle &Case) { return Case.getCaseValue() == C; }); |
3424 | if (I != case_end()) |
3425 | return I; |
3426 | |
3427 | return case_default(); |
3428 | } |
3429 | ConstCaseIt findCaseValue(const ConstantInt *C) const { |
3430 | ConstCaseIt I = llvm::find_if(cases(), [C](ConstCaseHandle &Case) { |
3431 | return Case.getCaseValue() == C; |
3432 | }); |
3433 | if (I != case_end()) |
3434 | return I; |
3435 | |
3436 | return case_default(); |
3437 | } |
3438 | |
3439 | /// Finds the unique case value for a given successor. Returns null if the |
3440 | /// successor is not found, not unique, or is the default case. |
3441 | ConstantInt *findCaseDest(BasicBlock *BB) { |
3442 | if (BB == getDefaultDest()) |
3443 | return nullptr; |
3444 | |
3445 | ConstantInt *CI = nullptr; |
3446 | for (auto Case : cases()) { |
3447 | if (Case.getCaseSuccessor() != BB) |
3448 | continue; |
3449 | |
3450 | if (CI) |
3451 | return nullptr; // Multiple cases lead to BB. |
3452 | |
3453 | CI = Case.getCaseValue(); |
3454 | } |
3455 | |
3456 | return CI; |
3457 | } |
3458 | |
3459 | /// Add an entry to the switch instruction. |
3460 | /// Note: |
3461 | /// This action invalidates case_end(). Old case_end() iterator will |
3462 | /// point to the added case. |
3463 | void addCase(ConstantInt *OnVal, BasicBlock *Dest); |
3464 | |
3465 | /// This method removes the specified case and its successor from the switch |
3466 | /// instruction. Note that this operation may reorder the remaining cases at |
3467 | /// index idx and above. |
3468 | /// Note: |
3469 | /// This action invalidates iterators for all cases following the one removed, |
3470 | /// including the case_end() iterator. It returns an iterator for the next |
3471 | /// case. |
3472 | CaseIt removeCase(CaseIt I); |
3473 | |
3474 | unsigned getNumSuccessors() const { return getNumOperands()/2; } |
3475 | BasicBlock *getSuccessor(unsigned idx) const { |
3476 | assert(idx < getNumSuccessors() &&"Successor idx out of range for switch!")((idx < getNumSuccessors() &&"Successor idx out of range for switch!" ) ? static_cast<void> (0) : __assert_fail ("idx < getNumSuccessors() &&\"Successor idx out of range for switch!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 3476, __PRETTY_FUNCTION__)); |
3477 | return cast<BasicBlock>(getOperand(idx*2+1)); |
3478 | } |
3479 | void setSuccessor(unsigned idx, BasicBlock *NewSucc) { |
3480 | assert(idx < getNumSuccessors() && "Successor # out of range for switch!")((idx < getNumSuccessors() && "Successor # out of range for switch!" ) ? static_cast<void> (0) : __assert_fail ("idx < getNumSuccessors() && \"Successor # out of range for switch!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 3480, __PRETTY_FUNCTION__)); |
3481 | setOperand(idx * 2 + 1, NewSucc); |
3482 | } |
3483 | |
3484 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
3485 | static bool classof(const Instruction *I) { |
3486 | return I->getOpcode() == Instruction::Switch; |
3487 | } |
3488 | static bool classof(const Value *V) { |
3489 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
3490 | } |
3491 | }; |
3492 | |
3493 | /// A wrapper class to simplify modification of SwitchInst cases along with |
3494 | /// their prof branch_weights metadata. |
3495 | class SwitchInstProfUpdateWrapper { |
3496 | SwitchInst &SI; |
3497 | Optional<SmallVector<uint32_t, 8> > Weights = None; |
3498 | bool Changed = false; |
3499 | |
3500 | protected: |
3501 | static MDNode *getProfBranchWeightsMD(const SwitchInst &SI); |
3502 | |
3503 | MDNode *buildProfBranchWeightsMD(); |
3504 | |
3505 | void init(); |
3506 | |
3507 | public: |
3508 | using CaseWeightOpt = Optional<uint32_t>; |
3509 | SwitchInst *operator->() { return &SI; } |
3510 | SwitchInst &operator*() { return SI; } |
3511 | operator SwitchInst *() { return &SI; } |
3512 | |
3513 | SwitchInstProfUpdateWrapper(SwitchInst &SI) : SI(SI) { init(); } |
3514 | |
3515 | ~SwitchInstProfUpdateWrapper() { |
3516 | if (Changed) |
3517 | SI.setMetadata(LLVMContext::MD_prof, buildProfBranchWeightsMD()); |
3518 | } |
3519 | |
3520 | /// Delegate the call to the underlying SwitchInst::removeCase() and remove |
3521 | /// correspondent branch weight. |
3522 | SwitchInst::CaseIt removeCase(SwitchInst::CaseIt I); |
3523 | |
3524 | /// Delegate the call to the underlying SwitchInst::addCase() and set the |
3525 | /// specified branch weight for the added case. |
3526 | void addCase(ConstantInt *OnVal, BasicBlock *Dest, CaseWeightOpt W); |
3527 | |
3528 | /// Delegate the call to the underlying SwitchInst::eraseFromParent() and mark |
3529 | /// this object to not touch the underlying SwitchInst in destructor. |
3530 | SymbolTableList<Instruction>::iterator eraseFromParent(); |
3531 | |
3532 | void setSuccessorWeight(unsigned idx, CaseWeightOpt W); |
3533 | CaseWeightOpt getSuccessorWeight(unsigned idx); |
3534 | |
3535 | static CaseWeightOpt getSuccessorWeight(const SwitchInst &SI, unsigned idx); |
3536 | }; |
3537 | |
3538 | template <> |
3539 | struct OperandTraits<SwitchInst> : public HungoffOperandTraits<2> { |
3540 | }; |
3541 | |
3542 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SwitchInst, Value)SwitchInst::op_iterator SwitchInst::op_begin() { return OperandTraits <SwitchInst>::op_begin(this); } SwitchInst::const_op_iterator SwitchInst::op_begin() const { return OperandTraits<SwitchInst >::op_begin(const_cast<SwitchInst*>(this)); } SwitchInst ::op_iterator SwitchInst::op_end() { return OperandTraits< SwitchInst>::op_end(this); } SwitchInst::const_op_iterator SwitchInst::op_end() const { return OperandTraits<SwitchInst >::op_end(const_cast<SwitchInst*>(this)); } Value *SwitchInst ::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<SwitchInst>::operands(this) && "getOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<SwitchInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 3542, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<SwitchInst>::op_begin(const_cast<SwitchInst *>(this))[i_nocapture].get()); } void SwitchInst::setOperand (unsigned i_nocapture, Value *Val_nocapture) { ((i_nocapture < OperandTraits<SwitchInst>::operands(this) && "setOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<SwitchInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 3542, __PRETTY_FUNCTION__)); OperandTraits<SwitchInst> ::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned SwitchInst ::getNumOperands() const { return OperandTraits<SwitchInst >::operands(this); } template <int Idx_nocapture> Use &SwitchInst::Op() { return this->OpFrom<Idx_nocapture >(this); } template <int Idx_nocapture> const Use & SwitchInst::Op() const { return this->OpFrom<Idx_nocapture >(this); } |
3543 | |
3544 | //===----------------------------------------------------------------------===// |
3545 | // IndirectBrInst Class |
3546 | //===----------------------------------------------------------------------===// |
3547 | |
3548 | //===--------------------------------------------------------------------------- |
3549 | /// Indirect Branch Instruction. |
3550 | /// |
3551 | class IndirectBrInst : public Instruction { |
3552 | unsigned ReservedSpace; |
3553 | |
3554 | // Operand[0] = Address to jump to |
3555 | // Operand[n+1] = n-th destination |
3556 | IndirectBrInst(const IndirectBrInst &IBI); |
3557 | |
3558 | /// Create a new indirectbr instruction, specifying an |
3559 | /// Address to jump to. The number of expected destinations can be specified |
3560 | /// here to make memory allocation more efficient. This constructor can also |
3561 | /// autoinsert before another instruction. |
3562 | IndirectBrInst(Value *Address, unsigned NumDests, Instruction *InsertBefore); |
3563 | |
3564 | /// Create a new indirectbr instruction, specifying an |
3565 | /// Address to jump to. The number of expected destinations can be specified |
3566 | /// here to make memory allocation more efficient. This constructor also |
3567 | /// autoinserts at the end of the specified BasicBlock. |
3568 | IndirectBrInst(Value *Address, unsigned NumDests, BasicBlock *InsertAtEnd); |
3569 | |
3570 | // allocate space for exactly zero operands |
3571 | void *operator new(size_t s) { |
3572 | return User::operator new(s); |
3573 | } |
3574 | |
3575 | void init(Value *Address, unsigned NumDests); |
3576 | void growOperands(); |
3577 | |
3578 | protected: |
3579 | // Note: Instruction needs to be a friend here to call cloneImpl. |
3580 | friend class Instruction; |
3581 | |
3582 | IndirectBrInst *cloneImpl() const; |
3583 | |
3584 | public: |
3585 | /// Iterator type that casts an operand to a basic block. |
3586 | /// |
3587 | /// This only makes sense because the successors are stored as adjacent |
3588 | /// operands for indirectbr instructions. |
3589 | struct succ_op_iterator |
3590 | : iterator_adaptor_base<succ_op_iterator, value_op_iterator, |
3591 | std::random_access_iterator_tag, BasicBlock *, |
3592 | ptrdiff_t, BasicBlock *, BasicBlock *> { |
3593 | explicit succ_op_iterator(value_op_iterator I) : iterator_adaptor_base(I) {} |
3594 | |
3595 | BasicBlock *operator*() const { return cast<BasicBlock>(*I); } |
3596 | BasicBlock *operator->() const { return operator*(); } |
3597 | }; |
3598 | |
3599 | /// The const version of `succ_op_iterator`. |
3600 | struct const_succ_op_iterator |
3601 | : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator, |
3602 | std::random_access_iterator_tag, |
3603 | const BasicBlock *, ptrdiff_t, const BasicBlock *, |
3604 | const BasicBlock *> { |
3605 | explicit const_succ_op_iterator(const_value_op_iterator I) |
3606 | : iterator_adaptor_base(I) {} |
3607 | |
3608 | const BasicBlock *operator*() const { return cast<BasicBlock>(*I); } |
3609 | const BasicBlock *operator->() const { return operator*(); } |
3610 | }; |
3611 | |
3612 | static IndirectBrInst *Create(Value *Address, unsigned NumDests, |
3613 | Instruction *InsertBefore = nullptr) { |
3614 | return new IndirectBrInst(Address, NumDests, InsertBefore); |
3615 | } |
3616 | |
3617 | static IndirectBrInst *Create(Value *Address, unsigned NumDests, |
3618 | BasicBlock *InsertAtEnd) { |
3619 | return new IndirectBrInst(Address, NumDests, InsertAtEnd); |
3620 | } |
3621 | |
3622 | /// Provide fast operand accessors. |
3623 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
3624 | |
3625 | // Accessor Methods for IndirectBrInst instruction. |
3626 | Value *getAddress() { return getOperand(0); } |
3627 | const Value *getAddress() const { return getOperand(0); } |
3628 | void setAddress(Value *V) { setOperand(0, V); } |
3629 | |
3630 | /// return the number of possible destinations in this |
3631 | /// indirectbr instruction. |
3632 | unsigned getNumDestinations() const { return getNumOperands()-1; } |
3633 | |
3634 | /// Return the specified destination. |
3635 | BasicBlock *getDestination(unsigned i) { return getSuccessor(i); } |
3636 | const BasicBlock *getDestination(unsigned i) const { return getSuccessor(i); } |
3637 | |
3638 | /// Add a destination. |
3639 | /// |
3640 | void addDestination(BasicBlock *Dest); |
3641 | |
3642 | /// This method removes the specified successor from the |
3643 | /// indirectbr instruction. |
3644 | void removeDestination(unsigned i); |
3645 | |
3646 | unsigned getNumSuccessors() const { return getNumOperands()-1; } |
3647 | BasicBlock *getSuccessor(unsigned i) const { |
3648 | return cast<BasicBlock>(getOperand(i+1)); |
3649 | } |
3650 | void setSuccessor(unsigned i, BasicBlock *NewSucc) { |
3651 | setOperand(i + 1, NewSucc); |
3652 | } |
3653 | |
3654 | iterator_range<succ_op_iterator> successors() { |
3655 | return make_range(succ_op_iterator(std::next(value_op_begin())), |
3656 | succ_op_iterator(value_op_end())); |
3657 | } |
3658 | |
3659 | iterator_range<const_succ_op_iterator> successors() const { |
3660 | return make_range(const_succ_op_iterator(std::next(value_op_begin())), |
3661 | const_succ_op_iterator(value_op_end())); |
3662 | } |
3663 | |
3664 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
3665 | static bool classof(const Instruction *I) { |
3666 | return I->getOpcode() == Instruction::IndirectBr; |
3667 | } |
3668 | static bool classof(const Value *V) { |
3669 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
3670 | } |
3671 | }; |
3672 | |
3673 | template <> |
3674 | struct OperandTraits<IndirectBrInst> : public HungoffOperandTraits<1> { |
3675 | }; |
3676 | |
3677 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(IndirectBrInst, Value)IndirectBrInst::op_iterator IndirectBrInst::op_begin() { return OperandTraits<IndirectBrInst>::op_begin(this); } IndirectBrInst ::const_op_iterator IndirectBrInst::op_begin() const { return OperandTraits<IndirectBrInst>::op_begin(const_cast< IndirectBrInst*>(this)); } IndirectBrInst::op_iterator IndirectBrInst ::op_end() { return OperandTraits<IndirectBrInst>::op_end (this); } IndirectBrInst::const_op_iterator IndirectBrInst::op_end () const { return OperandTraits<IndirectBrInst>::op_end (const_cast<IndirectBrInst*>(this)); } Value *IndirectBrInst ::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<IndirectBrInst>::operands(this) && "getOperand() out of range!") ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<IndirectBrInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 3677, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<IndirectBrInst>::op_begin(const_cast< IndirectBrInst*>(this))[i_nocapture].get()); } void IndirectBrInst ::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (( i_nocapture < OperandTraits<IndirectBrInst>::operands (this) && "setOperand() out of range!") ? static_cast <void> (0) : __assert_fail ("i_nocapture < OperandTraits<IndirectBrInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 3677, __PRETTY_FUNCTION__)); OperandTraits<IndirectBrInst >::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned IndirectBrInst::getNumOperands() const { return OperandTraits <IndirectBrInst>::operands(this); } template <int Idx_nocapture > Use &IndirectBrInst::Op() { return this->OpFrom< Idx_nocapture>(this); } template <int Idx_nocapture> const Use &IndirectBrInst::Op() const { return this-> OpFrom<Idx_nocapture>(this); } |
3678 | |
3679 | //===----------------------------------------------------------------------===// |
3680 | // InvokeInst Class |
3681 | //===----------------------------------------------------------------------===// |
3682 | |
3683 | /// Invoke instruction. The SubclassData field is used to hold the |
3684 | /// calling convention of the call. |
3685 | /// |
3686 | class InvokeInst : public CallBase { |
3687 | /// The number of operands for this call beyond the called function, |
3688 | /// arguments, and operand bundles. |
3689 | static constexpr int NumExtraOperands = 2; |
3690 | |
3691 | /// The index from the end of the operand array to the normal destination. |
3692 | static constexpr int NormalDestOpEndIdx = -3; |
3693 | |
3694 | /// The index from the end of the operand array to the unwind destination. |
3695 | static constexpr int UnwindDestOpEndIdx = -2; |
3696 | |
3697 | InvokeInst(const InvokeInst &BI); |
3698 | |
3699 | /// Construct an InvokeInst given a range of arguments. |
3700 | /// |
3701 | /// Construct an InvokeInst from a range of arguments |
3702 | inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
3703 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3704 | ArrayRef<OperandBundleDef> Bundles, int NumOperands, |
3705 | const Twine &NameStr, Instruction *InsertBefore); |
3706 | |
3707 | inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
3708 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3709 | ArrayRef<OperandBundleDef> Bundles, int NumOperands, |
3710 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
3711 | |
3712 | void init(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
3713 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3714 | ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr); |
3715 | |
3716 | /// Compute the number of operands to allocate. |
3717 | static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) { |
3718 | // We need one operand for the called function, plus our extra operands and |
3719 | // the input operand counts provided. |
3720 | return 1 + NumExtraOperands + NumArgs + NumBundleInputs; |
3721 | } |
3722 | |
3723 | protected: |
3724 | // Note: Instruction needs to be a friend here to call cloneImpl. |
3725 | friend class Instruction; |
3726 | |
3727 | InvokeInst *cloneImpl() const; |
3728 | |
3729 | public: |
3730 | static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
3731 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3732 | const Twine &NameStr, |
3733 | Instruction *InsertBefore = nullptr) { |
3734 | int NumOperands = ComputeNumOperands(Args.size()); |
3735 | return new (NumOperands) |
3736 | InvokeInst(Ty, Func, IfNormal, IfException, Args, None, NumOperands, |
3737 | NameStr, InsertBefore); |
3738 | } |
3739 | |
3740 | static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
3741 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3742 | ArrayRef<OperandBundleDef> Bundles = None, |
3743 | const Twine &NameStr = "", |
3744 | Instruction *InsertBefore = nullptr) { |
3745 | int NumOperands = |
3746 | ComputeNumOperands(Args.size(), CountBundleInputs(Bundles)); |
3747 | unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo); |
3748 | |
3749 | return new (NumOperands, DescriptorBytes) |
3750 | InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, NumOperands, |
3751 | NameStr, InsertBefore); |
3752 | } |
3753 | |
3754 | static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
3755 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3756 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
3757 | int NumOperands = ComputeNumOperands(Args.size()); |
3758 | return new (NumOperands) |
3759 | InvokeInst(Ty, Func, IfNormal, IfException, Args, None, NumOperands, |
3760 | NameStr, InsertAtEnd); |
3761 | } |
3762 | |
3763 | static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
3764 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3765 | ArrayRef<OperandBundleDef> Bundles, |
3766 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
3767 | int NumOperands = |
3768 | ComputeNumOperands(Args.size(), CountBundleInputs(Bundles)); |
3769 | unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo); |
3770 | |
3771 | return new (NumOperands, DescriptorBytes) |
3772 | InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, NumOperands, |
3773 | NameStr, InsertAtEnd); |
3774 | } |
3775 | |
3776 | static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal, |
3777 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3778 | const Twine &NameStr, |
3779 | Instruction *InsertBefore = nullptr) { |
3780 | return Create(Func.getFunctionType(), Func.getCallee(), IfNormal, |
3781 | IfException, Args, None, NameStr, InsertBefore); |
3782 | } |
3783 | |
3784 | static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal, |
3785 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3786 | ArrayRef<OperandBundleDef> Bundles = None, |
3787 | const Twine &NameStr = "", |
3788 | Instruction *InsertBefore = nullptr) { |
3789 | return Create(Func.getFunctionType(), Func.getCallee(), IfNormal, |
3790 | IfException, Args, Bundles, NameStr, InsertBefore); |
3791 | } |
3792 | |
3793 | static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal, |
3794 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3795 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
3796 | return Create(Func.getFunctionType(), Func.getCallee(), IfNormal, |
3797 | IfException, Args, NameStr, InsertAtEnd); |
3798 | } |
3799 | |
3800 | static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal, |
3801 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3802 | ArrayRef<OperandBundleDef> Bundles, |
3803 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
3804 | return Create(Func.getFunctionType(), Func.getCallee(), IfNormal, |
3805 | IfException, Args, Bundles, NameStr, InsertAtEnd); |
3806 | } |
3807 | |
3808 | /// Create a clone of \p II with a different set of operand bundles and |
3809 | /// insert it before \p InsertPt. |
3810 | /// |
3811 | /// The returned invoke instruction is identical to \p II in every way except |
3812 | /// that the operand bundles for the new instruction are set to the operand |
3813 | /// bundles in \p Bundles. |
3814 | static InvokeInst *Create(InvokeInst *II, ArrayRef<OperandBundleDef> Bundles, |
3815 | Instruction *InsertPt = nullptr); |
3816 | |
3817 | // get*Dest - Return the destination basic blocks... |
3818 | BasicBlock *getNormalDest() const { |
3819 | return cast<BasicBlock>(Op<NormalDestOpEndIdx>()); |
3820 | } |
3821 | BasicBlock *getUnwindDest() const { |
3822 | return cast<BasicBlock>(Op<UnwindDestOpEndIdx>()); |
3823 | } |
3824 | void setNormalDest(BasicBlock *B) { |
3825 | Op<NormalDestOpEndIdx>() = reinterpret_cast<Value *>(B); |
3826 | } |
3827 | void setUnwindDest(BasicBlock *B) { |
3828 | Op<UnwindDestOpEndIdx>() = reinterpret_cast<Value *>(B); |
3829 | } |
3830 | |
3831 | /// Get the landingpad instruction from the landing pad |
3832 | /// block (the unwind destination). |
3833 | LandingPadInst *getLandingPadInst() const; |
3834 | |
3835 | BasicBlock *getSuccessor(unsigned i) const { |
3836 | assert(i < 2 && "Successor # out of range for invoke!")((i < 2 && "Successor # out of range for invoke!") ? static_cast<void> (0) : __assert_fail ("i < 2 && \"Successor # out of range for invoke!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 3836, __PRETTY_FUNCTION__)); |
3837 | return i == 0 ? getNormalDest() : getUnwindDest(); |
3838 | } |
3839 | |
3840 | void setSuccessor(unsigned i, BasicBlock *NewSucc) { |
3841 | assert(i < 2 && "Successor # out of range for invoke!")((i < 2 && "Successor # out of range for invoke!") ? static_cast<void> (0) : __assert_fail ("i < 2 && \"Successor # out of range for invoke!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 3841, __PRETTY_FUNCTION__)); |
3842 | if (i == 0) |
3843 | setNormalDest(NewSucc); |
3844 | else |
3845 | setUnwindDest(NewSucc); |
3846 | } |
3847 | |
3848 | unsigned getNumSuccessors() const { return 2; } |
3849 | |
3850 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
3851 | static bool classof(const Instruction *I) { |
3852 | return (I->getOpcode() == Instruction::Invoke); |
3853 | } |
3854 | static bool classof(const Value *V) { |
3855 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
3856 | } |
3857 | |
3858 | private: |
3859 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
3860 | // method so that subclasses cannot accidentally use it. |
3861 | template <typename Bitfield> |
3862 | void setSubclassData(typename Bitfield::Type Value) { |
3863 | Instruction::setSubclassData<Bitfield>(Value); |
3864 | } |
3865 | }; |
3866 | |
3867 | InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
3868 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3869 | ArrayRef<OperandBundleDef> Bundles, int NumOperands, |
3870 | const Twine &NameStr, Instruction *InsertBefore) |
3871 | : CallBase(Ty->getReturnType(), Instruction::Invoke, |
3872 | OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands, |
3873 | InsertBefore) { |
3874 | init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr); |
3875 | } |
3876 | |
3877 | InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
3878 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3879 | ArrayRef<OperandBundleDef> Bundles, int NumOperands, |
3880 | const Twine &NameStr, BasicBlock *InsertAtEnd) |
3881 | : CallBase(Ty->getReturnType(), Instruction::Invoke, |
3882 | OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands, |
3883 | InsertAtEnd) { |
3884 | init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr); |
3885 | } |
3886 | |
3887 | //===----------------------------------------------------------------------===// |
3888 | // CallBrInst Class |
3889 | //===----------------------------------------------------------------------===// |
3890 | |
3891 | /// CallBr instruction, tracking function calls that may not return control but |
3892 | /// instead transfer it to a third location. The SubclassData field is used to |
3893 | /// hold the calling convention of the call. |
3894 | /// |
3895 | class CallBrInst : public CallBase { |
3896 | |
3897 | unsigned NumIndirectDests; |
3898 | |
3899 | CallBrInst(const CallBrInst &BI); |
3900 | |
3901 | /// Construct a CallBrInst given a range of arguments. |
3902 | /// |
3903 | /// Construct a CallBrInst from a range of arguments |
3904 | inline CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, |
3905 | ArrayRef<BasicBlock *> IndirectDests, |
3906 | ArrayRef<Value *> Args, |
3907 | ArrayRef<OperandBundleDef> Bundles, int NumOperands, |
3908 | const Twine &NameStr, Instruction *InsertBefore); |
3909 | |
3910 | inline CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, |
3911 | ArrayRef<BasicBlock *> IndirectDests, |
3912 | ArrayRef<Value *> Args, |
3913 | ArrayRef<OperandBundleDef> Bundles, int NumOperands, |
3914 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
3915 | |
3916 | void init(FunctionType *FTy, Value *Func, BasicBlock *DefaultDest, |
3917 | ArrayRef<BasicBlock *> IndirectDests, ArrayRef<Value *> Args, |
3918 | ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr); |
3919 | |
3920 | /// Should the Indirect Destinations change, scan + update the Arg list. |
3921 | void updateArgBlockAddresses(unsigned i, BasicBlock *B); |
3922 | |
3923 | /// Compute the number of operands to allocate. |
3924 | static int ComputeNumOperands(int NumArgs, int NumIndirectDests, |
3925 | int NumBundleInputs = 0) { |
3926 | // We need one operand for the called function, plus our extra operands and |
3927 | // the input operand counts provided. |
3928 | return 2 + NumIndirectDests + NumArgs + NumBundleInputs; |
3929 | } |
3930 | |
3931 | protected: |
3932 | // Note: Instruction needs to be a friend here to call cloneImpl. |
3933 | friend class Instruction; |
3934 | |
3935 | CallBrInst *cloneImpl() const; |
3936 | |
3937 | public: |
3938 | static CallBrInst *Create(FunctionType *Ty, Value *Func, |
3939 | BasicBlock *DefaultDest, |
3940 | ArrayRef<BasicBlock *> IndirectDests, |
3941 | ArrayRef<Value *> Args, const Twine &NameStr, |
3942 | Instruction *InsertBefore = nullptr) { |
3943 | int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size()); |
3944 | return new (NumOperands) |
3945 | CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, None, |
3946 | NumOperands, NameStr, InsertBefore); |
3947 | } |
3948 | |
3949 | static CallBrInst *Create(FunctionType *Ty, Value *Func, |
3950 | BasicBlock *DefaultDest, |
3951 | ArrayRef<BasicBlock *> IndirectDests, |
3952 | ArrayRef<Value *> Args, |
3953 | ArrayRef<OperandBundleDef> Bundles = None, |
3954 | const Twine &NameStr = "", |
3955 | Instruction *InsertBefore = nullptr) { |
3956 | int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size(), |
3957 | CountBundleInputs(Bundles)); |
3958 | unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo); |
3959 | |
3960 | return new (NumOperands, DescriptorBytes) |
3961 | CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, |
3962 | NumOperands, NameStr, InsertBefore); |
3963 | } |
3964 | |
3965 | static CallBrInst *Create(FunctionType *Ty, Value *Func, |
3966 | BasicBlock *DefaultDest, |
3967 | ArrayRef<BasicBlock *> IndirectDests, |
3968 | ArrayRef<Value *> Args, const Twine &NameStr, |
3969 | BasicBlock *InsertAtEnd) { |
3970 | int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size()); |
3971 | return new (NumOperands) |
3972 | CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, None, |
3973 | NumOperands, NameStr, InsertAtEnd); |
3974 | } |
3975 | |
3976 | static CallBrInst *Create(FunctionType *Ty, Value *Func, |
3977 | BasicBlock *DefaultDest, |
3978 | ArrayRef<BasicBlock *> IndirectDests, |
3979 | ArrayRef<Value *> Args, |
3980 | ArrayRef<OperandBundleDef> Bundles, |
3981 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
3982 | int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size(), |
3983 | CountBundleInputs(Bundles)); |
3984 | unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo); |
3985 | |
3986 | return new (NumOperands, DescriptorBytes) |
3987 | CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, |
3988 | NumOperands, NameStr, InsertAtEnd); |
3989 | } |
3990 | |
3991 | static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest, |
3992 | ArrayRef<BasicBlock *> IndirectDests, |
3993 | ArrayRef<Value *> Args, const Twine &NameStr, |
3994 | Instruction *InsertBefore = nullptr) { |
3995 | return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest, |
3996 | IndirectDests, Args, NameStr, InsertBefore); |
3997 | } |
3998 | |
3999 | static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest, |
4000 | ArrayRef<BasicBlock *> IndirectDests, |
4001 | ArrayRef<Value *> Args, |
4002 | ArrayRef<OperandBundleDef> Bundles = None, |
4003 | const Twine &NameStr = "", |
4004 | Instruction *InsertBefore = nullptr) { |
4005 | return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest, |
4006 | IndirectDests, Args, Bundles, NameStr, InsertBefore); |
4007 | } |
4008 | |
4009 | static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest, |
4010 | ArrayRef<BasicBlock *> IndirectDests, |
4011 | ArrayRef<Value *> Args, const Twine &NameStr, |
4012 | BasicBlock *InsertAtEnd) { |
4013 | return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest, |
4014 | IndirectDests, Args, NameStr, InsertAtEnd); |
4015 | } |
4016 | |
4017 | static CallBrInst *Create(FunctionCallee Func, |
4018 | BasicBlock *DefaultDest, |
4019 | ArrayRef<BasicBlock *> IndirectDests, |
4020 | ArrayRef<Value *> Args, |
4021 | ArrayRef<OperandBundleDef> Bundles, |
4022 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
4023 | return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest, |
4024 | IndirectDests, Args, Bundles, NameStr, InsertAtEnd); |
4025 | } |
4026 | |
4027 | /// Create a clone of \p CBI with a different set of operand bundles and |
4028 | /// insert it before \p InsertPt. |
4029 | /// |
4030 | /// The returned callbr instruction is identical to \p CBI in every way |
4031 | /// except that the operand bundles for the new instruction are set to the |
4032 | /// operand bundles in \p Bundles. |
4033 | static CallBrInst *Create(CallBrInst *CBI, |
4034 | ArrayRef<OperandBundleDef> Bundles, |
4035 | Instruction *InsertPt = nullptr); |
4036 | |
4037 | /// Return the number of callbr indirect dest labels. |
4038 | /// |
4039 | unsigned getNumIndirectDests() const { return NumIndirectDests; } |
4040 | |
4041 | /// getIndirectDestLabel - Return the i-th indirect dest label. |
4042 | /// |
4043 | Value *getIndirectDestLabel(unsigned i) const { |
4044 | assert(i < getNumIndirectDests() && "Out of bounds!")((i < getNumIndirectDests() && "Out of bounds!") ? static_cast<void> (0) : __assert_fail ("i < getNumIndirectDests() && \"Out of bounds!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 4044, __PRETTY_FUNCTION__)); |
4045 | return getOperand(i + getNumArgOperands() + getNumTotalBundleOperands() + |
4046 | 1); |
4047 | } |
4048 | |
4049 | Value *getIndirectDestLabelUse(unsigned i) const { |
4050 | assert(i < getNumIndirectDests() && "Out of bounds!")((i < getNumIndirectDests() && "Out of bounds!") ? static_cast<void> (0) : __assert_fail ("i < getNumIndirectDests() && \"Out of bounds!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 4050, __PRETTY_FUNCTION__)); |
4051 | return getOperandUse(i + getNumArgOperands() + getNumTotalBundleOperands() + |
4052 | 1); |
4053 | } |
4054 | |
4055 | // Return the destination basic blocks... |
4056 | BasicBlock *getDefaultDest() const { |
4057 | return cast<BasicBlock>(*(&Op<-1>() - getNumIndirectDests() - 1)); |
4058 | } |
4059 | BasicBlock *getIndirectDest(unsigned i) const { |
4060 | return cast_or_null<BasicBlock>(*(&Op<-1>() - getNumIndirectDests() + i)); |
4061 | } |
4062 | SmallVector<BasicBlock *, 16> getIndirectDests() const { |
4063 | SmallVector<BasicBlock *, 16> IndirectDests; |
4064 | for (unsigned i = 0, e = getNumIndirectDests(); i < e; ++i) |
4065 | IndirectDests.push_back(getIndirectDest(i)); |
4066 | return IndirectDests; |
4067 | } |
4068 | void setDefaultDest(BasicBlock *B) { |
4069 | *(&Op<-1>() - getNumIndirectDests() - 1) = reinterpret_cast<Value *>(B); |
4070 | } |
4071 | void setIndirectDest(unsigned i, BasicBlock *B) { |
4072 | updateArgBlockAddresses(i, B); |
4073 | *(&Op<-1>() - getNumIndirectDests() + i) = reinterpret_cast<Value *>(B); |
4074 | } |
4075 | |
4076 | BasicBlock *getSuccessor(unsigned i) const { |
4077 | assert(i < getNumSuccessors() + 1 &&((i < getNumSuccessors() + 1 && "Successor # out of range for callbr!" ) ? static_cast<void> (0) : __assert_fail ("i < getNumSuccessors() + 1 && \"Successor # out of range for callbr!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 4078, __PRETTY_FUNCTION__)) |
4078 | "Successor # out of range for callbr!")((i < getNumSuccessors() + 1 && "Successor # out of range for callbr!" ) ? static_cast<void> (0) : __assert_fail ("i < getNumSuccessors() + 1 && \"Successor # out of range for callbr!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 4078, __PRETTY_FUNCTION__)); |
4079 | return i == 0 ? getDefaultDest() : getIndirectDest(i - 1); |
4080 | } |
4081 | |
4082 | void setSuccessor(unsigned i, BasicBlock *NewSucc) { |
4083 | assert(i < getNumIndirectDests() + 1 &&((i < getNumIndirectDests() + 1 && "Successor # out of range for callbr!" ) ? static_cast<void> (0) : __assert_fail ("i < getNumIndirectDests() + 1 && \"Successor # out of range for callbr!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 4084, __PRETTY_FUNCTION__)) |
4084 | "Successor # out of range for callbr!")((i < getNumIndirectDests() + 1 && "Successor # out of range for callbr!" ) ? static_cast<void> (0) : __assert_fail ("i < getNumIndirectDests() + 1 && \"Successor # out of range for callbr!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 4084, __PRETTY_FUNCTION__)); |
4085 | return i == 0 ? setDefaultDest(NewSucc) : setIndirectDest(i - 1, NewSucc); |
4086 | } |
4087 | |
4088 | unsigned getNumSuccessors() const { return getNumIndirectDests() + 1; } |
4089 | |
4090 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
4091 | static bool classof(const Instruction *I) { |
4092 | return (I->getOpcode() == Instruction::CallBr); |
4093 | } |
4094 | static bool classof(const Value *V) { |
4095 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4096 | } |
4097 | |
4098 | private: |
4099 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
4100 | // method so that subclasses cannot accidentally use it. |
4101 | template <typename Bitfield> |
4102 | void setSubclassData(typename Bitfield::Type Value) { |
4103 | Instruction::setSubclassData<Bitfield>(Value); |
4104 | } |
4105 | }; |
4106 | |
4107 | CallBrInst::CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, |
4108 | ArrayRef<BasicBlock *> IndirectDests, |
4109 | ArrayRef<Value *> Args, |
4110 | ArrayRef<OperandBundleDef> Bundles, int NumOperands, |
4111 | const Twine &NameStr, Instruction *InsertBefore) |
4112 | : CallBase(Ty->getReturnType(), Instruction::CallBr, |
4113 | OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands, |
4114 | InsertBefore) { |
4115 | init(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, NameStr); |
4116 | } |
4117 | |
4118 | CallBrInst::CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, |
4119 | ArrayRef<BasicBlock *> IndirectDests, |
4120 | ArrayRef<Value *> Args, |
4121 | ArrayRef<OperandBundleDef> Bundles, int NumOperands, |
4122 | const Twine &NameStr, BasicBlock *InsertAtEnd) |
4123 | : CallBase(Ty->getReturnType(), Instruction::CallBr, |
4124 | OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands, |
4125 | InsertAtEnd) { |
4126 | init(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, NameStr); |
4127 | } |
4128 | |
4129 | //===----------------------------------------------------------------------===// |
4130 | // ResumeInst Class |
4131 | //===----------------------------------------------------------------------===// |
4132 | |
4133 | //===--------------------------------------------------------------------------- |
4134 | /// Resume the propagation of an exception. |
4135 | /// |
4136 | class ResumeInst : public Instruction { |
4137 | ResumeInst(const ResumeInst &RI); |
4138 | |
4139 | explicit ResumeInst(Value *Exn, Instruction *InsertBefore=nullptr); |
4140 | ResumeInst(Value *Exn, BasicBlock *InsertAtEnd); |
4141 | |
4142 | protected: |
4143 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4144 | friend class Instruction; |
4145 | |
4146 | ResumeInst *cloneImpl() const; |
4147 | |
4148 | public: |
4149 | static ResumeInst *Create(Value *Exn, Instruction *InsertBefore = nullptr) { |
4150 | return new(1) ResumeInst(Exn, InsertBefore); |
4151 | } |
4152 | |
4153 | static ResumeInst *Create(Value *Exn, BasicBlock *InsertAtEnd) { |
4154 | return new(1) ResumeInst(Exn, InsertAtEnd); |
4155 | } |
4156 | |
4157 | /// Provide fast operand accessors |
4158 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
4159 | |
4160 | /// Convenience accessor. |
4161 | Value *getValue() const { return Op<0>(); } |
4162 | |
4163 | unsigned getNumSuccessors() const { return 0; } |
4164 | |
4165 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
4166 | static bool classof(const Instruction *I) { |
4167 | return I->getOpcode() == Instruction::Resume; |
4168 | } |
4169 | static bool classof(const Value *V) { |
4170 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4171 | } |
4172 | |
4173 | private: |
4174 | BasicBlock *getSuccessor(unsigned idx) const { |
4175 | llvm_unreachable("ResumeInst has no successors!")::llvm::llvm_unreachable_internal("ResumeInst has no successors!" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 4175); |
4176 | } |
4177 | |
4178 | void setSuccessor(unsigned idx, BasicBlock *NewSucc) { |
4179 | llvm_unreachable("ResumeInst has no successors!")::llvm::llvm_unreachable_internal("ResumeInst has no successors!" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 4179); |
4180 | } |
4181 | }; |
4182 | |
4183 | template <> |
4184 | struct OperandTraits<ResumeInst> : |
4185 | public FixedNumOperandTraits<ResumeInst, 1> { |
4186 | }; |
4187 | |
4188 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ResumeInst, Value)ResumeInst::op_iterator ResumeInst::op_begin() { return OperandTraits <ResumeInst>::op_begin(this); } ResumeInst::const_op_iterator ResumeInst::op_begin() const { return OperandTraits<ResumeInst >::op_begin(const_cast<ResumeInst*>(this)); } ResumeInst ::op_iterator ResumeInst::op_end() { return OperandTraits< ResumeInst>::op_end(this); } ResumeInst::const_op_iterator ResumeInst::op_end() const { return OperandTraits<ResumeInst >::op_end(const_cast<ResumeInst*>(this)); } Value *ResumeInst ::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<ResumeInst>::operands(this) && "getOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ResumeInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 4188, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<ResumeInst>::op_begin(const_cast<ResumeInst *>(this))[i_nocapture].get()); } void ResumeInst::setOperand (unsigned i_nocapture, Value *Val_nocapture) { ((i_nocapture < OperandTraits<ResumeInst>::operands(this) && "setOperand() out of range!" ) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ResumeInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 4188, __PRETTY_FUNCTION__)); OperandTraits<ResumeInst> ::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned ResumeInst ::getNumOperands() const { return OperandTraits<ResumeInst >::operands(this); } template <int Idx_nocapture> Use &ResumeInst::Op() { return this->OpFrom<Idx_nocapture >(this); } template <int Idx_nocapture> const Use & ResumeInst::Op() const { return this->OpFrom<Idx_nocapture >(this); } |
4189 | |
4190 | //===----------------------------------------------------------------------===// |
4191 | // CatchSwitchInst Class |
4192 | //===----------------------------------------------------------------------===// |
4193 | class CatchSwitchInst : public Instruction { |
4194 | using UnwindDestField = BoolBitfieldElementT<0>; |
4195 | |
4196 | /// The number of operands actually allocated. NumOperands is |
4197 | /// the number actually in use. |
4198 | unsigned ReservedSpace; |
4199 | |
4200 | // Operand[0] = Outer scope |
4201 | // Operand[1] = Unwind block destination |
4202 | // Operand[n] = BasicBlock to go to on match |
4203 | CatchSwitchInst(const CatchSwitchInst &CSI); |
4204 | |
4205 | /// Create a new switch instruction, specifying a |
4206 | /// default destination. The number of additional handlers can be specified |
4207 | /// here to make memory allocation more efficient. |
4208 | /// This constructor can also autoinsert before another instruction. |
4209 | CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest, |
4210 | unsigned NumHandlers, const Twine &NameStr, |
4211 | Instruction *InsertBefore); |
4212 | |
4213 | /// Create a new switch instruction, specifying a |
4214 | /// default destination. The number of additional handlers can be specified |
4215 | /// here to make memory allocation more efficient. |
4216 | /// This constructor also autoinserts at the end of the specified BasicBlock. |
4217 | CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest, |
4218 | unsigned NumHandlers, const Twine &NameStr, |
4219 | BasicBlock *InsertAtEnd); |
4220 | |
4221 | // allocate space for exactly zero operands |
4222 | void *operator new(size_t s) { return User::operator new(s); } |
4223 | |
4224 | void init(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumReserved); |
4225 | void growOperands(unsigned Size); |
4226 | |
4227 | protected: |
4228 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4229 | friend class Instruction; |
4230 | |
4231 | CatchSwitchInst *cloneImpl() const; |
4232 | |
4233 | public: |
4234 | static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest, |
4235 | unsigned NumHandlers, |
4236 | const Twine &NameStr = "", |
4237 | Instruction *InsertBefore = nullptr) { |
4238 | return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr, |
4239 | InsertBefore); |
4240 | } |
4241 | |
4242 | static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest, |
4243 | unsigned NumHandlers, const Twine &NameStr, |
4244 | BasicBlock *InsertAtEnd) { |
4245 | return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr, |
4246 | InsertAtEnd); |
4247 | } |
4248 | |
4249 | /// Provide fast operand accessors |
4250 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
4251 | |
4252 | // Accessor Methods for CatchSwitch stmt |
4253 | Value *getParentPad() const { return getOperand(0); } |
4254 | void setParentPad(Value *ParentPad) { setOperand(0, ParentPad); } |
4255 | |
4256 | // Accessor Methods for CatchSwitch stmt |
4257 | bool hasUnwindDest() const { return getSubclassData<UnwindDestField>(); } |
4258 | bool unwindsToCaller() const { return !hasUnwindDest(); } |
4259 | BasicBlock *getUnwindDest() const { |
4260 | if (hasUnwindDest()) |
4261 | return cast<BasicBlock>(getOperand(1)); |
4262 | return nullptr; |
4263 | } |
4264 | void setUnwindDest(BasicBlock *UnwindDest) { |
4265 | assert(UnwindDest)((UnwindDest) ? static_cast<void> (0) : __assert_fail ( "UnwindDest", "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 4265, __PRETTY_FUNCTION__)); |
4266 | assert(hasUnwindDest())((hasUnwindDest()) ? static_cast<void> (0) : __assert_fail ("hasUnwindDest()", "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 4266, __PRETTY_FUNCTION__)); |
4267 | setOperand(1, UnwindDest); |
4268 | } |
4269 | |
4270 | /// return the number of 'handlers' in this catchswitch |
4271 | /// instruction, except the default handler |
4272 | unsigned getNumHandlers() const { |
4273 | if (hasUnwindDest()) |
4274 | return getNumOperands() - 2; |
4275 | return getNumOperands() - 1; |
4276 | } |
4277 | |
4278 | private: |
4279 | static BasicBlock *handler_helper(Value *V) { return cast<BasicBlock>(V); } |
4280 | static const BasicBlock *handler_helper(const Value *V) { |
4281 | return cast<BasicBlock>(V); |
4282 | } |
4283 | |
4284 | public: |
4285 | using DerefFnTy = BasicBlock *(*)(Value *); |
4286 | using handler_iterator = mapped_iterator<op_iterator, DerefFnTy>; |
4287 | using handler_range = iterator_range<handler_iterator>; |
4288 | using ConstDerefFnTy = const BasicBlock *(*)(const Value *); |
4289 | using const_handler_iterator = |
4290 | mapped_iterator<const_op_iterator, ConstDerefFnTy>; |
4291 | using const_handler_range = iterator_range<const_handler_iterator>; |
4292 | |
4293 | /// Returns an iterator that points to the first handler in CatchSwitchInst. |
4294 | handler_iterator handler_begin() { |
4295 | op_iterator It = op_begin() + 1; |
4296 | if (hasUnwindDest()) |
4297 | ++It; |
4298 | return handler_iterator(It, DerefFnTy(handler_helper)); |
4299 | } |
4300 | |
4301 | /// Returns an iterator that points to the first handler in the |
4302 | /// CatchSwitchInst. |
4303 | const_handler_iterator handler_begin() const { |
4304 | const_op_iterator It = op_begin() + 1; |
4305 | if (hasUnwindDest()) |
4306 | ++It; |
4307 | return const_handler_iterator(It, ConstDerefFnTy(handler_helper)); |
4308 | } |
4309 | |
4310 | /// Returns a read-only iterator that points one past the last |
4311 | /// handler in the CatchSwitchInst. |
4312 | handler_iterator handler_end() { |
4313 | return handler_iterator(op_end(), DerefFnTy(handler_helper)); |
4314 | } |
4315 | |
4316 | /// Returns an iterator that points one past the last handler in the |
4317 | /// CatchSwitchInst. |
4318 | const_handler_iterator handler_end() const { |
4319 | return const_handler_iterator(op_end(), ConstDerefFnTy(handler_helper)); |
4320 | } |
4321 | |
4322 | /// iteration adapter for range-for loops. |
4323 | handler_range handlers() { |
4324 | return make_range(handler_begin(), handler_end()); |
4325 | } |
4326 | |
4327 | /// iteration adapter for range-for loops. |
4328 | const_handler_range handlers() const { |
4329 | return make_range(handler_begin(), handler_end()); |
4330 | } |
4331 | |
4332 | /// Add an entry to the switch instruction... |
4333 | /// Note: |
4334 | /// This action invalidates handler_end(). Old handler_end() iterator will |
4335 | /// point to the added handler. |
4336 | void addHandler(BasicBlock *Dest); |
4337 | |
4338 | void removeHandler(handler_iterator HI); |
4339 | |
4340 | unsigned getNumSuccessors() const { return getNumOperands() - 1; } |
4341 | BasicBlock *getSuccessor(unsigned Idx) const { |
4342 | assert(Idx < getNumSuccessors() &&((Idx < getNumSuccessors() && "Successor # out of range for catchswitch!" ) ? static_cast<void> (0) : __assert_fail ("Idx < getNumSuccessors() && \"Successor # out of range for catchswitch!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 4343, __PRETTY_FUNCTION__)) |
4343 | "Successor # out of range for catchswitch!")((Idx < getNumSuccessors() && "Successor # out of range for catchswitch!" ) ? static_cast<void> (0) : __assert_fail ("Idx < getNumSuccessors() && \"Successor # out of range for catchswitch!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 4343, __PRETTY_FUNCTION__)); |
4344 | return cast<BasicBlock>(getOperand(Idx + 1)); |
4345 | } |
4346 | void setSuccessor(unsigned Idx, BasicBlock *NewSucc) { |
4347 | assert(Idx < getNumSuccessors() &&((Idx < getNumSuccessors() && "Successor # out of range for catchswitch!" ) ? static_cast<void> (0) : __assert_fail ("Idx < getNumSuccessors() && \"Successor # out of range for catchswitch!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 4348, __PRETTY_FUNCTION__)) |
4348 | "Successor # out of range for catchswitch!")((Idx < getNumSuccessors() && "Successor # out of range for catchswitch!" ) ? static_cast<void> (0) : __assert_fail ("Idx < getNumSuccessors() && \"Successor # out of range for catchswitch!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 4348, __PRETTY_FUNCTION__)); |
4349 | setOperand(Idx + 1, NewSucc); |
4350 | } |
4351 | |
4352 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
4353 | static bool classof(const Instruction *I) { |
4354 | return I->getOpcode() == Instruction::CatchSwitch; |
4355 | } |
4356 | static bool classof(const Value *V) { |
4357 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4358 | } |
4359 | }; |
4360 | |
4361 | template <> |
4362 | struct OperandTraits<CatchSwitchInst> : public HungoffOperandTraits<2> {}; |
4363 | |
4364 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchSwitchInst, Value)CatchSwitchInst::op_iterator CatchSwitchInst::op_begin() { return OperandTraits<CatchSwitchInst>::op_begin(this); } CatchSwitchInst ::const_op_iterator CatchSwitchInst::op_begin() const { return OperandTraits<CatchSwitchInst>::op_begin(const_cast< CatchSwitchInst*>(this)); } CatchSwitchInst::op_iterator CatchSwitchInst ::op_end() { return OperandTraits<CatchSwitchInst>::op_end (this); } CatchSwitchInst::const_op_iterator CatchSwitchInst:: op_end() const { return OperandTraits<CatchSwitchInst>:: op_end(const_cast<CatchSwitchInst*>(this)); } Value *CatchSwitchInst ::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<CatchSwitchInst>::operands(this) && "getOperand() out of range!") ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<CatchSwitchInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 4364, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<CatchSwitchInst>::op_begin(const_cast< CatchSwitchInst*>(this))[i_nocapture].get()); } void CatchSwitchInst ::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (( i_nocapture < OperandTraits<CatchSwitchInst>::operands (this) && "setOperand() out of range!") ? static_cast <void> (0) : __assert_fail ("i_nocapture < OperandTraits<CatchSwitchInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 4364, __PRETTY_FUNCTION__)); OperandTraits<CatchSwitchInst >::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned CatchSwitchInst::getNumOperands() const { return OperandTraits <CatchSwitchInst>::operands(this); } template <int Idx_nocapture > Use &CatchSwitchInst::Op() { return this->OpFrom< Idx_nocapture>(this); } template <int Idx_nocapture> const Use &CatchSwitchInst::Op() const { return this-> OpFrom<Idx_nocapture>(this); } |
4365 | |
4366 | //===----------------------------------------------------------------------===// |
4367 | // CleanupPadInst Class |
4368 | //===----------------------------------------------------------------------===// |
4369 | class CleanupPadInst : public FuncletPadInst { |
4370 | private: |
4371 | explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args, |
4372 | unsigned Values, const Twine &NameStr, |
4373 | Instruction *InsertBefore) |
4374 | : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values, |
4375 | NameStr, InsertBefore) {} |
4376 | explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args, |
4377 | unsigned Values, const Twine &NameStr, |
4378 | BasicBlock *InsertAtEnd) |
4379 | : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values, |
4380 | NameStr, InsertAtEnd) {} |
4381 | |
4382 | public: |
4383 | static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args = None, |
4384 | const Twine &NameStr = "", |
4385 | Instruction *InsertBefore = nullptr) { |
4386 | unsigned Values = 1 + Args.size(); |
4387 | return new (Values) |
4388 | CleanupPadInst(ParentPad, Args, Values, NameStr, InsertBefore); |
4389 | } |
4390 | |
4391 | static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args, |
4392 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
4393 | unsigned Values = 1 + Args.size(); |
4394 | return new (Values) |
4395 | CleanupPadInst(ParentPad, Args, Values, NameStr, InsertAtEnd); |
4396 | } |
4397 | |
4398 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
4399 | static bool classof(const Instruction *I) { |
4400 | return I->getOpcode() == Instruction::CleanupPad; |
4401 | } |
4402 | static bool classof(const Value *V) { |
4403 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4404 | } |
4405 | }; |
4406 | |
4407 | //===----------------------------------------------------------------------===// |
4408 | // CatchPadInst Class |
4409 | //===----------------------------------------------------------------------===// |
4410 | class CatchPadInst : public FuncletPadInst { |
4411 | private: |
4412 | explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args, |
4413 | unsigned Values, const Twine &NameStr, |
4414 | Instruction *InsertBefore) |
4415 | : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values, |
4416 | NameStr, InsertBefore) {} |
4417 | explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args, |
4418 | unsigned Values, const Twine &NameStr, |
4419 | BasicBlock *InsertAtEnd) |
4420 | : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values, |
4421 | NameStr, InsertAtEnd) {} |
4422 | |
4423 | public: |
4424 | static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args, |
4425 | const Twine &NameStr = "", |
4426 | Instruction *InsertBefore = nullptr) { |
4427 | unsigned Values = 1 + Args.size(); |
4428 | return new (Values) |
4429 | CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertBefore); |
4430 | } |
4431 | |
4432 | static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args, |
4433 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
4434 | unsigned Values = 1 + Args.size(); |
4435 | return new (Values) |
4436 | CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertAtEnd); |
4437 | } |
4438 | |
4439 | /// Convenience accessors |
4440 | CatchSwitchInst *getCatchSwitch() const { |
4441 | return cast<CatchSwitchInst>(Op<-1>()); |
4442 | } |
4443 | void setCatchSwitch(Value *CatchSwitch) { |
4444 | assert(CatchSwitch)((CatchSwitch) ? static_cast<void> (0) : __assert_fail ( "CatchSwitch", "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 4444, __PRETTY_FUNCTION__)); |
4445 | Op<-1>() = CatchSwitch; |
4446 | } |
4447 | |
4448 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
4449 | static bool classof(const Instruction *I) { |
4450 | return I->getOpcode() == Instruction::CatchPad; |
4451 | } |
4452 | static bool classof(const Value *V) { |
4453 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4454 | } |
4455 | }; |
4456 | |
4457 | //===----------------------------------------------------------------------===// |
4458 | // CatchReturnInst Class |
4459 | //===----------------------------------------------------------------------===// |
4460 | |
4461 | class CatchReturnInst : public Instruction { |
4462 | CatchReturnInst(const CatchReturnInst &RI); |
4463 | CatchReturnInst(Value *CatchPad, BasicBlock *BB, Instruction *InsertBefore); |
4464 | CatchReturnInst(Value *CatchPad, BasicBlock *BB, BasicBlock *InsertAtEnd); |
4465 | |
4466 | void init(Value *CatchPad, BasicBlock *BB); |
4467 | |
4468 | protected: |
4469 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4470 | friend class Instruction; |
4471 | |
4472 | CatchReturnInst *cloneImpl() const; |
4473 | |
4474 | public: |
4475 | static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB, |
4476 | Instruction *InsertBefore = nullptr) { |
4477 | assert(CatchPad)((CatchPad) ? static_cast<void> (0) : __assert_fail ("CatchPad" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 4477, __PRETTY_FUNCTION__)); |
4478 | assert(BB)((BB) ? static_cast<void> (0) : __assert_fail ("BB", "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 4478, __PRETTY_FUNCTION__)); |
4479 | return new (2) CatchReturnInst(CatchPad, BB, InsertBefore); |
4480 | } |
4481 | |
4482 | static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB, |
4483 | BasicBlock *InsertAtEnd) { |
4484 | assert(CatchPad)((CatchPad) ? static_cast<void> (0) : __assert_fail ("CatchPad" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 4484, __PRETTY_FUNCTION__)); |
4485 | assert(BB)((BB) ? static_cast<void> (0) : __assert_fail ("BB", "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 4485, __PRETTY_FUNCTION__)); |
4486 | return new (2) CatchReturnInst(CatchPad, BB, InsertAtEnd); |
4487 | } |
4488 | |
4489 | /// Provide fast operand accessors |
4490 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
4491 | |
4492 | /// Convenience accessors. |
4493 | CatchPadInst *getCatchPad() const { return cast<CatchPadInst>(Op<0>()); } |
4494 | void setCatchPad(CatchPadInst *CatchPad) { |
4495 | assert(CatchPad)((CatchPad) ? static_cast<void> (0) : __assert_fail ("CatchPad" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 4495, __PRETTY_FUNCTION__)); |
4496 | Op<0>() = CatchPad; |
4497 | } |
4498 | |
4499 | BasicBlock *getSuccessor() const { return cast<BasicBlock>(Op<1>()); } |
4500 | void setSuccessor(BasicBlock *NewSucc) { |
4501 | assert(NewSucc)((NewSucc) ? static_cast<void> (0) : __assert_fail ("NewSucc" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 4501, __PRETTY_FUNCTION__)); |
4502 | Op<1>() = NewSucc; |
4503 | } |
4504 | unsigned getNumSuccessors() const { return 1; } |
4505 | |
4506 | /// Get the parentPad of this catchret's catchpad's catchswitch. |
4507 | /// The successor block is implicitly a member of this funclet. |
4508 | Value *getCatchSwitchParentPad() const { |
4509 | return getCatchPad()->getCatchSwitch()->getParentPad(); |
4510 | } |
4511 | |
4512 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
4513 | static bool classof(const Instruction *I) { |
4514 | return (I->getOpcode() == Instruction::CatchRet); |
4515 | } |
4516 | static bool classof(const Value *V) { |
4517 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4518 | } |
4519 | |
4520 | private: |
4521 | BasicBlock *getSuccessor(unsigned Idx) const { |
4522 | assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!")((Idx < getNumSuccessors() && "Successor # out of range for catchret!" ) ? static_cast<void> (0) : __assert_fail ("Idx < getNumSuccessors() && \"Successor # out of range for catchret!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 4522, __PRETTY_FUNCTION__)); |
4523 | return getSuccessor(); |
4524 | } |
4525 | |
4526 | void setSuccessor(unsigned Idx, BasicBlock *B) { |
4527 | assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!")((Idx < getNumSuccessors() && "Successor # out of range for catchret!" ) ? static_cast<void> (0) : __assert_fail ("Idx < getNumSuccessors() && \"Successor # out of range for catchret!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 4527, __PRETTY_FUNCTION__)); |
4528 | setSuccessor(B); |
4529 | } |
4530 | }; |
4531 | |
4532 | template <> |
4533 | struct OperandTraits<CatchReturnInst> |
4534 | : public FixedNumOperandTraits<CatchReturnInst, 2> {}; |
4535 | |
4536 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CatchReturnInst, Value)CatchReturnInst::op_iterator CatchReturnInst::op_begin() { return OperandTraits<CatchReturnInst>::op_begin(this); } CatchReturnInst ::const_op_iterator CatchReturnInst::op_begin() const { return OperandTraits<CatchReturnInst>::op_begin(const_cast< CatchReturnInst*>(this)); } CatchReturnInst::op_iterator CatchReturnInst ::op_end() { return OperandTraits<CatchReturnInst>::op_end (this); } CatchReturnInst::const_op_iterator CatchReturnInst:: op_end() const { return OperandTraits<CatchReturnInst>:: op_end(const_cast<CatchReturnInst*>(this)); } Value *CatchReturnInst ::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<CatchReturnInst>::operands(this) && "getOperand() out of range!") ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<CatchReturnInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 4536, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<CatchReturnInst>::op_begin(const_cast< CatchReturnInst*>(this))[i_nocapture].get()); } void CatchReturnInst ::setOperand(unsigned i_nocapture, Value *Val_nocapture) { (( i_nocapture < OperandTraits<CatchReturnInst>::operands (this) && "setOperand() out of range!") ? static_cast <void> (0) : __assert_fail ("i_nocapture < OperandTraits<CatchReturnInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 4536, __PRETTY_FUNCTION__)); OperandTraits<CatchReturnInst >::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned CatchReturnInst::getNumOperands() const { return OperandTraits <CatchReturnInst>::operands(this); } template <int Idx_nocapture > Use &CatchReturnInst::Op() { return this->OpFrom< Idx_nocapture>(this); } template <int Idx_nocapture> const Use &CatchReturnInst::Op() const { return this-> OpFrom<Idx_nocapture>(this); } |
4537 | |
4538 | //===----------------------------------------------------------------------===// |
4539 | // CleanupReturnInst Class |
4540 | //===----------------------------------------------------------------------===// |
4541 | |
4542 | class CleanupReturnInst : public Instruction { |
4543 | using UnwindDestField = BoolBitfieldElementT<0>; |
4544 | |
4545 | private: |
4546 | CleanupReturnInst(const CleanupReturnInst &RI); |
4547 | CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values, |
4548 | Instruction *InsertBefore = nullptr); |
4549 | CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values, |
4550 | BasicBlock *InsertAtEnd); |
4551 | |
4552 | void init(Value *CleanupPad, BasicBlock *UnwindBB); |
4553 | |
4554 | protected: |
4555 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4556 | friend class Instruction; |
4557 | |
4558 | CleanupReturnInst *cloneImpl() const; |
4559 | |
4560 | public: |
4561 | static CleanupReturnInst *Create(Value *CleanupPad, |
4562 | BasicBlock *UnwindBB = nullptr, |
4563 | Instruction *InsertBefore = nullptr) { |
4564 | assert(CleanupPad)((CleanupPad) ? static_cast<void> (0) : __assert_fail ( "CleanupPad", "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 4564, __PRETTY_FUNCTION__)); |
4565 | unsigned Values = 1; |
4566 | if (UnwindBB) |
4567 | ++Values; |
4568 | return new (Values) |
4569 | CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertBefore); |
4570 | } |
4571 | |
4572 | static CleanupReturnInst *Create(Value *CleanupPad, BasicBlock *UnwindBB, |
4573 | BasicBlock *InsertAtEnd) { |
4574 | assert(CleanupPad)((CleanupPad) ? static_cast<void> (0) : __assert_fail ( "CleanupPad", "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 4574, __PRETTY_FUNCTION__)); |
4575 | unsigned Values = 1; |
4576 | if (UnwindBB) |
4577 | ++Values; |
4578 | return new (Values) |
4579 | CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertAtEnd); |
4580 | } |
4581 | |
4582 | /// Provide fast operand accessors |
4583 | DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void setOperand(unsigned, Value*); inline op_iterator op_begin(); inline const_op_iterator op_begin() const; inline op_iterator op_end(); inline const_op_iterator op_end() const; protected : template <int> inline Use &Op(); template <int > inline const Use &Op() const; public: inline unsigned getNumOperands() const; |
4584 | |
4585 | bool hasUnwindDest() const { return getSubclassData<UnwindDestField>(); } |
4586 | bool unwindsToCaller() const { return !hasUnwindDest(); } |
4587 | |
4588 | /// Convenience accessor. |
4589 | CleanupPadInst *getCleanupPad() const { |
4590 | return cast<CleanupPadInst>(Op<0>()); |
4591 | } |
4592 | void setCleanupPad(CleanupPadInst *CleanupPad) { |
4593 | assert(CleanupPad)((CleanupPad) ? static_cast<void> (0) : __assert_fail ( "CleanupPad", "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 4593, __PRETTY_FUNCTION__)); |
4594 | Op<0>() = CleanupPad; |
4595 | } |
4596 | |
4597 | unsigned getNumSuccessors() const { return hasUnwindDest() ? 1 : 0; } |
4598 | |
4599 | BasicBlock *getUnwindDest() const { |
4600 | return hasUnwindDest() ? cast<BasicBlock>(Op<1>()) : nullptr; |
4601 | } |
4602 | void setUnwindDest(BasicBlock *NewDest) { |
4603 | assert(NewDest)((NewDest) ? static_cast<void> (0) : __assert_fail ("NewDest" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 4603, __PRETTY_FUNCTION__)); |
4604 | assert(hasUnwindDest())((hasUnwindDest()) ? static_cast<void> (0) : __assert_fail ("hasUnwindDest()", "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 4604, __PRETTY_FUNCTION__)); |
4605 | Op<1>() = NewDest; |
4606 | } |
4607 | |
4608 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
4609 | static bool classof(const Instruction *I) { |
4610 | return (I->getOpcode() == Instruction::CleanupRet); |
4611 | } |
4612 | static bool classof(const Value *V) { |
4613 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4614 | } |
4615 | |
4616 | private: |
4617 | BasicBlock *getSuccessor(unsigned Idx) const { |
4618 | assert(Idx == 0)((Idx == 0) ? static_cast<void> (0) : __assert_fail ("Idx == 0" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 4618, __PRETTY_FUNCTION__)); |
4619 | return getUnwindDest(); |
4620 | } |
4621 | |
4622 | void setSuccessor(unsigned Idx, BasicBlock *B) { |
4623 | assert(Idx == 0)((Idx == 0) ? static_cast<void> (0) : __assert_fail ("Idx == 0" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 4623, __PRETTY_FUNCTION__)); |
4624 | setUnwindDest(B); |
4625 | } |
4626 | |
4627 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
4628 | // method so that subclasses cannot accidentally use it. |
4629 | template <typename Bitfield> |
4630 | void setSubclassData(typename Bitfield::Type Value) { |
4631 | Instruction::setSubclassData<Bitfield>(Value); |
4632 | } |
4633 | }; |
4634 | |
4635 | template <> |
4636 | struct OperandTraits<CleanupReturnInst> |
4637 | : public VariadicOperandTraits<CleanupReturnInst, /*MINARITY=*/1> {}; |
4638 | |
4639 | DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CleanupReturnInst, Value)CleanupReturnInst::op_iterator CleanupReturnInst::op_begin() { return OperandTraits<CleanupReturnInst>::op_begin(this ); } CleanupReturnInst::const_op_iterator CleanupReturnInst:: op_begin() const { return OperandTraits<CleanupReturnInst> ::op_begin(const_cast<CleanupReturnInst*>(this)); } CleanupReturnInst ::op_iterator CleanupReturnInst::op_end() { return OperandTraits <CleanupReturnInst>::op_end(this); } CleanupReturnInst:: const_op_iterator CleanupReturnInst::op_end() const { return OperandTraits <CleanupReturnInst>::op_end(const_cast<CleanupReturnInst *>(this)); } Value *CleanupReturnInst::getOperand(unsigned i_nocapture) const { ((i_nocapture < OperandTraits<CleanupReturnInst >::operands(this) && "getOperand() out of range!") ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<CleanupReturnInst>::operands(this) && \"getOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 4639, __PRETTY_FUNCTION__)); return cast_or_null<Value> ( OperandTraits<CleanupReturnInst>::op_begin(const_cast <CleanupReturnInst*>(this))[i_nocapture].get()); } void CleanupReturnInst::setOperand(unsigned i_nocapture, Value *Val_nocapture ) { ((i_nocapture < OperandTraits<CleanupReturnInst> ::operands(this) && "setOperand() out of range!") ? static_cast <void> (0) : __assert_fail ("i_nocapture < OperandTraits<CleanupReturnInst>::operands(this) && \"setOperand() out of range!\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 4639, __PRETTY_FUNCTION__)); OperandTraits<CleanupReturnInst >::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned CleanupReturnInst::getNumOperands() const { return OperandTraits <CleanupReturnInst>::operands(this); } template <int Idx_nocapture> Use &CleanupReturnInst::Op() { return this ->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture > const Use &CleanupReturnInst::Op() const { return this ->OpFrom<Idx_nocapture>(this); } |
4640 | |
4641 | //===----------------------------------------------------------------------===// |
4642 | // UnreachableInst Class |
4643 | //===----------------------------------------------------------------------===// |
4644 | |
4645 | //===--------------------------------------------------------------------------- |
4646 | /// This function has undefined behavior. In particular, the |
4647 | /// presence of this instruction indicates some higher level knowledge that the |
4648 | /// end of the block cannot be reached. |
4649 | /// |
4650 | class UnreachableInst : public Instruction { |
4651 | protected: |
4652 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4653 | friend class Instruction; |
4654 | |
4655 | UnreachableInst *cloneImpl() const; |
4656 | |
4657 | public: |
4658 | explicit UnreachableInst(LLVMContext &C, Instruction *InsertBefore = nullptr); |
4659 | explicit UnreachableInst(LLVMContext &C, BasicBlock *InsertAtEnd); |
4660 | |
4661 | // allocate space for exactly zero operands |
4662 | void *operator new(size_t s) { |
4663 | return User::operator new(s, 0); |
4664 | } |
4665 | |
4666 | unsigned getNumSuccessors() const { return 0; } |
4667 | |
4668 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
4669 | static bool classof(const Instruction *I) { |
4670 | return I->getOpcode() == Instruction::Unreachable; |
4671 | } |
4672 | static bool classof(const Value *V) { |
4673 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4674 | } |
4675 | |
4676 | private: |
4677 | BasicBlock *getSuccessor(unsigned idx) const { |
4678 | llvm_unreachable("UnreachableInst has no successors!")::llvm::llvm_unreachable_internal("UnreachableInst has no successors!" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 4678); |
4679 | } |
4680 | |
4681 | void setSuccessor(unsigned idx, BasicBlock *B) { |
4682 | llvm_unreachable("UnreachableInst has no successors!")::llvm::llvm_unreachable_internal("UnreachableInst has no successors!" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 4682); |
4683 | } |
4684 | }; |
4685 | |
4686 | //===----------------------------------------------------------------------===// |
4687 | // TruncInst Class |
4688 | //===----------------------------------------------------------------------===// |
4689 | |
4690 | /// This class represents a truncation of integer types. |
4691 | class TruncInst : public CastInst { |
4692 | protected: |
4693 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4694 | friend class Instruction; |
4695 | |
4696 | /// Clone an identical TruncInst |
4697 | TruncInst *cloneImpl() const; |
4698 | |
4699 | public: |
4700 | /// Constructor with insert-before-instruction semantics |
4701 | TruncInst( |
4702 | Value *S, ///< The value to be truncated |
4703 | Type *Ty, ///< The (smaller) type to truncate to |
4704 | const Twine &NameStr = "", ///< A name for the new instruction |
4705 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
4706 | ); |
4707 | |
4708 | /// Constructor with insert-at-end-of-block semantics |
4709 | TruncInst( |
4710 | Value *S, ///< The value to be truncated |
4711 | Type *Ty, ///< The (smaller) type to truncate to |
4712 | const Twine &NameStr, ///< A name for the new instruction |
4713 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
4714 | ); |
4715 | |
4716 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
4717 | static bool classof(const Instruction *I) { |
4718 | return I->getOpcode() == Trunc; |
4719 | } |
4720 | static bool classof(const Value *V) { |
4721 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4722 | } |
4723 | }; |
4724 | |
4725 | //===----------------------------------------------------------------------===// |
4726 | // ZExtInst Class |
4727 | //===----------------------------------------------------------------------===// |
4728 | |
4729 | /// This class represents zero extension of integer types. |
4730 | class ZExtInst : public CastInst { |
4731 | protected: |
4732 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4733 | friend class Instruction; |
4734 | |
4735 | /// Clone an identical ZExtInst |
4736 | ZExtInst *cloneImpl() const; |
4737 | |
4738 | public: |
4739 | /// Constructor with insert-before-instruction semantics |
4740 | ZExtInst( |
4741 | Value *S, ///< The value to be zero extended |
4742 | Type *Ty, ///< The type to zero extend to |
4743 | const Twine &NameStr = "", ///< A name for the new instruction |
4744 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
4745 | ); |
4746 | |
4747 | /// Constructor with insert-at-end semantics. |
4748 | ZExtInst( |
4749 | Value *S, ///< The value to be zero extended |
4750 | Type *Ty, ///< The type to zero extend to |
4751 | const Twine &NameStr, ///< A name for the new instruction |
4752 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
4753 | ); |
4754 | |
4755 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
4756 | static bool classof(const Instruction *I) { |
4757 | return I->getOpcode() == ZExt; |
4758 | } |
4759 | static bool classof(const Value *V) { |
4760 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4761 | } |
4762 | }; |
4763 | |
4764 | //===----------------------------------------------------------------------===// |
4765 | // SExtInst Class |
4766 | //===----------------------------------------------------------------------===// |
4767 | |
4768 | /// This class represents a sign extension of integer types. |
4769 | class SExtInst : public CastInst { |
4770 | protected: |
4771 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4772 | friend class Instruction; |
4773 | |
4774 | /// Clone an identical SExtInst |
4775 | SExtInst *cloneImpl() const; |
4776 | |
4777 | public: |
4778 | /// Constructor with insert-before-instruction semantics |
4779 | SExtInst( |
4780 | Value *S, ///< The value to be sign extended |
4781 | Type *Ty, ///< The type to sign extend to |
4782 | const Twine &NameStr = "", ///< A name for the new instruction |
4783 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
4784 | ); |
4785 | |
4786 | /// Constructor with insert-at-end-of-block semantics |
4787 | SExtInst( |
4788 | Value *S, ///< The value to be sign extended |
4789 | Type *Ty, ///< The type to sign extend to |
4790 | const Twine &NameStr, ///< A name for the new instruction |
4791 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
4792 | ); |
4793 | |
4794 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
4795 | static bool classof(const Instruction *I) { |
4796 | return I->getOpcode() == SExt; |
4797 | } |
4798 | static bool classof(const Value *V) { |
4799 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4800 | } |
4801 | }; |
4802 | |
4803 | //===----------------------------------------------------------------------===// |
4804 | // FPTruncInst Class |
4805 | //===----------------------------------------------------------------------===// |
4806 | |
4807 | /// This class represents a truncation of floating point types. |
4808 | class FPTruncInst : public CastInst { |
4809 | protected: |
4810 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4811 | friend class Instruction; |
4812 | |
4813 | /// Clone an identical FPTruncInst |
4814 | FPTruncInst *cloneImpl() const; |
4815 | |
4816 | public: |
4817 | /// Constructor with insert-before-instruction semantics |
4818 | FPTruncInst( |
4819 | Value *S, ///< The value to be truncated |
4820 | Type *Ty, ///< The type to truncate to |
4821 | const Twine &NameStr = "", ///< A name for the new instruction |
4822 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
4823 | ); |
4824 | |
4825 | /// Constructor with insert-before-instruction semantics |
4826 | FPTruncInst( |
4827 | Value *S, ///< The value to be truncated |
4828 | Type *Ty, ///< The type to truncate to |
4829 | const Twine &NameStr, ///< A name for the new instruction |
4830 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
4831 | ); |
4832 | |
4833 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
4834 | static bool classof(const Instruction *I) { |
4835 | return I->getOpcode() == FPTrunc; |
4836 | } |
4837 | static bool classof(const Value *V) { |
4838 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4839 | } |
4840 | }; |
4841 | |
4842 | //===----------------------------------------------------------------------===// |
4843 | // FPExtInst Class |
4844 | //===----------------------------------------------------------------------===// |
4845 | |
4846 | /// This class represents an extension of floating point types. |
4847 | class FPExtInst : public CastInst { |
4848 | protected: |
4849 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4850 | friend class Instruction; |
4851 | |
4852 | /// Clone an identical FPExtInst |
4853 | FPExtInst *cloneImpl() const; |
4854 | |
4855 | public: |
4856 | /// Constructor with insert-before-instruction semantics |
4857 | FPExtInst( |
4858 | Value *S, ///< The value to be extended |
4859 | Type *Ty, ///< The type to extend to |
4860 | const Twine &NameStr = "", ///< A name for the new instruction |
4861 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
4862 | ); |
4863 | |
4864 | /// Constructor with insert-at-end-of-block semantics |
4865 | FPExtInst( |
4866 | Value *S, ///< The value to be extended |
4867 | Type *Ty, ///< The type to extend to |
4868 | const Twine &NameStr, ///< A name for the new instruction |
4869 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
4870 | ); |
4871 | |
4872 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
4873 | static bool classof(const Instruction *I) { |
4874 | return I->getOpcode() == FPExt; |
4875 | } |
4876 | static bool classof(const Value *V) { |
4877 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4878 | } |
4879 | }; |
4880 | |
4881 | //===----------------------------------------------------------------------===// |
4882 | // UIToFPInst Class |
4883 | //===----------------------------------------------------------------------===// |
4884 | |
4885 | /// This class represents a cast unsigned integer to floating point. |
4886 | class UIToFPInst : public CastInst { |
4887 | protected: |
4888 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4889 | friend class Instruction; |
4890 | |
4891 | /// Clone an identical UIToFPInst |
4892 | UIToFPInst *cloneImpl() const; |
4893 | |
4894 | public: |
4895 | /// Constructor with insert-before-instruction semantics |
4896 | UIToFPInst( |
4897 | Value *S, ///< The value to be converted |
4898 | Type *Ty, ///< The type to convert to |
4899 | const Twine &NameStr = "", ///< A name for the new instruction |
4900 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
4901 | ); |
4902 | |
4903 | /// Constructor with insert-at-end-of-block semantics |
4904 | UIToFPInst( |
4905 | Value *S, ///< The value to be converted |
4906 | Type *Ty, ///< The type to convert to |
4907 | const Twine &NameStr, ///< A name for the new instruction |
4908 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
4909 | ); |
4910 | |
4911 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
4912 | static bool classof(const Instruction *I) { |
4913 | return I->getOpcode() == UIToFP; |
4914 | } |
4915 | static bool classof(const Value *V) { |
4916 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4917 | } |
4918 | }; |
4919 | |
4920 | //===----------------------------------------------------------------------===// |
4921 | // SIToFPInst Class |
4922 | //===----------------------------------------------------------------------===// |
4923 | |
4924 | /// This class represents a cast from signed integer to floating point. |
4925 | class SIToFPInst : public CastInst { |
4926 | protected: |
4927 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4928 | friend class Instruction; |
4929 | |
4930 | /// Clone an identical SIToFPInst |
4931 | SIToFPInst *cloneImpl() const; |
4932 | |
4933 | public: |
4934 | /// Constructor with insert-before-instruction semantics |
4935 | SIToFPInst( |
4936 | Value *S, ///< The value to be converted |
4937 | Type *Ty, ///< The type to convert to |
4938 | const Twine &NameStr = "", ///< A name for the new instruction |
4939 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
4940 | ); |
4941 | |
4942 | /// Constructor with insert-at-end-of-block semantics |
4943 | SIToFPInst( |
4944 | Value *S, ///< The value to be converted |
4945 | Type *Ty, ///< The type to convert to |
4946 | const Twine &NameStr, ///< A name for the new instruction |
4947 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
4948 | ); |
4949 | |
4950 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
4951 | static bool classof(const Instruction *I) { |
4952 | return I->getOpcode() == SIToFP; |
4953 | } |
4954 | static bool classof(const Value *V) { |
4955 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4956 | } |
4957 | }; |
4958 | |
4959 | //===----------------------------------------------------------------------===// |
4960 | // FPToUIInst Class |
4961 | //===----------------------------------------------------------------------===// |
4962 | |
4963 | /// This class represents a cast from floating point to unsigned integer |
4964 | class FPToUIInst : public CastInst { |
4965 | protected: |
4966 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4967 | friend class Instruction; |
4968 | |
4969 | /// Clone an identical FPToUIInst |
4970 | FPToUIInst *cloneImpl() const; |
4971 | |
4972 | public: |
4973 | /// Constructor with insert-before-instruction semantics |
4974 | FPToUIInst( |
4975 | Value *S, ///< The value to be converted |
4976 | Type *Ty, ///< The type to convert to |
4977 | const Twine &NameStr = "", ///< A name for the new instruction |
4978 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
4979 | ); |
4980 | |
4981 | /// Constructor with insert-at-end-of-block semantics |
4982 | FPToUIInst( |
4983 | Value *S, ///< The value to be converted |
4984 | Type *Ty, ///< The type to convert to |
4985 | const Twine &NameStr, ///< A name for the new instruction |
4986 | BasicBlock *InsertAtEnd ///< Where to insert the new instruction |
4987 | ); |
4988 | |
4989 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
4990 | static bool classof(const Instruction *I) { |
4991 | return I->getOpcode() == FPToUI; |
4992 | } |
4993 | static bool classof(const Value *V) { |
4994 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4995 | } |
4996 | }; |
4997 | |
4998 | //===----------------------------------------------------------------------===// |
4999 | // FPToSIInst Class |
5000 | //===----------------------------------------------------------------------===// |
5001 | |
5002 | /// This class represents a cast from floating point to signed integer. |
5003 | class FPToSIInst : public CastInst { |
5004 | protected: |
5005 | // Note: Instruction needs to be a friend here to call cloneImpl. |
5006 | friend class Instruction; |
5007 | |
5008 | /// Clone an identical FPToSIInst |
5009 | FPToSIInst *cloneImpl() const; |
5010 | |
5011 | public: |
5012 | /// Constructor with insert-before-instruction semantics |
5013 | FPToSIInst( |
5014 | Value *S, ///< The value to be converted |
5015 | Type *Ty, ///< The type to convert to |
5016 | const Twine &NameStr = "", ///< A name for the new instruction |
5017 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
5018 | ); |
5019 | |
5020 | /// Constructor with insert-at-end-of-block semantics |
5021 | FPToSIInst( |
5022 | Value *S, ///< The value to be converted |
5023 | Type *Ty, ///< The type to convert to |
5024 | const Twine &NameStr, ///< A name for the new instruction |
5025 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
5026 | ); |
5027 | |
5028 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
5029 | static bool classof(const Instruction *I) { |
5030 | return I->getOpcode() == FPToSI; |
5031 | } |
5032 | static bool classof(const Value *V) { |
5033 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
5034 | } |
5035 | }; |
5036 | |
5037 | //===----------------------------------------------------------------------===// |
5038 | // IntToPtrInst Class |
5039 | //===----------------------------------------------------------------------===// |
5040 | |
5041 | /// This class represents a cast from an integer to a pointer. |
5042 | class IntToPtrInst : public CastInst { |
5043 | public: |
5044 | // Note: Instruction needs to be a friend here to call cloneImpl. |
5045 | friend class Instruction; |
5046 | |
5047 | /// Constructor with insert-before-instruction semantics |
5048 | IntToPtrInst( |
5049 | Value *S, ///< The value to be converted |
5050 | Type *Ty, ///< The type to convert to |
5051 | const Twine &NameStr = "", ///< A name for the new instruction |
5052 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
5053 | ); |
5054 | |
5055 | /// Constructor with insert-at-end-of-block semantics |
5056 | IntToPtrInst( |
5057 | Value *S, ///< The value to be converted |
5058 | Type *Ty, ///< The type to convert to |
5059 | const Twine &NameStr, ///< A name for the new instruction |
5060 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
5061 | ); |
5062 | |
5063 | /// Clone an identical IntToPtrInst. |
5064 | IntToPtrInst *cloneImpl() const; |
5065 | |
5066 | /// Returns the address space of this instruction's pointer type. |
5067 | unsigned getAddressSpace() const { |
5068 | return getType()->getPointerAddressSpace(); |
5069 | } |
5070 | |
5071 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
5072 | static bool classof(const Instruction *I) { |
5073 | return I->getOpcode() == IntToPtr; |
5074 | } |
5075 | static bool classof(const Value *V) { |
5076 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
5077 | } |
5078 | }; |
5079 | |
5080 | //===----------------------------------------------------------------------===// |
5081 | // PtrToIntInst Class |
5082 | //===----------------------------------------------------------------------===// |
5083 | |
5084 | /// This class represents a cast from a pointer to an integer. |
5085 | class PtrToIntInst : public CastInst { |
5086 | protected: |
5087 | // Note: Instruction needs to be a friend here to call cloneImpl. |
5088 | friend class Instruction; |
5089 | |
5090 | /// Clone an identical PtrToIntInst. |
5091 | PtrToIntInst *cloneImpl() const; |
5092 | |
5093 | public: |
5094 | /// Constructor with insert-before-instruction semantics |
5095 | PtrToIntInst( |
5096 | Value *S, ///< The value to be converted |
5097 | Type *Ty, ///< The type to convert to |
5098 | const Twine &NameStr = "", ///< A name for the new instruction |
5099 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
5100 | ); |
5101 | |
5102 | /// Constructor with insert-at-end-of-block semantics |
5103 | PtrToIntInst( |
5104 | Value *S, ///< The value to be converted |
5105 | Type *Ty, ///< The type to convert to |
5106 | const Twine &NameStr, ///< A name for the new instruction |
5107 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
5108 | ); |
5109 | |
5110 | /// Gets the pointer operand. |
5111 | Value *getPointerOperand() { return getOperand(0); } |
5112 | /// Gets the pointer operand. |
5113 | const Value *getPointerOperand() const { return getOperand(0); } |
5114 | /// Gets the operand index of the pointer operand. |
5115 | static unsigned getPointerOperandIndex() { return 0U; } |
5116 | |
5117 | /// Returns the address space of the pointer operand. |
5118 | unsigned getPointerAddressSpace() const { |
5119 | return getPointerOperand()->getType()->getPointerAddressSpace(); |
5120 | } |
5121 | |
5122 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
5123 | static bool classof(const Instruction *I) { |
5124 | return I->getOpcode() == PtrToInt; |
5125 | } |
5126 | static bool classof(const Value *V) { |
5127 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
5128 | } |
5129 | }; |
5130 | |
5131 | //===----------------------------------------------------------------------===// |
5132 | // BitCastInst Class |
5133 | //===----------------------------------------------------------------------===// |
5134 | |
5135 | /// This class represents a no-op cast from one type to another. |
5136 | class BitCastInst : public CastInst { |
5137 | protected: |
5138 | // Note: Instruction needs to be a friend here to call cloneImpl. |
5139 | friend class Instruction; |
5140 | |
5141 | /// Clone an identical BitCastInst. |
5142 | BitCastInst *cloneImpl() const; |
5143 | |
5144 | public: |
5145 | /// Constructor with insert-before-instruction semantics |
5146 | BitCastInst( |
5147 | Value *S, ///< The value to be casted |
5148 | Type *Ty, ///< The type to casted to |
5149 | const Twine &NameStr = "", ///< A name for the new instruction |
5150 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
5151 | ); |
5152 | |
5153 | /// Constructor with insert-at-end-of-block semantics |
5154 | BitCastInst( |
5155 | Value *S, ///< The value to be casted |
5156 | Type *Ty, ///< The type to casted to |
5157 | const Twine &NameStr, ///< A name for the new instruction |
5158 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
5159 | ); |
5160 | |
5161 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
5162 | static bool classof(const Instruction *I) { |
5163 | return I->getOpcode() == BitCast; |
5164 | } |
5165 | static bool classof(const Value *V) { |
5166 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
5167 | } |
5168 | }; |
5169 | |
5170 | //===----------------------------------------------------------------------===// |
5171 | // AddrSpaceCastInst Class |
5172 | //===----------------------------------------------------------------------===// |
5173 | |
5174 | /// This class represents a conversion between pointers from one address space |
5175 | /// to another. |
5176 | class AddrSpaceCastInst : public CastInst { |
5177 | protected: |
5178 | // Note: Instruction needs to be a friend here to call cloneImpl. |
5179 | friend class Instruction; |
5180 | |
5181 | /// Clone an identical AddrSpaceCastInst. |
5182 | AddrSpaceCastInst *cloneImpl() const; |
5183 | |
5184 | public: |
5185 | /// Constructor with insert-before-instruction semantics |
5186 | AddrSpaceCastInst( |
5187 | Value *S, ///< The value to be casted |
5188 | Type *Ty, ///< The type to casted to |
5189 | const Twine &NameStr = "", ///< A name for the new instruction |
5190 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
5191 | ); |
5192 | |
5193 | /// Constructor with insert-at-end-of-block semantics |
5194 | AddrSpaceCastInst( |
5195 | Value *S, ///< The value to be casted |
5196 | Type *Ty, ///< The type to casted to |
5197 | const Twine &NameStr, ///< A name for the new instruction |
5198 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
5199 | ); |
5200 | |
5201 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
5202 | static bool classof(const Instruction *I) { |
5203 | return I->getOpcode() == AddrSpaceCast; |
5204 | } |
5205 | static bool classof(const Value *V) { |
5206 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
5207 | } |
5208 | |
5209 | /// Gets the pointer operand. |
5210 | Value *getPointerOperand() { |
5211 | return getOperand(0); |
5212 | } |
5213 | |
5214 | /// Gets the pointer operand. |
5215 | const Value *getPointerOperand() const { |
5216 | return getOperand(0); |
5217 | } |
5218 | |
5219 | /// Gets the operand index of the pointer operand. |
5220 | static unsigned getPointerOperandIndex() { |
5221 | return 0U; |
5222 | } |
5223 | |
5224 | /// Returns the address space of the pointer operand. |
5225 | unsigned getSrcAddressSpace() const { |
5226 | return getPointerOperand()->getType()->getPointerAddressSpace(); |
5227 | } |
5228 | |
5229 | /// Returns the address space of the result. |
5230 | unsigned getDestAddressSpace() const { |
5231 | return getType()->getPointerAddressSpace(); |
5232 | } |
5233 | }; |
5234 | |
5235 | /// A helper function that returns the pointer operand of a load or store |
5236 | /// instruction. Returns nullptr if not load or store. |
5237 | inline const Value *getLoadStorePointerOperand(const Value *V) { |
5238 | if (auto *Load = dyn_cast<LoadInst>(V)) |
5239 | return Load->getPointerOperand(); |
5240 | if (auto *Store = dyn_cast<StoreInst>(V)) |
5241 | return Store->getPointerOperand(); |
5242 | return nullptr; |
5243 | } |
5244 | inline Value *getLoadStorePointerOperand(Value *V) { |
5245 | return const_cast<Value *>( |
5246 | getLoadStorePointerOperand(static_cast<const Value *>(V))); |
5247 | } |
5248 | |
5249 | /// A helper function that returns the pointer operand of a load, store |
5250 | /// or GEP instruction. Returns nullptr if not load, store, or GEP. |
5251 | inline const Value *getPointerOperand(const Value *V) { |
5252 | if (auto *Ptr = getLoadStorePointerOperand(V)) |
5253 | return Ptr; |
5254 | if (auto *Gep = dyn_cast<GetElementPtrInst>(V)) |
5255 | return Gep->getPointerOperand(); |
5256 | return nullptr; |
5257 | } |
5258 | inline Value *getPointerOperand(Value *V) { |
5259 | return const_cast<Value *>(getPointerOperand(static_cast<const Value *>(V))); |
5260 | } |
5261 | |
5262 | /// A helper function that returns the alignment of load or store instruction. |
5263 | inline Align getLoadStoreAlignment(Value *I) { |
5264 | assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&(((isa<LoadInst>(I) || isa<StoreInst>(I)) && "Expected Load or Store instruction") ? static_cast<void> (0) : __assert_fail ("(isa<LoadInst>(I) || isa<StoreInst>(I)) && \"Expected Load or Store instruction\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 5265, __PRETTY_FUNCTION__)) |
5265 | "Expected Load or Store instruction")(((isa<LoadInst>(I) || isa<StoreInst>(I)) && "Expected Load or Store instruction") ? static_cast<void> (0) : __assert_fail ("(isa<LoadInst>(I) || isa<StoreInst>(I)) && \"Expected Load or Store instruction\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 5265, __PRETTY_FUNCTION__)); |
5266 | if (auto *LI = dyn_cast<LoadInst>(I)) |
5267 | return LI->getAlign(); |
5268 | return cast<StoreInst>(I)->getAlign(); |
5269 | } |
5270 | |
5271 | /// A helper function that returns the address space of the pointer operand of |
5272 | /// load or store instruction. |
5273 | inline unsigned getLoadStoreAddressSpace(Value *I) { |
5274 | assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&(((isa<LoadInst>(I) || isa<StoreInst>(I)) && "Expected Load or Store instruction") ? static_cast<void> (0) : __assert_fail ("(isa<LoadInst>(I) || isa<StoreInst>(I)) && \"Expected Load or Store instruction\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 5275, __PRETTY_FUNCTION__)) |
5275 | "Expected Load or Store instruction")(((isa<LoadInst>(I) || isa<StoreInst>(I)) && "Expected Load or Store instruction") ? static_cast<void> (0) : __assert_fail ("(isa<LoadInst>(I) || isa<StoreInst>(I)) && \"Expected Load or Store instruction\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/Instructions.h" , 5275, __PRETTY_FUNCTION__)); |
5276 | if (auto *LI = dyn_cast<LoadInst>(I)) |
5277 | return LI->getPointerAddressSpace(); |
5278 | return cast<StoreInst>(I)->getPointerAddressSpace(); |
5279 | } |
5280 | |
5281 | //===----------------------------------------------------------------------===// |
5282 | // FreezeInst Class |
5283 | //===----------------------------------------------------------------------===// |
5284 | |
5285 | /// This class represents a freeze function that returns random concrete |
5286 | /// value if an operand is either a poison value or an undef value |
5287 | class FreezeInst : public UnaryInstruction { |
5288 | protected: |
5289 | // Note: Instruction needs to be a friend here to call cloneImpl. |
5290 | friend class Instruction; |
5291 | |
5292 | /// Clone an identical FreezeInst |
5293 | FreezeInst *cloneImpl() const; |
5294 | |
5295 | public: |
5296 | explicit FreezeInst(Value *S, |
5297 | const Twine &NameStr = "", |
5298 | Instruction *InsertBefore = nullptr); |
5299 | FreezeInst(Value *S, const Twine &NameStr, BasicBlock *InsertAtEnd); |
5300 | |
5301 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
5302 | static inline bool classof(const Instruction *I) { |
5303 | return I->getOpcode() == Freeze; |
5304 | } |
5305 | static inline bool classof(const Value *V) { |
5306 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
5307 | } |
5308 | }; |
5309 | |
5310 | } // end namespace llvm |
5311 | |
5312 | #endif // LLVM_IR_INSTRUCTIONS_H |
1 | //===- PatternMatch.h - Match on the LLVM IR --------------------*- C++ -*-===// |
2 | // |
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 |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | // |
9 | // This file provides a simple and efficient mechanism for performing general |
10 | // tree-based pattern matches on the LLVM IR. The power of these routines is |
11 | // that it allows you to write concise patterns that are expressive and easy to |
12 | // understand. The other major advantage of this is that it allows you to |
13 | // trivially capture/bind elements in the pattern to variables. For example, |
14 | // you can do something like this: |
15 | // |
16 | // Value *Exp = ... |
17 | // Value *X, *Y; ConstantInt *C1, *C2; // (X & C1) | (Y & C2) |
18 | // if (match(Exp, m_Or(m_And(m_Value(X), m_ConstantInt(C1)), |
19 | // m_And(m_Value(Y), m_ConstantInt(C2))))) { |
20 | // ... Pattern is matched and variables are bound ... |
21 | // } |
22 | // |
23 | // This is primarily useful to things like the instruction combiner, but can |
24 | // also be useful for static analysis tools or code generators. |
25 | // |
26 | //===----------------------------------------------------------------------===// |
27 | |
28 | #ifndef LLVM_IR_PATTERNMATCH_H |
29 | #define LLVM_IR_PATTERNMATCH_H |
30 | |
31 | #include "llvm/ADT/APFloat.h" |
32 | #include "llvm/ADT/APInt.h" |
33 | #include "llvm/IR/Constant.h" |
34 | #include "llvm/IR/Constants.h" |
35 | #include "llvm/IR/DataLayout.h" |
36 | #include "llvm/IR/InstrTypes.h" |
37 | #include "llvm/IR/Instruction.h" |
38 | #include "llvm/IR/Instructions.h" |
39 | #include "llvm/IR/IntrinsicInst.h" |
40 | #include "llvm/IR/Intrinsics.h" |
41 | #include "llvm/IR/Operator.h" |
42 | #include "llvm/IR/Value.h" |
43 | #include "llvm/Support/Casting.h" |
44 | #include <cstdint> |
45 | |
46 | namespace llvm { |
47 | namespace PatternMatch { |
48 | |
49 | template <typename Val, typename Pattern> bool match(Val *V, const Pattern &P) { |
50 | return const_cast<Pattern &>(P).match(V); |
51 | } |
52 | |
53 | template <typename Pattern> bool match(ArrayRef<int> Mask, const Pattern &P) { |
54 | return const_cast<Pattern &>(P).match(Mask); |
55 | } |
56 | |
57 | template <typename SubPattern_t> struct OneUse_match { |
58 | SubPattern_t SubPattern; |
59 | |
60 | OneUse_match(const SubPattern_t &SP) : SubPattern(SP) {} |
61 | |
62 | template <typename OpTy> bool match(OpTy *V) { |
63 | return V->hasOneUse() && SubPattern.match(V); |
64 | } |
65 | }; |
66 | |
67 | template <typename T> inline OneUse_match<T> m_OneUse(const T &SubPattern) { |
68 | return SubPattern; |
69 | } |
70 | |
71 | template <typename Class> struct class_match { |
72 | template <typename ITy> bool match(ITy *V) { return isa<Class>(V); } |
73 | }; |
74 | |
75 | /// Match an arbitrary value and ignore it. |
76 | inline class_match<Value> m_Value() { return class_match<Value>(); } |
77 | |
78 | /// Match an arbitrary unary operation and ignore it. |
79 | inline class_match<UnaryOperator> m_UnOp() { |
80 | return class_match<UnaryOperator>(); |
81 | } |
82 | |
83 | /// Match an arbitrary binary operation and ignore it. |
84 | inline class_match<BinaryOperator> m_BinOp() { |
85 | return class_match<BinaryOperator>(); |
86 | } |
87 | |
88 | /// Matches any compare instruction and ignore it. |
89 | inline class_match<CmpInst> m_Cmp() { return class_match<CmpInst>(); } |
90 | |
91 | /// Match an arbitrary undef constant. |
92 | inline class_match<UndefValue> m_Undef() { return class_match<UndefValue>(); } |
93 | |
94 | /// Match an arbitrary poison constant. |
95 | inline class_match<PoisonValue> m_Poison() { return class_match<PoisonValue>(); } |
96 | |
97 | /// Match an arbitrary Constant and ignore it. |
98 | inline class_match<Constant> m_Constant() { return class_match<Constant>(); } |
99 | |
100 | /// Match an arbitrary ConstantInt and ignore it. |
101 | inline class_match<ConstantInt> m_ConstantInt() { |
102 | return class_match<ConstantInt>(); |
103 | } |
104 | |
105 | /// Match an arbitrary ConstantFP and ignore it. |
106 | inline class_match<ConstantFP> m_ConstantFP() { |
107 | return class_match<ConstantFP>(); |
108 | } |
109 | |
110 | /// Match an arbitrary ConstantExpr and ignore it. |
111 | inline class_match<ConstantExpr> m_ConstantExpr() { |
112 | return class_match<ConstantExpr>(); |
113 | } |
114 | |
115 | /// Match an arbitrary basic block value and ignore it. |
116 | inline class_match<BasicBlock> m_BasicBlock() { |
117 | return class_match<BasicBlock>(); |
118 | } |
119 | |
120 | /// Inverting matcher |
121 | template <typename Ty> struct match_unless { |
122 | Ty M; |
123 | |
124 | match_unless(const Ty &Matcher) : M(Matcher) {} |
125 | |
126 | template <typename ITy> bool match(ITy *V) { return !M.match(V); } |
127 | }; |
128 | |
129 | /// Match if the inner matcher does *NOT* match. |
130 | template <typename Ty> inline match_unless<Ty> m_Unless(const Ty &M) { |
131 | return match_unless<Ty>(M); |
132 | } |
133 | |
134 | /// Matching combinators |
135 | template <typename LTy, typename RTy> struct match_combine_or { |
136 | LTy L; |
137 | RTy R; |
138 | |
139 | match_combine_or(const LTy &Left, const RTy &Right) : L(Left), R(Right) {} |
140 | |
141 | template <typename ITy> bool match(ITy *V) { |
142 | if (L.match(V)) |
143 | return true; |
144 | if (R.match(V)) |
145 | return true; |
146 | return false; |
147 | } |
148 | }; |
149 | |
150 | template <typename LTy, typename RTy> struct match_combine_and { |
151 | LTy L; |
152 | RTy R; |
153 | |
154 | match_combine_and(const LTy &Left, const RTy &Right) : L(Left), R(Right) {} |
155 | |
156 | template <typename ITy> bool match(ITy *V) { |
157 | if (L.match(V)) |
158 | if (R.match(V)) |
159 | return true; |
160 | return false; |
161 | } |
162 | }; |
163 | |
164 | /// Combine two pattern matchers matching L || R |
165 | template <typename LTy, typename RTy> |
166 | inline match_combine_or<LTy, RTy> m_CombineOr(const LTy &L, const RTy &R) { |
167 | return match_combine_or<LTy, RTy>(L, R); |
168 | } |
169 | |
170 | /// Combine two pattern matchers matching L && R |
171 | template <typename LTy, typename RTy> |
172 | inline match_combine_and<LTy, RTy> m_CombineAnd(const LTy &L, const RTy &R) { |
173 | return match_combine_and<LTy, RTy>(L, R); |
174 | } |
175 | |
176 | struct apint_match { |
177 | const APInt *&Res; |
178 | bool AllowUndef; |
179 | |
180 | apint_match(const APInt *&Res, bool AllowUndef) |
181 | : Res(Res), AllowUndef(AllowUndef) {} |
182 | |
183 | template <typename ITy> bool match(ITy *V) { |
184 | if (auto *CI = dyn_cast<ConstantInt>(V)) { |
185 | Res = &CI->getValue(); |
186 | return true; |
187 | } |
188 | if (V->getType()->isVectorTy()) |
189 | if (const auto *C = dyn_cast<Constant>(V)) |
190 | if (auto *CI = dyn_cast_or_null<ConstantInt>( |
191 | C->getSplatValue(AllowUndef))) { |
192 | Res = &CI->getValue(); |
193 | return true; |
194 | } |
195 | return false; |
196 | } |
197 | }; |
198 | // Either constexpr if or renaming ConstantFP::getValueAPF to |
199 | // ConstantFP::getValue is needed to do it via single template |
200 | // function for both apint/apfloat. |
201 | struct apfloat_match { |
202 | const APFloat *&Res; |
203 | bool AllowUndef; |
204 | |
205 | apfloat_match(const APFloat *&Res, bool AllowUndef) |
206 | : Res(Res), AllowUndef(AllowUndef) {} |
207 | |
208 | template <typename ITy> bool match(ITy *V) { |
209 | if (auto *CI = dyn_cast<ConstantFP>(V)) { |
210 | Res = &CI->getValueAPF(); |
211 | return true; |
212 | } |
213 | if (V->getType()->isVectorTy()) |
214 | if (const auto *C = dyn_cast<Constant>(V)) |
215 | if (auto *CI = dyn_cast_or_null<ConstantFP>( |
216 | C->getSplatValue(AllowUndef))) { |
217 | Res = &CI->getValueAPF(); |
218 | return true; |
219 | } |
220 | return false; |
221 | } |
222 | }; |
223 | |
224 | /// Match a ConstantInt or splatted ConstantVector, binding the |
225 | /// specified pointer to the contained APInt. |
226 | inline apint_match m_APInt(const APInt *&Res) { |
227 | // Forbid undefs by default to maintain previous behavior. |
228 | return apint_match(Res, /* AllowUndef */ false); |
229 | } |
230 | |
231 | /// Match APInt while allowing undefs in splat vector constants. |
232 | inline apint_match m_APIntAllowUndef(const APInt *&Res) { |
233 | return apint_match(Res, /* AllowUndef */ true); |
234 | } |
235 | |
236 | /// Match APInt while forbidding undefs in splat vector constants. |
237 | inline apint_match m_APIntForbidUndef(const APInt *&Res) { |
238 | return apint_match(Res, /* AllowUndef */ false); |
239 | } |
240 | |
241 | /// Match a ConstantFP or splatted ConstantVector, binding the |
242 | /// specified pointer to the contained APFloat. |
243 | inline apfloat_match m_APFloat(const APFloat *&Res) { |
244 | // Forbid undefs by default to maintain previous behavior. |
245 | return apfloat_match(Res, /* AllowUndef */ false); |
246 | } |
247 | |
248 | /// Match APFloat while allowing undefs in splat vector constants. |
249 | inline apfloat_match m_APFloatAllowUndef(const APFloat *&Res) { |
250 | return apfloat_match(Res, /* AllowUndef */ true); |
251 | } |
252 | |
253 | /// Match APFloat while forbidding undefs in splat vector constants. |
254 | inline apfloat_match m_APFloatForbidUndef(const APFloat *&Res) { |
255 | return apfloat_match(Res, /* AllowUndef */ false); |
256 | } |
257 | |
258 | template <int64_t Val> struct constantint_match { |
259 | template <typename ITy> bool match(ITy *V) { |
260 | if (const auto *CI = dyn_cast<ConstantInt>(V)) { |
261 | const APInt &CIV = CI->getValue(); |
262 | if (Val >= 0) |
263 | return CIV == static_cast<uint64_t>(Val); |
264 | // If Val is negative, and CI is shorter than it, truncate to the right |
265 | // number of bits. If it is larger, then we have to sign extend. Just |
266 | // compare their negated values. |
267 | return -CIV == -Val; |
268 | } |
269 | return false; |
270 | } |
271 | }; |
272 | |
273 | /// Match a ConstantInt with a specific value. |
274 | template <int64_t Val> inline constantint_match<Val> m_ConstantInt() { |
275 | return constantint_match<Val>(); |
276 | } |
277 | |
278 | /// This helper class is used to match constant scalars, vector splats, |
279 | /// and fixed width vectors that satisfy a specified predicate. |
280 | /// For fixed width vector constants, undefined elements are ignored. |
281 | template <typename Predicate, typename ConstantVal> |
282 | struct cstval_pred_ty : public Predicate { |
283 | template <typename ITy> bool match(ITy *V) { |
284 | if (const auto *CV = dyn_cast<ConstantVal>(V)) |
285 | return this->isValue(CV->getValue()); |
286 | if (const auto *VTy = dyn_cast<VectorType>(V->getType())) { |
287 | if (const auto *C = dyn_cast<Constant>(V)) { |
288 | if (const auto *CV = dyn_cast_or_null<ConstantVal>(C->getSplatValue())) |
289 | return this->isValue(CV->getValue()); |
290 | |
291 | // Number of elements of a scalable vector unknown at compile time |
292 | auto *FVTy = dyn_cast<FixedVectorType>(VTy); |
293 | if (!FVTy) |
294 | return false; |
295 | |
296 | // Non-splat vector constant: check each element for a match. |
297 | unsigned NumElts = FVTy->getNumElements(); |
298 | assert(NumElts != 0 && "Constant vector with no elements?")((NumElts != 0 && "Constant vector with no elements?" ) ? static_cast<void> (0) : __assert_fail ("NumElts != 0 && \"Constant vector with no elements?\"" , "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/PatternMatch.h" , 298, __PRETTY_FUNCTION__)); |
299 | bool HasNonUndefElements = false; |
300 | for (unsigned i = 0; i != NumElts; ++i) { |
301 | Constant *Elt = C->getAggregateElement(i); |
302 | if (!Elt) |
303 | return false; |
304 | if (isa<UndefValue>(Elt)) |
305 | continue; |
306 | auto *CV = dyn_cast<ConstantVal>(Elt); |
307 | if (!CV || !this->isValue(CV->getValue())) |
308 | return false; |
309 | HasNonUndefElements = true; |
310 | } |
311 | return HasNonUndefElements; |
312 | } |
313 | } |
314 | return false; |
315 | } |
316 | }; |
317 | |
318 | /// specialization of cstval_pred_ty for ConstantInt |
319 | template <typename Predicate> |
320 | using cst_pred_ty = cstval_pred_ty<Predicate, ConstantInt>; |
321 | |
322 | /// specialization of cstval_pred_ty for ConstantFP |
323 | template <typename Predicate> |
324 | using cstfp_pred_ty = cstval_pred_ty<Predicate, ConstantFP>; |
325 | |
326 | /// This helper class is used to match scalar and vector constants that |
327 | /// satisfy a specified predicate, and bind them to an APInt. |
328 | template <typename Predicate> struct api_pred_ty : public Predicate { |
329 | const APInt *&Res; |
330 | |
331 | api_pred_ty(const APInt *&R) : Res(R) {} |
332 | |
333 | template <typename ITy> bool match(ITy *V) { |
334 | if (const auto *CI = dyn_cast<ConstantInt>(V)) |
335 | if (this->isValue(CI->getValue())) { |
336 | Res = &CI->getValue(); |
337 | return true; |
338 | } |
339 | if (V->getType()->isVectorTy()) |
340 | if (const auto *C = dyn_cast<Constant>(V)) |
341 | if (auto *CI = dyn_cast_or_null<ConstantInt>(C->getSplatValue())) |
342 | if (this->isValue(CI->getValue())) { |
343 | Res = &CI->getValue(); |
344 | return true; |
345 | } |
346 | |
347 | return false; |
348 | } |
349 | }; |
350 | |
351 | /// This helper class is used to match scalar and vector constants that |
352 | /// satisfy a specified predicate, and bind them to an APFloat. |
353 | /// Undefs are allowed in splat vector constants. |
354 | template <typename Predicate> struct apf_pred_ty : public Predicate { |
355 | const APFloat *&Res; |
356 | |
357 | apf_pred_ty(const APFloat *&R) : Res(R) {} |
358 | |
359 | template <typename ITy> bool match(ITy *V) { |
360 | if (const auto *CI = dyn_cast<ConstantFP>(V)) |
361 | if (this->isValue(CI->getValue())) { |
362 | Res = &CI->getValue(); |
363 | return true; |
364 | } |
365 | if (V->getType()->isVectorTy()) |
366 | if (const auto *C = dyn_cast<Constant>(V)) |
367 | if (auto *CI = dyn_cast_or_null<ConstantFP>( |
368 | C->getSplatValue(/* AllowUndef */ true))) |
369 | if (this->isValue(CI->getValue())) { |
370 | Res = &CI->getValue(); |
371 | return true; |
372 | } |
373 | |
374 | return false; |
375 | } |
376 | }; |
377 | |
378 | /////////////////////////////////////////////////////////////////////////////// |
379 | // |
380 | // Encapsulate constant value queries for use in templated predicate matchers. |
381 | // This allows checking if constants match using compound predicates and works |
382 | // with vector constants, possibly with relaxed constraints. For example, ignore |
383 | // undef values. |
384 | // |
385 | /////////////////////////////////////////////////////////////////////////////// |
386 | |
387 | struct is_any_apint { |
388 | bool isValue(const APInt &C) { return true; } |
389 | }; |
390 | /// Match an integer or vector with any integral constant. |
391 | /// For vectors, this includes constants with undefined elements. |
392 | inline cst_pred_ty<is_any_apint> m_AnyIntegralConstant() { |
393 | return cst_pred_ty<is_any_apint>(); |
394 | } |
395 | |
396 | struct is_all_ones { |
397 | bool isValue(const APInt &C) { return C.isAllOnesValue(); } |
398 | }; |
399 | /// Match an integer or vector with all bits set. |
400 | /// For vectors, this includes constants with undefined elements. |
401 | inline cst_pred_ty<is_all_ones> m_AllOnes() { |
402 | return cst_pred_ty<is_all_ones>(); |
403 | } |
404 | |
405 | struct is_maxsignedvalue { |
406 | bool isValue(const APInt &C) { return C.isMaxSignedValue(); } |
407 | }; |
408 | /// Match an integer or vector with values having all bits except for the high |
409 | /// bit set (0x7f...). |
410 | /// For vectors, this includes constants with undefined elements. |
411 | inline cst_pred_ty<is_maxsignedvalue> m_MaxSignedValue() { |
412 | return cst_pred_ty<is_maxsignedvalue>(); |
413 | } |
414 | inline api_pred_ty<is_maxsignedvalue> m_MaxSignedValue(const APInt *&V) { |
415 | return V; |
416 | } |
417 | |
418 | struct is_negative { |
419 | bool isValue(const APInt &C) { return C.isNegative(); } |
420 | }; |
421 | /// Match an integer or vector of negative values. |
422 | /// For vectors, this includes constants with undefined elements. |
423 | inline cst_pred_ty<is_negative> m_Negative() { |
424 | return cst_pred_ty<is_negative>(); |
425 | } |
426 | inline api_pred_ty<is_negative> m_Negative(const APInt *&V) { |
427 | return V; |
428 | } |
429 | |
430 | struct is_nonnegative { |
431 | bool isValue(const APInt &C) { return C.isNonNegative(); } |
432 | }; |
433 | /// Match an integer or vector of non-negative values. |
434 | /// For vectors, this includes constants with undefined elements. |
435 | inline cst_pred_ty<is_nonnegative> m_NonNegative() { |
436 | return cst_pred_ty<is_nonnegative>(); |
437 | } |
438 | inline api_pred_ty<is_nonnegative> m_NonNegative(const APInt *&V) { |
439 | return V; |
440 | } |
441 | |
442 | struct is_strictlypositive { |
443 | bool isValue(const APInt &C) { return C.isStrictlyPositive(); } |
444 | }; |
445 | /// Match an integer or vector of strictly positive values. |
446 | /// For vectors, this includes constants with undefined elements. |
447 | inline cst_pred_ty<is_strictlypositive> m_StrictlyPositive() { |
448 | return cst_pred_ty<is_strictlypositive>(); |
449 | } |
450 | inline api_pred_ty<is_strictlypositive> m_StrictlyPositive(const APInt *&V) { |
451 | return V; |
452 | } |
453 | |
454 | struct is_nonpositive { |
455 | bool isValue(const APInt &C) { return C.isNonPositive(); } |
456 | }; |
457 | /// Match an integer or vector of non-positive values. |
458 | /// For vectors, this includes constants with undefined elements. |
459 | inline cst_pred_ty<is_nonpositive> m_NonPositive() { |
460 | return cst_pred_ty<is_nonpositive>(); |
461 | } |
462 | inline api_pred_ty<is_nonpositive> m_NonPositive(const APInt *&V) { return V; } |
463 | |
464 | struct is_one { |
465 | bool isValue(const APInt &C) { return C.isOneValue(); } |
466 | }; |
467 | /// Match an integer 1 or a vector with all elements equal to 1. |
468 | /// For vectors, this includes constants with undefined elements. |
469 | inline cst_pred_ty<is_one> m_One() { |
470 | return cst_pred_ty<is_one>(); |
471 | } |
472 | |
473 | struct is_zero_int { |
474 | bool isValue(const APInt &C) { return C.isNullValue(); } |
475 | }; |
476 | /// Match an integer 0 or a vector with all elements equal to 0. |
477 | /// For vectors, this includes constants with undefined elements. |
478 | inline cst_pred_ty<is_zero_int> m_ZeroInt() { |
479 | return cst_pred_ty<is_zero_int>(); |
480 | } |
481 | |
482 | struct is_zero { |
483 | template <typename ITy> bool match(ITy *V) { |
484 | auto *C = dyn_cast<Constant>(V); |
485 | // FIXME: this should be able to do something for scalable vectors |
486 | return C && (C->isNullValue() || cst_pred_ty<is_zero_int>().match(C)); |
487 | } |
488 | }; |
489 | /// Match any null constant or a vector with all elements equal to 0. |
490 | /// For vectors, this includes constants with undefined elements. |
491 | inline is_zero m_Zero() { |
492 | return is_zero(); |
493 | } |
494 | |
495 | struct is_power2 { |
496 | bool isValue(const APInt &C) { return C.isPowerOf2(); } |
497 | }; |
498 | /// Match an integer or vector power-of-2. |
499 | /// For vectors, this includes constants with undefined elements. |
500 | inline cst_pred_ty<is_power2> m_Power2() { |
501 | return cst_pred_ty<is_power2>(); |
502 | } |
503 | inline api_pred_ty<is_power2> m_Power2(const APInt *&V) { |
504 | return V; |
505 | } |
506 | |
507 | struct is_negated_power2 { |
508 | bool isValue(const APInt &C) { return (-C).isPowerOf2(); } |
509 | }; |
510 | /// Match a integer or vector negated power-of-2. |
511 | /// For vectors, this includes constants with undefined elements. |
512 | inline cst_pred_ty<is_negated_power2> m_NegatedPower2() { |
513 | return cst_pred_ty<is_negated_power2>(); |
514 | } |
515 | inline api_pred_ty<is_negated_power2> m_NegatedPower2(const APInt *&V) { |
516 | return V; |
517 | } |
518 | |
519 | struct is_power2_or_zero { |
520 | bool isValue(const APInt &C) { return !C || C.isPowerOf2(); } |
521 | }; |
522 | /// Match an integer or vector of 0 or power-of-2 values. |
523 | /// For vectors, this includes constants with undefined elements. |
524 | inline cst_pred_ty<is_power2_or_zero> m_Power2OrZero() { |
525 | return cst_pred_ty<is_power2_or_zero>(); |
526 | } |
527 | inline api_pred_ty<is_power2_or_zero> m_Power2OrZero(const APInt *&V) { |
528 | return V; |
529 | } |
530 | |
531 | struct is_sign_mask { |
532 | bool isValue(const APInt &C) { return C.isSignMask(); } |
533 | }; |
534 | /// Match an integer or vector with only the sign bit(s) set. |
535 | /// For vectors, this includes constants with undefined elements. |
536 | inline cst_pred_ty<is_sign_mask> m_SignMask() { |
537 | return cst_pred_ty<is_sign_mask>(); |
538 | } |
539 | |
540 | struct is_lowbit_mask { |
541 | bool isValue(const APInt &C) { return C.isMask(); } |
542 | }; |
543 | /// Match an integer or vector with only the low bit(s) set. |
544 | /// For vectors, this includes constants with undefined elements. |
545 | inline cst_pred_ty<is_lowbit_mask> m_LowBitMask() { |
546 | return cst_pred_ty<is_lowbit_mask>(); |
547 | } |
548 | |
549 | struct icmp_pred_with_threshold { |
550 | ICmpInst::Predicate Pred; |
551 | const APInt *Thr; |
552 | bool isValue(const APInt &C) { |
553 | switch (Pred) { |
554 | case ICmpInst::Predicate::ICMP_EQ: |
555 | return C.eq(*Thr); |
556 | case ICmpInst::Predicate::ICMP_NE: |
557 | return C.ne(*Thr); |
558 | case ICmpInst::Predicate::ICMP_UGT: |
559 | return C.ugt(*Thr); |
560 | case ICmpInst::Predicate::ICMP_UGE: |
561 | return C.uge(*Thr); |
562 | case ICmpInst::Predicate::ICMP_ULT: |
563 | return C.ult(*Thr); |
564 | case ICmpInst::Predicate::ICMP_ULE: |
565 | return C.ule(*Thr); |
566 | case ICmpInst::Predicate::ICMP_SGT: |
567 | return C.sgt(*Thr); |
568 | case ICmpInst::Predicate::ICMP_SGE: |
569 | return C.sge(*Thr); |
570 | case ICmpInst::Predicate::ICMP_SLT: |
571 | return C.slt(*Thr); |
572 | case ICmpInst::Predicate::ICMP_SLE: |
573 | return C.sle(*Thr); |
574 | default: |
575 | llvm_unreachable("Unhandled ICmp predicate")::llvm::llvm_unreachable_internal("Unhandled ICmp predicate", "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/PatternMatch.h" , 575); |
576 | } |
577 | } |
578 | }; |
579 | /// Match an integer or vector with every element comparing 'pred' (eg/ne/...) |
580 | /// to Threshold. For vectors, this includes constants with undefined elements. |
581 | inline cst_pred_ty<icmp_pred_with_threshold> |
582 | m_SpecificInt_ICMP(ICmpInst::Predicate Predicate, const APInt &Threshold) { |
583 | cst_pred_ty<icmp_pred_with_threshold> P; |
584 | P.Pred = Predicate; |
585 | P.Thr = &Threshold; |
586 | return P; |
587 | } |
588 | |
589 | struct is_nan { |
590 | bool isValue(const APFloat &C) { return C.isNaN(); } |
591 | }; |
592 | /// Match an arbitrary NaN constant. This includes quiet and signalling nans. |
593 | /// For vectors, this includes constants with undefined elements. |
594 | inline cstfp_pred_ty<is_nan> m_NaN() { |
595 | return cstfp_pred_ty<is_nan>(); |
596 | } |
597 | |
598 | struct is_nonnan { |
599 | bool isValue(const APFloat &C) { return !C.isNaN(); } |
600 | }; |
601 | /// Match a non-NaN FP constant. |
602 | /// For vectors, this includes constants with undefined elements. |
603 | inline cstfp_pred_ty<is_nonnan> m_NonNaN() { |
604 | return cstfp_pred_ty<is_nonnan>(); |
605 | } |
606 | |
607 | struct is_inf { |
608 | bool isValue(const APFloat &C) { return C.isInfinity(); } |
609 | }; |
610 | /// Match a positive or negative infinity FP constant. |
611 | /// For vectors, this includes constants with undefined elements. |
612 | inline cstfp_pred_ty<is_inf> m_Inf() { |
613 | return cstfp_pred_ty<is_inf>(); |
614 | } |
615 | |
616 | struct is_noninf { |
617 | bool isValue(const APFloat &C) { return !C.isInfinity(); } |
618 | }; |
619 | /// Match a non-infinity FP constant, i.e. finite or NaN. |
620 | /// For vectors, this includes constants with undefined elements. |
621 | inline cstfp_pred_ty<is_noninf> m_NonInf() { |
622 | return cstfp_pred_ty<is_noninf>(); |
623 | } |
624 | |
625 | struct is_finite { |
626 | bool isValue(const APFloat &C) { return C.isFinite(); } |
627 | }; |
628 | /// Match a finite FP constant, i.e. not infinity or NaN. |
629 | /// For vectors, this includes constants with undefined elements. |
630 | inline cstfp_pred_ty<is_finite> m_Finite() { |
631 | return cstfp_pred_ty<is_finite>(); |
632 | } |
633 | inline apf_pred_ty<is_finite> m_Finite(const APFloat *&V) { return V; } |
634 | |
635 | struct is_finitenonzero { |
636 | bool isValue(const APFloat &C) { return C.isFiniteNonZero(); } |
637 | }; |
638 | /// Match a finite non-zero FP constant. |
639 | /// For vectors, this includes constants with undefined elements. |
640 | inline cstfp_pred_ty<is_finitenonzero> m_FiniteNonZero() { |
641 | return cstfp_pred_ty<is_finitenonzero>(); |
642 | } |
643 | inline apf_pred_ty<is_finitenonzero> m_FiniteNonZero(const APFloat *&V) { |
644 | return V; |
645 | } |
646 | |
647 | struct is_any_zero_fp { |
648 | bool isValue(const APFloat &C) { return C.isZero(); } |
649 | }; |
650 | /// Match a floating-point negative zero or positive zero. |
651 | /// For vectors, this includes constants with undefined elements. |
652 | inline cstfp_pred_ty<is_any_zero_fp> m_AnyZeroFP() { |
653 | return cstfp_pred_ty<is_any_zero_fp>(); |
654 | } |
655 | |
656 | struct is_pos_zero_fp { |
657 | bool isValue(const APFloat &C) { return C.isPosZero(); } |
658 | }; |
659 | /// Match a floating-point positive zero. |
660 | /// For vectors, this includes constants with undefined elements. |
661 | inline cstfp_pred_ty<is_pos_zero_fp> m_PosZeroFP() { |
662 | return cstfp_pred_ty<is_pos_zero_fp>(); |
663 | } |
664 | |
665 | struct is_neg_zero_fp { |
666 | bool isValue(const APFloat &C) { return C.isNegZero(); } |
667 | }; |
668 | /// Match a floating-point negative zero. |
669 | /// For vectors, this includes constants with undefined elements. |
670 | inline cstfp_pred_ty<is_neg_zero_fp> m_NegZeroFP() { |
671 | return cstfp_pred_ty<is_neg_zero_fp>(); |
672 | } |
673 | |
674 | struct is_non_zero_fp { |
675 | bool isValue(const APFloat &C) { return C.isNonZero(); } |
676 | }; |
677 | /// Match a floating-point non-zero. |
678 | /// For vectors, this includes constants with undefined elements. |
679 | inline cstfp_pred_ty<is_non_zero_fp> m_NonZeroFP() { |
680 | return cstfp_pred_ty<is_non_zero_fp>(); |
681 | } |
682 | |
683 | /////////////////////////////////////////////////////////////////////////////// |
684 | |
685 | template <typename Class> struct bind_ty { |
686 | Class *&VR; |
687 | |
688 | bind_ty(Class *&V) : VR(V) {} |
689 | |
690 | template <typename ITy> bool match(ITy *V) { |
691 | if (auto *CV = dyn_cast<Class>(V)) { |
692 | VR = CV; |
693 | return true; |
694 | } |
695 | return false; |
696 | } |
697 | }; |
698 | |
699 | /// Match a value, capturing it if we match. |
700 | inline bind_ty<Value> m_Value(Value *&V) { return V; } |
701 | inline bind_ty<const Value> m_Value(const Value *&V) { return V; } |
702 | |
703 | /// Match an instruction, capturing it if we match. |
704 | inline bind_ty<Instruction> m_Instruction(Instruction *&I) { return I; } |
705 | /// Match a unary operator, capturing it if we match. |
706 | inline bind_ty<UnaryOperator> m_UnOp(UnaryOperator *&I) { return I; } |
707 | /// Match a binary operator, capturing it if we match. |
708 | inline bind_ty<BinaryOperator> m_BinOp(BinaryOperator *&I) { return I; } |
709 | /// Match a with overflow intrinsic, capturing it if we match. |
710 | inline bind_ty<WithOverflowInst> m_WithOverflowInst(WithOverflowInst *&I) { return I; } |
711 | inline bind_ty<const WithOverflowInst> |
712 | m_WithOverflowInst(const WithOverflowInst *&I) { |
713 | return I; |
714 | } |
715 | |
716 | /// Match a Constant, capturing the value if we match. |
717 | inline bind_ty<Constant> m_Constant(Constant *&C) { return C; } |
718 | |
719 | /// Match a ConstantInt, capturing the value if we match. |
720 | inline bind_ty<ConstantInt> m_ConstantInt(ConstantInt *&CI) { return CI; } |
721 | |
722 | /// Match a ConstantFP, capturing the value if we match. |
723 | inline bind_ty<ConstantFP> m_ConstantFP(ConstantFP *&C) { return C; } |
724 | |
725 | /// Match a ConstantExpr, capturing the value if we match. |
726 | inline bind_ty<ConstantExpr> m_ConstantExpr(ConstantExpr *&C) { return C; } |
727 | |
728 | /// Match a basic block value, capturing it if we match. |
729 | inline bind_ty<BasicBlock> m_BasicBlock(BasicBlock *&V) { return V; } |
730 | inline bind_ty<const BasicBlock> m_BasicBlock(const BasicBlock *&V) { |
731 | return V; |
732 | } |
733 | |
734 | /// Match an arbitrary immediate Constant and ignore it. |
735 | inline match_combine_and<class_match<Constant>, |
736 | match_unless<class_match<ConstantExpr>>> |
737 | m_ImmConstant() { |
738 | return m_CombineAnd(m_Constant(), m_Unless(m_ConstantExpr())); |
739 | } |
740 | |
741 | /// Match an immediate Constant, capturing the value if we match. |
742 | inline match_combine_and<bind_ty<Constant>, |
743 | match_unless<class_match<ConstantExpr>>> |
744 | m_ImmConstant(Constant *&C) { |
745 | return m_CombineAnd(m_Constant(C), m_Unless(m_ConstantExpr())); |
746 | } |
747 | |
748 | /// Match a specified Value*. |
749 | struct specificval_ty { |
750 | const Value *Val; |
751 | |
752 | specificval_ty(const Value *V) : Val(V) {} |
753 | |
754 | template <typename ITy> bool match(ITy *V) { return V == Val; } |
755 | }; |
756 | |
757 | /// Match if we have a specific specified value. |
758 | inline specificval_ty m_Specific(const Value *V) { return V; } |
759 | |
760 | /// Stores a reference to the Value *, not the Value * itself, |
761 | /// thus can be used in commutative matchers. |
762 | template <typename Class> struct deferredval_ty { |
763 | Class *const &Val; |
764 | |
765 | deferredval_ty(Class *const &V) : Val(V) {} |
766 | |
767 | template <typename ITy> bool match(ITy *const V) { return V == Val; } |
768 | }; |
769 | |
770 | /// A commutative-friendly version of m_Specific(). |
771 | inline deferredval_ty<Value> m_Deferred(Value *const &V) { return V; } |
772 | inline deferredval_ty<const Value> m_Deferred(const Value *const &V) { |
773 | return V; |
774 | } |
775 | |
776 | /// Match a specified floating point value or vector of all elements of |
777 | /// that value. |
778 | struct specific_fpval { |
779 | double Val; |
780 | |
781 | specific_fpval(double V) : Val(V) {} |
782 | |
783 | template <typename ITy> bool match(ITy *V) { |
784 | if (const auto *CFP = dyn_cast<ConstantFP>(V)) |
785 | return CFP->isExactlyValue(Val); |
786 | if (V->getType()->isVectorTy()) |
787 | if (const auto *C = dyn_cast<Constant>(V)) |
788 | if (auto *CFP = dyn_cast_or_null<ConstantFP>(C->getSplatValue())) |
789 | return CFP->isExactlyValue(Val); |
790 | return false; |
791 | } |
792 | }; |
793 | |
794 | /// Match a specific floating point value or vector with all elements |
795 | /// equal to the value. |
796 | inline specific_fpval m_SpecificFP(double V) { return specific_fpval(V); } |
797 | |
798 | /// Match a float 1.0 or vector with all elements equal to 1.0. |
799 | inline specific_fpval m_FPOne() { return m_SpecificFP(1.0); } |
800 | |
801 | struct bind_const_intval_ty { |
802 | uint64_t &VR; |
803 | |
804 | bind_const_intval_ty(uint64_t &V) : VR(V) {} |
805 | |
806 | template <typename ITy> bool match(ITy *V) { |
807 | if (const auto *CV = dyn_cast<ConstantInt>(V)) |
808 | if (CV->getValue().ule(UINT64_MAX(18446744073709551615UL))) { |
809 | VR = CV->getZExtValue(); |
810 | return true; |
811 | } |
812 | return false; |
813 | } |
814 | }; |
815 | |
816 | /// Match a specified integer value or vector of all elements of that |
817 | /// value. |
818 | template <bool AllowUndefs> |
819 | struct specific_intval { |
820 | APInt Val; |
821 | |
822 | specific_intval(APInt V) : Val(std::move(V)) {} |
823 | |
824 | template <typename ITy> bool match(ITy *V) { |
825 | const auto *CI = dyn_cast<ConstantInt>(V); |
826 | if (!CI && V->getType()->isVectorTy()) |
827 | if (const auto *C = dyn_cast<Constant>(V)) |
828 | CI = dyn_cast_or_null<ConstantInt>(C->getSplatValue(AllowUndefs)); |
829 | |
830 | return CI && APInt::isSameValue(CI->getValue(), Val); |
831 | } |
832 | }; |
833 | |
834 | /// Match a specific integer value or vector with all elements equal to |
835 | /// the value. |
836 | inline specific_intval<false> m_SpecificInt(APInt V) { |
837 | return specific_intval<false>(std::move(V)); |
838 | } |
839 | |
840 | inline specific_intval<false> m_SpecificInt(uint64_t V) { |
841 | return m_SpecificInt(APInt(64, V)); |
842 | } |
843 | |
844 | inline specific_intval<true> m_SpecificIntAllowUndef(APInt V) { |
845 | return specific_intval<true>(std::move(V)); |
846 | } |
847 | |
848 | inline specific_intval<true> m_SpecificIntAllowUndef(uint64_t V) { |
849 | return m_SpecificIntAllowUndef(APInt(64, V)); |
850 | } |
851 | |
852 | /// Match a ConstantInt and bind to its value. This does not match |
853 | /// ConstantInts wider than 64-bits. |
854 | inline bind_const_intval_ty m_ConstantInt(uint64_t &V) { return V; } |
855 | |
856 | /// Match a specified basic block value. |
857 | struct specific_bbval { |
858 | BasicBlock *Val; |
859 | |
860 | specific_bbval(BasicBlock *Val) : Val(Val) {} |
861 | |
862 | template <typename ITy> bool match(ITy *V) { |
863 | const auto *BB = dyn_cast<BasicBlock>(V); |
864 | return BB && BB == Val; |
865 | } |
866 | }; |
867 | |
868 | /// Match a specific basic block value. |
869 | inline specific_bbval m_SpecificBB(BasicBlock *BB) { |
870 | return specific_bbval(BB); |
871 | } |
872 | |
873 | /// A commutative-friendly version of m_Specific(). |
874 | inline deferredval_ty<BasicBlock> m_Deferred(BasicBlock *const &BB) { |
875 | return BB; |
876 | } |
877 | inline deferredval_ty<const BasicBlock> |
878 | m_Deferred(const BasicBlock *const &BB) { |
879 | return BB; |
880 | } |
881 | |
882 | //===----------------------------------------------------------------------===// |
883 | // Matcher for any binary operator. |
884 | // |
885 | template <typename LHS_t, typename RHS_t, bool Commutable = false> |
886 | struct AnyBinaryOp_match { |
887 | LHS_t L; |
888 | RHS_t R; |
889 | |
890 | // The evaluation order is always stable, regardless of Commutability. |
891 | // The LHS is always matched first. |
892 | AnyBinaryOp_match(const LHS_t &LHS, const RHS_t &RHS) : L(LHS), R(RHS) {} |
893 | |
894 | template <typename OpTy> bool match(OpTy *V) { |
895 | if (auto *I = dyn_cast<BinaryOperator>(V)) |
896 | return (L.match(I->getOperand(0)) && R.match(I->getOperand(1))) || |
897 | (Commutable && L.match(I->getOperand(1)) && |
898 | R.match(I->getOperand(0))); |
899 | return false; |
900 | } |
901 | }; |
902 | |
903 | template <typename LHS, typename RHS> |
904 | inline AnyBinaryOp_match<LHS, RHS> m_BinOp(const LHS &L, const RHS &R) { |
905 | return AnyBinaryOp_match<LHS, RHS>(L, R); |
906 | } |
907 | |
908 | //===----------------------------------------------------------------------===// |
909 | // Matcher for any unary operator. |
910 | // TODO fuse unary, binary matcher into n-ary matcher |
911 | // |
912 | template <typename OP_t> struct AnyUnaryOp_match { |
913 | OP_t X; |
914 | |
915 | AnyUnaryOp_match(const OP_t &X) : X(X) {} |
916 | |
917 | template <typename OpTy> bool match(OpTy *V) { |
918 | if (auto *I = dyn_cast<UnaryOperator>(V)) |
919 | return X.match(I->getOperand(0)); |
920 | return false; |
921 | } |
922 | }; |
923 | |
924 | template <typename OP_t> inline AnyUnaryOp_match<OP_t> m_UnOp(const OP_t &X) { |
925 | return AnyUnaryOp_match<OP_t>(X); |
926 | } |
927 | |
928 | //===----------------------------------------------------------------------===// |
929 | // Matchers for specific binary operators. |
930 | // |
931 | |
932 | template <typename LHS_t, typename RHS_t, unsigned Opcode, |
933 | bool Commutable = false> |
934 | struct BinaryOp_match { |
935 | LHS_t L; |
936 | RHS_t R; |
937 | |
938 | // The evaluation order is always stable, regardless of Commutability. |
939 | // The LHS is always matched first. |
940 | BinaryOp_match(const LHS_t &LHS, const RHS_t &RHS) : L(LHS), R(RHS) {} |
941 | |
942 | template <typename OpTy> bool match(OpTy *V) { |
943 | if (V->getValueID() == Value::InstructionVal + Opcode) { |
944 | auto *I = cast<BinaryOperator>(V); |
945 | return (L.match(I->getOperand(0)) && R.match(I->getOperand(1))) || |
946 | (Commutable && L.match(I->getOperand(1)) && |
947 | R.match(I->getOperand(0))); |
948 | } |
949 | if (auto *CE = dyn_cast<ConstantExpr>(V)) |
950 | return CE->getOpcode() == Opcode && |
951 | ((L.match(CE->getOperand(0)) && R.match(CE->getOperand(1))) || |
952 | (Commutable && L.match(CE->getOperand(1)) && |
953 | R.match(CE->getOperand(0)))); |
954 | return false; |
955 | } |
956 | }; |
957 | |
958 | template <typename LHS, typename RHS> |
959 | inline BinaryOp_match<LHS, RHS, Instruction::Add> m_Add(const LHS &L, |
960 | const RHS &R) { |
961 | return BinaryOp_match<LHS, RHS, Instruction::Add>(L, R); |
962 | } |
963 | |
964 | template <typename LHS, typename RHS> |
965 | inline BinaryOp_match<LHS, RHS, Instruction::FAdd> m_FAdd(const LHS &L, |
966 | const RHS &R) { |
967 | return BinaryOp_match<LHS, RHS, Instruction::FAdd>(L, R); |
968 | } |
969 | |
970 | template <typename LHS, typename RHS> |
971 | inline BinaryOp_match<LHS, RHS, Instruction::Sub> m_Sub(const LHS &L, |
972 | const RHS &R) { |
973 | return BinaryOp_match<LHS, RHS, Instruction::Sub>(L, R); |
974 | } |
975 | |
976 | template <typename LHS, typename RHS> |
977 | inline BinaryOp_match<LHS, RHS, Instruction::FSub> m_FSub(const LHS &L, |
978 | const RHS &R) { |
979 | return BinaryOp_match<LHS, RHS, Instruction::FSub>(L, R); |
980 | } |
981 | |
982 | template <typename Op_t> struct FNeg_match { |
983 | Op_t X; |
984 | |
985 | FNeg_match(const Op_t &Op) : X(Op) {} |
986 | template <typename OpTy> bool match(OpTy *V) { |
987 | auto *FPMO = dyn_cast<FPMathOperator>(V); |
988 | if (!FPMO) return false; |
989 | |
990 | if (FPMO->getOpcode() == Instruction::FNeg) |
991 | return X.match(FPMO->getOperand(0)); |
992 | |
993 | if (FPMO->getOpcode() == Instruction::FSub) { |
994 | if (FPMO->hasNoSignedZeros()) { |
995 | // With 'nsz', any zero goes. |
996 | if (!cstfp_pred_ty<is_any_zero_fp>().match(FPMO->getOperand(0))) |
997 | return false; |
998 | } else { |
999 | // Without 'nsz', we need fsub -0.0, X exactly. |
1000 | if (!cstfp_pred_ty<is_neg_zero_fp>().match(FPMO->getOperand(0))) |
1001 | return false; |
1002 | } |
1003 | |
1004 | return X.match(FPMO->getOperand(1)); |
1005 | } |
1006 | |
1007 | return false; |
1008 | } |
1009 | }; |
1010 | |
1011 | /// Match 'fneg X' as 'fsub -0.0, X'. |
1012 | template <typename OpTy> |
1013 | inline FNeg_match<OpTy> |
1014 | m_FNeg(const OpTy &X) { |
1015 | return FNeg_match<OpTy>(X); |
1016 | } |
1017 | |
1018 | /// Match 'fneg X' as 'fsub +-0.0, X'. |
1019 | template <typename RHS> |
1020 | inline BinaryOp_match<cstfp_pred_ty<is_any_zero_fp>, RHS, Instruction::FSub> |
1021 | m_FNegNSZ(const RHS &X) { |
1022 | return m_FSub(m_AnyZeroFP(), X); |
1023 | } |
1024 | |
1025 | template <typename LHS, typename RHS> |
1026 | inline BinaryOp_match<LHS, RHS, Instruction::Mul> m_Mul(const LHS &L, |
1027 | const RHS &R) { |
1028 | return BinaryOp_match<LHS, RHS, Instruction::Mul>(L, R); |
1029 | } |
1030 | |
1031 | template <typename LHS, typename RHS> |
1032 | inline BinaryOp_match<LHS, RHS, Instruction::FMul> m_FMul(const LHS &L, |
1033 | const RHS &R) { |
1034 | return BinaryOp_match<LHS, RHS, Instruction::FMul>(L, R); |
1035 | } |
1036 | |
1037 | template <typename LHS, typename RHS> |
1038 | inline BinaryOp_match<LHS, RHS, Instruction::UDiv> m_UDiv(const LHS &L, |
1039 | const RHS &R) { |
1040 | return BinaryOp_match<LHS, RHS, Instruction::UDiv>(L, R); |
1041 | } |
1042 | |
1043 | template <typename LHS, typename RHS> |
1044 | inline BinaryOp_match<LHS, RHS, Instruction::SDiv> m_SDiv(const LHS &L, |
1045 | const RHS &R) { |
1046 | return BinaryOp_match<LHS, RHS, Instruction::SDiv>(L, R); |
1047 | } |
1048 | |
1049 | template <typename LHS, typename RHS> |
1050 | inline BinaryOp_match<LHS, RHS, Instruction::FDiv> m_FDiv(const LHS &L, |
1051 | const RHS &R) { |
1052 | return BinaryOp_match<LHS, RHS, Instruction::FDiv>(L, R); |
1053 | } |
1054 | |
1055 | template <typename LHS, typename RHS> |
1056 | inline BinaryOp_match<LHS, RHS, Instruction::URem> m_URem(const LHS &L, |
1057 | const RHS &R) { |
1058 | return BinaryOp_match<LHS, RHS, Instruction::URem>(L, R); |
1059 | } |
1060 | |
1061 | template <typename LHS, typename RHS> |
1062 | inline BinaryOp_match<LHS, RHS, Instruction::SRem> m_SRem(const LHS &L, |
1063 | const RHS &R) { |
1064 | return BinaryOp_match<LHS, RHS, Instruction::SRem>(L, R); |
1065 | } |
1066 | |
1067 | template <typename LHS, typename RHS> |
1068 | inline BinaryOp_match<LHS, RHS, Instruction::FRem> m_FRem(const LHS &L, |
1069 | const RHS &R) { |
1070 | return BinaryOp_match<LHS, RHS, Instruction::FRem>(L, R); |
1071 | } |
1072 | |
1073 | template <typename LHS, typename RHS> |
1074 | inline BinaryOp_match<LHS, RHS, Instruction::And> m_And(const LHS &L, |
1075 | const RHS &R) { |
1076 | return BinaryOp_match<LHS, RHS, Instruction::And>(L, R); |
1077 | } |
1078 | |
1079 | template <typename LHS, typename RHS> |
1080 | inline BinaryOp_match<LHS, RHS, Instruction::Or> m_Or(const LHS &L, |
1081 | const RHS &R) { |
1082 | return BinaryOp_match<LHS, RHS, Instruction::Or>(L, R); |
1083 | } |
1084 | |
1085 | template <typename LHS, typename RHS> |
1086 | inline BinaryOp_match<LHS, RHS, Instruction::Xor> m_Xor(const LHS &L, |
1087 | const RHS &R) { |
1088 | return BinaryOp_match<LHS, RHS, Instruction::Xor>(L, R); |
1089 | } |
1090 | |
1091 | template <typename LHS, typename RHS> |
1092 | inline BinaryOp_match<LHS, RHS, Instruction::Shl> m_Shl(const LHS &L, |
1093 | const RHS &R) { |
1094 | return BinaryOp_match<LHS, RHS, Instruction::Shl>(L, R); |
1095 | } |
1096 | |
1097 | template <typename LHS, typename RHS> |
1098 | inline BinaryOp_match<LHS, RHS, Instruction::LShr> m_LShr(const LHS &L, |
1099 | const RHS &R) { |
1100 | return BinaryOp_match<LHS, RHS, Instruction::LShr>(L, R); |
1101 | } |
1102 | |
1103 | template <typename LHS, typename RHS> |
1104 | inline BinaryOp_match<LHS, RHS, Instruction::AShr> m_AShr(const LHS &L, |
1105 | const RHS &R) { |
1106 | return BinaryOp_match<LHS, RHS, Instruction::AShr>(L, R); |
1107 | } |
1108 | |
1109 | template <typename LHS_t, typename RHS_t, unsigned Opcode, |
1110 | unsigned WrapFlags = 0> |
1111 | struct OverflowingBinaryOp_match { |
1112 | LHS_t L; |
1113 | RHS_t R; |
1114 | |
1115 | OverflowingBinaryOp_match(const LHS_t &LHS, const RHS_t &RHS) |
1116 | : L(LHS), R(RHS) {} |
1117 | |
1118 | template <typename OpTy> bool match(OpTy *V) { |
1119 | if (auto *Op = dyn_cast<OverflowingBinaryOperator>(V)) { |
1120 | if (Op->getOpcode() != Opcode) |
1121 | return false; |
1122 | if (WrapFlags & OverflowingBinaryOperator::NoUnsignedWrap && |
1123 | !Op->hasNoUnsignedWrap()) |
1124 | return false; |
1125 | if (WrapFlags & OverflowingBinaryOperator::NoSignedWrap && |
1126 | !Op->hasNoSignedWrap()) |
1127 | return false; |
1128 | return L.match(Op->getOperand(0)) && R.match(Op->getOperand(1)); |
1129 | } |
1130 | return false; |
1131 | } |
1132 | }; |
1133 | |
1134 | template <typename LHS, typename RHS> |
1135 | inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Add, |
1136 | OverflowingBinaryOperator::NoSignedWrap> |
1137 | m_NSWAdd(const LHS &L, const RHS &R) { |
1138 | return OverflowingBinaryOp_match<LHS, RHS, Instruction::Add, |
1139 | OverflowingBinaryOperator::NoSignedWrap>( |
1140 | L, R); |
1141 | } |
1142 | template <typename LHS, typename RHS> |
1143 | inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Sub, |
1144 | OverflowingBinaryOperator::NoSignedWrap> |
1145 | m_NSWSub(const LHS &L, const RHS &R) { |
1146 | return OverflowingBinaryOp_match<LHS, RHS, Instruction::Sub, |
1147 | OverflowingBinaryOperator::NoSignedWrap>( |
1148 | L, R); |
1149 | } |
1150 | template <typename LHS, typename RHS> |
1151 | inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Mul, |
1152 | OverflowingBinaryOperator::NoSignedWrap> |
1153 | m_NSWMul(const LHS &L, const RHS &R) { |
1154 | return OverflowingBinaryOp_match<LHS, RHS, Instruction::Mul, |
1155 | OverflowingBinaryOperator::NoSignedWrap>( |
1156 | L, R); |
1157 | } |
1158 | template <typename LHS, typename RHS> |
1159 | inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Shl, |
1160 | OverflowingBinaryOperator::NoSignedWrap> |
1161 | m_NSWShl(const LHS &L, const RHS &R) { |
1162 | return OverflowingBinaryOp_match<LHS, RHS, Instruction::Shl, |
1163 | OverflowingBinaryOperator::NoSignedWrap>( |
1164 | L, R); |
1165 | } |
1166 | |
1167 | template <typename LHS, typename RHS> |
1168 | inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Add, |
1169 | OverflowingBinaryOperator::NoUnsignedWrap> |
1170 | m_NUWAdd(const LHS &L, const RHS &R) { |
1171 | return OverflowingBinaryOp_match<LHS, RHS, Instruction::Add, |
1172 | OverflowingBinaryOperator::NoUnsignedWrap>( |
1173 | L, R); |
1174 | } |
1175 | template <typename LHS, typename RHS> |
1176 | inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Sub, |
1177 | OverflowingBinaryOperator::NoUnsignedWrap> |
1178 | m_NUWSub(const LHS &L, const RHS &R) { |
1179 | return OverflowingBinaryOp_match<LHS, RHS, Instruction::Sub, |
1180 | OverflowingBinaryOperator::NoUnsignedWrap>( |
1181 | L, R); |
1182 | } |
1183 | template <typename LHS, typename RHS> |
1184 | inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Mul, |
1185 | OverflowingBinaryOperator::NoUnsignedWrap> |
1186 | m_NUWMul(const LHS &L, const RHS &R) { |
1187 | return OverflowingBinaryOp_match<LHS, RHS, Instruction::Mul, |
1188 | OverflowingBinaryOperator::NoUnsignedWrap>( |
1189 | L, R); |
1190 | } |
1191 | template <typename LHS, typename RHS> |
1192 | inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Shl, |
1193 | OverflowingBinaryOperator::NoUnsignedWrap> |
1194 | m_NUWShl(const LHS &L, const RHS &R) { |
1195 | return OverflowingBinaryOp_match<LHS, RHS, Instruction::Shl, |
1196 | OverflowingBinaryOperator::NoUnsignedWrap>( |
1197 | L, R); |
1198 | } |
1199 | |
1200 | //===----------------------------------------------------------------------===// |
1201 | // Class that matches a group of binary opcodes. |
1202 | // |
1203 | template <typename LHS_t, typename RHS_t, typename Predicate> |
1204 | struct BinOpPred_match : Predicate { |
1205 | LHS_t L; |
1206 | RHS_t R; |
1207 | |
1208 | BinOpPred_match(const LHS_t &LHS, const RHS_t &RHS) : L(LHS), R(RHS) {} |
1209 | |
1210 | template <typename OpTy> bool match(OpTy *V) { |
1211 | if (auto *I = dyn_cast<Instruction>(V)) |
1212 | return this->isOpType(I->getOpcode()) && L.match(I->getOperand(0)) && |
1213 | R.match(I->getOperand(1)); |
1214 | if (auto *CE = dyn_cast<ConstantExpr>(V)) |
1215 | return this->isOpType(CE->getOpcode()) && L.match(CE->getOperand(0)) && |
1216 | R.match(CE->getOperand(1)); |
1217 | return false; |
1218 | } |
1219 | }; |
1220 | |
1221 | struct is_shift_op { |
1222 | bool isOpType(unsigned Opcode) { return Instruction::isShift(Opcode); } |
1223 | }; |
1224 | |
1225 | struct is_right_shift_op { |
1226 | bool isOpType(unsigned Opcode) { |
1227 | return Opcode == Instruction::LShr || Opcode == Instruction::AShr; |
1228 | } |
1229 | }; |
1230 | |
1231 | struct is_logical_shift_op { |
1232 | bool isOpType(unsigned Opcode) { |
1233 | return Opcode == Instruction::LShr || Opcode == Instruction::Shl; |
1234 | } |
1235 | }; |
1236 | |
1237 | struct is_bitwiselogic_op { |
1238 | bool isOpType(unsigned Opcode) { |
1239 | return Instruction::isBitwiseLogicOp(Opcode); |
1240 | } |
1241 | }; |
1242 | |
1243 | struct is_idiv_op { |
1244 | bool isOpType(unsigned Opcode) { |
1245 | return Opcode == Instruction::SDiv || Opcode == Instruction::UDiv; |
1246 | } |
1247 | }; |
1248 | |
1249 | struct is_irem_op { |
1250 | bool isOpType(unsigned Opcode) { |
1251 | return Opcode == Instruction::SRem || Opcode == Instruction::URem; |
1252 | } |
1253 | }; |
1254 | |
1255 | /// Matches shift operations. |
1256 | template <typename LHS, typename RHS> |
1257 | inline BinOpPred_match<LHS, RHS, is_shift_op> m_Shift(const LHS &L, |
1258 | const RHS &R) { |
1259 | return BinOpPred_match<LHS, RHS, is_shift_op>(L, R); |
1260 | } |
1261 | |
1262 | /// Matches logical shift operations. |
1263 | template <typename LHS, typename RHS> |
1264 | inline BinOpPred_match<LHS, RHS, is_right_shift_op> m_Shr(const LHS &L, |
1265 | const RHS &R) { |
1266 | return BinOpPred_match<LHS, RHS, is_right_shift_op>(L, R); |
1267 | } |
1268 | |
1269 | /// Matches logical shift operations. |
1270 | template <typename LHS, typename RHS> |
1271 | inline BinOpPred_match<LHS, RHS, is_logical_shift_op> |
1272 | m_LogicalShift(const LHS &L, const RHS &R) { |
1273 | return BinOpPred_match<LHS, RHS, is_logical_shift_op>(L, R); |
1274 | } |
1275 | |
1276 | /// Matches bitwise logic operations. |
1277 | template <typename LHS, typename RHS> |
1278 | inline BinOpPred_match<LHS, RHS, is_bitwiselogic_op> |
1279 | m_BitwiseLogic(const LHS &L, const RHS &R) { |
1280 | return BinOpPred_match<LHS, RHS, is_bitwiselogic_op>(L, R); |
1281 | } |
1282 | |
1283 | /// Matches integer division operations. |
1284 | template <typename LHS, typename RHS> |
1285 | inline BinOpPred_match<LHS, RHS, is_idiv_op> m_IDiv(const LHS &L, |
1286 | const RHS &R) { |
1287 | return BinOpPred_match<LHS, RHS, is_idiv_op>(L, R); |
1288 | } |
1289 | |
1290 | /// Matches integer remainder operations. |
1291 | template <typename LHS, typename RHS> |
1292 | inline BinOpPred_match<LHS, RHS, is_irem_op> m_IRem(const LHS &L, |
1293 | const RHS &R) { |
1294 | return BinOpPred_match<LHS, RHS, is_irem_op>(L, R); |
1295 | } |
1296 | |
1297 | //===----------------------------------------------------------------------===// |
1298 | // Class that matches exact binary ops. |
1299 | // |
1300 | template <typename SubPattern_t> struct Exact_match { |
1301 | SubPattern_t SubPattern; |
1302 | |
1303 | Exact_match(const SubPattern_t &SP) : SubPattern(SP) {} |
1304 | |
1305 | template <typename OpTy> bool match(OpTy *V) { |
1306 | if (auto *PEO = dyn_cast<PossiblyExactOperator>(V)) |
1307 | return PEO->isExact() && SubPattern.match(V); |
1308 | return false; |
1309 | } |
1310 | }; |
1311 | |
1312 | template <typename T> inline Exact_match<T> m_Exact(const T &SubPattern) { |
1313 | return SubPattern; |
1314 | } |
1315 | |
1316 | //===----------------------------------------------------------------------===// |
1317 | // Matchers for CmpInst classes |
1318 | // |
1319 | |
1320 | template <typename LHS_t, typename RHS_t, typename Class, typename PredicateTy, |
1321 | bool Commutable = false> |
1322 | struct CmpClass_match { |
1323 | PredicateTy &Predicate; |
1324 | LHS_t L; |
1325 | RHS_t R; |
1326 | |
1327 | // The evaluation order is always stable, regardless of Commutability. |
1328 | // The LHS is always matched first. |
1329 | CmpClass_match(PredicateTy &Pred, const LHS_t &LHS, const RHS_t &RHS) |
1330 | : Predicate(Pred), L(LHS), R(RHS) {} |
1331 | |
1332 | template <typename OpTy> bool match(OpTy *V) { |
1333 | if (auto *I = dyn_cast<Class>(V)) { |
1334 | if (L.match(I->getOperand(0)) && R.match(I->getOperand(1))) { |
1335 | Predicate = I->getPredicate(); |
1336 | return true; |
1337 | } else if (Commutable && L.match(I->getOperand(1)) && |
1338 | R.match(I->getOperand(0))) { |
1339 | Predicate = I->getSwappedPredicate(); |
1340 | return true; |
1341 | } |
1342 | } |
1343 | return false; |
1344 | } |
1345 | }; |
1346 | |
1347 | template <typename LHS, typename RHS> |
1348 | inline CmpClass_match<LHS, RHS, CmpInst, CmpInst::Predicate> |
1349 | m_Cmp(CmpInst::Predicate &Pred, const LHS &L, const RHS &R) { |
1350 | return CmpClass_match<LHS, RHS, CmpInst, CmpInst::Predicate>(Pred, L, R); |
1351 | } |
1352 | |
1353 | template <typename LHS, typename RHS> |
1354 | inline CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate> |
1355 | m_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R) { |
1356 | return CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>(Pred, L, R); |
1357 | } |
1358 | |
1359 | template <typename LHS, typename RHS> |
1360 | inline CmpClass_match<LHS, RHS, FCmpInst, FCmpInst::Predicate> |
1361 | m_FCmp(FCmpInst::Predicate &Pred, const LHS &L, const RHS &R) { |
1362 | return CmpClass_match<LHS, RHS, FCmpInst, FCmpInst::Predicate>(Pred, L, R); |
1363 | } |
1364 | |
1365 | //===----------------------------------------------------------------------===// |
1366 | // Matchers for instructions with a given opcode and number of operands. |
1367 | // |
1368 | |
1369 | /// Matches instructions with Opcode and three operands. |
1370 | template <typename T0, unsigned Opcode> struct OneOps_match { |
1371 | T0 Op1; |
1372 | |
1373 | OneOps_match(const T0 &Op1) : Op1(Op1) {} |
1374 | |
1375 | template <typename OpTy> bool match(OpTy *V) { |
1376 | if (V->getValueID() == Value::InstructionVal + Opcode) { |
1377 | auto *I = cast<Instruction>(V); |
1378 | return Op1.match(I->getOperand(0)); |
1379 | } |
1380 | return false; |
1381 | } |
1382 | }; |
1383 | |
1384 | /// Matches instructions with Opcode and three operands. |
1385 | template <typename T0, typename T1, unsigned Opcode> struct TwoOps_match { |
1386 | T0 Op1; |
1387 | T1 Op2; |
1388 | |
1389 | TwoOps_match(const T0 &Op1, const T1 &Op2) : Op1(Op1), Op2(Op2) {} |
1390 | |
1391 | template <typename OpTy> bool match(OpTy *V) { |
1392 | if (V->getValueID() == Value::InstructionVal + Opcode) { |
1393 | auto *I = cast<Instruction>(V); |
1394 | return Op1.match(I->getOperand(0)) && Op2.match(I->getOperand(1)); |
1395 | } |
1396 | return false; |
1397 | } |
1398 | }; |
1399 | |
1400 | /// Matches instructions with Opcode and three operands. |
1401 | template <typename T0, typename T1, typename T2, unsigned Opcode> |
1402 | struct ThreeOps_match { |
1403 | T0 Op1; |
1404 | T1 Op2; |
1405 | T2 Op3; |
1406 | |
1407 | ThreeOps_match(const T0 &Op1, const T1 &Op2, const T2 &Op3) |
1408 | : Op1(Op1), Op2(Op2), Op3(Op3) {} |
1409 | |
1410 | template <typename OpTy> bool match(OpTy *V) { |
1411 | if (V->getValueID() == Value::InstructionVal + Opcode) { |
1412 | auto *I = cast<Instruction>(V); |
1413 | return Op1.match(I->getOperand(0)) && Op2.match(I->getOperand(1)) && |
1414 | Op3.match(I->getOperand(2)); |
1415 | } |
1416 | return false; |
1417 | } |
1418 | }; |
1419 | |
1420 | /// Matches SelectInst. |
1421 | template <typename Cond, typename LHS, typename RHS> |
1422 | inline ThreeOps_match<Cond, LHS, RHS, Instruction::Select> |
1423 | m_Select(const Cond &C, const LHS &L, const RHS &R) { |
1424 | return ThreeOps_match<Cond, LHS, RHS, Instruction::Select>(C, L, R); |
1425 | } |
1426 | |
1427 | /// This matches a select of two constants, e.g.: |
1428 | /// m_SelectCst<-1, 0>(m_Value(V)) |
1429 | template <int64_t L, int64_t R, typename Cond> |
1430 | inline ThreeOps_match<Cond, constantint_match<L>, constantint_match<R>, |
1431 | Instruction::Select> |
1432 | m_SelectCst(const Cond &C) { |
1433 | return m_Select(C, m_ConstantInt<L>(), m_ConstantInt<R>()); |
1434 | } |
1435 | |
1436 | /// Matches FreezeInst. |
1437 | template <typename OpTy> |
1438 | inline OneOps_match<OpTy, Instruction::Freeze> m_Freeze(const OpTy &Op) { |
1439 | return OneOps_match<OpTy, Instruction::Freeze>(Op); |
1440 | } |
1441 | |
1442 | /// Matches InsertElementInst. |
1443 | template <typename Val_t, typename Elt_t, typename Idx_t> |
1444 | inline ThreeOps_match<Val_t, Elt_t, Idx_t, Instruction::InsertElement> |
1445 | m_InsertElt(const Val_t &Val, const Elt_t &Elt, const Idx_t &Idx) { |
1446 | return ThreeOps_match<Val_t, Elt_t, Idx_t, Instruction::InsertElement>( |
1447 | Val, Elt, Idx); |
1448 | } |
1449 | |
1450 | /// Matches ExtractElementInst. |
1451 | template <typename Val_t, typename Idx_t> |
1452 | inline TwoOps_match<Val_t, Idx_t, Instruction::ExtractElement> |
1453 | m_ExtractElt(const Val_t &Val, const Idx_t &Idx) { |
1454 | return TwoOps_match<Val_t, Idx_t, Instruction::ExtractElement>(Val, Idx); |
1455 | } |
1456 | |
1457 | /// Matches shuffle. |
1458 | template <typename T0, typename T1, typename T2> struct Shuffle_match { |
1459 | T0 Op1; |
1460 | T1 Op2; |
1461 | T2 Mask; |
1462 | |
1463 | Shuffle_match(const T0 &Op1, const T1 &Op2, const T2 &Mask) |
1464 | : Op1(Op1), Op2(Op2), Mask(Mask) {} |
1465 | |
1466 | template <typename OpTy> bool match(OpTy *V) { |
1467 | if (auto *I = dyn_cast<ShuffleVectorInst>(V)) { |
1468 | return Op1.match(I->getOperand(0)) && Op2.match(I->getOperand(1)) && |
1469 | Mask.match(I->getShuffleMask()); |
1470 | } |
1471 | return false; |
1472 | } |
1473 | }; |
1474 | |
1475 | struct m_Mask { |
1476 | ArrayRef<int> &MaskRef; |
1477 | m_Mask(ArrayRef<int> &MaskRef) : MaskRef(MaskRef) {} |
1478 | bool match(ArrayRef<int> Mask) { |
1479 | MaskRef = Mask; |
1480 | return true; |
1481 | } |
1482 | }; |
1483 | |
1484 | struct m_ZeroMask { |
1485 | bool match(ArrayRef<int> Mask) { |
1486 | return all_of(Mask, [](int Elem) { return Elem == 0 || Elem == -1; }); |
1487 | } |
1488 | }; |
1489 | |
1490 | struct m_SpecificMask { |
1491 | ArrayRef<int> &MaskRef; |
1492 | m_SpecificMask(ArrayRef<int> &MaskRef) : MaskRef(MaskRef) {} |
1493 | bool match(ArrayRef<int> Mask) { return MaskRef == Mask; } |
1494 | }; |
1495 | |
1496 | struct m_SplatOrUndefMask { |
1497 | int &SplatIndex; |
1498 | m_SplatOrUndefMask(int &SplatIndex) : SplatIndex(SplatIndex) {} |
1499 | bool match(ArrayRef<int> Mask) { |
1500 | auto First = find_if(Mask, [](int Elem) { return Elem != -1; }); |
1501 | if (First == Mask.end()) |
1502 | return false; |
1503 | SplatIndex = *First; |
1504 | return all_of(Mask, |
1505 | [First](int Elem) { return Elem == *First || Elem == -1; }); |
1506 | } |
1507 | }; |
1508 | |
1509 | /// Matches ShuffleVectorInst independently of mask value. |
1510 | template <typename V1_t, typename V2_t> |
1511 | inline TwoOps_match<V1_t, V2_t, Instruction::ShuffleVector> |
1512 | m_Shuffle(const V1_t &v1, const V2_t &v2) { |
1513 | return TwoOps_match<V1_t, V2_t, Instruction::ShuffleVector>(v1, v2); |
1514 | } |
1515 | |
1516 | template <typename V1_t, typename V2_t, typename Mask_t> |
1517 | inline Shuffle_match<V1_t, V2_t, Mask_t> |
1518 | m_Shuffle(const V1_t &v1, const V2_t &v2, const Mask_t &mask) { |
1519 | return Shuffle_match<V1_t, V2_t, Mask_t>(v1, v2, mask); |
1520 | } |
1521 | |
1522 | /// Matches LoadInst. |
1523 | template <typename OpTy> |
1524 | inline OneOps_match<OpTy, Instruction::Load> m_Load(const OpTy &Op) { |
1525 | return OneOps_match<OpTy, Instruction::Load>(Op); |
1526 | } |
1527 | |
1528 | /// Matches StoreInst. |
1529 | template <typename ValueOpTy, typename PointerOpTy> |
1530 | inline TwoOps_match<ValueOpTy, PointerOpTy, Instruction::Store> |
1531 | m_Store(const ValueOpTy &ValueOp, const PointerOpTy &PointerOp) { |
1532 | return TwoOps_match<ValueOpTy, PointerOpTy, Instruction::Store>(ValueOp, |
1533 | PointerOp); |
1534 | } |
1535 | |
1536 | //===----------------------------------------------------------------------===// |
1537 | // Matchers for CastInst classes |
1538 | // |
1539 | |
1540 | template <typename Op_t, unsigned Opcode> struct CastClass_match { |
1541 | Op_t Op; |
1542 | |
1543 | CastClass_match(const Op_t &OpMatch) : Op(OpMatch) {} |
1544 | |
1545 | template <typename OpTy> bool match(OpTy *V) { |
1546 | if (auto *O = dyn_cast<Operator>(V)) |
1547 | return O->getOpcode() == Opcode && Op.match(O->getOperand(0)); |
1548 | return false; |
1549 | } |
1550 | }; |
1551 | |
1552 | /// Matches BitCast. |
1553 | template <typename OpTy> |
1554 | inline CastClass_match<OpTy, Instruction::BitCast> m_BitCast(const OpTy &Op) { |
1555 | return CastClass_match<OpTy, Instruction::BitCast>(Op); |
1556 | } |
1557 | |
1558 | /// Matches PtrToInt. |
1559 | template <typename OpTy> |
1560 | inline CastClass_match<OpTy, Instruction::PtrToInt> m_PtrToInt(const OpTy &Op) { |
1561 | return CastClass_match<OpTy, Instruction::PtrToInt>(Op); |
1562 | } |
1563 | |
1564 | /// Matches IntToPtr. |
1565 | template <typename OpTy> |
1566 | inline CastClass_match<OpTy, Instruction::IntToPtr> m_IntToPtr(const OpTy &Op) { |
1567 | return CastClass_match<OpTy, Instruction::IntToPtr>(Op); |
1568 | } |
1569 | |
1570 | /// Matches Trunc. |
1571 | template <typename OpTy> |
1572 | inline CastClass_match<OpTy, Instruction::Trunc> m_Trunc(const OpTy &Op) { |
1573 | return CastClass_match<OpTy, Instruction::Trunc>(Op); |
1574 | } |
1575 | |
1576 | template <typename OpTy> |
1577 | inline match_combine_or<CastClass_match<OpTy, Instruction::Trunc>, OpTy> |
1578 | m_TruncOrSelf(const OpTy &Op) { |
1579 | return m_CombineOr(m_Trunc(Op), Op); |
1580 | } |
1581 | |
1582 | /// Matches SExt. |
1583 | template <typename OpTy> |
1584 | inline CastClass_match<OpTy, Instruction::SExt> m_SExt(const OpTy &Op) { |
1585 | return CastClass_match<OpTy, Instruction::SExt>(Op); |
1586 | } |
1587 | |
1588 | /// Matches ZExt. |
1589 | template <typename OpTy> |
1590 | inline CastClass_match<OpTy, Instruction::ZExt> m_ZExt(const OpTy &Op) { |
1591 | return CastClass_match<OpTy, Instruction::ZExt>(Op); |
1592 | } |
1593 | |
1594 | template <typename OpTy> |
1595 | inline match_combine_or<CastClass_match<OpTy, Instruction::ZExt>, OpTy> |
1596 | m_ZExtOrSelf(const OpTy &Op) { |
1597 | return m_CombineOr(m_ZExt(Op), Op); |
1598 | } |
1599 | |
1600 | template <typename OpTy> |
1601 | inline match_combine_or<CastClass_match<OpTy, Instruction::SExt>, OpTy> |
1602 | m_SExtOrSelf(const OpTy &Op) { |
1603 | return m_CombineOr(m_SExt(Op), Op); |
1604 | } |
1605 | |
1606 | template <typename OpTy> |
1607 | inline match_combine_or<CastClass_match<OpTy, Instruction::ZExt>, |
1608 | CastClass_match<OpTy, Instruction::SExt>> |
1609 | m_ZExtOrSExt(const OpTy &Op) { |
1610 | return m_CombineOr(m_ZExt(Op), m_SExt(Op)); |
1611 | } |
1612 | |
1613 | template <typename OpTy> |
1614 | inline match_combine_or< |
1615 | match_combine_or<CastClass_match<OpTy, Instruction::ZExt>, |
1616 | CastClass_match<OpTy, Instruction::SExt>>, |
1617 | OpTy> |
1618 | m_ZExtOrSExtOrSelf(const OpTy &Op) { |
1619 | return m_CombineOr(m_ZExtOrSExt(Op), Op); |
1620 | } |
1621 | |
1622 | template <typename OpTy> |
1623 | inline CastClass_match<OpTy, Instruction::UIToFP> m_UIToFP(const OpTy &Op) { |
1624 | return CastClass_match<OpTy, Instruction::UIToFP>(Op); |
1625 | } |
1626 | |
1627 | template <typename OpTy> |
1628 | inline CastClass_match<OpTy, Instruction::SIToFP> m_SIToFP(const OpTy &Op) { |
1629 | return CastClass_match<OpTy, Instruction::SIToFP>(Op); |
1630 | } |
1631 | |
1632 | template <typename OpTy> |
1633 | inline CastClass_match<OpTy, Instruction::FPToUI> m_FPToUI(const OpTy &Op) { |
1634 | return CastClass_match<OpTy, Instruction::FPToUI>(Op); |
1635 | } |
1636 | |
1637 | template <typename OpTy> |
1638 | inline CastClass_match<OpTy, Instruction::FPToSI> m_FPToSI(const OpTy &Op) { |
1639 | return CastClass_match<OpTy, Instruction::FPToSI>(Op); |
1640 | } |
1641 | |
1642 | template <typename OpTy> |
1643 | inline CastClass_match<OpTy, Instruction::FPTrunc> m_FPTrunc(const OpTy &Op) { |
1644 | return CastClass_match<OpTy, Instruction::FPTrunc>(Op); |
1645 | } |
1646 | |
1647 | template <typename OpTy> |
1648 | inline CastClass_match<OpTy, Instruction::FPExt> m_FPExt(const OpTy &Op) { |
1649 | return CastClass_match<OpTy, Instruction::FPExt>(Op); |
1650 | } |
1651 | |
1652 | //===----------------------------------------------------------------------===// |
1653 | // Matchers for control flow. |
1654 | // |
1655 | |
1656 | struct br_match { |
1657 | BasicBlock *&Succ; |
1658 | |
1659 | br_match(BasicBlock *&Succ) : Succ(Succ) {} |
1660 | |
1661 | template <typename OpTy> bool match(OpTy *V) { |
1662 | if (auto *BI = dyn_cast<BranchInst>(V)) |
1663 | if (BI->isUnconditional()) { |
1664 | Succ = BI->getSuccessor(0); |
1665 | return true; |
1666 | } |
1667 | return false; |
1668 | } |
1669 | }; |
1670 | |
1671 | inline br_match m_UnconditionalBr(BasicBlock *&Succ) { return br_match(Succ); } |
1672 | |
1673 | template <typename Cond_t, typename TrueBlock_t, typename FalseBlock_t> |
1674 | struct brc_match { |
1675 | Cond_t Cond; |
1676 | TrueBlock_t T; |
1677 | FalseBlock_t F; |
1678 | |
1679 | brc_match(const Cond_t &C, const TrueBlock_t &t, const FalseBlock_t &f) |
1680 | : Cond(C), T(t), F(f) {} |
1681 | |
1682 | template <typename OpTy> bool match(OpTy *V) { |
1683 | if (auto *BI = dyn_cast<BranchInst>(V)) |
1684 | if (BI->isConditional() && Cond.match(BI->getCondition())) |
1685 | return T.match(BI->getSuccessor(0)) && F.match(BI->getSuccessor(1)); |
1686 | return false; |
1687 | } |
1688 | }; |
1689 | |
1690 | template <typename Cond_t> |
1691 | inline brc_match<Cond_t, bind_ty<BasicBlock>, bind_ty<BasicBlock>> |
1692 | m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F) { |
1693 | return brc_match<Cond_t, bind_ty<BasicBlock>, bind_ty<BasicBlock>>( |
1694 | C, m_BasicBlock(T), m_BasicBlock(F)); |
1695 | } |
1696 | |
1697 | template <typename Cond_t, typename TrueBlock_t, typename FalseBlock_t> |
1698 | inline brc_match<Cond_t, TrueBlock_t, FalseBlock_t> |
1699 | m_Br(const Cond_t &C, const TrueBlock_t &T, const FalseBlock_t &F) { |
1700 | return brc_match<Cond_t, TrueBlock_t, FalseBlock_t>(C, T, F); |
1701 | } |
1702 | |
1703 | //===----------------------------------------------------------------------===// |
1704 | // Matchers for max/min idioms, eg: "select (sgt x, y), x, y" -> smax(x,y). |
1705 | // |
1706 | |
1707 | template <typename CmpInst_t, typename LHS_t, typename RHS_t, typename Pred_t, |
1708 | bool Commutable = false> |
1709 | struct MaxMin_match { |
1710 | LHS_t L; |
1711 | RHS_t R; |
1712 | |
1713 | // The evaluation order is always stable, regardless of Commutability. |
1714 | // The LHS is always matched first. |
1715 | MaxMin_match(const LHS_t &LHS, const RHS_t &RHS) : L(LHS), R(RHS) {} |
1716 | |
1717 | template <typename OpTy> bool match(OpTy *V) { |
1718 | if (auto *II = dyn_cast<IntrinsicInst>(V)) { |
1719 | Intrinsic::ID IID = II->getIntrinsicID(); |
1720 | if ((IID == Intrinsic::smax && Pred_t::match(ICmpInst::ICMP_SGT)) || |
1721 | (IID == Intrinsic::smin && Pred_t::match(ICmpInst::ICMP_SLT)) || |
1722 | (IID == Intrinsic::umax && Pred_t::match(ICmpInst::ICMP_UGT)) || |
1723 | (IID == Intrinsic::umin && Pred_t::match(ICmpInst::ICMP_ULT))) { |
1724 | Value *LHS = II->getOperand(0), *RHS = II->getOperand(1); |
1725 | return (L.match(LHS) && R.match(RHS)) || |
1726 | (Commutable && L.match(RHS) && R.match(LHS)); |
1727 | } |
1728 | } |
1729 | // Look for "(x pred y) ? x : y" or "(x pred y) ? y : x". |
1730 | auto *SI = dyn_cast<SelectInst>(V); |
1731 | if (!SI) |
1732 | return false; |
1733 | auto *Cmp = dyn_cast<CmpInst_t>(SI->getCondition()); |
1734 | if (!Cmp) |
1735 | return false; |
1736 | // At this point we have a select conditioned on a comparison. Check that |
1737 | // it is the values returned by the select that are being compared. |
1738 | Value *TrueVal = SI->getTrueValue(); |
1739 | Value *FalseVal = SI->getFalseValue(); |
1740 | Value *LHS = Cmp->getOperand(0); |
1741 | Value *RHS = Cmp->getOperand(1); |
1742 | if ((TrueVal != LHS || FalseVal != RHS) && |
1743 | (TrueVal != RHS || FalseVal != LHS)) |
1744 | return false; |
1745 | typename CmpInst_t::Predicate Pred = |
1746 | LHS == TrueVal ? Cmp->getPredicate() : Cmp->getInversePredicate(); |
1747 | // Does "(x pred y) ? x : y" represent the desired max/min operation? |
1748 | if (!Pred_t::match(Pred)) |
1749 | return false; |
1750 | // It does! Bind the operands. |
1751 | return (L.match(LHS) && R.match(RHS)) || |
1752 | (Commutable && L.match(RHS) && R.match(LHS)); |
1753 | } |
1754 | }; |
1755 | |
1756 | /// Helper class for identifying signed max predicates. |
1757 | struct smax_pred_ty { |
1758 | static bool match(ICmpInst::Predicate Pred) { |
1759 | return Pred == CmpInst::ICMP_SGT || Pred == CmpInst::ICMP_SGE; |
1760 | } |
1761 | }; |
1762 | |
1763 | /// Helper class for identifying signed min predicates. |
1764 | struct smin_pred_ty { |
1765 | static bool match(ICmpInst::Predicate Pred) { |
1766 | return Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_SLE; |
1767 | } |
1768 | }; |
1769 | |
1770 | /// Helper class for identifying unsigned max predicates. |
1771 | struct umax_pred_ty { |
1772 | static bool match(ICmpInst::Predicate Pred) { |
1773 | return Pred == CmpInst::ICMP_UGT || Pred == CmpInst::ICMP_UGE; |
1774 | } |
1775 | }; |
1776 | |
1777 | /// Helper class for identifying unsigned min predicates. |
1778 | struct umin_pred_ty { |
1779 | static bool match(ICmpInst::Predicate Pred) { |
1780 | return Pred == CmpInst::ICMP_ULT || Pred == CmpInst::ICMP_ULE; |
1781 | } |
1782 | }; |
1783 | |
1784 | /// Helper class for identifying ordered max predicates. |
1785 | struct ofmax_pred_ty { |
1786 | static bool match(FCmpInst::Predicate Pred) { |
1787 | return Pred == CmpInst::FCMP_OGT || Pred == CmpInst::FCMP_OGE; |
1788 | } |
1789 | }; |
1790 | |
1791 | /// Helper class for identifying ordered min predicates. |
1792 | struct ofmin_pred_ty { |
1793 | static bool match(FCmpInst::Predicate Pred) { |
1794 | return Pred == CmpInst::FCMP_OLT || Pred == CmpInst::FCMP_OLE; |
1795 | } |
1796 | }; |
1797 | |
1798 | /// Helper class for identifying unordered max predicates. |
1799 | struct ufmax_pred_ty { |
1800 | static bool match(FCmpInst::Predicate Pred) { |
1801 | return Pred == CmpInst::FCMP_UGT || Pred == CmpInst::FCMP_UGE; |
1802 | } |
1803 | }; |
1804 | |
1805 | /// Helper class for identifying unordered min predicates. |
1806 | struct ufmin_pred_ty { |
1807 | static bool match(FCmpInst::Predicate Pred) { |
1808 | return Pred == CmpInst::FCMP_ULT || Pred == CmpInst::FCMP_ULE; |
1809 | } |
1810 | }; |
1811 | |
1812 | template <typename LHS, typename RHS> |
1813 | inline MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty> m_SMax(const LHS &L, |
1814 | const RHS &R) { |
1815 | return MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty>(L, R); |
1816 | } |
1817 | |
1818 | template <typename LHS, typename RHS> |
1819 | inline MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty> m_SMin(const LHS &L, |
1820 | const RHS &R) { |
1821 | return MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty>(L, R); |
1822 | } |
1823 | |
1824 | template <typename LHS, typename RHS> |
1825 | inline MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty> m_UMax(const LHS &L, |
1826 | const RHS &R) { |
1827 | return MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty>(L, R); |
1828 | } |
1829 | |
1830 | template <typename LHS, typename RHS> |
1831 | inline MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty> m_UMin(const LHS &L, |
1832 | const RHS &R) { |
1833 | return MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty>(L, R); |
1834 | } |
1835 | |
1836 | template <typename LHS, typename RHS> |
1837 | inline match_combine_or< |
1838 | match_combine_or<MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty>, |
1839 | MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty>>, |
1840 | match_combine_or<MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty>, |
1841 | MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty>>> |
1842 | m_MaxOrMin(const LHS &L, const RHS &R) { |
1843 | return m_CombineOr(m_CombineOr(m_SMax(L, R), m_SMin(L, R)), |
1844 | m_CombineOr(m_UMax(L, R), m_UMin(L, R))); |
1845 | } |
1846 | |
1847 | /// Match an 'ordered' floating point maximum function. |
1848 | /// Floating point has one special value 'NaN'. Therefore, there is no total |
1849 | /// order. However, if we can ignore the 'NaN' value (for example, because of a |
1850 | /// 'no-nans-float-math' flag) a combination of a fcmp and select has 'maximum' |
1851 | /// semantics. In the presence of 'NaN' we have to preserve the original |
1852 | /// select(fcmp(ogt/ge, L, R), L, R) semantics matched by this predicate. |
1853 | /// |
1854 | /// max(L, R) iff L and R are not NaN |
1855 | /// m_OrdFMax(L, R) = R iff L or R are NaN |
1856 | template <typename LHS, typename RHS> |
1857 | inline MaxMin_match<FCmpInst, LHS, RHS, ofmax_pred_ty> m_OrdFMax(const LHS &L, |
1858 | const RHS &R) { |
1859 | return MaxMin_match<FCmpInst, LHS, RHS, ofmax_pred_ty>(L, R); |
1860 | } |
1861 | |
1862 | /// Match an 'ordered' floating point minimum function. |
1863 | /// Floating point has one special value 'NaN'. Therefore, there is no total |
1864 | /// order. However, if we can ignore the 'NaN' value (for example, because of a |
1865 | /// 'no-nans-float-math' flag) a combination of a fcmp and select has 'minimum' |
1866 | /// semantics. In the presence of 'NaN' we have to preserve the original |
1867 | /// select(fcmp(olt/le, L, R), L, R) semantics matched by this predicate. |
1868 | /// |
1869 | /// min(L, R) iff L and R are not NaN |
1870 | /// m_OrdFMin(L, R) = R iff L or R are NaN |
1871 | template <typename LHS, typename RHS> |
1872 | inline MaxMin_match<FCmpInst, LHS, RHS, ofmin_pred_ty> m_OrdFMin(const LHS &L, |
1873 | const RHS &R) { |
1874 | return MaxMin_match<FCmpInst, LHS, RHS, ofmin_pred_ty>(L, R); |
1875 | } |
1876 | |
1877 | /// Match an 'unordered' floating point maximum function. |
1878 | /// Floating point has one special value 'NaN'. Therefore, there is no total |
1879 | /// order. However, if we can ignore the 'NaN' value (for example, because of a |
1880 | /// 'no-nans-float-math' flag) a combination of a fcmp and select has 'maximum' |
1881 | /// semantics. In the presence of 'NaN' we have to preserve the original |
1882 | /// select(fcmp(ugt/ge, L, R), L, R) semantics matched by this predicate. |
1883 | /// |
1884 | /// max(L, R) iff L and R are not NaN |
1885 | /// m_UnordFMax(L, R) = L iff L or R are NaN |
1886 | template <typename LHS, typename RHS> |
1887 | inline MaxMin_match<FCmpInst, LHS, RHS, ufmax_pred_ty> |
1888 | m_UnordFMax(const LHS &L, const RHS &R) { |
1889 | return MaxMin_match<FCmpInst, LHS, RHS, ufmax_pred_ty>(L, R); |
1890 | } |
1891 | |
1892 | /// Match an 'unordered' floating point minimum function. |
1893 | /// Floating point has one special value 'NaN'. Therefore, there is no total |
1894 | /// order. However, if we can ignore the 'NaN' value (for example, because of a |
1895 | /// 'no-nans-float-math' flag) a combination of a fcmp and select has 'minimum' |
1896 | /// semantics. In the presence of 'NaN' we have to preserve the original |
1897 | /// select(fcmp(ult/le, L, R), L, R) semantics matched by this predicate. |
1898 | /// |
1899 | /// min(L, R) iff L and R are not NaN |
1900 | /// m_UnordFMin(L, R) = L iff L or R are NaN |
1901 | template <typename LHS, typename RHS> |
1902 | inline MaxMin_match<FCmpInst, LHS, RHS, ufmin_pred_ty> |
1903 | m_UnordFMin(const LHS &L, const RHS &R) { |
1904 | return MaxMin_match<FCmpInst, LHS, RHS, ufmin_pred_ty>(L, R); |
1905 | } |
1906 | |
1907 | //===----------------------------------------------------------------------===// |
1908 | // Matchers for overflow check patterns: e.g. (a + b) u< a, (a ^ -1) <u b |
1909 | // Note that S might be matched to other instructions than AddInst. |
1910 | // |
1911 | |
1912 | template <typename LHS_t, typename RHS_t, typename Sum_t> |
1913 | struct UAddWithOverflow_match { |
1914 | LHS_t L; |
1915 | RHS_t R; |
1916 | Sum_t S; |
1917 | |
1918 | UAddWithOverflow_match(const LHS_t &L, const RHS_t &R, const Sum_t &S) |
1919 | : L(L), R(R), S(S) {} |
1920 | |
1921 | template <typename OpTy> bool match(OpTy *V) { |
1922 | Value *ICmpLHS, *ICmpRHS; |
1923 | ICmpInst::Predicate Pred; |
1924 | if (!m_ICmp(Pred, m_Value(ICmpLHS), m_Value(ICmpRHS)).match(V)) |
1925 | return false; |
1926 | |
1927 | Value *AddLHS, *AddRHS; |
1928 | auto AddExpr = m_Add(m_Value(AddLHS), m_Value(AddRHS)); |
1929 | |
1930 | // (a + b) u< a, (a + b) u< b |
1931 | if (Pred == ICmpInst::ICMP_ULT) |
1932 | if (AddExpr.match(ICmpLHS) && (ICmpRHS == AddLHS || ICmpRHS == AddRHS)) |
1933 | return L.match(AddLHS) && R.match(AddRHS) && S.match(ICmpLHS); |
1934 | |
1935 | // a >u (a + b), b >u (a + b) |
1936 | if (Pred == ICmpInst::ICMP_UGT) |
1937 | if (AddExpr.match(ICmpRHS) && (ICmpLHS == AddLHS || ICmpLHS == AddRHS)) |
1938 | return L.match(AddLHS) && R.match(AddRHS) && S.match(ICmpRHS); |
1939 | |
1940 | Value *Op1; |
1941 | auto XorExpr = m_OneUse(m_Xor(m_Value(Op1), m_AllOnes())); |
1942 | // (a ^ -1) <u b |
1943 | if (Pred == ICmpInst::ICMP_ULT) { |
1944 | if (XorExpr.match(ICmpLHS)) |
1945 | return L.match(Op1) && R.match(ICmpRHS) && S.match(ICmpLHS); |
1946 | } |
1947 | // b > u (a ^ -1) |
1948 | if (Pred == ICmpInst::ICMP_UGT) { |
1949 | if (XorExpr.match(ICmpRHS)) |
1950 | return L.match(Op1) && R.match(ICmpLHS) && S.match(ICmpRHS); |
1951 | } |
1952 | |
1953 | // Match special-case for increment-by-1. |
1954 | if (Pred == ICmpInst::ICMP_EQ) { |
1955 | // (a + 1) == 0 |
1956 | // (1 + a) == 0 |
1957 | if (AddExpr.match(ICmpLHS) && m_ZeroInt().match(ICmpRHS) && |
1958 | (m_One().match(AddLHS) || m_One().match(AddRHS))) |
1959 | return L.match(AddLHS) && R.match(AddRHS) && S.match(ICmpLHS); |
1960 | // 0 == (a + 1) |
1961 | // 0 == (1 + a) |
1962 | if (m_ZeroInt().match(ICmpLHS) && AddExpr.match(ICmpRHS) && |
1963 | (m_One().match(AddLHS) || m_One().match(AddRHS))) |
1964 | return L.match(AddLHS) && R.match(AddRHS) && S.match(ICmpRHS); |
1965 | } |
1966 | |
1967 | return false; |
1968 | } |
1969 | }; |
1970 | |
1971 | /// Match an icmp instruction checking for unsigned overflow on addition. |
1972 | /// |
1973 | /// S is matched to the addition whose result is being checked for overflow, and |
1974 | /// L and R are matched to the LHS and RHS of S. |
1975 | template <typename LHS_t, typename RHS_t, typename Sum_t> |
1976 | UAddWithOverflow_match<LHS_t, RHS_t, Sum_t> |
1977 | m_UAddWithOverflow(const LHS_t &L, const RHS_t &R, const Sum_t &S) { |
1978 | return UAddWithOverflow_match<LHS_t, RHS_t, Sum_t>(L, R, S); |
1979 | } |
1980 | |
1981 | template <typename Opnd_t> struct Argument_match { |
1982 | unsigned OpI; |
1983 | Opnd_t Val; |
1984 | |
1985 | Argument_match(unsigned OpIdx, const Opnd_t &V) : OpI(OpIdx), Val(V) {} |
1986 | |
1987 | template <typename OpTy> bool match(OpTy *V) { |
1988 | // FIXME: Should likely be switched to use `CallBase`. |
1989 | if (const auto *CI = dyn_cast<CallInst>(V)) |
1990 | return Val.match(CI->getArgOperand(OpI)); |
1991 | return false; |
1992 | } |
1993 | }; |
1994 | |
1995 | /// Match an argument. |
1996 | template <unsigned OpI, typename Opnd_t> |
1997 | inline Argument_match<Opnd_t> m_Argument(const Opnd_t &Op) { |
1998 | return Argument_match<Opnd_t>(OpI, Op); |
1999 | } |
2000 | |
2001 | /// Intrinsic matchers. |
2002 | struct IntrinsicID_match { |
2003 | unsigned ID; |
2004 | |
2005 | IntrinsicID_match(Intrinsic::ID IntrID) : ID(IntrID) {} |
2006 | |
2007 | template <typename OpTy> bool match(OpTy *V) { |
2008 | if (const auto *CI = dyn_cast<CallInst>(V)) |
2009 | if (const auto *F = CI->getCalledFunction()) |
2010 | return F->getIntrinsicID() == ID; |
2011 | return false; |
2012 | } |
2013 | }; |
2014 | |
2015 | /// Intrinsic matches are combinations of ID matchers, and argument |
2016 | /// matchers. Higher arity matcher are defined recursively in terms of and-ing |
2017 | /// them with lower arity matchers. Here's some convenient typedefs for up to |
2018 | /// several arguments, and more can be added as needed |
2019 | template <typename T0 = void, typename T1 = void, typename T2 = void, |
2020 | typename T3 = void, typename T4 = void, typename T5 = void, |
2021 | typename T6 = void, typename T7 = void, typename T8 = void, |
2022 | typename T9 = void, typename T10 = void> |
2023 | struct m_Intrinsic_Ty; |
2024 | template <typename T0> struct m_Intrinsic_Ty<T0> { |
2025 | using Ty = match_combine_and<IntrinsicID_match, Argument_match<T0>>; |
2026 | }; |
2027 | template <typename T0, typename T1> struct m_Intrinsic_Ty<T0, T1> { |
2028 | using Ty = |
2029 | match_combine_and<typename m_Intrinsic_Ty<T0>::Ty, Argument_match<T1>>; |
2030 | }; |
2031 | template <typename T0, typename T1, typename T2> |
2032 | struct m_Intrinsic_Ty<T0, T1, T2> { |
2033 | using Ty = |
2034 | match_combine_and<typename m_Intrinsic_Ty<T0, T1>::Ty, |
2035 | Argument_match<T2>>; |
2036 | }; |
2037 | template <typename T0, typename T1, typename T2, typename T3> |
2038 | struct m_Intrinsic_Ty<T0, T1, T2, T3> { |
2039 | using Ty = |
2040 | match_combine_and<typename m_Intrinsic_Ty<T0, T1, T2>::Ty, |
2041 | Argument_match<T3>>; |
2042 | }; |
2043 | |
2044 | template <typename T0, typename T1, typename T2, typename T3, typename T4> |
2045 | struct m_Intrinsic_Ty<T0, T1, T2, T3, T4> { |
2046 | using Ty = match_combine_and<typename m_Intrinsic_Ty<T0, T1, T2, T3>::Ty, |
2047 | Argument_match<T4>>; |
2048 | }; |
2049 | |
2050 | template <typename T0, typename T1, typename T2, typename T3, typename T4, typename T5> |
2051 | struct m_Intrinsic_Ty<T0, T1, T2, T3, T4, T5> { |
2052 | using Ty = match_combine_and<typename m_Intrinsic_Ty<T0, T1, T2, T3, T4>::Ty, |
2053 | Argument_match<T5>>; |
2054 | }; |
2055 | |
2056 | /// Match intrinsic calls like this: |
2057 | /// m_Intrinsic<Intrinsic::fabs>(m_Value(X)) |
2058 | template <Intrinsic::ID IntrID> inline IntrinsicID_match m_Intrinsic() { |
2059 | return IntrinsicID_match(IntrID); |
2060 | } |
2061 | |
2062 | template <Intrinsic::ID IntrID, typename T0> |
2063 | inline typename m_Intrinsic_Ty<T0>::Ty m_Intrinsic(const T0 &Op0) { |
2064 | return m_CombineAnd(m_Intrinsic<IntrID>(), m_Argument<0>(Op0)); |
2065 | } |
2066 | |
2067 | template <Intrinsic::ID IntrID, typename T0, typename T1> |
2068 | inline typename m_Intrinsic_Ty<T0, T1>::Ty m_Intrinsic(const T0 &Op0, |
2069 | const T1 &Op1) { |
2070 | return m_CombineAnd(m_Intrinsic<IntrID>(Op0), m_Argument<1>(Op1)); |
2071 | } |
2072 | |
2073 | template <Intrinsic::ID IntrID, typename T0, typename T1, typename T2> |
2074 | inline typename m_Intrinsic_Ty<T0, T1, T2>::Ty |
2075 | m_Intrinsic(const T0 &Op0, const T1 &Op1, const T2 &Op2) { |
2076 | return m_CombineAnd(m_Intrinsic<IntrID>(Op0, Op1), m_Argument<2>(Op2)); |
2077 | } |
2078 | |
2079 | template <Intrinsic::ID IntrID, typename T0, typename T1, typename T2, |
2080 | typename T3> |
2081 | inline typename m_Intrinsic_Ty<T0, T1, T2, T3>::Ty |
2082 | m_Intrinsic(const T0 &Op0, const T1 &Op1, const T2 &Op2, const T3 &Op3) { |
2083 | return m_CombineAnd(m_Intrinsic<IntrID>(Op0, Op1, Op2), m_Argument<3>(Op3)); |
2084 | } |
2085 | |
2086 | template <Intrinsic::ID IntrID, typename T0, typename T1, typename T2, |
2087 | typename T3, typename T4> |
2088 | inline typename m_Intrinsic_Ty<T0, T1, T2, T3, T4>::Ty |
2089 | m_Intrinsic(const T0 &Op0, const T1 &Op1, const T2 &Op2, const T3 &Op3, |
2090 | const T4 &Op4) { |
2091 | return m_CombineAnd(m_Intrinsic<IntrID>(Op0, Op1, Op2, Op3), |
2092 | m_Argument<4>(Op4)); |
2093 | } |
2094 | |
2095 | template <Intrinsic::ID IntrID, typename T0, typename T1, typename T2, |
2096 | typename T3, typename T4, typename T5> |
2097 | inline typename m_Intrinsic_Ty<T0, T1, T2, T3, T4, T5>::Ty |
2098 | m_Intrinsic(const T0 &Op0, const T1 &Op1, const T2 &Op2, const T3 &Op3, |
2099 | const T4 &Op4, const T5 &Op5) { |
2100 | return m_CombineAnd(m_Intrinsic<IntrID>(Op0, Op1, Op2, Op3, Op4), |
2101 | m_Argument<5>(Op5)); |
2102 | } |
2103 | |
2104 | // Helper intrinsic matching specializations. |
2105 | template <typename Opnd0> |
2106 | inline typename m_Intrinsic_Ty<Opnd0>::Ty m_BitReverse(const Opnd0 &Op0) { |
2107 | return m_Intrinsic<Intrinsic::bitreverse>(Op0); |
2108 | } |
2109 | |
2110 | template <typename Opnd0> |
2111 | inline typename m_Intrinsic_Ty<Opnd0>::Ty m_BSwap(const Opnd0 &Op0) { |
2112 | return m_Intrinsic<Intrinsic::bswap>(Op0); |
2113 | } |
2114 | |
2115 | template <typename Opnd0> |
2116 | inline typename m_Intrinsic_Ty<Opnd0>::Ty m_FAbs(const Opnd0 &Op0) { |
2117 | return m_Intrinsic<Intrinsic::fabs>(Op0); |
2118 | } |
2119 | |
2120 | template <typename Opnd0> |
2121 | inline typename m_Intrinsic_Ty<Opnd0>::Ty m_FCanonicalize(const Opnd0 &Op0) { |
2122 | return m_Intrinsic<Intrinsic::canonicalize>(Op0); |
2123 | } |
2124 | |
2125 | template <typename Opnd0, typename Opnd1> |
2126 | inline typename m_Intrinsic_Ty<Opnd0, Opnd1>::Ty m_FMin(const Opnd0 &Op0, |
2127 | const Opnd1 &Op1) { |
2128 | return m_Intrinsic<Intrinsic::minnum>(Op0, Op1); |
2129 | } |
2130 | |
2131 | template <typename Opnd0, typename Opnd1> |
2132 | inline typename m_Intrinsic_Ty<Opnd0, Opnd1>::Ty m_FMax(const Opnd0 &Op0, |
2133 | const Opnd1 &Op1) { |
2134 | return m_Intrinsic<Intrinsic::maxnum>(Op0, Op1); |
2135 | } |
2136 | |
2137 | template <typename Opnd0, typename Opnd1, typename Opnd2> |
2138 | inline typename m_Intrinsic_Ty<Opnd0, Opnd1, Opnd2>::Ty |
2139 | m_FShl(const Opnd0 &Op0, const Opnd1 &Op1, const Opnd2 &Op2) { |
2140 | return m_Intrinsic<Intrinsic::fshl>(Op0, Op1, Op2); |
2141 | } |
2142 | |
2143 | template <typename Opnd0, typename Opnd1, typename Opnd2> |
2144 | inline typename m_Intrinsic_Ty<Opnd0, Opnd1, Opnd2>::Ty |
2145 | m_FShr(const Opnd0 &Op0, const Opnd1 &Op1, const Opnd2 &Op2) { |
2146 | return m_Intrinsic<Intrinsic::fshr>(Op0, Op1, Op2); |
2147 | } |
2148 | |
2149 | //===----------------------------------------------------------------------===// |
2150 | // Matchers for two-operands operators with the operators in either order |
2151 | // |
2152 | |
2153 | /// Matches a BinaryOperator with LHS and RHS in either order. |
2154 | template <typename LHS, typename RHS> |
2155 | inline AnyBinaryOp_match<LHS, RHS, true> m_c_BinOp(const LHS &L, const RHS &R) { |
2156 | return AnyBinaryOp_match<LHS, RHS, true>(L, R); |
2157 | } |
2158 | |
2159 | /// Matches an ICmp with a predicate over LHS and RHS in either order. |
2160 | /// Swaps the predicate if operands are commuted. |
2161 | template <typename LHS, typename RHS> |
2162 | inline CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate, true> |
2163 | m_c_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R) { |
2164 | return CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate, true>(Pred, L, |
2165 | R); |
2166 | } |
2167 | |
2168 | /// Matches a Add with LHS and RHS in either order. |
2169 | template <typename LHS, typename RHS> |
2170 | inline BinaryOp_match<LHS, RHS, Instruction::Add, true> m_c_Add(const LHS &L, |
2171 | const RHS &R) { |
2172 | return BinaryOp_match<LHS, RHS, Instruction::Add, true>(L, R); |
2173 | } |
2174 | |
2175 | /// Matches a Mul with LHS and RHS in either order. |
2176 | template <typename LHS, typename RHS> |
2177 | inline BinaryOp_match<LHS, RHS, Instruction::Mul, true> m_c_Mul(const LHS &L, |
2178 | const RHS &R) { |
2179 | return BinaryOp_match<LHS, RHS, Instruction::Mul, true>(L, R); |
2180 | } |
2181 | |
2182 | /// Matches an And with LHS and RHS in either order. |
2183 | template <typename LHS, typename RHS> |
2184 | inline BinaryOp_match<LHS, RHS, Instruction::And, true> m_c_And(const LHS &L, |
2185 | const RHS &R) { |
2186 | return BinaryOp_match<LHS, RHS, Instruction::And, true>(L, R); |
2187 | } |
2188 | |
2189 | /// Matches an Or with LHS and RHS in either order. |
2190 | template <typename LHS, typename RHS> |
2191 | inline BinaryOp_match<LHS, RHS, Instruction::Or, true> m_c_Or(const LHS &L, |
2192 | const RHS &R) { |
2193 | return BinaryOp_match<LHS, RHS, Instruction::Or, true>(L, R); |
2194 | } |
2195 | |
2196 | /// Matches an Xor with LHS and RHS in either order. |
2197 | template <typename LHS, typename RHS> |
2198 | inline BinaryOp_match<LHS, RHS, Instruction::Xor, true> m_c_Xor(const LHS &L, |
2199 | const RHS &R) { |
2200 | return BinaryOp_match<LHS, RHS, Instruction::Xor, true>(L, R); |
2201 | } |
2202 | |
2203 | /// Matches a 'Neg' as 'sub 0, V'. |
2204 | template <typename ValTy> |
2205 | inline BinaryOp_match<cst_pred_ty<is_zero_int>, ValTy, Instruction::Sub> |
2206 | m_Neg(const ValTy &V) { |
2207 | return m_Sub(m_ZeroInt(), V); |
2208 | } |
2209 | |
2210 | /// Matches a 'Neg' as 'sub nsw 0, V'. |
2211 | template <typename ValTy> |
2212 | inline OverflowingBinaryOp_match<cst_pred_ty<is_zero_int>, ValTy, |
2213 | Instruction::Sub, |
2214 | OverflowingBinaryOperator::NoSignedWrap> |
2215 | m_NSWNeg(const ValTy &V) { |
2216 | return m_NSWSub(m_ZeroInt(), V); |
2217 | } |
2218 | |
2219 | /// Matches a 'Not' as 'xor V, -1' or 'xor -1, V'. |
2220 | template <typename ValTy> |
2221 | inline BinaryOp_match<ValTy, cst_pred_ty<is_all_ones>, Instruction::Xor, true> |
2222 | m_Not(const ValTy &V) { |
2223 | return m_c_Xor(V, m_AllOnes()); |
2224 | } |
2225 | |
2226 | /// Matches an SMin with LHS and RHS in either order. |
2227 | template <typename LHS, typename RHS> |
2228 | inline MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty, true> |
2229 | m_c_SMin(const LHS &L, const RHS &R) { |
2230 | return MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty, true>(L, R); |
2231 | } |
2232 | /// Matches an SMax with LHS and RHS in either order. |
2233 | template <typename LHS, typename RHS> |
2234 | inline MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty, true> |
2235 | m_c_SMax(const LHS &L, const RHS &R) { |
2236 | return MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty, true>(L, R); |
2237 | } |
2238 | /// Matches a UMin with LHS and RHS in either order. |
2239 | template <typename LHS, typename RHS> |
2240 | inline MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty, true> |
2241 | m_c_UMin(const LHS &L, const RHS &R) { |
2242 | return MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty, true>(L, R); |
2243 | } |
2244 | /// Matches a UMax with LHS and RHS in either order. |
2245 | template <typename LHS, typename RHS> |
2246 | inline MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty, true> |
2247 | m_c_UMax(const LHS &L, const RHS &R) { |
2248 | return MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty, true>(L, R); |
2249 | } |
2250 | |
2251 | template <typename LHS, typename RHS> |
2252 | inline match_combine_or< |
2253 | match_combine_or<MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty, true>, |
2254 | MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty, true>>, |
2255 | match_combine_or<MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty, true>, |
2256 | MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty, true>>> |
2257 | m_c_MaxOrMin(const LHS &L, const RHS &R) { |
2258 | return m_CombineOr(m_CombineOr(m_c_SMax(L, R), m_c_SMin(L, R)), |
2259 | m_CombineOr(m_c_UMax(L, R), m_c_UMin(L, R))); |
2260 | } |
2261 | |
2262 | /// Matches FAdd with LHS and RHS in either order. |
2263 | template <typename LHS, typename RHS> |
2264 | inline BinaryOp_match<LHS, RHS, Instruction::FAdd, true> |
2265 | m_c_FAdd(const LHS &L, const RHS &R) { |
2266 | return BinaryOp_match<LHS, RHS, Instruction::FAdd, true>(L, R); |
2267 | } |
2268 | |
2269 | /// Matches FMul with LHS and RHS in either order. |
2270 | template <typename LHS, typename RHS> |
2271 | inline BinaryOp_match<LHS, RHS, Instruction::FMul, true> |
2272 | m_c_FMul(const LHS &L, const RHS &R) { |
2273 | return BinaryOp_match<LHS, RHS, Instruction::FMul, true>(L, R); |
2274 | } |
2275 | |
2276 | template <typename Opnd_t> struct Signum_match { |
2277 | Opnd_t Val; |
2278 | Signum_match(const Opnd_t &V) : Val(V) {} |
2279 | |
2280 | template <typename OpTy> bool match(OpTy *V) { |
2281 | unsigned TypeSize = V->getType()->getScalarSizeInBits(); |
2282 | if (TypeSize == 0) |
2283 | return false; |
2284 | |
2285 | unsigned ShiftWidth = TypeSize - 1; |
2286 | Value *OpL = nullptr, *OpR = nullptr; |
2287 | |
2288 | // This is the representation of signum we match: |
2289 | // |
2290 | // signum(x) == (x >> 63) | (-x >>u 63) |
2291 | // |
2292 | // An i1 value is its own signum, so it's correct to match |
2293 | // |
2294 | // signum(x) == (x >> 0) | (-x >>u 0) |
2295 | // |
2296 | // for i1 values. |
2297 | |
2298 | auto LHS = m_AShr(m_Value(OpL), m_SpecificInt(ShiftWidth)); |
2299 | auto RHS = m_LShr(m_Neg(m_Value(OpR)), m_SpecificInt(ShiftWidth)); |
2300 | auto Signum = m_Or(LHS, RHS); |
2301 | |
2302 | return Signum.match(V) && OpL == OpR && Val.match(OpL); |
2303 | } |
2304 | }; |
2305 | |
2306 | /// Matches a signum pattern. |
2307 | /// |
2308 | /// signum(x) = |
2309 | /// x > 0 -> 1 |
2310 | /// x == 0 -> 0 |
2311 | /// x < 0 -> -1 |
2312 | template <typename Val_t> inline Signum_match<Val_t> m_Signum(const Val_t &V) { |
2313 | return Signum_match<Val_t>(V); |
2314 | } |
2315 | |
2316 | template <int Ind, typename Opnd_t> struct ExtractValue_match { |
2317 | Opnd_t Val; |
2318 | ExtractValue_match(const Opnd_t &V) : Val(V) {} |
2319 | |
2320 | template <typename OpTy> bool match(OpTy *V) { |
2321 | if (auto *I = dyn_cast<ExtractValueInst>(V)) { |
2322 | // If Ind is -1, don't inspect indices |
2323 | if (Ind != -1 && |
2324 | !(I->getNumIndices() == 1 && I->getIndices()[0] == (unsigned)Ind)) |
2325 | return false; |
2326 | return Val.match(I->getAggregateOperand()); |
2327 | } |
2328 | return false; |
2329 | } |
2330 | }; |
2331 | |
2332 | /// Match a single index ExtractValue instruction. |
2333 | /// For example m_ExtractValue<1>(...) |
2334 | template <int Ind, typename Val_t> |
2335 | inline ExtractValue_match<Ind, Val_t> m_ExtractValue(const Val_t &V) { |
2336 | return ExtractValue_match<Ind, Val_t>(V); |
2337 | } |
2338 | |
2339 | /// Match an ExtractValue instruction with any index. |
2340 | /// For example m_ExtractValue(...) |
2341 | template <typename Val_t> |
2342 | inline ExtractValue_match<-1, Val_t> m_ExtractValue(const Val_t &V) { |
2343 | return ExtractValue_match<-1, Val_t>(V); |
2344 | } |
2345 | |
2346 | /// Matcher for a single index InsertValue instruction. |
2347 | template <int Ind, typename T0, typename T1> struct InsertValue_match { |
2348 | T0 Op0; |
2349 | T1 Op1; |
2350 | |
2351 | InsertValue_match(const T0 &Op0, const T1 &Op1) : Op0(Op0), Op1(Op1) {} |
2352 | |
2353 | template <typename OpTy> bool match(OpTy *V) { |
2354 | if (auto *I = dyn_cast<InsertValueInst>(V)) { |
2355 | return Op0.match(I->getOperand(0)) && Op1.match(I->getOperand(1)) && |
2356 | I->getNumIndices() == 1 && Ind == I->getIndices()[0]; |
2357 | } |
2358 | return false; |
2359 | } |
2360 | }; |
2361 | |
2362 | /// Matches a single index InsertValue instruction. |
2363 | template <int Ind, typename Val_t, typename Elt_t> |
2364 | inline InsertValue_match<Ind, Val_t, Elt_t> m_InsertValue(const Val_t &Val, |
2365 | const Elt_t &Elt) { |
2366 | return InsertValue_match<Ind, Val_t, Elt_t>(Val, Elt); |
2367 | } |
2368 | |
2369 | /// Matches patterns for `vscale`. This can either be a call to `llvm.vscale` or |
2370 | /// the constant expression |
2371 | /// `ptrtoint(gep <vscale x 1 x i8>, <vscale x 1 x i8>* null, i32 1>` |
2372 | /// under the right conditions determined by DataLayout. |
2373 | struct VScaleVal_match { |
2374 | private: |
2375 | template <typename Base, typename Offset> |
2376 | inline BinaryOp_match<Base, Offset, Instruction::GetElementPtr> |
2377 | m_OffsetGep(const Base &B, const Offset &O) { |
2378 | return BinaryOp_match<Base, Offset, Instruction::GetElementPtr>(B, O); |
2379 | } |
2380 | |
2381 | public: |
2382 | const DataLayout &DL; |
2383 | VScaleVal_match(const DataLayout &DL) : DL(DL) {} |
2384 | |
2385 | template <typename ITy> bool match(ITy *V) { |
2386 | if (m_Intrinsic<Intrinsic::vscale>().match(V)) |
2387 | return true; |
2388 | |
2389 | if (m_PtrToInt(m_OffsetGep(m_Zero(), m_SpecificInt(1))).match(V)) { |
2390 | Type *PtrTy = cast<Operator>(V)->getOperand(0)->getType(); |
2391 | auto *DerefTy = PtrTy->getPointerElementType(); |
2392 | if (isa<ScalableVectorType>(DerefTy) && |
2393 | DL.getTypeAllocSizeInBits(DerefTy).getKnownMinSize() == 8) |
2394 | return true; |
2395 | } |
2396 | |
2397 | return false; |
2398 | } |
2399 | }; |
2400 | |
2401 | inline VScaleVal_match m_VScale(const DataLayout &DL) { |
2402 | return VScaleVal_match(DL); |
2403 | } |
2404 | |
2405 | template <typename LHS, typename RHS, unsigned Opcode> |
2406 | struct LogicalOp_match { |
2407 | LHS L; |
2408 | RHS R; |
2409 | |
2410 | LogicalOp_match(const LHS &L, const RHS &R) : L(L), R(R) {} |
2411 | |
2412 | template <typename T> bool match(T *V) { |
2413 | if (auto *I = dyn_cast<Instruction>(V)) { |
2414 | if (!I->getType()->isIntOrIntVectorTy(1)) |
2415 | return false; |
2416 | |
2417 | if (I->getOpcode() == Opcode && L.match(I->getOperand(0)) && |
2418 | R.match(I->getOperand(1))) |
2419 | return true; |
2420 | |
2421 | if (auto *SI = dyn_cast<SelectInst>(I)) { |
2422 | if (Opcode == Instruction::And) { |
2423 | if (const auto *C = dyn_cast<Constant>(SI->getFalseValue())) |
2424 | if (C->isNullValue() && L.match(SI->getCondition()) && |
2425 | R.match(SI->getTrueValue())) |
2426 | return true; |
2427 | } else { |
2428 | assert(Opcode == Instruction::Or)((Opcode == Instruction::Or) ? static_cast<void> (0) : __assert_fail ("Opcode == Instruction::Or", "/build/llvm-toolchain-snapshot-13~++20210314100619+a28facba1ccd/llvm/include/llvm/IR/PatternMatch.h" , 2428, __PRETTY_FUNCTION__)); |
2429 | if (const auto *C = dyn_cast<Constant>(SI->getTrueValue())) |
2430 | if (C->isOneValue() && L.match(SI->getCondition()) && |
2431 | R.match(SI->getFalseValue())) |
2432 | return true; |
2433 | } |
2434 | } |
2435 | } |
2436 | |
2437 | return false; |
2438 | } |
2439 | }; |
2440 | |
2441 | /// Matches L && R either in the form of L & R or L ? R : false. |
2442 | /// Note that the latter form is poison-blocking. |
2443 | template <typename LHS, typename RHS> |
2444 | inline LogicalOp_match<LHS, RHS, Instruction::And> |
2445 | m_LogicalAnd(const LHS &L, const RHS &R) { |
2446 | return LogicalOp_match<LHS, RHS, Instruction::And>(L, R); |
2447 | } |
2448 | |
2449 | /// Matches L && R where L and R are arbitrary values. |
2450 | inline auto m_LogicalAnd() { return m_LogicalAnd(m_Value(), m_Value()); } |
2451 | |
2452 | /// Matches L || R either in the form of L | R or L ? true : R. |
2453 | /// Note that the latter form is poison-blocking. |
2454 | template <typename LHS, typename RHS> |
2455 | inline LogicalOp_match<LHS, RHS, Instruction::Or> |
2456 | m_LogicalOr(const LHS &L, const RHS &R) { |
2457 | return LogicalOp_match<LHS, RHS, Instruction::Or>(L, R); |
2458 | } |
2459 | |
2460 | /// Matches L || R where L and R are arbitrary values. |
2461 | inline auto m_LogicalOr() { |
2462 | return m_LogicalOr(m_Value(), m_Value()); |
2463 | } |
2464 | |
2465 | } // end namespace PatternMatch |
2466 | } // end namespace llvm |
2467 | |
2468 | #endif // LLVM_IR_PATTERNMATCH_H |