File: | lib/Analysis/InstructionSimplify.cpp |
Warning: | line 425, column 20 Called C++ object pointer is null |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===- InstructionSimplify.cpp - Fold instruction operands ----------------===// | |||
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 implements routines for folding instructions into simpler forms | |||
10 | // that do not require creating new instructions. This does constant folding | |||
11 | // ("add i32 1, 1" -> "2") but can also handle non-constant operands, either | |||
12 | // returning a constant ("and i32 %x, 0" -> "0") or an already existing value | |||
13 | // ("and i32 %x, %x" -> "%x"). All operands are assumed to have already been | |||
14 | // simplified: This is usually true and assuming it simplifies the logic (if | |||
15 | // they have not been simplified then results are correct but maybe suboptimal). | |||
16 | // | |||
17 | //===----------------------------------------------------------------------===// | |||
18 | ||||
19 | #include "llvm/Analysis/InstructionSimplify.h" | |||
20 | #include "llvm/ADT/SetVector.h" | |||
21 | #include "llvm/ADT/Statistic.h" | |||
22 | #include "llvm/Analysis/AliasAnalysis.h" | |||
23 | #include "llvm/Analysis/AssumptionCache.h" | |||
24 | #include "llvm/Analysis/CaptureTracking.h" | |||
25 | #include "llvm/Analysis/CmpInstAnalysis.h" | |||
26 | #include "llvm/Analysis/ConstantFolding.h" | |||
27 | #include "llvm/Analysis/LoopAnalysisManager.h" | |||
28 | #include "llvm/Analysis/MemoryBuiltins.h" | |||
29 | #include "llvm/Analysis/ValueTracking.h" | |||
30 | #include "llvm/Analysis/VectorUtils.h" | |||
31 | #include "llvm/IR/ConstantRange.h" | |||
32 | #include "llvm/IR/DataLayout.h" | |||
33 | #include "llvm/IR/Dominators.h" | |||
34 | #include "llvm/IR/GetElementPtrTypeIterator.h" | |||
35 | #include "llvm/IR/GlobalAlias.h" | |||
36 | #include "llvm/IR/InstrTypes.h" | |||
37 | #include "llvm/IR/Instructions.h" | |||
38 | #include "llvm/IR/Operator.h" | |||
39 | #include "llvm/IR/PatternMatch.h" | |||
40 | #include "llvm/IR/ValueHandle.h" | |||
41 | #include "llvm/Support/KnownBits.h" | |||
42 | #include <algorithm> | |||
43 | using namespace llvm; | |||
44 | using namespace llvm::PatternMatch; | |||
45 | ||||
46 | #define DEBUG_TYPE"instsimplify" "instsimplify" | |||
47 | ||||
48 | enum { RecursionLimit = 3 }; | |||
49 | ||||
50 | STATISTIC(NumExpand, "Number of expansions")static llvm::Statistic NumExpand = {"instsimplify", "NumExpand" , "Number of expansions", {0}, {false}}; | |||
51 | STATISTIC(NumReassoc, "Number of reassociations")static llvm::Statistic NumReassoc = {"instsimplify", "NumReassoc" , "Number of reassociations", {0}, {false}}; | |||
52 | ||||
53 | static Value *SimplifyAndInst(Value *, Value *, const SimplifyQuery &, unsigned); | |||
54 | static Value *simplifyUnOp(unsigned, Value *, const SimplifyQuery &, unsigned); | |||
55 | static Value *simplifyFPUnOp(unsigned, Value *, const FastMathFlags &, | |||
56 | const SimplifyQuery &, unsigned); | |||
57 | static Value *SimplifyBinOp(unsigned, Value *, Value *, const SimplifyQuery &, | |||
58 | unsigned); | |||
59 | static Value *SimplifyFPBinOp(unsigned, Value *, Value *, const FastMathFlags &, | |||
60 | const SimplifyQuery &, unsigned); | |||
61 | static Value *SimplifyCmpInst(unsigned, Value *, Value *, const SimplifyQuery &, | |||
62 | unsigned); | |||
63 | static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS, | |||
64 | const SimplifyQuery &Q, unsigned MaxRecurse); | |||
65 | static Value *SimplifyOrInst(Value *, Value *, const SimplifyQuery &, unsigned); | |||
66 | static Value *SimplifyXorInst(Value *, Value *, const SimplifyQuery &, unsigned); | |||
67 | static Value *SimplifyCastInst(unsigned, Value *, Type *, | |||
68 | const SimplifyQuery &, unsigned); | |||
69 | static Value *SimplifyGEPInst(Type *, ArrayRef<Value *>, const SimplifyQuery &, | |||
70 | unsigned); | |||
71 | ||||
72 | static Value *foldSelectWithBinaryOp(Value *Cond, Value *TrueVal, | |||
73 | Value *FalseVal) { | |||
74 | BinaryOperator::BinaryOps BinOpCode; | |||
75 | if (auto *BO = dyn_cast<BinaryOperator>(Cond)) | |||
76 | BinOpCode = BO->getOpcode(); | |||
77 | else | |||
78 | return nullptr; | |||
79 | ||||
80 | CmpInst::Predicate ExpectedPred, Pred1, Pred2; | |||
81 | if (BinOpCode == BinaryOperator::Or) { | |||
82 | ExpectedPred = ICmpInst::ICMP_NE; | |||
83 | } else if (BinOpCode == BinaryOperator::And) { | |||
84 | ExpectedPred = ICmpInst::ICMP_EQ; | |||
85 | } else | |||
86 | return nullptr; | |||
87 | ||||
88 | // %A = icmp eq %TV, %FV | |||
89 | // %B = icmp eq %X, %Y (and one of these is a select operand) | |||
90 | // %C = and %A, %B | |||
91 | // %D = select %C, %TV, %FV | |||
92 | // --> | |||
93 | // %FV | |||
94 | ||||
95 | // %A = icmp ne %TV, %FV | |||
96 | // %B = icmp ne %X, %Y (and one of these is a select operand) | |||
97 | // %C = or %A, %B | |||
98 | // %D = select %C, %TV, %FV | |||
99 | // --> | |||
100 | // %TV | |||
101 | Value *X, *Y; | |||
102 | if (!match(Cond, m_c_BinOp(m_c_ICmp(Pred1, m_Specific(TrueVal), | |||
103 | m_Specific(FalseVal)), | |||
104 | m_ICmp(Pred2, m_Value(X), m_Value(Y)))) || | |||
105 | Pred1 != Pred2 || Pred1 != ExpectedPred) | |||
106 | return nullptr; | |||
107 | ||||
108 | if (X == TrueVal || X == FalseVal || Y == TrueVal || Y == FalseVal) | |||
109 | return BinOpCode == BinaryOperator::Or ? TrueVal : FalseVal; | |||
110 | ||||
111 | return nullptr; | |||
112 | } | |||
113 | ||||
114 | /// For a boolean type or a vector of boolean type, return false or a vector | |||
115 | /// with every element false. | |||
116 | static Constant *getFalse(Type *Ty) { | |||
117 | return ConstantInt::getFalse(Ty); | |||
118 | } | |||
119 | ||||
120 | /// For a boolean type or a vector of boolean type, return true or a vector | |||
121 | /// with every element true. | |||
122 | static Constant *getTrue(Type *Ty) { | |||
123 | return ConstantInt::getTrue(Ty); | |||
124 | } | |||
125 | ||||
126 | /// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"? | |||
127 | static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS, | |||
128 | Value *RHS) { | |||
129 | CmpInst *Cmp = dyn_cast<CmpInst>(V); | |||
130 | if (!Cmp) | |||
131 | return false; | |||
132 | CmpInst::Predicate CPred = Cmp->getPredicate(); | |||
133 | Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1); | |||
134 | if (CPred == Pred && CLHS == LHS && CRHS == RHS) | |||
135 | return true; | |||
136 | return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS && | |||
137 | CRHS == LHS; | |||
138 | } | |||
139 | ||||
140 | /// Does the given value dominate the specified phi node? | |||
141 | static bool valueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) { | |||
142 | Instruction *I = dyn_cast<Instruction>(V); | |||
143 | if (!I) | |||
144 | // Arguments and constants dominate all instructions. | |||
145 | return true; | |||
146 | ||||
147 | // If we are processing instructions (and/or basic blocks) that have not been | |||
148 | // fully added to a function, the parent nodes may still be null. Simply | |||
149 | // return the conservative answer in these cases. | |||
150 | if (!I->getParent() || !P->getParent() || !I->getFunction()) | |||
151 | return false; | |||
152 | ||||
153 | // If we have a DominatorTree then do a precise test. | |||
154 | if (DT) | |||
155 | return DT->dominates(I, P); | |||
156 | ||||
157 | // Otherwise, if the instruction is in the entry block and is not an invoke, | |||
158 | // then it obviously dominates all phi nodes. | |||
159 | if (I->getParent() == &I->getFunction()->getEntryBlock() && | |||
160 | !isa<InvokeInst>(I)) | |||
161 | return true; | |||
162 | ||||
163 | return false; | |||
164 | } | |||
165 | ||||
166 | /// Simplify "A op (B op' C)" by distributing op over op', turning it into | |||
167 | /// "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is | |||
168 | /// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS. | |||
169 | /// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)". | |||
170 | /// Returns the simplified value, or null if no simplification was performed. | |||
171 | static Value *ExpandBinOp(Instruction::BinaryOps Opcode, Value *LHS, Value *RHS, | |||
172 | Instruction::BinaryOps OpcodeToExpand, | |||
173 | const SimplifyQuery &Q, unsigned MaxRecurse) { | |||
174 | // Recursion is always used, so bail out at once if we already hit the limit. | |||
175 | if (!MaxRecurse--) | |||
176 | return nullptr; | |||
177 | ||||
178 | // Check whether the expression has the form "(A op' B) op C". | |||
179 | if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS)) | |||
180 | if (Op0->getOpcode() == OpcodeToExpand) { | |||
181 | // It does! Try turning it into "(A op C) op' (B op C)". | |||
182 | Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS; | |||
183 | // Do "A op C" and "B op C" both simplify? | |||
184 | if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) | |||
185 | if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) { | |||
186 | // They do! Return "L op' R" if it simplifies or is already available. | |||
187 | // If "L op' R" equals "A op' B" then "L op' R" is just the LHS. | |||
188 | if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand) | |||
189 | && L == B && R == A)) { | |||
190 | ++NumExpand; | |||
191 | return LHS; | |||
192 | } | |||
193 | // Otherwise return "L op' R" if it simplifies. | |||
194 | if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) { | |||
195 | ++NumExpand; | |||
196 | return V; | |||
197 | } | |||
198 | } | |||
199 | } | |||
200 | ||||
201 | // Check whether the expression has the form "A op (B op' C)". | |||
202 | if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS)) | |||
203 | if (Op1->getOpcode() == OpcodeToExpand) { | |||
204 | // It does! Try turning it into "(A op B) op' (A op C)". | |||
205 | Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1); | |||
206 | // Do "A op B" and "A op C" both simplify? | |||
207 | if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) | |||
208 | if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) { | |||
209 | // They do! Return "L op' R" if it simplifies or is already available. | |||
210 | // If "L op' R" equals "B op' C" then "L op' R" is just the RHS. | |||
211 | if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand) | |||
212 | && L == C && R == B)) { | |||
213 | ++NumExpand; | |||
214 | return RHS; | |||
215 | } | |||
216 | // Otherwise return "L op' R" if it simplifies. | |||
217 | if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) { | |||
218 | ++NumExpand; | |||
219 | return V; | |||
220 | } | |||
221 | } | |||
222 | } | |||
223 | ||||
224 | return nullptr; | |||
225 | } | |||
226 | ||||
227 | /// Generic simplifications for associative binary operations. | |||
228 | /// Returns the simpler value, or null if none was found. | |||
229 | static Value *SimplifyAssociativeBinOp(Instruction::BinaryOps Opcode, | |||
230 | Value *LHS, Value *RHS, | |||
231 | const SimplifyQuery &Q, | |||
232 | unsigned MaxRecurse) { | |||
233 | assert(Instruction::isAssociative(Opcode) && "Not an associative operation!")((Instruction::isAssociative(Opcode) && "Not an associative operation!" ) ? static_cast<void> (0) : __assert_fail ("Instruction::isAssociative(Opcode) && \"Not an associative operation!\"" , "/build/llvm-toolchain-snapshot-9~svn360825/lib/Analysis/InstructionSimplify.cpp" , 233, __PRETTY_FUNCTION__)); | |||
234 | ||||
235 | // Recursion is always used, so bail out at once if we already hit the limit. | |||
236 | if (!MaxRecurse--) | |||
237 | return nullptr; | |||
238 | ||||
239 | BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS); | |||
240 | BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS); | |||
241 | ||||
242 | // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely. | |||
243 | if (Op0 && Op0->getOpcode() == Opcode) { | |||
244 | Value *A = Op0->getOperand(0); | |||
245 | Value *B = Op0->getOperand(1); | |||
246 | Value *C = RHS; | |||
247 | ||||
248 | // Does "B op C" simplify? | |||
249 | if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) { | |||
250 | // It does! Return "A op V" if it simplifies or is already available. | |||
251 | // If V equals B then "A op V" is just the LHS. | |||
252 | if (V == B) return LHS; | |||
253 | // Otherwise return "A op V" if it simplifies. | |||
254 | if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) { | |||
255 | ++NumReassoc; | |||
256 | return W; | |||
257 | } | |||
258 | } | |||
259 | } | |||
260 | ||||
261 | // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely. | |||
262 | if (Op1 && Op1->getOpcode() == Opcode) { | |||
263 | Value *A = LHS; | |||
264 | Value *B = Op1->getOperand(0); | |||
265 | Value *C = Op1->getOperand(1); | |||
266 | ||||
267 | // Does "A op B" simplify? | |||
268 | if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) { | |||
269 | // It does! Return "V op C" if it simplifies or is already available. | |||
270 | // If V equals B then "V op C" is just the RHS. | |||
271 | if (V == B) return RHS; | |||
272 | // Otherwise return "V op C" if it simplifies. | |||
273 | if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) { | |||
274 | ++NumReassoc; | |||
275 | return W; | |||
276 | } | |||
277 | } | |||
278 | } | |||
279 | ||||
280 | // The remaining transforms require commutativity as well as associativity. | |||
281 | if (!Instruction::isCommutative(Opcode)) | |||
282 | return nullptr; | |||
283 | ||||
284 | // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely. | |||
285 | if (Op0 && Op0->getOpcode() == Opcode) { | |||
286 | Value *A = Op0->getOperand(0); | |||
287 | Value *B = Op0->getOperand(1); | |||
288 | Value *C = RHS; | |||
289 | ||||
290 | // Does "C op A" simplify? | |||
291 | if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) { | |||
292 | // It does! Return "V op B" if it simplifies or is already available. | |||
293 | // If V equals A then "V op B" is just the LHS. | |||
294 | if (V == A) return LHS; | |||
295 | // Otherwise return "V op B" if it simplifies. | |||
296 | if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) { | |||
297 | ++NumReassoc; | |||
298 | return W; | |||
299 | } | |||
300 | } | |||
301 | } | |||
302 | ||||
303 | // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely. | |||
304 | if (Op1 && Op1->getOpcode() == Opcode) { | |||
305 | Value *A = LHS; | |||
306 | Value *B = Op1->getOperand(0); | |||
307 | Value *C = Op1->getOperand(1); | |||
308 | ||||
309 | // Does "C op A" simplify? | |||
310 | if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) { | |||
311 | // It does! Return "B op V" if it simplifies or is already available. | |||
312 | // If V equals C then "B op V" is just the RHS. | |||
313 | if (V == C) return RHS; | |||
314 | // Otherwise return "B op V" if it simplifies. | |||
315 | if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) { | |||
316 | ++NumReassoc; | |||
317 | return W; | |||
318 | } | |||
319 | } | |||
320 | } | |||
321 | ||||
322 | return nullptr; | |||
323 | } | |||
324 | ||||
325 | /// In the case of a binary operation with a select instruction as an operand, | |||
326 | /// try to simplify the binop by seeing whether evaluating it on both branches | |||
327 | /// of the select results in the same value. Returns the common value if so, | |||
328 | /// otherwise returns null. | |||
329 | static Value *ThreadBinOpOverSelect(Instruction::BinaryOps Opcode, Value *LHS, | |||
330 | Value *RHS, const SimplifyQuery &Q, | |||
331 | unsigned MaxRecurse) { | |||
332 | // Recursion is always used, so bail out at once if we already hit the limit. | |||
333 | if (!MaxRecurse--) | |||
334 | return nullptr; | |||
335 | ||||
336 | SelectInst *SI; | |||
337 | if (isa<SelectInst>(LHS)) { | |||
338 | SI = cast<SelectInst>(LHS); | |||
339 | } else { | |||
340 | assert(isa<SelectInst>(RHS) && "No select instruction operand!")((isa<SelectInst>(RHS) && "No select instruction operand!" ) ? static_cast<void> (0) : __assert_fail ("isa<SelectInst>(RHS) && \"No select instruction operand!\"" , "/build/llvm-toolchain-snapshot-9~svn360825/lib/Analysis/InstructionSimplify.cpp" , 340, __PRETTY_FUNCTION__)); | |||
341 | SI = cast<SelectInst>(RHS); | |||
342 | } | |||
343 | ||||
344 | // Evaluate the BinOp on the true and false branches of the select. | |||
345 | Value *TV; | |||
346 | Value *FV; | |||
347 | if (SI == LHS) { | |||
348 | TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse); | |||
349 | FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse); | |||
350 | } else { | |||
351 | TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse); | |||
352 | FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse); | |||
353 | } | |||
354 | ||||
355 | // If they simplified to the same value, then return the common value. | |||
356 | // If they both failed to simplify then return null. | |||
357 | if (TV == FV) | |||
358 | return TV; | |||
359 | ||||
360 | // If one branch simplified to undef, return the other one. | |||
361 | if (TV && isa<UndefValue>(TV)) | |||
362 | return FV; | |||
363 | if (FV && isa<UndefValue>(FV)) | |||
364 | return TV; | |||
365 | ||||
366 | // If applying the operation did not change the true and false select values, | |||
367 | // then the result of the binop is the select itself. | |||
368 | if (TV == SI->getTrueValue() && FV == SI->getFalseValue()) | |||
369 | return SI; | |||
370 | ||||
371 | // If one branch simplified and the other did not, and the simplified | |||
372 | // value is equal to the unsimplified one, return the simplified value. | |||
373 | // For example, select (cond, X, X & Z) & Z -> X & Z. | |||
374 | if ((FV && !TV) || (TV && !FV)) { | |||
375 | // Check that the simplified value has the form "X op Y" where "op" is the | |||
376 | // same as the original operation. | |||
377 | Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV); | |||
378 | if (Simplified && Simplified->getOpcode() == unsigned(Opcode)) { | |||
379 | // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS". | |||
380 | // We already know that "op" is the same as for the simplified value. See | |||
381 | // if the operands match too. If so, return the simplified value. | |||
382 | Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue(); | |||
383 | Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS; | |||
384 | Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch; | |||
385 | if (Simplified->getOperand(0) == UnsimplifiedLHS && | |||
386 | Simplified->getOperand(1) == UnsimplifiedRHS) | |||
387 | return Simplified; | |||
388 | if (Simplified->isCommutative() && | |||
389 | Simplified->getOperand(1) == UnsimplifiedLHS && | |||
390 | Simplified->getOperand(0) == UnsimplifiedRHS) | |||
391 | return Simplified; | |||
392 | } | |||
393 | } | |||
394 | ||||
395 | return nullptr; | |||
396 | } | |||
397 | ||||
398 | /// In the case of a comparison with a select instruction, try to simplify the | |||
399 | /// comparison by seeing whether both branches of the select result in the same | |||
400 | /// value. Returns the common value if so, otherwise returns null. | |||
401 | static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS, | |||
402 | Value *RHS, const SimplifyQuery &Q, | |||
403 | unsigned MaxRecurse) { | |||
404 | // Recursion is always used, so bail out at once if we already hit the limit. | |||
405 | if (!MaxRecurse--) | |||
406 | return nullptr; | |||
407 | ||||
408 | // Make sure the select is on the LHS. | |||
409 | if (!isa<SelectInst>(LHS)) { | |||
410 | std::swap(LHS, RHS); | |||
411 | Pred = CmpInst::getSwappedPredicate(Pred); | |||
412 | } | |||
413 | assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!")((isa<SelectInst>(LHS) && "Not comparing with a select instruction!" ) ? static_cast<void> (0) : __assert_fail ("isa<SelectInst>(LHS) && \"Not comparing with a select instruction!\"" , "/build/llvm-toolchain-snapshot-9~svn360825/lib/Analysis/InstructionSimplify.cpp" , 413, __PRETTY_FUNCTION__)); | |||
414 | SelectInst *SI = cast<SelectInst>(LHS); | |||
415 | Value *Cond = SI->getCondition(); | |||
416 | Value *TV = SI->getTrueValue(); | |||
417 | Value *FV = SI->getFalseValue(); | |||
418 | ||||
419 | // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it. | |||
420 | // Does "cmp TV, RHS" simplify? | |||
421 | Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse); | |||
422 | if (TCmp == Cond) { | |||
423 | // It not only simplified, it simplified to the select condition. Replace | |||
424 | // it with 'true'. | |||
425 | TCmp = getTrue(Cond->getType()); | |||
| ||||
426 | } else if (!TCmp) { | |||
427 | // It didn't simplify. However if "cmp TV, RHS" is equal to the select | |||
428 | // condition then we can replace it with 'true'. Otherwise give up. | |||
429 | if (!isSameCompare(Cond, Pred, TV, RHS)) | |||
430 | return nullptr; | |||
431 | TCmp = getTrue(Cond->getType()); | |||
432 | } | |||
433 | ||||
434 | // Does "cmp FV, RHS" simplify? | |||
435 | Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse); | |||
436 | if (FCmp == Cond) { | |||
437 | // It not only simplified, it simplified to the select condition. Replace | |||
438 | // it with 'false'. | |||
439 | FCmp = getFalse(Cond->getType()); | |||
440 | } else if (!FCmp) { | |||
441 | // It didn't simplify. However if "cmp FV, RHS" is equal to the select | |||
442 | // condition then we can replace it with 'false'. Otherwise give up. | |||
443 | if (!isSameCompare(Cond, Pred, FV, RHS)) | |||
444 | return nullptr; | |||
445 | FCmp = getFalse(Cond->getType()); | |||
446 | } | |||
447 | ||||
448 | // If both sides simplified to the same value, then use it as the result of | |||
449 | // the original comparison. | |||
450 | if (TCmp == FCmp) | |||
451 | return TCmp; | |||
452 | ||||
453 | // The remaining cases only make sense if the select condition has the same | |||
454 | // type as the result of the comparison, so bail out if this is not so. | |||
455 | if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy()) | |||
456 | return nullptr; | |||
457 | // If the false value simplified to false, then the result of the compare | |||
458 | // is equal to "Cond && TCmp". This also catches the case when the false | |||
459 | // value simplified to false and the true value to true, returning "Cond". | |||
460 | if (match(FCmp, m_Zero())) | |||
461 | if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse)) | |||
462 | return V; | |||
463 | // If the true value simplified to true, then the result of the compare | |||
464 | // is equal to "Cond || FCmp". | |||
465 | if (match(TCmp, m_One())) | |||
466 | if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse)) | |||
467 | return V; | |||
468 | // Finally, if the false value simplified to true and the true value to | |||
469 | // false, then the result of the compare is equal to "!Cond". | |||
470 | if (match(FCmp, m_One()) && match(TCmp, m_Zero())) | |||
471 | if (Value *V = | |||
472 | SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()), | |||
473 | Q, MaxRecurse)) | |||
474 | return V; | |||
475 | ||||
476 | return nullptr; | |||
477 | } | |||
478 | ||||
479 | /// In the case of a binary operation with an operand that is a PHI instruction, | |||
480 | /// try to simplify the binop by seeing whether evaluating it on the incoming | |||
481 | /// phi values yields the same result for every value. If so returns the common | |||
482 | /// value, otherwise returns null. | |||
483 | static Value *ThreadBinOpOverPHI(Instruction::BinaryOps Opcode, Value *LHS, | |||
484 | Value *RHS, const SimplifyQuery &Q, | |||
485 | unsigned MaxRecurse) { | |||
486 | // Recursion is always used, so bail out at once if we already hit the limit. | |||
487 | if (!MaxRecurse--) | |||
488 | return nullptr; | |||
489 | ||||
490 | PHINode *PI; | |||
491 | if (isa<PHINode>(LHS)) { | |||
492 | PI = cast<PHINode>(LHS); | |||
493 | // Bail out if RHS and the phi may be mutually interdependent due to a loop. | |||
494 | if (!valueDominatesPHI(RHS, PI, Q.DT)) | |||
495 | return nullptr; | |||
496 | } else { | |||
497 | assert(isa<PHINode>(RHS) && "No PHI instruction operand!")((isa<PHINode>(RHS) && "No PHI instruction operand!" ) ? static_cast<void> (0) : __assert_fail ("isa<PHINode>(RHS) && \"No PHI instruction operand!\"" , "/build/llvm-toolchain-snapshot-9~svn360825/lib/Analysis/InstructionSimplify.cpp" , 497, __PRETTY_FUNCTION__)); | |||
498 | PI = cast<PHINode>(RHS); | |||
499 | // Bail out if LHS and the phi may be mutually interdependent due to a loop. | |||
500 | if (!valueDominatesPHI(LHS, PI, Q.DT)) | |||
501 | return nullptr; | |||
502 | } | |||
503 | ||||
504 | // Evaluate the BinOp on the incoming phi values. | |||
505 | Value *CommonValue = nullptr; | |||
506 | for (Value *Incoming : PI->incoming_values()) { | |||
507 | // If the incoming value is the phi node itself, it can safely be skipped. | |||
508 | if (Incoming == PI) continue; | |||
509 | Value *V = PI == LHS ? | |||
510 | SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) : | |||
511 | SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse); | |||
512 | // If the operation failed to simplify, or simplified to a different value | |||
513 | // to previously, then give up. | |||
514 | if (!V || (CommonValue && V != CommonValue)) | |||
515 | return nullptr; | |||
516 | CommonValue = V; | |||
517 | } | |||
518 | ||||
519 | return CommonValue; | |||
520 | } | |||
521 | ||||
522 | /// In the case of a comparison with a PHI instruction, try to simplify the | |||
523 | /// comparison by seeing whether comparing with all of the incoming phi values | |||
524 | /// yields the same result every time. If so returns the common result, | |||
525 | /// otherwise returns null. | |||
526 | static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS, | |||
527 | const SimplifyQuery &Q, unsigned MaxRecurse) { | |||
528 | // Recursion is always used, so bail out at once if we already hit the limit. | |||
529 | if (!MaxRecurse--) | |||
530 | return nullptr; | |||
531 | ||||
532 | // Make sure the phi is on the LHS. | |||
533 | if (!isa<PHINode>(LHS)) { | |||
534 | std::swap(LHS, RHS); | |||
535 | Pred = CmpInst::getSwappedPredicate(Pred); | |||
536 | } | |||
537 | assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!")((isa<PHINode>(LHS) && "Not comparing with a phi instruction!" ) ? static_cast<void> (0) : __assert_fail ("isa<PHINode>(LHS) && \"Not comparing with a phi instruction!\"" , "/build/llvm-toolchain-snapshot-9~svn360825/lib/Analysis/InstructionSimplify.cpp" , 537, __PRETTY_FUNCTION__)); | |||
538 | PHINode *PI = cast<PHINode>(LHS); | |||
539 | ||||
540 | // Bail out if RHS and the phi may be mutually interdependent due to a loop. | |||
541 | if (!valueDominatesPHI(RHS, PI, Q.DT)) | |||
542 | return nullptr; | |||
543 | ||||
544 | // Evaluate the BinOp on the incoming phi values. | |||
545 | Value *CommonValue = nullptr; | |||
546 | for (Value *Incoming : PI->incoming_values()) { | |||
547 | // If the incoming value is the phi node itself, it can safely be skipped. | |||
548 | if (Incoming == PI) continue; | |||
549 | Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse); | |||
550 | // If the operation failed to simplify, or simplified to a different value | |||
551 | // to previously, then give up. | |||
552 | if (!V || (CommonValue && V != CommonValue)) | |||
553 | return nullptr; | |||
554 | CommonValue = V; | |||
555 | } | |||
556 | ||||
557 | return CommonValue; | |||
558 | } | |||
559 | ||||
560 | static Constant *foldOrCommuteConstant(Instruction::BinaryOps Opcode, | |||
561 | Value *&Op0, Value *&Op1, | |||
562 | const SimplifyQuery &Q) { | |||
563 | if (auto *CLHS = dyn_cast<Constant>(Op0)) { | |||
564 | if (auto *CRHS = dyn_cast<Constant>(Op1)) | |||
565 | return ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, Q.DL); | |||
566 | ||||
567 | // Canonicalize the constant to the RHS if this is a commutative operation. | |||
568 | if (Instruction::isCommutative(Opcode)) | |||
569 | std::swap(Op0, Op1); | |||
570 | } | |||
571 | return nullptr; | |||
572 | } | |||
573 | ||||
574 | /// Given operands for an Add, see if we can fold the result. | |||
575 | /// If not, this returns null. | |||
576 | static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW, | |||
577 | const SimplifyQuery &Q, unsigned MaxRecurse) { | |||
578 | if (Constant *C = foldOrCommuteConstant(Instruction::Add, Op0, Op1, Q)) | |||
579 | return C; | |||
580 | ||||
581 | // X + undef -> undef | |||
582 | if (match(Op1, m_Undef())) | |||
583 | return Op1; | |||
584 | ||||
585 | // X + 0 -> X | |||
586 | if (match(Op1, m_Zero())) | |||
587 | return Op0; | |||
588 | ||||
589 | // If two operands are negative, return 0. | |||
590 | if (isKnownNegation(Op0, Op1)) | |||
591 | return Constant::getNullValue(Op0->getType()); | |||
592 | ||||
593 | // X + (Y - X) -> Y | |||
594 | // (Y - X) + X -> Y | |||
595 | // Eg: X + -X -> 0 | |||
596 | Value *Y = nullptr; | |||
597 | if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) || | |||
598 | match(Op0, m_Sub(m_Value(Y), m_Specific(Op1)))) | |||
599 | return Y; | |||
600 | ||||
601 | // X + ~X -> -1 since ~X = -X-1 | |||
602 | Type *Ty = Op0->getType(); | |||
603 | if (match(Op0, m_Not(m_Specific(Op1))) || | |||
604 | match(Op1, m_Not(m_Specific(Op0)))) | |||
605 | return Constant::getAllOnesValue(Ty); | |||
606 | ||||
607 | // add nsw/nuw (xor Y, signmask), signmask --> Y | |||
608 | // The no-wrapping add guarantees that the top bit will be set by the add. | |||
609 | // Therefore, the xor must be clearing the already set sign bit of Y. | |||
610 | if ((IsNSW || IsNUW) && match(Op1, m_SignMask()) && | |||
611 | match(Op0, m_Xor(m_Value(Y), m_SignMask()))) | |||
612 | return Y; | |||
613 | ||||
614 | // add nuw %x, -1 -> -1, because %x can only be 0. | |||
615 | if (IsNUW && match(Op1, m_AllOnes())) | |||
616 | return Op1; // Which is -1. | |||
617 | ||||
618 | /// i1 add -> xor. | |||
619 | if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1)) | |||
620 | if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1)) | |||
621 | return V; | |||
622 | ||||
623 | // Try some generic simplifications for associative operations. | |||
624 | if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q, | |||
625 | MaxRecurse)) | |||
626 | return V; | |||
627 | ||||
628 | // Threading Add over selects and phi nodes is pointless, so don't bother. | |||
629 | // Threading over the select in "A + select(cond, B, C)" means evaluating | |||
630 | // "A+B" and "A+C" and seeing if they are equal; but they are equal if and | |||
631 | // only if B and C are equal. If B and C are equal then (since we assume | |||
632 | // that operands have already been simplified) "select(cond, B, C)" should | |||
633 | // have been simplified to the common value of B and C already. Analysing | |||
634 | // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly | |||
635 | // for threading over phi nodes. | |||
636 | ||||
637 | return nullptr; | |||
638 | } | |||
639 | ||||
640 | Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW, | |||
641 | const SimplifyQuery &Query) { | |||
642 | return ::SimplifyAddInst(Op0, Op1, IsNSW, IsNUW, Query, RecursionLimit); | |||
643 | } | |||
644 | ||||
645 | /// Compute the base pointer and cumulative constant offsets for V. | |||
646 | /// | |||
647 | /// This strips all constant offsets off of V, leaving it the base pointer, and | |||
648 | /// accumulates the total constant offset applied in the returned constant. It | |||
649 | /// returns 0 if V is not a pointer, and returns the constant '0' if there are | |||
650 | /// no constant offsets applied. | |||
651 | /// | |||
652 | /// This is very similar to GetPointerBaseWithConstantOffset except it doesn't | |||
653 | /// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc. | |||
654 | /// folding. | |||
655 | static Constant *stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V, | |||
656 | bool AllowNonInbounds = false) { | |||
657 | assert(V->getType()->isPtrOrPtrVectorTy())((V->getType()->isPtrOrPtrVectorTy()) ? static_cast< void> (0) : __assert_fail ("V->getType()->isPtrOrPtrVectorTy()" , "/build/llvm-toolchain-snapshot-9~svn360825/lib/Analysis/InstructionSimplify.cpp" , 657, __PRETTY_FUNCTION__)); | |||
658 | ||||
659 | Type *IntPtrTy = DL.getIntPtrType(V->getType())->getScalarType(); | |||
660 | APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth()); | |||
661 | ||||
662 | // Even though we don't look through PHI nodes, we could be called on an | |||
663 | // instruction in an unreachable block, which may be on a cycle. | |||
664 | SmallPtrSet<Value *, 4> Visited; | |||
665 | Visited.insert(V); | |||
666 | do { | |||
667 | if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) { | |||
668 | if ((!AllowNonInbounds && !GEP->isInBounds()) || | |||
669 | !GEP->accumulateConstantOffset(DL, Offset)) | |||
670 | break; | |||
671 | V = GEP->getPointerOperand(); | |||
672 | } else if (Operator::getOpcode(V) == Instruction::BitCast) { | |||
673 | V = cast<Operator>(V)->getOperand(0); | |||
674 | } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) { | |||
675 | if (GA->isInterposable()) | |||
676 | break; | |||
677 | V = GA->getAliasee(); | |||
678 | } else { | |||
679 | if (auto *Call = dyn_cast<CallBase>(V)) | |||
680 | if (Value *RV = Call->getReturnedArgOperand()) { | |||
681 | V = RV; | |||
682 | continue; | |||
683 | } | |||
684 | break; | |||
685 | } | |||
686 | assert(V->getType()->isPtrOrPtrVectorTy() && "Unexpected operand type!")((V->getType()->isPtrOrPtrVectorTy() && "Unexpected operand type!" ) ? static_cast<void> (0) : __assert_fail ("V->getType()->isPtrOrPtrVectorTy() && \"Unexpected operand type!\"" , "/build/llvm-toolchain-snapshot-9~svn360825/lib/Analysis/InstructionSimplify.cpp" , 686, __PRETTY_FUNCTION__)); | |||
687 | } while (Visited.insert(V).second); | |||
688 | ||||
689 | Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset); | |||
690 | if (V->getType()->isVectorTy()) | |||
691 | return ConstantVector::getSplat(V->getType()->getVectorNumElements(), | |||
692 | OffsetIntPtr); | |||
693 | return OffsetIntPtr; | |||
694 | } | |||
695 | ||||
696 | /// Compute the constant difference between two pointer values. | |||
697 | /// If the difference is not a constant, returns zero. | |||
698 | static Constant *computePointerDifference(const DataLayout &DL, Value *LHS, | |||
699 | Value *RHS) { | |||
700 | Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS); | |||
701 | Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS); | |||
702 | ||||
703 | // If LHS and RHS are not related via constant offsets to the same base | |||
704 | // value, there is nothing we can do here. | |||
705 | if (LHS != RHS) | |||
706 | return nullptr; | |||
707 | ||||
708 | // Otherwise, the difference of LHS - RHS can be computed as: | |||
709 | // LHS - RHS | |||
710 | // = (LHSOffset + Base) - (RHSOffset + Base) | |||
711 | // = LHSOffset - RHSOffset | |||
712 | return ConstantExpr::getSub(LHSOffset, RHSOffset); | |||
713 | } | |||
714 | ||||
715 | /// Given operands for a Sub, see if we can fold the result. | |||
716 | /// If not, this returns null. | |||
717 | static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW, | |||
718 | const SimplifyQuery &Q, unsigned MaxRecurse) { | |||
719 | if (Constant *C = foldOrCommuteConstant(Instruction::Sub, Op0, Op1, Q)) | |||
720 | return C; | |||
721 | ||||
722 | // X - undef -> undef | |||
723 | // undef - X -> undef | |||
724 | if (match(Op0, m_Undef()) || match(Op1, m_Undef())) | |||
725 | return UndefValue::get(Op0->getType()); | |||
726 | ||||
727 | // X - 0 -> X | |||
728 | if (match(Op1, m_Zero())) | |||
729 | return Op0; | |||
730 | ||||
731 | // X - X -> 0 | |||
732 | if (Op0 == Op1) | |||
733 | return Constant::getNullValue(Op0->getType()); | |||
734 | ||||
735 | // Is this a negation? | |||
736 | if (match(Op0, m_Zero())) { | |||
737 | // 0 - X -> 0 if the sub is NUW. | |||
738 | if (isNUW) | |||
739 | return Constant::getNullValue(Op0->getType()); | |||
740 | ||||
741 | KnownBits Known = computeKnownBits(Op1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); | |||
742 | if (Known.Zero.isMaxSignedValue()) { | |||
743 | // Op1 is either 0 or the minimum signed value. If the sub is NSW, then | |||
744 | // Op1 must be 0 because negating the minimum signed value is undefined. | |||
745 | if (isNSW) | |||
746 | return Constant::getNullValue(Op0->getType()); | |||
747 | ||||
748 | // 0 - X -> X if X is 0 or the minimum signed value. | |||
749 | return Op1; | |||
750 | } | |||
751 | } | |||
752 | ||||
753 | // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies. | |||
754 | // For example, (X + Y) - Y -> X; (Y + X) - Y -> X | |||
755 | Value *X = nullptr, *Y = nullptr, *Z = Op1; | |||
756 | if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z | |||
757 | // See if "V === Y - Z" simplifies. | |||
758 | if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1)) | |||
759 | // It does! Now see if "X + V" simplifies. | |||
760 | if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) { | |||
761 | // It does, we successfully reassociated! | |||
762 | ++NumReassoc; | |||
763 | return W; | |||
764 | } | |||
765 | // See if "V === X - Z" simplifies. | |||
766 | if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1)) | |||
767 | // It does! Now see if "Y + V" simplifies. | |||
768 | if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) { | |||
769 | // It does, we successfully reassociated! | |||
770 | ++NumReassoc; | |||
771 | return W; | |||
772 | } | |||
773 | } | |||
774 | ||||
775 | // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies. | |||
776 | // For example, X - (X + 1) -> -1 | |||
777 | X = Op0; | |||
778 | if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z) | |||
779 | // See if "V === X - Y" simplifies. | |||
780 | if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1)) | |||
781 | // It does! Now see if "V - Z" simplifies. | |||
782 | if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) { | |||
783 | // It does, we successfully reassociated! | |||
784 | ++NumReassoc; | |||
785 | return W; | |||
786 | } | |||
787 | // See if "V === X - Z" simplifies. | |||
788 | if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1)) | |||
789 | // It does! Now see if "V - Y" simplifies. | |||
790 | if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) { | |||
791 | // It does, we successfully reassociated! | |||
792 | ++NumReassoc; | |||
793 | return W; | |||
794 | } | |||
795 | } | |||
796 | ||||
797 | // Z - (X - Y) -> (Z - X) + Y if everything simplifies. | |||
798 | // For example, X - (X - Y) -> Y. | |||
799 | Z = Op0; | |||
800 | if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y) | |||
801 | // See if "V === Z - X" simplifies. | |||
802 | if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1)) | |||
803 | // It does! Now see if "V + Y" simplifies. | |||
804 | if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) { | |||
805 | // It does, we successfully reassociated! | |||
806 | ++NumReassoc; | |||
807 | return W; | |||
808 | } | |||
809 | ||||
810 | // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies. | |||
811 | if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) && | |||
812 | match(Op1, m_Trunc(m_Value(Y)))) | |||
813 | if (X->getType() == Y->getType()) | |||
814 | // See if "V === X - Y" simplifies. | |||
815 | if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1)) | |||
816 | // It does! Now see if "trunc V" simplifies. | |||
817 | if (Value *W = SimplifyCastInst(Instruction::Trunc, V, Op0->getType(), | |||
818 | Q, MaxRecurse - 1)) | |||
819 | // It does, return the simplified "trunc V". | |||
820 | return W; | |||
821 | ||||
822 | // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...). | |||
823 | if (match(Op0, m_PtrToInt(m_Value(X))) && | |||
824 | match(Op1, m_PtrToInt(m_Value(Y)))) | |||
825 | if (Constant *Result = computePointerDifference(Q.DL, X, Y)) | |||
826 | return ConstantExpr::getIntegerCast(Result, Op0->getType(), true); | |||
827 | ||||
828 | // i1 sub -> xor. | |||
829 | if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1)) | |||
830 | if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1)) | |||
831 | return V; | |||
832 | ||||
833 | // Threading Sub over selects and phi nodes is pointless, so don't bother. | |||
834 | // Threading over the select in "A - select(cond, B, C)" means evaluating | |||
835 | // "A-B" and "A-C" and seeing if they are equal; but they are equal if and | |||
836 | // only if B and C are equal. If B and C are equal then (since we assume | |||
837 | // that operands have already been simplified) "select(cond, B, C)" should | |||
838 | // have been simplified to the common value of B and C already. Analysing | |||
839 | // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly | |||
840 | // for threading over phi nodes. | |||
841 | ||||
842 | return nullptr; | |||
843 | } | |||
844 | ||||
845 | Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW, | |||
846 | const SimplifyQuery &Q) { | |||
847 | return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Q, RecursionLimit); | |||
848 | } | |||
849 | ||||
850 | /// Given operands for a Mul, see if we can fold the result. | |||
851 | /// If not, this returns null. | |||
852 | static Value *SimplifyMulInst(Value *Op0, Value *Op1, const SimplifyQuery &Q, | |||
853 | unsigned MaxRecurse) { | |||
854 | if (Constant *C = foldOrCommuteConstant(Instruction::Mul, Op0, Op1, Q)) | |||
855 | return C; | |||
856 | ||||
857 | // X * undef -> 0 | |||
858 | // X * 0 -> 0 | |||
859 | if (match(Op1, m_CombineOr(m_Undef(), m_Zero()))) | |||
860 | return Constant::getNullValue(Op0->getType()); | |||
861 | ||||
862 | // X * 1 -> X | |||
863 | if (match(Op1, m_One())) | |||
864 | return Op0; | |||
865 | ||||
866 | // (X / Y) * Y -> X if the division is exact. | |||
867 | Value *X = nullptr; | |||
868 | if (Q.IIQ.UseInstrInfo && | |||
869 | (match(Op0, | |||
870 | m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y | |||
871 | match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0)))))) // Y * (X / Y) | |||
872 | return X; | |||
873 | ||||
874 | // i1 mul -> and. | |||
875 | if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1)) | |||
876 | if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1)) | |||
877 | return V; | |||
878 | ||||
879 | // Try some generic simplifications for associative operations. | |||
880 | if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q, | |||
881 | MaxRecurse)) | |||
882 | return V; | |||
883 | ||||
884 | // Mul distributes over Add. Try some generic simplifications based on this. | |||
885 | if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add, | |||
886 | Q, MaxRecurse)) | |||
887 | return V; | |||
888 | ||||
889 | // If the operation is with the result of a select instruction, check whether | |||
890 | // operating on either branch of the select always yields the same value. | |||
891 | if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) | |||
892 | if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q, | |||
893 | MaxRecurse)) | |||
894 | return V; | |||
895 | ||||
896 | // If the operation is with the result of a phi instruction, check whether | |||
897 | // operating on all incoming values of the phi always yields the same value. | |||
898 | if (isa<PHINode>(Op0) || isa<PHINode>(Op1)) | |||
899 | if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q, | |||
900 | MaxRecurse)) | |||
901 | return V; | |||
902 | ||||
903 | return nullptr; | |||
904 | } | |||
905 | ||||
906 | Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) { | |||
907 | return ::SimplifyMulInst(Op0, Op1, Q, RecursionLimit); | |||
908 | } | |||
909 | ||||
910 | /// Check for common or similar folds of integer division or integer remainder. | |||
911 | /// This applies to all 4 opcodes (sdiv/udiv/srem/urem). | |||
912 | static Value *simplifyDivRem(Value *Op0, Value *Op1, bool IsDiv) { | |||
913 | Type *Ty = Op0->getType(); | |||
914 | ||||
915 | // X / undef -> undef | |||
916 | // X % undef -> undef | |||
917 | if (match(Op1, m_Undef())) | |||
918 | return Op1; | |||
919 | ||||
920 | // X / 0 -> undef | |||
921 | // X % 0 -> undef | |||
922 | // We don't need to preserve faults! | |||
923 | if (match(Op1, m_Zero())) | |||
924 | return UndefValue::get(Ty); | |||
925 | ||||
926 | // If any element of a constant divisor vector is zero or undef, the whole op | |||
927 | // is undef. | |||
928 | auto *Op1C = dyn_cast<Constant>(Op1); | |||
929 | if (Op1C && Ty->isVectorTy()) { | |||
930 | unsigned NumElts = Ty->getVectorNumElements(); | |||
931 | for (unsigned i = 0; i != NumElts; ++i) { | |||
932 | Constant *Elt = Op1C->getAggregateElement(i); | |||
933 | if (Elt && (Elt->isNullValue() || isa<UndefValue>(Elt))) | |||
934 | return UndefValue::get(Ty); | |||
935 | } | |||
936 | } | |||
937 | ||||
938 | // undef / X -> 0 | |||
939 | // undef % X -> 0 | |||
940 | if (match(Op0, m_Undef())) | |||
941 | return Constant::getNullValue(Ty); | |||
942 | ||||
943 | // 0 / X -> 0 | |||
944 | // 0 % X -> 0 | |||
945 | if (match(Op0, m_Zero())) | |||
946 | return Constant::getNullValue(Op0->getType()); | |||
947 | ||||
948 | // X / X -> 1 | |||
949 | // X % X -> 0 | |||
950 | if (Op0 == Op1) | |||
951 | return IsDiv ? ConstantInt::get(Ty, 1) : Constant::getNullValue(Ty); | |||
952 | ||||
953 | // X / 1 -> X | |||
954 | // X % 1 -> 0 | |||
955 | // If this is a boolean op (single-bit element type), we can't have | |||
956 | // division-by-zero or remainder-by-zero, so assume the divisor is 1. | |||
957 | // Similarly, if we're zero-extending a boolean divisor, then assume it's a 1. | |||
958 | Value *X; | |||
959 | if (match(Op1, m_One()) || Ty->isIntOrIntVectorTy(1) || | |||
960 | (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))) | |||
961 | return IsDiv ? Op0 : Constant::getNullValue(Ty); | |||
962 | ||||
963 | return nullptr; | |||
964 | } | |||
965 | ||||
966 | /// Given a predicate and two operands, return true if the comparison is true. | |||
967 | /// This is a helper for div/rem simplification where we return some other value | |||
968 | /// when we can prove a relationship between the operands. | |||
969 | static bool isICmpTrue(ICmpInst::Predicate Pred, Value *LHS, Value *RHS, | |||
970 | const SimplifyQuery &Q, unsigned MaxRecurse) { | |||
971 | Value *V = SimplifyICmpInst(Pred, LHS, RHS, Q, MaxRecurse); | |||
972 | Constant *C = dyn_cast_or_null<Constant>(V); | |||
973 | return (C && C->isAllOnesValue()); | |||
974 | } | |||
975 | ||||
976 | /// Return true if we can simplify X / Y to 0. Remainder can adapt that answer | |||
977 | /// to simplify X % Y to X. | |||
978 | static bool isDivZero(Value *X, Value *Y, const SimplifyQuery &Q, | |||
979 | unsigned MaxRecurse, bool IsSigned) { | |||
980 | // Recursion is always used, so bail out at once if we already hit the limit. | |||
981 | if (!MaxRecurse--) | |||
982 | return false; | |||
983 | ||||
984 | if (IsSigned) { | |||
985 | // |X| / |Y| --> 0 | |||
986 | // | |||
987 | // We require that 1 operand is a simple constant. That could be extended to | |||
988 | // 2 variables if we computed the sign bit for each. | |||
989 | // | |||
990 | // Make sure that a constant is not the minimum signed value because taking | |||
991 | // the abs() of that is undefined. | |||
992 | Type *Ty = X->getType(); | |||
993 | const APInt *C; | |||
994 | if (match(X, m_APInt(C)) && !C->isMinSignedValue()) { | |||
995 | // Is the variable divisor magnitude always greater than the constant | |||
996 | // dividend magnitude? | |||
997 | // |Y| > |C| --> Y < -abs(C) or Y > abs(C) | |||
998 | Constant *PosDividendC = ConstantInt::get(Ty, C->abs()); | |||
999 | Constant *NegDividendC = ConstantInt::get(Ty, -C->abs()); | |||
1000 | if (isICmpTrue(CmpInst::ICMP_SLT, Y, NegDividendC, Q, MaxRecurse) || | |||
1001 | isICmpTrue(CmpInst::ICMP_SGT, Y, PosDividendC, Q, MaxRecurse)) | |||
1002 | return true; | |||
1003 | } | |||
1004 | if (match(Y, m_APInt(C))) { | |||
1005 | // Special-case: we can't take the abs() of a minimum signed value. If | |||
1006 | // that's the divisor, then all we have to do is prove that the dividend | |||
1007 | // is also not the minimum signed value. | |||
1008 | if (C->isMinSignedValue()) | |||
1009 | return isICmpTrue(CmpInst::ICMP_NE, X, Y, Q, MaxRecurse); | |||
1010 | ||||
1011 | // Is the variable dividend magnitude always less than the constant | |||
1012 | // divisor magnitude? | |||
1013 | // |X| < |C| --> X > -abs(C) and X < abs(C) | |||
1014 | Constant *PosDivisorC = ConstantInt::get(Ty, C->abs()); | |||
1015 | Constant *NegDivisorC = ConstantInt::get(Ty, -C->abs()); | |||
1016 | if (isICmpTrue(CmpInst::ICMP_SGT, X, NegDivisorC, Q, MaxRecurse) && | |||
1017 | isICmpTrue(CmpInst::ICMP_SLT, X, PosDivisorC, Q, MaxRecurse)) | |||
1018 | return true; | |||
1019 | } | |||
1020 | return false; | |||
1021 | } | |||
1022 | ||||
1023 | // IsSigned == false. | |||
1024 | // Is the dividend unsigned less than the divisor? | |||
1025 | return isICmpTrue(ICmpInst::ICMP_ULT, X, Y, Q, MaxRecurse); | |||
1026 | } | |||
1027 | ||||
1028 | /// These are simplifications common to SDiv and UDiv. | |||
1029 | static Value *simplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1, | |||
1030 | const SimplifyQuery &Q, unsigned MaxRecurse) { | |||
1031 | if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q)) | |||
1032 | return C; | |||
1033 | ||||
1034 | if (Value *V = simplifyDivRem(Op0, Op1, true)) | |||
1035 | return V; | |||
1036 | ||||
1037 | bool IsSigned = Opcode == Instruction::SDiv; | |||
1038 | ||||
1039 | // (X * Y) / Y -> X if the multiplication does not overflow. | |||
1040 | Value *X; | |||
1041 | if (match(Op0, m_c_Mul(m_Value(X), m_Specific(Op1)))) { | |||
1042 | auto *Mul = cast<OverflowingBinaryOperator>(Op0); | |||
1043 | // If the Mul does not overflow, then we are good to go. | |||
1044 | if ((IsSigned && Q.IIQ.hasNoSignedWrap(Mul)) || | |||
1045 | (!IsSigned && Q.IIQ.hasNoUnsignedWrap(Mul))) | |||
1046 | return X; | |||
1047 | // If X has the form X = A / Y, then X * Y cannot overflow. | |||
1048 | if ((IsSigned && match(X, m_SDiv(m_Value(), m_Specific(Op1)))) || | |||
1049 | (!IsSigned && match(X, m_UDiv(m_Value(), m_Specific(Op1))))) | |||
1050 | return X; | |||
1051 | } | |||
1052 | ||||
1053 | // (X rem Y) / Y -> 0 | |||
1054 | if ((IsSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) || | |||
1055 | (!IsSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1))))) | |||
1056 | return Constant::getNullValue(Op0->getType()); | |||
1057 | ||||
1058 | // (X /u C1) /u C2 -> 0 if C1 * C2 overflow | |||
1059 | ConstantInt *C1, *C2; | |||
1060 | if (!IsSigned && match(Op0, m_UDiv(m_Value(X), m_ConstantInt(C1))) && | |||
1061 | match(Op1, m_ConstantInt(C2))) { | |||
1062 | bool Overflow; | |||
1063 | (void)C1->getValue().umul_ov(C2->getValue(), Overflow); | |||
1064 | if (Overflow) | |||
1065 | return Constant::getNullValue(Op0->getType()); | |||
1066 | } | |||
1067 | ||||
1068 | // If the operation is with the result of a select instruction, check whether | |||
1069 | // operating on either branch of the select always yields the same value. | |||
1070 | if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) | |||
1071 | if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse)) | |||
1072 | return V; | |||
1073 | ||||
1074 | // If the operation is with the result of a phi instruction, check whether | |||
1075 | // operating on all incoming values of the phi always yields the same value. | |||
1076 | if (isa<PHINode>(Op0) || isa<PHINode>(Op1)) | |||
1077 | if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse)) | |||
1078 | return V; | |||
1079 | ||||
1080 | if (isDivZero(Op0, Op1, Q, MaxRecurse, IsSigned)) | |||
1081 | return Constant::getNullValue(Op0->getType()); | |||
1082 | ||||
1083 | return nullptr; | |||
1084 | } | |||
1085 | ||||
1086 | /// These are simplifications common to SRem and URem. | |||
1087 | static Value *simplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1, | |||
1088 | const SimplifyQuery &Q, unsigned MaxRecurse) { | |||
1089 | if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q)) | |||
1090 | return C; | |||
1091 | ||||
1092 | if (Value *V = simplifyDivRem(Op0, Op1, false)) | |||
1093 | return V; | |||
1094 | ||||
1095 | // (X % Y) % Y -> X % Y | |||
1096 | if ((Opcode == Instruction::SRem && | |||
1097 | match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) || | |||
1098 | (Opcode == Instruction::URem && | |||
1099 | match(Op0, m_URem(m_Value(), m_Specific(Op1))))) | |||
1100 | return Op0; | |||
1101 | ||||
1102 | // (X << Y) % X -> 0 | |||
1103 | if (Q.IIQ.UseInstrInfo && | |||
1104 | ((Opcode == Instruction::SRem && | |||
1105 | match(Op0, m_NSWShl(m_Specific(Op1), m_Value()))) || | |||
1106 | (Opcode == Instruction::URem && | |||
1107 | match(Op0, m_NUWShl(m_Specific(Op1), m_Value()))))) | |||
1108 | return Constant::getNullValue(Op0->getType()); | |||
1109 | ||||
1110 | // If the operation is with the result of a select instruction, check whether | |||
1111 | // operating on either branch of the select always yields the same value. | |||
1112 | if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) | |||
1113 | if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse)) | |||
1114 | return V; | |||
1115 | ||||
1116 | // If the operation is with the result of a phi instruction, check whether | |||
1117 | // operating on all incoming values of the phi always yields the same value. | |||
1118 | if (isa<PHINode>(Op0) || isa<PHINode>(Op1)) | |||
1119 | if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse)) | |||
1120 | return V; | |||
1121 | ||||
1122 | // If X / Y == 0, then X % Y == X. | |||
1123 | if (isDivZero(Op0, Op1, Q, MaxRecurse, Opcode == Instruction::SRem)) | |||
1124 | return Op0; | |||
1125 | ||||
1126 | return nullptr; | |||
1127 | } | |||
1128 | ||||
1129 | /// Given operands for an SDiv, see if we can fold the result. | |||
1130 | /// If not, this returns null. | |||
1131 | static Value *SimplifySDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q, | |||
1132 | unsigned MaxRecurse) { | |||
1133 | // If two operands are negated and no signed overflow, return -1. | |||
1134 | if (isKnownNegation(Op0, Op1, /*NeedNSW=*/true)) | |||
1135 | return Constant::getAllOnesValue(Op0->getType()); | |||
1136 | ||||
1137 | return simplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse); | |||
1138 | } | |||
1139 | ||||
1140 | Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) { | |||
1141 | return ::SimplifySDivInst(Op0, Op1, Q, RecursionLimit); | |||
1142 | } | |||
1143 | ||||
1144 | /// Given operands for a UDiv, see if we can fold the result. | |||
1145 | /// If not, this returns null. | |||
1146 | static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q, | |||
1147 | unsigned MaxRecurse) { | |||
1148 | return simplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse); | |||
1149 | } | |||
1150 | ||||
1151 | Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) { | |||
1152 | return ::SimplifyUDivInst(Op0, Op1, Q, RecursionLimit); | |||
1153 | } | |||
1154 | ||||
1155 | /// Given operands for an SRem, see if we can fold the result. | |||
1156 | /// If not, this returns null. | |||
1157 | static Value *SimplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q, | |||
1158 | unsigned MaxRecurse) { | |||
1159 | // If the divisor is 0, the result is undefined, so assume the divisor is -1. | |||
1160 | // srem Op0, (sext i1 X) --> srem Op0, -1 --> 0 | |||
1161 | Value *X; | |||
1162 | if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) | |||
1163 | return ConstantInt::getNullValue(Op0->getType()); | |||
1164 | ||||
1165 | // If the two operands are negated, return 0. | |||
1166 | if (isKnownNegation(Op0, Op1)) | |||
1167 | return ConstantInt::getNullValue(Op0->getType()); | |||
1168 | ||||
1169 | return simplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse); | |||
1170 | } | |||
1171 | ||||
1172 | Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) { | |||
1173 | return ::SimplifySRemInst(Op0, Op1, Q, RecursionLimit); | |||
1174 | } | |||
1175 | ||||
1176 | /// Given operands for a URem, see if we can fold the result. | |||
1177 | /// If not, this returns null. | |||
1178 | static Value *SimplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q, | |||
1179 | unsigned MaxRecurse) { | |||
1180 | return simplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse); | |||
1181 | } | |||
1182 | ||||
1183 | Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) { | |||
1184 | return ::SimplifyURemInst(Op0, Op1, Q, RecursionLimit); | |||
1185 | } | |||
1186 | ||||
1187 | /// Returns true if a shift by \c Amount always yields undef. | |||
1188 | static bool isUndefShift(Value *Amount) { | |||
1189 | Constant *C = dyn_cast<Constant>(Amount); | |||
1190 | if (!C) | |||
1191 | return false; | |||
1192 | ||||
1193 | // X shift by undef -> undef because it may shift by the bitwidth. | |||
1194 | if (isa<UndefValue>(C)) | |||
1195 | return true; | |||
1196 | ||||
1197 | // Shifting by the bitwidth or more is undefined. | |||
1198 | if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) | |||
1199 | if (CI->getValue().getLimitedValue() >= | |||
1200 | CI->getType()->getScalarSizeInBits()) | |||
1201 | return true; | |||
1202 | ||||
1203 | // If all lanes of a vector shift are undefined the whole shift is. | |||
1204 | if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) { | |||
1205 | for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I) | |||
1206 | if (!isUndefShift(C->getAggregateElement(I))) | |||
1207 | return false; | |||
1208 | return true; | |||
1209 | } | |||
1210 | ||||
1211 | return false; | |||
1212 | } | |||
1213 | ||||
1214 | /// Given operands for an Shl, LShr or AShr, see if we can fold the result. | |||
1215 | /// If not, this returns null. | |||
1216 | static Value *SimplifyShift(Instruction::BinaryOps Opcode, Value *Op0, | |||
1217 | Value *Op1, const SimplifyQuery &Q, unsigned MaxRecurse) { | |||
1218 | if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q)) | |||
1219 | return C; | |||
1220 | ||||
1221 | // 0 shift by X -> 0 | |||
1222 | if (match(Op0, m_Zero())) | |||
1223 | return Constant::getNullValue(Op0->getType()); | |||
1224 | ||||
1225 | // X shift by 0 -> X | |||
1226 | // Shift-by-sign-extended bool must be shift-by-0 because shift-by-all-ones | |||
1227 | // would be poison. | |||
1228 | Value *X; | |||
1229 | if (match(Op1, m_Zero()) || | |||
1230 | (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))) | |||
1231 | return Op0; | |||
1232 | ||||
1233 | // Fold undefined shifts. | |||
1234 | if (isUndefShift(Op1)) | |||
1235 | return UndefValue::get(Op0->getType()); | |||
1236 | ||||
1237 | // If the operation is with the result of a select instruction, check whether | |||
1238 | // operating on either branch of the select always yields the same value. | |||
1239 | if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) | |||
1240 | if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse)) | |||
1241 | return V; | |||
1242 | ||||
1243 | // If the operation is with the result of a phi instruction, check whether | |||
1244 | // operating on all incoming values of the phi always yields the same value. | |||
1245 | if (isa<PHINode>(Op0) || isa<PHINode>(Op1)) | |||
1246 | if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse)) | |||
1247 | return V; | |||
1248 | ||||
1249 | // If any bits in the shift amount make that value greater than or equal to | |||
1250 | // the number of bits in the type, the shift is undefined. | |||
1251 | KnownBits Known = computeKnownBits(Op1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); | |||
1252 | if (Known.One.getLimitedValue() >= Known.getBitWidth()) | |||
1253 | return UndefValue::get(Op0->getType()); | |||
1254 | ||||
1255 | // If all valid bits in the shift amount are known zero, the first operand is | |||
1256 | // unchanged. | |||
1257 | unsigned NumValidShiftBits = Log2_32_Ceil(Known.getBitWidth()); | |||
1258 | if (Known.countMinTrailingZeros() >= NumValidShiftBits) | |||
1259 | return Op0; | |||
1260 | ||||
1261 | return nullptr; | |||
1262 | } | |||
1263 | ||||
1264 | /// Given operands for an Shl, LShr or AShr, see if we can | |||
1265 | /// fold the result. If not, this returns null. | |||
1266 | static Value *SimplifyRightShift(Instruction::BinaryOps Opcode, Value *Op0, | |||
1267 | Value *Op1, bool isExact, const SimplifyQuery &Q, | |||
1268 | unsigned MaxRecurse) { | |||
1269 | if (Value *V = SimplifyShift(Opcode, Op0, Op1, Q, MaxRecurse)) | |||
1270 | return V; | |||
1271 | ||||
1272 | // X >> X -> 0 | |||
1273 | if (Op0 == Op1) | |||
1274 | return Constant::getNullValue(Op0->getType()); | |||
1275 | ||||
1276 | // undef >> X -> 0 | |||
1277 | // undef >> X -> undef (if it's exact) | |||
1278 | if (match(Op0, m_Undef())) | |||
1279 | return isExact ? Op0 : Constant::getNullValue(Op0->getType()); | |||
1280 | ||||
1281 | // The low bit cannot be shifted out of an exact shift if it is set. | |||
1282 | if (isExact) { | |||
1283 | KnownBits Op0Known = computeKnownBits(Op0, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT); | |||
1284 | if (Op0Known.One[0]) | |||
1285 | return Op0; | |||
1286 | } | |||
1287 | ||||
1288 | return nullptr; | |||
1289 | } | |||
1290 | ||||
1291 | /// Given operands for an Shl, see if we can fold the result. | |||
1292 | /// If not, this returns null. | |||
1293 | static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW, | |||
1294 | const SimplifyQuery &Q, unsigned MaxRecurse) { | |||
1295 | if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse)) | |||
1296 | return V; | |||
1297 | ||||
1298 | // undef << X -> 0 | |||
1299 | // undef << X -> undef if (if it's NSW/NUW) | |||
1300 | if (match(Op0, m_Undef())) | |||
1301 | return isNSW || isNUW ? Op0 : Constant::getNullValue(Op0->getType()); | |||
1302 | ||||
1303 | // (X >> A) << A -> X | |||
1304 | Value *X; | |||
1305 | if (Q.IIQ.UseInstrInfo && | |||
1306 | match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1))))) | |||
1307 | return X; | |||
1308 | ||||
1309 | // shl nuw i8 C, %x -> C iff C has sign bit set. | |||
1310 | if (isNUW && match(Op0, m_Negative())) | |||
1311 | return Op0; | |||
1312 | // NOTE: could use computeKnownBits() / LazyValueInfo, | |||
1313 | // but the cost-benefit analysis suggests it isn't worth it. | |||
1314 | ||||
1315 | return nullptr; | |||
1316 | } | |||
1317 | ||||
1318 | Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW, | |||
1319 | const SimplifyQuery &Q) { | |||
1320 | return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Q, RecursionLimit); | |||
1321 | } | |||
1322 | ||||
1323 | /// Given operands for an LShr, see if we can fold the result. | |||
1324 | /// If not, this returns null. | |||
1325 | static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact, | |||
1326 | const SimplifyQuery &Q, unsigned MaxRecurse) { | |||
1327 | if (Value *V = SimplifyRightShift(Instruction::LShr, Op0, Op1, isExact, Q, | |||
1328 | MaxRecurse)) | |||
1329 | return V; | |||
1330 | ||||
1331 | // (X << A) >> A -> X | |||
1332 | Value *X; | |||
1333 | if (match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1)))) | |||
1334 | return X; | |||
1335 | ||||
1336 | // ((X << A) | Y) >> A -> X if effective width of Y is not larger than A. | |||
1337 | // We can return X as we do in the above case since OR alters no bits in X. | |||
1338 | // SimplifyDemandedBits in InstCombine can do more general optimization for | |||
1339 | // bit manipulation. This pattern aims to provide opportunities for other | |||
1340 | // optimizers by supporting a simple but common case in InstSimplify. | |||
1341 | Value *Y; | |||
1342 | const APInt *ShRAmt, *ShLAmt; | |||
1343 | if (match(Op1, m_APInt(ShRAmt)) && | |||
1344 | match(Op0, m_c_Or(m_NUWShl(m_Value(X), m_APInt(ShLAmt)), m_Value(Y))) && | |||
1345 | *ShRAmt == *ShLAmt) { | |||
1346 | const KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); | |||
1347 | const unsigned Width = Op0->getType()->getScalarSizeInBits(); | |||
1348 | const unsigned EffWidthY = Width - YKnown.countMinLeadingZeros(); | |||
1349 | if (ShRAmt->uge(EffWidthY)) | |||
1350 | return X; | |||
1351 | } | |||
1352 | ||||
1353 | return nullptr; | |||
1354 | } | |||
1355 | ||||
1356 | Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact, | |||
1357 | const SimplifyQuery &Q) { | |||
1358 | return ::SimplifyLShrInst(Op0, Op1, isExact, Q, RecursionLimit); | |||
1359 | } | |||
1360 | ||||
1361 | /// Given operands for an AShr, see if we can fold the result. | |||
1362 | /// If not, this returns null. | |||
1363 | static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact, | |||
1364 | const SimplifyQuery &Q, unsigned MaxRecurse) { | |||
1365 | if (Value *V = SimplifyRightShift(Instruction::AShr, Op0, Op1, isExact, Q, | |||
1366 | MaxRecurse)) | |||
1367 | return V; | |||
1368 | ||||
1369 | // all ones >>a X -> -1 | |||
1370 | // Do not return Op0 because it may contain undef elements if it's a vector. | |||
1371 | if (match(Op0, m_AllOnes())) | |||
1372 | return Constant::getAllOnesValue(Op0->getType()); | |||
1373 | ||||
1374 | // (X << A) >> A -> X | |||
1375 | Value *X; | |||
1376 | if (Q.IIQ.UseInstrInfo && match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1)))) | |||
1377 | return X; | |||
1378 | ||||
1379 | // Arithmetic shifting an all-sign-bit value is a no-op. | |||
1380 | unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); | |||
1381 | if (NumSignBits == Op0->getType()->getScalarSizeInBits()) | |||
1382 | return Op0; | |||
1383 | ||||
1384 | return nullptr; | |||
1385 | } | |||
1386 | ||||
1387 | Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact, | |||
1388 | const SimplifyQuery &Q) { | |||
1389 | return ::SimplifyAShrInst(Op0, Op1, isExact, Q, RecursionLimit); | |||
1390 | } | |||
1391 | ||||
1392 | /// Commuted variants are assumed to be handled by calling this function again | |||
1393 | /// with the parameters swapped. | |||
1394 | static Value *simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp, | |||
1395 | ICmpInst *UnsignedICmp, bool IsAnd) { | |||
1396 | Value *X, *Y; | |||
1397 | ||||
1398 | ICmpInst::Predicate EqPred; | |||
1399 | if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) || | |||
1400 | !ICmpInst::isEquality(EqPred)) | |||
1401 | return nullptr; | |||
1402 | ||||
1403 | ICmpInst::Predicate UnsignedPred; | |||
1404 | if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) && | |||
1405 | ICmpInst::isUnsigned(UnsignedPred)) | |||
1406 | ; | |||
1407 | else if (match(UnsignedICmp, | |||
1408 | m_ICmp(UnsignedPred, m_Specific(Y), m_Value(X))) && | |||
1409 | ICmpInst::isUnsigned(UnsignedPred)) | |||
1410 | UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred); | |||
1411 | else | |||
1412 | return nullptr; | |||
1413 | ||||
1414 | // X < Y && Y != 0 --> X < Y | |||
1415 | // X < Y || Y != 0 --> Y != 0 | |||
1416 | if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE) | |||
1417 | return IsAnd ? UnsignedICmp : ZeroICmp; | |||
1418 | ||||
1419 | // X >= Y || Y != 0 --> true | |||
1420 | // X >= Y || Y == 0 --> X >= Y | |||
1421 | if (UnsignedPred == ICmpInst::ICMP_UGE && !IsAnd) { | |||
1422 | if (EqPred == ICmpInst::ICMP_NE) | |||
1423 | return getTrue(UnsignedICmp->getType()); | |||
1424 | return UnsignedICmp; | |||
1425 | } | |||
1426 | ||||
1427 | // X < Y && Y == 0 --> false | |||
1428 | if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ && | |||
1429 | IsAnd) | |||
1430 | return getFalse(UnsignedICmp->getType()); | |||
1431 | ||||
1432 | return nullptr; | |||
1433 | } | |||
1434 | ||||
1435 | /// Commuted variants are assumed to be handled by calling this function again | |||
1436 | /// with the parameters swapped. | |||
1437 | static Value *simplifyAndOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) { | |||
1438 | ICmpInst::Predicate Pred0, Pred1; | |||
1439 | Value *A ,*B; | |||
1440 | if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) || | |||
1441 | !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B)))) | |||
1442 | return nullptr; | |||
1443 | ||||
1444 | // We have (icmp Pred0, A, B) & (icmp Pred1, A, B). | |||
1445 | // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we | |||
1446 | // can eliminate Op1 from this 'and'. | |||
1447 | if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1)) | |||
1448 | return Op0; | |||
1449 | ||||
1450 | // Check for any combination of predicates that are guaranteed to be disjoint. | |||
1451 | if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) || | |||
1452 | (Pred0 == ICmpInst::ICMP_EQ && ICmpInst::isFalseWhenEqual(Pred1)) || | |||
1453 | (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT) || | |||
1454 | (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)) | |||
1455 | return getFalse(Op0->getType()); | |||
1456 | ||||
1457 | return nullptr; | |||
1458 | } | |||
1459 | ||||
1460 | /// Commuted variants are assumed to be handled by calling this function again | |||
1461 | /// with the parameters swapped. | |||
1462 | static Value *simplifyOrOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) { | |||
1463 | ICmpInst::Predicate Pred0, Pred1; | |||
1464 | Value *A ,*B; | |||
1465 | if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) || | |||
1466 | !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B)))) | |||
1467 | return nullptr; | |||
1468 | ||||
1469 | // We have (icmp Pred0, A, B) | (icmp Pred1, A, B). | |||
1470 | // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we | |||
1471 | // can eliminate Op0 from this 'or'. | |||
1472 | if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1)) | |||
1473 | return Op1; | |||
1474 | ||||
1475 | // Check for any combination of predicates that cover the entire range of | |||
1476 | // possibilities. | |||
1477 | if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) || | |||
1478 | (Pred0 == ICmpInst::ICMP_NE && ICmpInst::isTrueWhenEqual(Pred1)) || | |||
1479 | (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGE) || | |||
1480 | (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGE)) | |||
1481 | return getTrue(Op0->getType()); | |||
1482 | ||||
1483 | return nullptr; | |||
1484 | } | |||
1485 | ||||
1486 | /// Test if a pair of compares with a shared operand and 2 constants has an | |||
1487 | /// empty set intersection, full set union, or if one compare is a superset of | |||
1488 | /// the other. | |||
1489 | static Value *simplifyAndOrOfICmpsWithConstants(ICmpInst *Cmp0, ICmpInst *Cmp1, | |||
1490 | bool IsAnd) { | |||
1491 | // Look for this pattern: {and/or} (icmp X, C0), (icmp X, C1)). | |||
1492 | if (Cmp0->getOperand(0) != Cmp1->getOperand(0)) | |||
1493 | return nullptr; | |||
1494 | ||||
1495 | const APInt *C0, *C1; | |||
1496 | if (!match(Cmp0->getOperand(1), m_APInt(C0)) || | |||
1497 | !match(Cmp1->getOperand(1), m_APInt(C1))) | |||
1498 | return nullptr; | |||
1499 | ||||
1500 | auto Range0 = ConstantRange::makeExactICmpRegion(Cmp0->getPredicate(), *C0); | |||
1501 | auto Range1 = ConstantRange::makeExactICmpRegion(Cmp1->getPredicate(), *C1); | |||
1502 | ||||
1503 | // For and-of-compares, check if the intersection is empty: | |||
1504 | // (icmp X, C0) && (icmp X, C1) --> empty set --> false | |||
1505 | if (IsAnd && Range0.intersectWith(Range1).isEmptySet()) | |||
1506 | return getFalse(Cmp0->getType()); | |||
1507 | ||||
1508 | // For or-of-compares, check if the union is full: | |||
1509 | // (icmp X, C0) || (icmp X, C1) --> full set --> true | |||
1510 | if (!IsAnd && Range0.unionWith(Range1).isFullSet()) | |||
1511 | return getTrue(Cmp0->getType()); | |||
1512 | ||||
1513 | // Is one range a superset of the other? | |||
1514 | // If this is and-of-compares, take the smaller set: | |||
1515 | // (icmp sgt X, 4) && (icmp sgt X, 42) --> icmp sgt X, 42 | |||
1516 | // If this is or-of-compares, take the larger set: | |||
1517 | // (icmp sgt X, 4) || (icmp sgt X, 42) --> icmp sgt X, 4 | |||
1518 | if (Range0.contains(Range1)) | |||
1519 | return IsAnd ? Cmp1 : Cmp0; | |||
1520 | if (Range1.contains(Range0)) | |||
1521 | return IsAnd ? Cmp0 : Cmp1; | |||
1522 | ||||
1523 | return nullptr; | |||
1524 | } | |||
1525 | ||||
1526 | static Value *simplifyAndOrOfICmpsWithZero(ICmpInst *Cmp0, ICmpInst *Cmp1, | |||
1527 | bool IsAnd) { | |||
1528 | ICmpInst::Predicate P0 = Cmp0->getPredicate(), P1 = Cmp1->getPredicate(); | |||
1529 | if (!match(Cmp0->getOperand(1), m_Zero()) || | |||
1530 | !match(Cmp1->getOperand(1), m_Zero()) || P0 != P1) | |||
1531 | return nullptr; | |||
1532 | ||||
1533 | if ((IsAnd && P0 != ICmpInst::ICMP_NE) || (!IsAnd && P1 != ICmpInst::ICMP_EQ)) | |||
1534 | return nullptr; | |||
1535 | ||||
1536 | // We have either "(X == 0 || Y == 0)" or "(X != 0 && Y != 0)". | |||
1537 | Value *X = Cmp0->getOperand(0); | |||
1538 | Value *Y = Cmp1->getOperand(0); | |||
1539 | ||||
1540 | // If one of the compares is a masked version of a (not) null check, then | |||
1541 | // that compare implies the other, so we eliminate the other. Optionally, look | |||
1542 | // through a pointer-to-int cast to match a null check of a pointer type. | |||
1543 | ||||
1544 | // (X == 0) || (([ptrtoint] X & ?) == 0) --> ([ptrtoint] X & ?) == 0 | |||
1545 | // (X == 0) || ((? & [ptrtoint] X) == 0) --> (? & [ptrtoint] X) == 0 | |||
1546 | // (X != 0) && (([ptrtoint] X & ?) != 0) --> ([ptrtoint] X & ?) != 0 | |||
1547 | // (X != 0) && ((? & [ptrtoint] X) != 0) --> (? & [ptrtoint] X) != 0 | |||
1548 | if (match(Y, m_c_And(m_Specific(X), m_Value())) || | |||
1549 | match(Y, m_c_And(m_PtrToInt(m_Specific(X)), m_Value()))) | |||
1550 | return Cmp1; | |||
1551 | ||||
1552 | // (([ptrtoint] Y & ?) == 0) || (Y == 0) --> ([ptrtoint] Y & ?) == 0 | |||
1553 | // ((? & [ptrtoint] Y) == 0) || (Y == 0) --> (? & [ptrtoint] Y) == 0 | |||
1554 | // (([ptrtoint] Y & ?) != 0) && (Y != 0) --> ([ptrtoint] Y & ?) != 0 | |||
1555 | // ((? & [ptrtoint] Y) != 0) && (Y != 0) --> (? & [ptrtoint] Y) != 0 | |||
1556 | if (match(X, m_c_And(m_Specific(Y), m_Value())) || | |||
1557 | match(X, m_c_And(m_PtrToInt(m_Specific(Y)), m_Value()))) | |||
1558 | return Cmp0; | |||
1559 | ||||
1560 | return nullptr; | |||
1561 | } | |||
1562 | ||||
1563 | static Value *simplifyAndOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1, | |||
1564 | const InstrInfoQuery &IIQ) { | |||
1565 | // (icmp (add V, C0), C1) & (icmp V, C0) | |||
1566 | ICmpInst::Predicate Pred0, Pred1; | |||
1567 | const APInt *C0, *C1; | |||
1568 | Value *V; | |||
1569 | if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1)))) | |||
1570 | return nullptr; | |||
1571 | ||||
1572 | if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value()))) | |||
1573 | return nullptr; | |||
1574 | ||||
1575 | auto *AddInst = cast<OverflowingBinaryOperator>(Op0->getOperand(0)); | |||
1576 | if (AddInst->getOperand(1) != Op1->getOperand(1)) | |||
1577 | return nullptr; | |||
1578 | ||||
1579 | Type *ITy = Op0->getType(); | |||
1580 | bool isNSW = IIQ.hasNoSignedWrap(AddInst); | |||
1581 | bool isNUW = IIQ.hasNoUnsignedWrap(AddInst); | |||
1582 | ||||
1583 | const APInt Delta = *C1 - *C0; | |||
1584 | if (C0->isStrictlyPositive()) { | |||
1585 | if (Delta == 2) { | |||
1586 | if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT) | |||
1587 | return getFalse(ITy); | |||
1588 | if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW) | |||
1589 | return getFalse(ITy); | |||
1590 | } | |||
1591 | if (Delta == 1) { | |||
1592 | if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT) | |||
1593 | return getFalse(ITy); | |||
1594 | if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW) | |||
1595 | return getFalse(ITy); | |||
1596 | } | |||
1597 | } | |||
1598 | if (C0->getBoolValue() && isNUW) { | |||
1599 | if (Delta == 2) | |||
1600 | if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT) | |||
1601 | return getFalse(ITy); | |||
1602 | if (Delta == 1) | |||
1603 | if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT) | |||
1604 | return getFalse(ITy); | |||
1605 | } | |||
1606 | ||||
1607 | return nullptr; | |||
1608 | } | |||
1609 | ||||
1610 | static Value *simplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1, | |||
1611 | const InstrInfoQuery &IIQ) { | |||
1612 | if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true)) | |||
1613 | return X; | |||
1614 | if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/true)) | |||
1615 | return X; | |||
1616 | ||||
1617 | if (Value *X = simplifyAndOfICmpsWithSameOperands(Op0, Op1)) | |||
1618 | return X; | |||
1619 | if (Value *X = simplifyAndOfICmpsWithSameOperands(Op1, Op0)) | |||
1620 | return X; | |||
1621 | ||||
1622 | if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, true)) | |||
1623 | return X; | |||
1624 | ||||
1625 | if (Value *X = simplifyAndOrOfICmpsWithZero(Op0, Op1, true)) | |||
1626 | return X; | |||
1627 | ||||
1628 | if (Value *X = simplifyAndOfICmpsWithAdd(Op0, Op1, IIQ)) | |||
1629 | return X; | |||
1630 | if (Value *X = simplifyAndOfICmpsWithAdd(Op1, Op0, IIQ)) | |||
1631 | return X; | |||
1632 | ||||
1633 | return nullptr; | |||
1634 | } | |||
1635 | ||||
1636 | static Value *simplifyOrOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1, | |||
1637 | const InstrInfoQuery &IIQ) { | |||
1638 | // (icmp (add V, C0), C1) | (icmp V, C0) | |||
1639 | ICmpInst::Predicate Pred0, Pred1; | |||
1640 | const APInt *C0, *C1; | |||
1641 | Value *V; | |||
1642 | if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1)))) | |||
1643 | return nullptr; | |||
1644 | ||||
1645 | if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value()))) | |||
1646 | return nullptr; | |||
1647 | ||||
1648 | auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0)); | |||
1649 | if (AddInst->getOperand(1) != Op1->getOperand(1)) | |||
1650 | return nullptr; | |||
1651 | ||||
1652 | Type *ITy = Op0->getType(); | |||
1653 | bool isNSW = IIQ.hasNoSignedWrap(AddInst); | |||
1654 | bool isNUW = IIQ.hasNoUnsignedWrap(AddInst); | |||
1655 | ||||
1656 | const APInt Delta = *C1 - *C0; | |||
1657 | if (C0->isStrictlyPositive()) { | |||
1658 | if (Delta == 2) { | |||
1659 | if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE) | |||
1660 | return getTrue(ITy); | |||
1661 | if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW) | |||
1662 | return getTrue(ITy); | |||
1663 | } | |||
1664 | if (Delta == 1) { | |||
1665 | if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE) | |||
1666 | return getTrue(ITy); | |||
1667 | if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW) | |||
1668 | return getTrue(ITy); | |||
1669 | } | |||
1670 | } | |||
1671 | if (C0->getBoolValue() && isNUW) { | |||
1672 | if (Delta == 2) | |||
1673 | if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE) | |||
1674 | return getTrue(ITy); | |||
1675 | if (Delta == 1) | |||
1676 | if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE) | |||
1677 | return getTrue(ITy); | |||
1678 | } | |||
1679 | ||||
1680 | return nullptr; | |||
1681 | } | |||
1682 | ||||
1683 | static Value *simplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1, | |||
1684 | const InstrInfoQuery &IIQ) { | |||
1685 | if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false)) | |||
1686 | return X; | |||
1687 | if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/false)) | |||
1688 | return X; | |||
1689 | ||||
1690 | if (Value *X = simplifyOrOfICmpsWithSameOperands(Op0, Op1)) | |||
1691 | return X; | |||
1692 | if (Value *X = simplifyOrOfICmpsWithSameOperands(Op1, Op0)) | |||
1693 | return X; | |||
1694 | ||||
1695 | if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, false)) | |||
1696 | return X; | |||
1697 | ||||
1698 | if (Value *X = simplifyAndOrOfICmpsWithZero(Op0, Op1, false)) | |||
1699 | return X; | |||
1700 | ||||
1701 | if (Value *X = simplifyOrOfICmpsWithAdd(Op0, Op1, IIQ)) | |||
1702 | return X; | |||
1703 | if (Value *X = simplifyOrOfICmpsWithAdd(Op1, Op0, IIQ)) | |||
1704 | return X; | |||
1705 | ||||
1706 | return nullptr; | |||
1707 | } | |||
1708 | ||||
1709 | static Value *simplifyAndOrOfFCmps(const TargetLibraryInfo *TLI, | |||
1710 | FCmpInst *LHS, FCmpInst *RHS, bool IsAnd) { | |||
1711 | Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1); | |||
1712 | Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1); | |||
1713 | if (LHS0->getType() != RHS0->getType()) | |||
1714 | return nullptr; | |||
1715 | ||||
1716 | FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate(); | |||
1717 | if ((PredL == FCmpInst::FCMP_ORD && PredR == FCmpInst::FCMP_ORD && IsAnd) || | |||
1718 | (PredL == FCmpInst::FCMP_UNO && PredR == FCmpInst::FCMP_UNO && !IsAnd)) { | |||
1719 | // (fcmp ord NNAN, X) & (fcmp ord X, Y) --> fcmp ord X, Y | |||
1720 | // (fcmp ord NNAN, X) & (fcmp ord Y, X) --> fcmp ord Y, X | |||
1721 | // (fcmp ord X, NNAN) & (fcmp ord X, Y) --> fcmp ord X, Y | |||
1722 | // (fcmp ord X, NNAN) & (fcmp ord Y, X) --> fcmp ord Y, X | |||
1723 | // (fcmp uno NNAN, X) | (fcmp uno X, Y) --> fcmp uno X, Y | |||
1724 | // (fcmp uno NNAN, X) | (fcmp uno Y, X) --> fcmp uno Y, X | |||
1725 | // (fcmp uno X, NNAN) | (fcmp uno X, Y) --> fcmp uno X, Y | |||
1726 | // (fcmp uno X, NNAN) | (fcmp uno Y, X) --> fcmp uno Y, X | |||
1727 | if ((isKnownNeverNaN(LHS0, TLI) && (LHS1 == RHS0 || LHS1 == RHS1)) || | |||
1728 | (isKnownNeverNaN(LHS1, TLI) && (LHS0 == RHS0 || LHS0 == RHS1))) | |||
1729 | return RHS; | |||
1730 | ||||
1731 | // (fcmp ord X, Y) & (fcmp ord NNAN, X) --> fcmp ord X, Y | |||
1732 | // (fcmp ord Y, X) & (fcmp ord NNAN, X) --> fcmp ord Y, X | |||
1733 | // (fcmp ord X, Y) & (fcmp ord X, NNAN) --> fcmp ord X, Y | |||
1734 | // (fcmp ord Y, X) & (fcmp ord X, NNAN) --> fcmp ord Y, X | |||
1735 | // (fcmp uno X, Y) | (fcmp uno NNAN, X) --> fcmp uno X, Y | |||
1736 | // (fcmp uno Y, X) | (fcmp uno NNAN, X) --> fcmp uno Y, X | |||
1737 | // (fcmp uno X, Y) | (fcmp uno X, NNAN) --> fcmp uno X, Y | |||
1738 | // (fcmp uno Y, X) | (fcmp uno X, NNAN) --> fcmp uno Y, X | |||
1739 | if ((isKnownNeverNaN(RHS0, TLI) && (RHS1 == LHS0 || RHS1 == LHS1)) || | |||
1740 | (isKnownNeverNaN(RHS1, TLI) && (RHS0 == LHS0 || RHS0 == LHS1))) | |||
1741 | return LHS; | |||
1742 | } | |||
1743 | ||||
1744 | return nullptr; | |||
1745 | } | |||
1746 | ||||
1747 | static Value *simplifyAndOrOfCmps(const SimplifyQuery &Q, | |||
1748 | Value *Op0, Value *Op1, bool IsAnd) { | |||
1749 | // Look through casts of the 'and' operands to find compares. | |||
1750 | auto *Cast0 = dyn_cast<CastInst>(Op0); | |||
1751 | auto *Cast1 = dyn_cast<CastInst>(Op1); | |||
1752 | if (Cast0 && Cast1 && Cast0->getOpcode() == Cast1->getOpcode() && | |||
1753 | Cast0->getSrcTy() == Cast1->getSrcTy()) { | |||
1754 | Op0 = Cast0->getOperand(0); | |||
1755 | Op1 = Cast1->getOperand(0); | |||
1756 | } | |||
1757 | ||||
1758 | Value *V = nullptr; | |||
1759 | auto *ICmp0 = dyn_cast<ICmpInst>(Op0); | |||
1760 | auto *ICmp1 = dyn_cast<ICmpInst>(Op1); | |||
1761 | if (ICmp0 && ICmp1) | |||
1762 | V = IsAnd ? simplifyAndOfICmps(ICmp0, ICmp1, Q.IIQ) | |||
1763 | : simplifyOrOfICmps(ICmp0, ICmp1, Q.IIQ); | |||
1764 | ||||
1765 | auto *FCmp0 = dyn_cast<FCmpInst>(Op0); | |||
1766 | auto *FCmp1 = dyn_cast<FCmpInst>(Op1); | |||
1767 | if (FCmp0 && FCmp1) | |||
1768 | V = simplifyAndOrOfFCmps(Q.TLI, FCmp0, FCmp1, IsAnd); | |||
1769 | ||||
1770 | if (!V) | |||
1771 | return nullptr; | |||
1772 | if (!Cast0) | |||
1773 | return V; | |||
1774 | ||||
1775 | // If we looked through casts, we can only handle a constant simplification | |||
1776 | // because we are not allowed to create a cast instruction here. | |||
1777 | if (auto *C = dyn_cast<Constant>(V)) | |||
1778 | return ConstantExpr::getCast(Cast0->getOpcode(), C, Cast0->getType()); | |||
1779 | ||||
1780 | return nullptr; | |||
1781 | } | |||
1782 | ||||
1783 | /// Given operands for an And, see if we can fold the result. | |||
1784 | /// If not, this returns null. | |||
1785 | static Value *SimplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q, | |||
1786 | unsigned MaxRecurse) { | |||
1787 | if (Constant *C = foldOrCommuteConstant(Instruction::And, Op0, Op1, Q)) | |||
1788 | return C; | |||
1789 | ||||
1790 | // X & undef -> 0 | |||
1791 | if (match(Op1, m_Undef())) | |||
1792 | return Constant::getNullValue(Op0->getType()); | |||
1793 | ||||
1794 | // X & X = X | |||
1795 | if (Op0 == Op1) | |||
1796 | return Op0; | |||
1797 | ||||
1798 | // X & 0 = 0 | |||
1799 | if (match(Op1, m_Zero())) | |||
1800 | return Constant::getNullValue(Op0->getType()); | |||
1801 | ||||
1802 | // X & -1 = X | |||
1803 | if (match(Op1, m_AllOnes())) | |||
1804 | return Op0; | |||
1805 | ||||
1806 | // A & ~A = ~A & A = 0 | |||
1807 | if (match(Op0, m_Not(m_Specific(Op1))) || | |||
1808 | match(Op1, m_Not(m_Specific(Op0)))) | |||
1809 | return Constant::getNullValue(Op0->getType()); | |||
1810 | ||||
1811 | // (A | ?) & A = A | |||
1812 | if (match(Op0, m_c_Or(m_Specific(Op1), m_Value()))) | |||
1813 | return Op1; | |||
1814 | ||||
1815 | // A & (A | ?) = A | |||
1816 | if (match(Op1, m_c_Or(m_Specific(Op0), m_Value()))) | |||
1817 | return Op0; | |||
1818 | ||||
1819 | // A mask that only clears known zeros of a shifted value is a no-op. | |||
1820 | Value *X; | |||
1821 | const APInt *Mask; | |||
1822 | const APInt *ShAmt; | |||
1823 | if (match(Op1, m_APInt(Mask))) { | |||
1824 | // If all bits in the inverted and shifted mask are clear: | |||
1825 | // and (shl X, ShAmt), Mask --> shl X, ShAmt | |||
1826 | if (match(Op0, m_Shl(m_Value(X), m_APInt(ShAmt))) && | |||
1827 | (~(*Mask)).lshr(*ShAmt).isNullValue()) | |||
1828 | return Op0; | |||
1829 | ||||
1830 | // If all bits in the inverted and shifted mask are clear: | |||
1831 | // and (lshr X, ShAmt), Mask --> lshr X, ShAmt | |||
1832 | if (match(Op0, m_LShr(m_Value(X), m_APInt(ShAmt))) && | |||
1833 | (~(*Mask)).shl(*ShAmt).isNullValue()) | |||
1834 | return Op0; | |||
1835 | } | |||
1836 | ||||
1837 | // A & (-A) = A if A is a power of two or zero. | |||
1838 | if (match(Op0, m_Neg(m_Specific(Op1))) || | |||
1839 | match(Op1, m_Neg(m_Specific(Op0)))) { | |||
1840 | if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI, | |||
1841 | Q.DT)) | |||
1842 | return Op0; | |||
1843 | if (isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI, | |||
1844 | Q.DT)) | |||
1845 | return Op1; | |||
1846 | } | |||
1847 | ||||
1848 | if (Value *V = simplifyAndOrOfCmps(Q, Op0, Op1, true)) | |||
1849 | return V; | |||
1850 | ||||
1851 | // Try some generic simplifications for associative operations. | |||
1852 | if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q, | |||
1853 | MaxRecurse)) | |||
1854 | return V; | |||
1855 | ||||
1856 | // And distributes over Or. Try some generic simplifications based on this. | |||
1857 | if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or, | |||
1858 | Q, MaxRecurse)) | |||
1859 | return V; | |||
1860 | ||||
1861 | // And distributes over Xor. Try some generic simplifications based on this. | |||
1862 | if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor, | |||
1863 | Q, MaxRecurse)) | |||
1864 | return V; | |||
1865 | ||||
1866 | // If the operation is with the result of a select instruction, check whether | |||
1867 | // operating on either branch of the select always yields the same value. | |||
1868 | if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) | |||
1869 | if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q, | |||
1870 | MaxRecurse)) | |||
1871 | return V; | |||
1872 | ||||
1873 | // If the operation is with the result of a phi instruction, check whether | |||
1874 | // operating on all incoming values of the phi always yields the same value. | |||
1875 | if (isa<PHINode>(Op0) || isa<PHINode>(Op1)) | |||
1876 | if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q, | |||
1877 | MaxRecurse)) | |||
1878 | return V; | |||
1879 | ||||
1880 | // Assuming the effective width of Y is not larger than A, i.e. all bits | |||
1881 | // from X and Y are disjoint in (X << A) | Y, | |||
1882 | // if the mask of this AND op covers all bits of X or Y, while it covers | |||
1883 | // no bits from the other, we can bypass this AND op. E.g., | |||
1884 | // ((X << A) | Y) & Mask -> Y, | |||
1885 | // if Mask = ((1 << effective_width_of(Y)) - 1) | |||
1886 | // ((X << A) | Y) & Mask -> X << A, | |||
1887 | // if Mask = ((1 << effective_width_of(X)) - 1) << A | |||
1888 | // SimplifyDemandedBits in InstCombine can optimize the general case. | |||
1889 | // This pattern aims to help other passes for a common case. | |||
1890 | Value *Y, *XShifted; | |||
1891 | if (match(Op1, m_APInt(Mask)) && | |||
1892 | match(Op0, m_c_Or(m_CombineAnd(m_NUWShl(m_Value(X), m_APInt(ShAmt)), | |||
1893 | m_Value(XShifted)), | |||
1894 | m_Value(Y)))) { | |||
1895 | const unsigned Width = Op0->getType()->getScalarSizeInBits(); | |||
1896 | const unsigned ShftCnt = ShAmt->getLimitedValue(Width); | |||
1897 | const KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); | |||
1898 | const unsigned EffWidthY = Width - YKnown.countMinLeadingZeros(); | |||
1899 | if (EffWidthY <= ShftCnt) { | |||
1900 | const KnownBits XKnown = computeKnownBits(X, Q.DL, 0, Q.AC, Q.CxtI, | |||
1901 | Q.DT); | |||
1902 | const unsigned EffWidthX = Width - XKnown.countMinLeadingZeros(); | |||
1903 | const APInt EffBitsY = APInt::getLowBitsSet(Width, EffWidthY); | |||
1904 | const APInt EffBitsX = APInt::getLowBitsSet(Width, EffWidthX) << ShftCnt; | |||
1905 | // If the mask is extracting all bits from X or Y as is, we can skip | |||
1906 | // this AND op. | |||
1907 | if (EffBitsY.isSubsetOf(*Mask) && !EffBitsX.intersects(*Mask)) | |||
1908 | return Y; | |||
1909 | if (EffBitsX.isSubsetOf(*Mask) && !EffBitsY.intersects(*Mask)) | |||
1910 | return XShifted; | |||
1911 | } | |||
1912 | } | |||
1913 | ||||
1914 | return nullptr; | |||
1915 | } | |||
1916 | ||||
1917 | Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) { | |||
1918 | return ::SimplifyAndInst(Op0, Op1, Q, RecursionLimit); | |||
1919 | } | |||
1920 | ||||
1921 | /// Given operands for an Or, see if we can fold the result. | |||
1922 | /// If not, this returns null. | |||
1923 | static Value *SimplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q, | |||
1924 | unsigned MaxRecurse) { | |||
1925 | if (Constant *C = foldOrCommuteConstant(Instruction::Or, Op0, Op1, Q)) | |||
1926 | return C; | |||
1927 | ||||
1928 | // X | undef -> -1 | |||
1929 | // X | -1 = -1 | |||
1930 | // Do not return Op1 because it may contain undef elements if it's a vector. | |||
1931 | if (match(Op1, m_Undef()) || match(Op1, m_AllOnes())) | |||
1932 | return Constant::getAllOnesValue(Op0->getType()); | |||
1933 | ||||
1934 | // X | X = X | |||
1935 | // X | 0 = X | |||
1936 | if (Op0 == Op1 || match(Op1, m_Zero())) | |||
1937 | return Op0; | |||
1938 | ||||
1939 | // A | ~A = ~A | A = -1 | |||
1940 | if (match(Op0, m_Not(m_Specific(Op1))) || | |||
1941 | match(Op1, m_Not(m_Specific(Op0)))) | |||
1942 | return Constant::getAllOnesValue(Op0->getType()); | |||
1943 | ||||
1944 | // (A & ?) | A = A | |||
1945 | if (match(Op0, m_c_And(m_Specific(Op1), m_Value()))) | |||
1946 | return Op1; | |||
1947 | ||||
1948 | // A | (A & ?) = A | |||
1949 | if (match(Op1, m_c_And(m_Specific(Op0), m_Value()))) | |||
1950 | return Op0; | |||
1951 | ||||
1952 | // ~(A & ?) | A = -1 | |||
1953 | if (match(Op0, m_Not(m_c_And(m_Specific(Op1), m_Value())))) | |||
1954 | return Constant::getAllOnesValue(Op1->getType()); | |||
1955 | ||||
1956 | // A | ~(A & ?) = -1 | |||
1957 | if (match(Op1, m_Not(m_c_And(m_Specific(Op1), m_Value())))) | |||
1958 | return Constant::getAllOnesValue(Op0->getType()); | |||
1959 | ||||
1960 | Value *A, *B; | |||
1961 | // (A & ~B) | (A ^ B) -> (A ^ B) | |||
1962 | // (~B & A) | (A ^ B) -> (A ^ B) | |||
1963 | // (A & ~B) | (B ^ A) -> (B ^ A) | |||
1964 | // (~B & A) | (B ^ A) -> (B ^ A) | |||
1965 | if (match(Op1, m_Xor(m_Value(A), m_Value(B))) && | |||
1966 | (match(Op0, m_c_And(m_Specific(A), m_Not(m_Specific(B)))) || | |||
1967 | match(Op0, m_c_And(m_Not(m_Specific(A)), m_Specific(B))))) | |||
1968 | return Op1; | |||
1969 | ||||
1970 | // Commute the 'or' operands. | |||
1971 | // (A ^ B) | (A & ~B) -> (A ^ B) | |||
1972 | // (A ^ B) | (~B & A) -> (A ^ B) | |||
1973 | // (B ^ A) | (A & ~B) -> (B ^ A) | |||
1974 | // (B ^ A) | (~B & A) -> (B ^ A) | |||
1975 | if (match(Op0, m_Xor(m_Value(A), m_Value(B))) && | |||
1976 | (match(Op1, m_c_And(m_Specific(A), m_Not(m_Specific(B)))) || | |||
1977 | match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B))))) | |||
1978 | return Op0; | |||
1979 | ||||
1980 | // (A & B) | (~A ^ B) -> (~A ^ B) | |||
1981 | // (B & A) | (~A ^ B) -> (~A ^ B) | |||
1982 | // (A & B) | (B ^ ~A) -> (B ^ ~A) | |||
1983 | // (B & A) | (B ^ ~A) -> (B ^ ~A) | |||
1984 | if (match(Op0, m_And(m_Value(A), m_Value(B))) && | |||
1985 | (match(Op1, m_c_Xor(m_Specific(A), m_Not(m_Specific(B)))) || | |||
1986 | match(Op1, m_c_Xor(m_Not(m_Specific(A)), m_Specific(B))))) | |||
1987 | return Op1; | |||
1988 | ||||
1989 | // (~A ^ B) | (A & B) -> (~A ^ B) | |||
1990 | // (~A ^ B) | (B & A) -> (~A ^ B) | |||
1991 | // (B ^ ~A) | (A & B) -> (B ^ ~A) | |||
1992 | // (B ^ ~A) | (B & A) -> (B ^ ~A) | |||
1993 | if (match(Op1, m_And(m_Value(A), m_Value(B))) && | |||
1994 | (match(Op0, m_c_Xor(m_Specific(A), m_Not(m_Specific(B)))) || | |||
1995 | match(Op0, m_c_Xor(m_Not(m_Specific(A)), m_Specific(B))))) | |||
1996 | return Op0; | |||
1997 | ||||
1998 | if (Value *V = simplifyAndOrOfCmps(Q, Op0, Op1, false)) | |||
1999 | return V; | |||
2000 | ||||
2001 | // Try some generic simplifications for associative operations. | |||
2002 | if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q, | |||
2003 | MaxRecurse)) | |||
2004 | return V; | |||
2005 | ||||
2006 | // Or distributes over And. Try some generic simplifications based on this. | |||
2007 | if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q, | |||
2008 | MaxRecurse)) | |||
2009 | return V; | |||
2010 | ||||
2011 | // If the operation is with the result of a select instruction, check whether | |||
2012 | // operating on either branch of the select always yields the same value. | |||
2013 | if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) | |||
2014 | if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q, | |||
2015 | MaxRecurse)) | |||
2016 | return V; | |||
2017 | ||||
2018 | // (A & C1)|(B & C2) | |||
2019 | const APInt *C1, *C2; | |||
2020 | if (match(Op0, m_And(m_Value(A), m_APInt(C1))) && | |||
2021 | match(Op1, m_And(m_Value(B), m_APInt(C2)))) { | |||
2022 | if (*C1 == ~*C2) { | |||
2023 | // (A & C1)|(B & C2) | |||
2024 | // If we have: ((V + N) & C1) | (V & C2) | |||
2025 | // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0 | |||
2026 | // replace with V+N. | |||
2027 | Value *N; | |||
2028 | if (C2->isMask() && // C2 == 0+1+ | |||
2029 | match(A, m_c_Add(m_Specific(B), m_Value(N)))) { | |||
2030 | // Add commutes, try both ways. | |||
2031 | if (MaskedValueIsZero(N, *C2, Q.DL, 0, Q.AC, Q.CxtI, Q.DT)) | |||
2032 | return A; | |||
2033 | } | |||
2034 | // Or commutes, try both ways. | |||
2035 | if (C1->isMask() && | |||
2036 | match(B, m_c_Add(m_Specific(A), m_Value(N)))) { | |||
2037 | // Add commutes, try both ways. | |||
2038 | if (MaskedValueIsZero(N, *C1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT)) | |||
2039 | return B; | |||
2040 | } | |||
2041 | } | |||
2042 | } | |||
2043 | ||||
2044 | // If the operation is with the result of a phi instruction, check whether | |||
2045 | // operating on all incoming values of the phi always yields the same value. | |||
2046 | if (isa<PHINode>(Op0) || isa<PHINode>(Op1)) | |||
2047 | if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse)) | |||
2048 | return V; | |||
2049 | ||||
2050 | return nullptr; | |||
2051 | } | |||
2052 | ||||
2053 | Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) { | |||
2054 | return ::SimplifyOrInst(Op0, Op1, Q, RecursionLimit); | |||
2055 | } | |||
2056 | ||||
2057 | /// Given operands for a Xor, see if we can fold the result. | |||
2058 | /// If not, this returns null. | |||
2059 | static Value *SimplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q, | |||
2060 | unsigned MaxRecurse) { | |||
2061 | if (Constant *C = foldOrCommuteConstant(Instruction::Xor, Op0, Op1, Q)) | |||
2062 | return C; | |||
2063 | ||||
2064 | // A ^ undef -> undef | |||
2065 | if (match(Op1, m_Undef())) | |||
2066 | return Op1; | |||
2067 | ||||
2068 | // A ^ 0 = A | |||
2069 | if (match(Op1, m_Zero())) | |||
2070 | return Op0; | |||
2071 | ||||
2072 | // A ^ A = 0 | |||
2073 | if (Op0 == Op1) | |||
2074 | return Constant::getNullValue(Op0->getType()); | |||
2075 | ||||
2076 | // A ^ ~A = ~A ^ A = -1 | |||
2077 | if (match(Op0, m_Not(m_Specific(Op1))) || | |||
2078 | match(Op1, m_Not(m_Specific(Op0)))) | |||
2079 | return Constant::getAllOnesValue(Op0->getType()); | |||
2080 | ||||
2081 | // Try some generic simplifications for associative operations. | |||
2082 | if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q, | |||
2083 | MaxRecurse)) | |||
2084 | return V; | |||
2085 | ||||
2086 | // Threading Xor over selects and phi nodes is pointless, so don't bother. | |||
2087 | // Threading over the select in "A ^ select(cond, B, C)" means evaluating | |||
2088 | // "A^B" and "A^C" and seeing if they are equal; but they are equal if and | |||
2089 | // only if B and C are equal. If B and C are equal then (since we assume | |||
2090 | // that operands have already been simplified) "select(cond, B, C)" should | |||
2091 | // have been simplified to the common value of B and C already. Analysing | |||
2092 | // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly | |||
2093 | // for threading over phi nodes. | |||
2094 | ||||
2095 | return nullptr; | |||
2096 | } | |||
2097 | ||||
2098 | Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) { | |||
2099 | return ::SimplifyXorInst(Op0, Op1, Q, RecursionLimit); | |||
2100 | } | |||
2101 | ||||
2102 | ||||
2103 | static Type *GetCompareTy(Value *Op) { | |||
2104 | return CmpInst::makeCmpResultType(Op->getType()); | |||
2105 | } | |||
2106 | ||||
2107 | /// Rummage around inside V looking for something equivalent to the comparison | |||
2108 | /// "LHS Pred RHS". Return such a value if found, otherwise return null. | |||
2109 | /// Helper function for analyzing max/min idioms. | |||
2110 | static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred, | |||
2111 | Value *LHS, Value *RHS) { | |||
2112 | SelectInst *SI = dyn_cast<SelectInst>(V); | |||
2113 | if (!SI) | |||
2114 | return nullptr; | |||
2115 | CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition()); | |||
2116 | if (!Cmp) | |||
2117 | return nullptr; | |||
2118 | Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1); | |||
2119 | if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS) | |||
2120 | return Cmp; | |||
2121 | if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) && | |||
2122 | LHS == CmpRHS && RHS == CmpLHS) | |||
2123 | return Cmp; | |||
2124 | return nullptr; | |||
2125 | } | |||
2126 | ||||
2127 | // A significant optimization not implemented here is assuming that alloca | |||
2128 | // addresses are not equal to incoming argument values. They don't *alias*, | |||
2129 | // as we say, but that doesn't mean they aren't equal, so we take a | |||
2130 | // conservative approach. | |||
2131 | // | |||
2132 | // This is inspired in part by C++11 5.10p1: | |||
2133 | // "Two pointers of the same type compare equal if and only if they are both | |||
2134 | // null, both point to the same function, or both represent the same | |||
2135 | // address." | |||
2136 | // | |||
2137 | // This is pretty permissive. | |||
2138 | // | |||
2139 | // It's also partly due to C11 6.5.9p6: | |||
2140 | // "Two pointers compare equal if and only if both are null pointers, both are | |||
2141 | // pointers to the same object (including a pointer to an object and a | |||
2142 | // subobject at its beginning) or function, both are pointers to one past the | |||
2143 | // last element of the same array object, or one is a pointer to one past the | |||
2144 | // end of one array object and the other is a pointer to the start of a | |||
2145 | // different array object that happens to immediately follow the first array | |||
2146 | // object in the address space.) | |||
2147 | // | |||
2148 | // C11's version is more restrictive, however there's no reason why an argument | |||
2149 | // couldn't be a one-past-the-end value for a stack object in the caller and be | |||
2150 | // equal to the beginning of a stack object in the callee. | |||
2151 | // | |||
2152 | // If the C and C++ standards are ever made sufficiently restrictive in this | |||
2153 | // area, it may be possible to update LLVM's semantics accordingly and reinstate | |||
2154 | // this optimization. | |||
2155 | static Constant * | |||
2156 | computePointerICmp(const DataLayout &DL, const TargetLibraryInfo *TLI, | |||
2157 | const DominatorTree *DT, CmpInst::Predicate Pred, | |||
2158 | AssumptionCache *AC, const Instruction *CxtI, | |||
2159 | const InstrInfoQuery &IIQ, Value *LHS, Value *RHS) { | |||
2160 | // First, skip past any trivial no-ops. | |||
2161 | LHS = LHS->stripPointerCasts(); | |||
2162 | RHS = RHS->stripPointerCasts(); | |||
2163 | ||||
2164 | // A non-null pointer is not equal to a null pointer. | |||
2165 | if (llvm::isKnownNonZero(LHS, DL, 0, nullptr, nullptr, nullptr, | |||
2166 | IIQ.UseInstrInfo) && | |||
2167 | isa<ConstantPointerNull>(RHS) && | |||
2168 | (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE)) | |||
2169 | return ConstantInt::get(GetCompareTy(LHS), | |||
2170 | !CmpInst::isTrueWhenEqual(Pred)); | |||
2171 | ||||
2172 | // We can only fold certain predicates on pointer comparisons. | |||
2173 | switch (Pred) { | |||
2174 | default: | |||
2175 | return nullptr; | |||
2176 | ||||
2177 | // Equality comaprisons are easy to fold. | |||
2178 | case CmpInst::ICMP_EQ: | |||
2179 | case CmpInst::ICMP_NE: | |||
2180 | break; | |||
2181 | ||||
2182 | // We can only handle unsigned relational comparisons because 'inbounds' on | |||
2183 | // a GEP only protects against unsigned wrapping. | |||
2184 | case CmpInst::ICMP_UGT: | |||
2185 | case CmpInst::ICMP_UGE: | |||
2186 | case CmpInst::ICMP_ULT: | |||
2187 | case CmpInst::ICMP_ULE: | |||
2188 | // However, we have to switch them to their signed variants to handle | |||
2189 | // negative indices from the base pointer. | |||
2190 | Pred = ICmpInst::getSignedPredicate(Pred); | |||
2191 | break; | |||
2192 | } | |||
2193 | ||||
2194 | // Strip off any constant offsets so that we can reason about them. | |||
2195 | // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets | |||
2196 | // here and compare base addresses like AliasAnalysis does, however there are | |||
2197 | // numerous hazards. AliasAnalysis and its utilities rely on special rules | |||
2198 | // governing loads and stores which don't apply to icmps. Also, AliasAnalysis | |||
2199 | // doesn't need to guarantee pointer inequality when it says NoAlias. | |||
2200 | Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS); | |||
2201 | Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS); | |||
2202 | ||||
2203 | // If LHS and RHS are related via constant offsets to the same base | |||
2204 | // value, we can replace it with an icmp which just compares the offsets. | |||
2205 | if (LHS == RHS) | |||
2206 | return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset); | |||
2207 | ||||
2208 | // Various optimizations for (in)equality comparisons. | |||
2209 | if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) { | |||
2210 | // Different non-empty allocations that exist at the same time have | |||
2211 | // different addresses (if the program can tell). Global variables always | |||
2212 | // exist, so they always exist during the lifetime of each other and all | |||
2213 | // allocas. Two different allocas usually have different addresses... | |||
2214 | // | |||
2215 | // However, if there's an @llvm.stackrestore dynamically in between two | |||
2216 | // allocas, they may have the same address. It's tempting to reduce the | |||
2217 | // scope of the problem by only looking at *static* allocas here. That would | |||
2218 | // cover the majority of allocas while significantly reducing the likelihood | |||
2219 | // of having an @llvm.stackrestore pop up in the middle. However, it's not | |||
2220 | // actually impossible for an @llvm.stackrestore to pop up in the middle of | |||
2221 | // an entry block. Also, if we have a block that's not attached to a | |||
2222 | // function, we can't tell if it's "static" under the current definition. | |||
2223 | // Theoretically, this problem could be fixed by creating a new kind of | |||
2224 | // instruction kind specifically for static allocas. Such a new instruction | |||
2225 | // could be required to be at the top of the entry block, thus preventing it | |||
2226 | // from being subject to a @llvm.stackrestore. Instcombine could even | |||
2227 | // convert regular allocas into these special allocas. It'd be nifty. | |||
2228 | // However, until then, this problem remains open. | |||
2229 | // | |||
2230 | // So, we'll assume that two non-empty allocas have different addresses | |||
2231 | // for now. | |||
2232 | // | |||
2233 | // With all that, if the offsets are within the bounds of their allocations | |||
2234 | // (and not one-past-the-end! so we can't use inbounds!), and their | |||
2235 | // allocations aren't the same, the pointers are not equal. | |||
2236 | // | |||
2237 | // Note that it's not necessary to check for LHS being a global variable | |||
2238 | // address, due to canonicalization and constant folding. | |||
2239 | if (isa<AllocaInst>(LHS) && | |||
2240 | (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) { | |||
2241 | ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset); | |||
2242 | ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset); | |||
2243 | uint64_t LHSSize, RHSSize; | |||
2244 | ObjectSizeOpts Opts; | |||
2245 | Opts.NullIsUnknownSize = | |||
2246 | NullPointerIsDefined(cast<AllocaInst>(LHS)->getFunction()); | |||
2247 | if (LHSOffsetCI && RHSOffsetCI && | |||
2248 | getObjectSize(LHS, LHSSize, DL, TLI, Opts) && | |||
2249 | getObjectSize(RHS, RHSSize, DL, TLI, Opts)) { | |||
2250 | const APInt &LHSOffsetValue = LHSOffsetCI->getValue(); | |||
2251 | const APInt &RHSOffsetValue = RHSOffsetCI->getValue(); | |||
2252 | if (!LHSOffsetValue.isNegative() && | |||
2253 | !RHSOffsetValue.isNegative() && | |||
2254 | LHSOffsetValue.ult(LHSSize) && | |||
2255 | RHSOffsetValue.ult(RHSSize)) { | |||
2256 | return ConstantInt::get(GetCompareTy(LHS), | |||
2257 | !CmpInst::isTrueWhenEqual(Pred)); | |||
2258 | } | |||
2259 | } | |||
2260 | ||||
2261 | // Repeat the above check but this time without depending on DataLayout | |||
2262 | // or being able to compute a precise size. | |||
2263 | if (!cast<PointerType>(LHS->getType())->isEmptyTy() && | |||
2264 | !cast<PointerType>(RHS->getType())->isEmptyTy() && | |||
2265 | LHSOffset->isNullValue() && | |||
2266 | RHSOffset->isNullValue()) | |||
2267 | return ConstantInt::get(GetCompareTy(LHS), | |||
2268 | !CmpInst::isTrueWhenEqual(Pred)); | |||
2269 | } | |||
2270 | ||||
2271 | // Even if an non-inbounds GEP occurs along the path we can still optimize | |||
2272 | // equality comparisons concerning the result. We avoid walking the whole | |||
2273 | // chain again by starting where the last calls to | |||
2274 | // stripAndComputeConstantOffsets left off and accumulate the offsets. | |||
2275 | Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true); | |||
2276 | Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true); | |||
2277 | if (LHS == RHS) | |||
2278 | return ConstantExpr::getICmp(Pred, | |||
2279 | ConstantExpr::getAdd(LHSOffset, LHSNoBound), | |||
2280 | ConstantExpr::getAdd(RHSOffset, RHSNoBound)); | |||
2281 | ||||
2282 | // If one side of the equality comparison must come from a noalias call | |||
2283 | // (meaning a system memory allocation function), and the other side must | |||
2284 | // come from a pointer that cannot overlap with dynamically-allocated | |||
2285 | // memory within the lifetime of the current function (allocas, byval | |||
2286 | // arguments, globals), then determine the comparison result here. | |||
2287 | SmallVector<const Value *, 8> LHSUObjs, RHSUObjs; | |||
2288 | GetUnderlyingObjects(LHS, LHSUObjs, DL); | |||
2289 | GetUnderlyingObjects(RHS, RHSUObjs, DL); | |||
2290 | ||||
2291 | // Is the set of underlying objects all noalias calls? | |||
2292 | auto IsNAC = [](ArrayRef<const Value *> Objects) { | |||
2293 | return all_of(Objects, isNoAliasCall); | |||
2294 | }; | |||
2295 | ||||
2296 | // Is the set of underlying objects all things which must be disjoint from | |||
2297 | // noalias calls. For allocas, we consider only static ones (dynamic | |||
2298 | // allocas might be transformed into calls to malloc not simultaneously | |||
2299 | // live with the compared-to allocation). For globals, we exclude symbols | |||
2300 | // that might be resolve lazily to symbols in another dynamically-loaded | |||
2301 | // library (and, thus, could be malloc'ed by the implementation). | |||
2302 | auto IsAllocDisjoint = [](ArrayRef<const Value *> Objects) { | |||
2303 | return all_of(Objects, [](const Value *V) { | |||
2304 | if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) | |||
2305 | return AI->getParent() && AI->getFunction() && AI->isStaticAlloca(); | |||
2306 | if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) | |||
2307 | return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() || | |||
2308 | GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) && | |||
2309 | !GV->isThreadLocal(); | |||
2310 | if (const Argument *A = dyn_cast<Argument>(V)) | |||
2311 | return A->hasByValAttr(); | |||
2312 | return false; | |||
2313 | }); | |||
2314 | }; | |||
2315 | ||||
2316 | if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) || | |||
2317 | (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs))) | |||
2318 | return ConstantInt::get(GetCompareTy(LHS), | |||
2319 | !CmpInst::isTrueWhenEqual(Pred)); | |||
2320 | ||||
2321 | // Fold comparisons for non-escaping pointer even if the allocation call | |||
2322 | // cannot be elided. We cannot fold malloc comparison to null. Also, the | |||
2323 | // dynamic allocation call could be either of the operands. | |||
2324 | Value *MI = nullptr; | |||
2325 | if (isAllocLikeFn(LHS, TLI) && | |||
2326 | llvm::isKnownNonZero(RHS, DL, 0, nullptr, CxtI, DT)) | |||
2327 | MI = LHS; | |||
2328 | else if (isAllocLikeFn(RHS, TLI) && | |||
2329 | llvm::isKnownNonZero(LHS, DL, 0, nullptr, CxtI, DT)) | |||
2330 | MI = RHS; | |||
2331 | // FIXME: We should also fold the compare when the pointer escapes, but the | |||
2332 | // compare dominates the pointer escape | |||
2333 | if (MI && !PointerMayBeCaptured(MI, true, true)) | |||
2334 | return ConstantInt::get(GetCompareTy(LHS), | |||
2335 | CmpInst::isFalseWhenEqual(Pred)); | |||
2336 | } | |||
2337 | ||||
2338 | // Otherwise, fail. | |||
2339 | return nullptr; | |||
2340 | } | |||
2341 | ||||
2342 | /// Fold an icmp when its operands have i1 scalar type. | |||
2343 | static Value *simplifyICmpOfBools(CmpInst::Predicate Pred, Value *LHS, | |||
2344 | Value *RHS, const SimplifyQuery &Q) { | |||
2345 | Type *ITy = GetCompareTy(LHS); // The return type. | |||
2346 | Type *OpTy = LHS->getType(); // The operand type. | |||
2347 | if (!OpTy->isIntOrIntVectorTy(1)) | |||
2348 | return nullptr; | |||
2349 | ||||
2350 | // A boolean compared to true/false can be simplified in 14 out of the 20 | |||
2351 | // (10 predicates * 2 constants) possible combinations. Cases not handled here | |||
2352 | // require a 'not' of the LHS, so those must be transformed in InstCombine. | |||
2353 | if (match(RHS, m_Zero())) { | |||
2354 | switch (Pred) { | |||
2355 | case CmpInst::ICMP_NE: // X != 0 -> X | |||
2356 | case CmpInst::ICMP_UGT: // X >u 0 -> X | |||
2357 | case CmpInst::ICMP_SLT: // X <s 0 -> X | |||
2358 | return LHS; | |||
2359 | ||||
2360 | case CmpInst::ICMP_ULT: // X <u 0 -> false | |||
2361 | case CmpInst::ICMP_SGT: // X >s 0 -> false | |||
2362 | return getFalse(ITy); | |||
2363 | ||||
2364 | case CmpInst::ICMP_UGE: // X >=u 0 -> true | |||
2365 | case CmpInst::ICMP_SLE: // X <=s 0 -> true | |||
2366 | return getTrue(ITy); | |||
2367 | ||||
2368 | default: break; | |||
2369 | } | |||
2370 | } else if (match(RHS, m_One())) { | |||
2371 | switch (Pred) { | |||
2372 | case CmpInst::ICMP_EQ: // X == 1 -> X | |||
2373 | case CmpInst::ICMP_UGE: // X >=u 1 -> X | |||
2374 | case CmpInst::ICMP_SLE: // X <=s -1 -> X | |||
2375 | return LHS; | |||
2376 | ||||
2377 | case CmpInst::ICMP_UGT: // X >u 1 -> false | |||
2378 | case CmpInst::ICMP_SLT: // X <s -1 -> false | |||
2379 | return getFalse(ITy); | |||
2380 | ||||
2381 | case CmpInst::ICMP_ULE: // X <=u 1 -> true | |||
2382 | case CmpInst::ICMP_SGE: // X >=s -1 -> true | |||
2383 | return getTrue(ITy); | |||
2384 | ||||
2385 | default: break; | |||
2386 | } | |||
2387 | } | |||
2388 | ||||
2389 | switch (Pred) { | |||
2390 | default: | |||
2391 | break; | |||
2392 | case ICmpInst::ICMP_UGE: | |||
2393 | if (isImpliedCondition(RHS, LHS, Q.DL).getValueOr(false)) | |||
2394 | return getTrue(ITy); | |||
2395 | break; | |||
2396 | case ICmpInst::ICMP_SGE: | |||
2397 | /// For signed comparison, the values for an i1 are 0 and -1 | |||
2398 | /// respectively. This maps into a truth table of: | |||
2399 | /// LHS | RHS | LHS >=s RHS | LHS implies RHS | |||
2400 | /// 0 | 0 | 1 (0 >= 0) | 1 | |||
2401 | /// 0 | 1 | 1 (0 >= -1) | 1 | |||
2402 | /// 1 | 0 | 0 (-1 >= 0) | 0 | |||
2403 | /// 1 | 1 | 1 (-1 >= -1) | 1 | |||
2404 | if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false)) | |||
2405 | return getTrue(ITy); | |||
2406 | break; | |||
2407 | case ICmpInst::ICMP_ULE: | |||
2408 | if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false)) | |||
2409 | return getTrue(ITy); | |||
2410 | break; | |||
2411 | } | |||
2412 | ||||
2413 | return nullptr; | |||
2414 | } | |||
2415 | ||||
2416 | /// Try hard to fold icmp with zero RHS because this is a common case. | |||
2417 | static Value *simplifyICmpWithZero(CmpInst::Predicate Pred, Value *LHS, | |||
2418 | Value *RHS, const SimplifyQuery &Q) { | |||
2419 | if (!match(RHS, m_Zero())) | |||
2420 | return nullptr; | |||
2421 | ||||
2422 | Type *ITy = GetCompareTy(LHS); // The return type. | |||
2423 | switch (Pred) { | |||
2424 | default: | |||
2425 | llvm_unreachable("Unknown ICmp predicate!")::llvm::llvm_unreachable_internal("Unknown ICmp predicate!", "/build/llvm-toolchain-snapshot-9~svn360825/lib/Analysis/InstructionSimplify.cpp" , 2425); | |||
2426 | case ICmpInst::ICMP_ULT: | |||
2427 | return getFalse(ITy); | |||
2428 | case ICmpInst::ICMP_UGE: | |||
2429 | return getTrue(ITy); | |||
2430 | case ICmpInst::ICMP_EQ: | |||
2431 | case ICmpInst::ICMP_ULE: | |||
2432 | if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo)) | |||
2433 | return getFalse(ITy); | |||
2434 | break; | |||
2435 | case ICmpInst::ICMP_NE: | |||
2436 | case ICmpInst::ICMP_UGT: | |||
2437 | if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo)) | |||
2438 | return getTrue(ITy); | |||
2439 | break; | |||
2440 | case ICmpInst::ICMP_SLT: { | |||
2441 | KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); | |||
2442 | if (LHSKnown.isNegative()) | |||
2443 | return getTrue(ITy); | |||
2444 | if (LHSKnown.isNonNegative()) | |||
2445 | return getFalse(ITy); | |||
2446 | break; | |||
2447 | } | |||
2448 | case ICmpInst::ICMP_SLE: { | |||
2449 | KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); | |||
2450 | if (LHSKnown.isNegative()) | |||
2451 | return getTrue(ITy); | |||
2452 | if (LHSKnown.isNonNegative() && | |||
2453 | isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT)) | |||
2454 | return getFalse(ITy); | |||
2455 | break; | |||
2456 | } | |||
2457 | case ICmpInst::ICMP_SGE: { | |||
2458 | KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); | |||
2459 | if (LHSKnown.isNegative()) | |||
2460 | return getFalse(ITy); | |||
2461 | if (LHSKnown.isNonNegative()) | |||
2462 | return getTrue(ITy); | |||
2463 | break; | |||
2464 | } | |||
2465 | case ICmpInst::ICMP_SGT: { | |||
2466 | KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); | |||
2467 | if (LHSKnown.isNegative()) | |||
2468 | return getFalse(ITy); | |||
2469 | if (LHSKnown.isNonNegative() && | |||
2470 | isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT)) | |||
2471 | return getTrue(ITy); | |||
2472 | break; | |||
2473 | } | |||
2474 | } | |||
2475 | ||||
2476 | return nullptr; | |||
2477 | } | |||
2478 | ||||
2479 | static Value *simplifyICmpWithConstant(CmpInst::Predicate Pred, Value *LHS, | |||
2480 | Value *RHS, const InstrInfoQuery &IIQ) { | |||
2481 | Type *ITy = GetCompareTy(RHS); // The return type. | |||
2482 | ||||
2483 | Value *X; | |||
2484 | // Sign-bit checks can be optimized to true/false after unsigned | |||
2485 | // floating-point casts: | |||
2486 | // icmp slt (bitcast (uitofp X)), 0 --> false | |||
2487 | // icmp sgt (bitcast (uitofp X)), -1 --> true | |||
2488 | if (match(LHS, m_BitCast(m_UIToFP(m_Value(X))))) { | |||
2489 | if (Pred == ICmpInst::ICMP_SLT && match(RHS, m_Zero())) | |||
2490 | return ConstantInt::getFalse(ITy); | |||
2491 | if (Pred == ICmpInst::ICMP_SGT && match(RHS, m_AllOnes())) | |||
2492 | return ConstantInt::getTrue(ITy); | |||
2493 | } | |||
2494 | ||||
2495 | const APInt *C; | |||
2496 | if (!match(RHS, m_APInt(C))) | |||
2497 | return nullptr; | |||
2498 | ||||
2499 | // Rule out tautological comparisons (eg., ult 0 or uge 0). | |||
2500 | ConstantRange RHS_CR = ConstantRange::makeExactICmpRegion(Pred, *C); | |||
2501 | if (RHS_CR.isEmptySet()) | |||
2502 | return ConstantInt::getFalse(ITy); | |||
2503 | if (RHS_CR.isFullSet()) | |||
2504 | return ConstantInt::getTrue(ITy); | |||
2505 | ||||
2506 | ConstantRange LHS_CR = computeConstantRange(LHS, IIQ.UseInstrInfo); | |||
2507 | if (!LHS_CR.isFullSet()) { | |||
2508 | if (RHS_CR.contains(LHS_CR)) | |||
2509 | return ConstantInt::getTrue(ITy); | |||
2510 | if (RHS_CR.inverse().contains(LHS_CR)) | |||
2511 | return ConstantInt::getFalse(ITy); | |||
2512 | } | |||
2513 | ||||
2514 | return nullptr; | |||
2515 | } | |||
2516 | ||||
2517 | /// TODO: A large part of this logic is duplicated in InstCombine's | |||
2518 | /// foldICmpBinOp(). We should be able to share that and avoid the code | |||
2519 | /// duplication. | |||
2520 | static Value *simplifyICmpWithBinOp(CmpInst::Predicate Pred, Value *LHS, | |||
2521 | Value *RHS, const SimplifyQuery &Q, | |||
2522 | unsigned MaxRecurse) { | |||
2523 | Type *ITy = GetCompareTy(LHS); // The return type. | |||
2524 | ||||
2525 | BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS); | |||
2526 | BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS); | |||
2527 | if (MaxRecurse && (LBO || RBO)) { | |||
2528 | // Analyze the case when either LHS or RHS is an add instruction. | |||
2529 | Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr; | |||
2530 | // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null). | |||
2531 | bool NoLHSWrapProblem = false, NoRHSWrapProblem = false; | |||
2532 | if (LBO && LBO->getOpcode() == Instruction::Add) { | |||
2533 | A = LBO->getOperand(0); | |||
2534 | B = LBO->getOperand(1); | |||
2535 | NoLHSWrapProblem = | |||
2536 | ICmpInst::isEquality(Pred) || | |||
2537 | (CmpInst::isUnsigned(Pred) && | |||
2538 | Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO))) || | |||
2539 | (CmpInst::isSigned(Pred) && | |||
2540 | Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO))); | |||
2541 | } | |||
2542 | if (RBO && RBO->getOpcode() == Instruction::Add) { | |||
2543 | C = RBO->getOperand(0); | |||
2544 | D = RBO->getOperand(1); | |||
2545 | NoRHSWrapProblem = | |||
2546 | ICmpInst::isEquality(Pred) || | |||
2547 | (CmpInst::isUnsigned(Pred) && | |||
2548 | Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(RBO))) || | |||
2549 | (CmpInst::isSigned(Pred) && | |||
2550 | Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(RBO))); | |||
2551 | } | |||
2552 | ||||
2553 | // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow. | |||
2554 | if ((A == RHS || B == RHS) && NoLHSWrapProblem) | |||
2555 | if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A, | |||
2556 | Constant::getNullValue(RHS->getType()), Q, | |||
2557 | MaxRecurse - 1)) | |||
2558 | return V; | |||
2559 | ||||
2560 | // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow. | |||
2561 | if ((C == LHS || D == LHS) && NoRHSWrapProblem) | |||
2562 | if (Value *V = | |||
2563 | SimplifyICmpInst(Pred, Constant::getNullValue(LHS->getType()), | |||
2564 | C == LHS ? D : C, Q, MaxRecurse - 1)) | |||
2565 | return V; | |||
2566 | ||||
2567 | // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow. | |||
2568 | if (A && C && (A == C || A == D || B == C || B == D) && NoLHSWrapProblem && | |||
2569 | NoRHSWrapProblem) { | |||
2570 | // Determine Y and Z in the form icmp (X+Y), (X+Z). | |||
2571 | Value *Y, *Z; | |||
2572 | if (A == C) { | |||
2573 | // C + B == C + D -> B == D | |||
2574 | Y = B; | |||
2575 | Z = D; | |||
2576 | } else if (A == D) { | |||
2577 | // D + B == C + D -> B == C | |||
2578 | Y = B; | |||
2579 | Z = C; | |||
2580 | } else if (B == C) { | |||
2581 | // A + C == C + D -> A == D | |||
2582 | Y = A; | |||
2583 | Z = D; | |||
2584 | } else { | |||
2585 | assert(B == D)((B == D) ? static_cast<void> (0) : __assert_fail ("B == D" , "/build/llvm-toolchain-snapshot-9~svn360825/lib/Analysis/InstructionSimplify.cpp" , 2585, __PRETTY_FUNCTION__)); | |||
2586 | // A + D == C + D -> A == C | |||
2587 | Y = A; | |||
2588 | Z = C; | |||
2589 | } | |||
2590 | if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse - 1)) | |||
2591 | return V; | |||
2592 | } | |||
2593 | } | |||
2594 | ||||
2595 | { | |||
2596 | Value *Y = nullptr; | |||
2597 | // icmp pred (or X, Y), X | |||
2598 | if (LBO && match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) { | |||
2599 | if (Pred == ICmpInst::ICMP_ULT) | |||
2600 | return getFalse(ITy); | |||
2601 | if (Pred == ICmpInst::ICMP_UGE) | |||
2602 | return getTrue(ITy); | |||
2603 | ||||
2604 | if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) { | |||
2605 | KnownBits RHSKnown = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); | |||
2606 | KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); | |||
2607 | if (RHSKnown.isNonNegative() && YKnown.isNegative()) | |||
2608 | return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy); | |||
2609 | if (RHSKnown.isNegative() || YKnown.isNonNegative()) | |||
2610 | return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy); | |||
2611 | } | |||
2612 | } | |||
2613 | // icmp pred X, (or X, Y) | |||
2614 | if (RBO && match(RBO, m_c_Or(m_Value(Y), m_Specific(LHS)))) { | |||
2615 | if (Pred == ICmpInst::ICMP_ULE) | |||
2616 | return getTrue(ITy); | |||
2617 | if (Pred == ICmpInst::ICMP_UGT) | |||
2618 | return getFalse(ITy); | |||
2619 | ||||
2620 | if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLE) { | |||
2621 | KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); | |||
2622 | KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); | |||
2623 | if (LHSKnown.isNonNegative() && YKnown.isNegative()) | |||
2624 | return Pred == ICmpInst::ICMP_SGT ? getTrue(ITy) : getFalse(ITy); | |||
2625 | if (LHSKnown.isNegative() || YKnown.isNonNegative()) | |||
2626 | return Pred == ICmpInst::ICMP_SGT ? getFalse(ITy) : getTrue(ITy); | |||
2627 | } | |||
2628 | } | |||
2629 | } | |||
2630 | ||||
2631 | // icmp pred (and X, Y), X | |||
2632 | if (LBO && match(LBO, m_c_And(m_Value(), m_Specific(RHS)))) { | |||
2633 | if (Pred == ICmpInst::ICMP_UGT) | |||
2634 | return getFalse(ITy); | |||
2635 | if (Pred == ICmpInst::ICMP_ULE) | |||
2636 | return getTrue(ITy); | |||
2637 | } | |||
2638 | // icmp pred X, (and X, Y) | |||
2639 | if (RBO && match(RBO, m_c_And(m_Value(), m_Specific(LHS)))) { | |||
2640 | if (Pred == ICmpInst::ICMP_UGE) | |||
2641 | return getTrue(ITy); | |||
2642 | if (Pred == ICmpInst::ICMP_ULT) | |||
2643 | return getFalse(ITy); | |||
2644 | } | |||
2645 | ||||
2646 | // 0 - (zext X) pred C | |||
2647 | if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) { | |||
2648 | if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) { | |||
2649 | if (RHSC->getValue().isStrictlyPositive()) { | |||
2650 | if (Pred == ICmpInst::ICMP_SLT) | |||
2651 | return ConstantInt::getTrue(RHSC->getContext()); | |||
2652 | if (Pred == ICmpInst::ICMP_SGE) | |||
2653 | return ConstantInt::getFalse(RHSC->getContext()); | |||
2654 | if (Pred == ICmpInst::ICMP_EQ) | |||
2655 | return ConstantInt::getFalse(RHSC->getContext()); | |||
2656 | if (Pred == ICmpInst::ICMP_NE) | |||
2657 | return ConstantInt::getTrue(RHSC->getContext()); | |||
2658 | } | |||
2659 | if (RHSC->getValue().isNonNegative()) { | |||
2660 | if (Pred == ICmpInst::ICMP_SLE) | |||
2661 | return ConstantInt::getTrue(RHSC->getContext()); | |||
2662 | if (Pred == ICmpInst::ICMP_SGT) | |||
2663 | return ConstantInt::getFalse(RHSC->getContext()); | |||
2664 | } | |||
2665 | } | |||
2666 | } | |||
2667 | ||||
2668 | // icmp pred (urem X, Y), Y | |||
2669 | if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) { | |||
2670 | switch (Pred) { | |||
2671 | default: | |||
2672 | break; | |||
2673 | case ICmpInst::ICMP_SGT: | |||
2674 | case ICmpInst::ICMP_SGE: { | |||
2675 | KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); | |||
2676 | if (!Known.isNonNegative()) | |||
2677 | break; | |||
2678 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
2679 | } | |||
2680 | case ICmpInst::ICMP_EQ: | |||
2681 | case ICmpInst::ICMP_UGT: | |||
2682 | case ICmpInst::ICMP_UGE: | |||
2683 | return getFalse(ITy); | |||
2684 | case ICmpInst::ICMP_SLT: | |||
2685 | case ICmpInst::ICMP_SLE: { | |||
2686 | KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); | |||
2687 | if (!Known.isNonNegative()) | |||
2688 | break; | |||
2689 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
2690 | } | |||
2691 | case ICmpInst::ICMP_NE: | |||
2692 | case ICmpInst::ICMP_ULT: | |||
2693 | case ICmpInst::ICMP_ULE: | |||
2694 | return getTrue(ITy); | |||
2695 | } | |||
2696 | } | |||
2697 | ||||
2698 | // icmp pred X, (urem Y, X) | |||
2699 | if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) { | |||
2700 | switch (Pred) { | |||
2701 | default: | |||
2702 | break; | |||
2703 | case ICmpInst::ICMP_SGT: | |||
2704 | case ICmpInst::ICMP_SGE: { | |||
2705 | KnownBits Known = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); | |||
2706 | if (!Known.isNonNegative()) | |||
2707 | break; | |||
2708 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
2709 | } | |||
2710 | case ICmpInst::ICMP_NE: | |||
2711 | case ICmpInst::ICMP_UGT: | |||
2712 | case ICmpInst::ICMP_UGE: | |||
2713 | return getTrue(ITy); | |||
2714 | case ICmpInst::ICMP_SLT: | |||
2715 | case ICmpInst::ICMP_SLE: { | |||
2716 | KnownBits Known = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); | |||
2717 | if (!Known.isNonNegative()) | |||
2718 | break; | |||
2719 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
2720 | } | |||
2721 | case ICmpInst::ICMP_EQ: | |||
2722 | case ICmpInst::ICMP_ULT: | |||
2723 | case ICmpInst::ICMP_ULE: | |||
2724 | return getFalse(ITy); | |||
2725 | } | |||
2726 | } | |||
2727 | ||||
2728 | // x >> y <=u x | |||
2729 | // x udiv y <=u x. | |||
2730 | if (LBO && (match(LBO, m_LShr(m_Specific(RHS), m_Value())) || | |||
2731 | match(LBO, m_UDiv(m_Specific(RHS), m_Value())))) { | |||
2732 | // icmp pred (X op Y), X | |||
2733 | if (Pred == ICmpInst::ICMP_UGT) | |||
2734 | return getFalse(ITy); | |||
2735 | if (Pred == ICmpInst::ICMP_ULE) | |||
2736 | return getTrue(ITy); | |||
2737 | } | |||
2738 | ||||
2739 | // x >=u x >> y | |||
2740 | // x >=u x udiv y. | |||
2741 | if (RBO && (match(RBO, m_LShr(m_Specific(LHS), m_Value())) || | |||
2742 | match(RBO, m_UDiv(m_Specific(LHS), m_Value())))) { | |||
2743 | // icmp pred X, (X op Y) | |||
2744 | if (Pred == ICmpInst::ICMP_ULT) | |||
2745 | return getFalse(ITy); | |||
2746 | if (Pred == ICmpInst::ICMP_UGE) | |||
2747 | return getTrue(ITy); | |||
2748 | } | |||
2749 | ||||
2750 | // handle: | |||
2751 | // CI2 << X == CI | |||
2752 | // CI2 << X != CI | |||
2753 | // | |||
2754 | // where CI2 is a power of 2 and CI isn't | |||
2755 | if (auto *CI = dyn_cast<ConstantInt>(RHS)) { | |||
2756 | const APInt *CI2Val, *CIVal = &CI->getValue(); | |||
2757 | if (LBO && match(LBO, m_Shl(m_APInt(CI2Val), m_Value())) && | |||
2758 | CI2Val->isPowerOf2()) { | |||
2759 | if (!CIVal->isPowerOf2()) { | |||
2760 | // CI2 << X can equal zero in some circumstances, | |||
2761 | // this simplification is unsafe if CI is zero. | |||
2762 | // | |||
2763 | // We know it is safe if: | |||
2764 | // - The shift is nsw, we can't shift out the one bit. | |||
2765 | // - The shift is nuw, we can't shift out the one bit. | |||
2766 | // - CI2 is one | |||
2767 | // - CI isn't zero | |||
2768 | if (Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO)) || | |||
2769 | Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO)) || | |||
2770 | CI2Val->isOneValue() || !CI->isZero()) { | |||
2771 | if (Pred == ICmpInst::ICMP_EQ) | |||
2772 | return ConstantInt::getFalse(RHS->getContext()); | |||
2773 | if (Pred == ICmpInst::ICMP_NE) | |||
2774 | return ConstantInt::getTrue(RHS->getContext()); | |||
2775 | } | |||
2776 | } | |||
2777 | if (CIVal->isSignMask() && CI2Val->isOneValue()) { | |||
2778 | if (Pred == ICmpInst::ICMP_UGT) | |||
2779 | return ConstantInt::getFalse(RHS->getContext()); | |||
2780 | if (Pred == ICmpInst::ICMP_ULE) | |||
2781 | return ConstantInt::getTrue(RHS->getContext()); | |||
2782 | } | |||
2783 | } | |||
2784 | } | |||
2785 | ||||
2786 | if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() && | |||
2787 | LBO->getOperand(1) == RBO->getOperand(1)) { | |||
2788 | switch (LBO->getOpcode()) { | |||
2789 | default: | |||
2790 | break; | |||
2791 | case Instruction::UDiv: | |||
2792 | case Instruction::LShr: | |||
2793 | if (ICmpInst::isSigned(Pred) || !Q.IIQ.isExact(LBO) || | |||
2794 | !Q.IIQ.isExact(RBO)) | |||
2795 | break; | |||
2796 | if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0), | |||
2797 | RBO->getOperand(0), Q, MaxRecurse - 1)) | |||
2798 | return V; | |||
2799 | break; | |||
2800 | case Instruction::SDiv: | |||
2801 | if (!ICmpInst::isEquality(Pred) || !Q.IIQ.isExact(LBO) || | |||
2802 | !Q.IIQ.isExact(RBO)) | |||
2803 | break; | |||
2804 | if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0), | |||
2805 | RBO->getOperand(0), Q, MaxRecurse - 1)) | |||
2806 | return V; | |||
2807 | break; | |||
2808 | case Instruction::AShr: | |||
2809 | if (!Q.IIQ.isExact(LBO) || !Q.IIQ.isExact(RBO)) | |||
2810 | break; | |||
2811 | if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0), | |||
2812 | RBO->getOperand(0), Q, MaxRecurse - 1)) | |||
2813 | return V; | |||
2814 | break; | |||
2815 | case Instruction::Shl: { | |||
2816 | bool NUW = Q.IIQ.hasNoUnsignedWrap(LBO) && Q.IIQ.hasNoUnsignedWrap(RBO); | |||
2817 | bool NSW = Q.IIQ.hasNoSignedWrap(LBO) && Q.IIQ.hasNoSignedWrap(RBO); | |||
2818 | if (!NUW && !NSW) | |||
2819 | break; | |||
2820 | if (!NSW && ICmpInst::isSigned(Pred)) | |||
2821 | break; | |||
2822 | if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0), | |||
2823 | RBO->getOperand(0), Q, MaxRecurse - 1)) | |||
2824 | return V; | |||
2825 | break; | |||
2826 | } | |||
2827 | } | |||
2828 | } | |||
2829 | return nullptr; | |||
2830 | } | |||
2831 | ||||
2832 | /// Simplify integer comparisons where at least one operand of the compare | |||
2833 | /// matches an integer min/max idiom. | |||
2834 | static Value *simplifyICmpWithMinMax(CmpInst::Predicate Pred, Value *LHS, | |||
2835 | Value *RHS, const SimplifyQuery &Q, | |||
2836 | unsigned MaxRecurse) { | |||
2837 | Type *ITy = GetCompareTy(LHS); // The return type. | |||
2838 | Value *A, *B; | |||
2839 | CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE; | |||
2840 | CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B". | |||
2841 | ||||
2842 | // Signed variants on "max(a,b)>=a -> true". | |||
2843 | if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) { | |||
2844 | if (A != RHS) | |||
2845 | std::swap(A, B); // smax(A, B) pred A. | |||
2846 | EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B". | |||
2847 | // We analyze this as smax(A, B) pred A. | |||
2848 | P = Pred; | |||
2849 | } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) && | |||
2850 | (A == LHS || B == LHS)) { | |||
2851 | if (A != LHS) | |||
2852 | std::swap(A, B); // A pred smax(A, B). | |||
2853 | EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B". | |||
2854 | // We analyze this as smax(A, B) swapped-pred A. | |||
2855 | P = CmpInst::getSwappedPredicate(Pred); | |||
2856 | } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) && | |||
2857 | (A == RHS || B == RHS)) { | |||
2858 | if (A != RHS) | |||
2859 | std::swap(A, B); // smin(A, B) pred A. | |||
2860 | EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B". | |||
2861 | // We analyze this as smax(-A, -B) swapped-pred -A. | |||
2862 | // Note that we do not need to actually form -A or -B thanks to EqP. | |||
2863 | P = CmpInst::getSwappedPredicate(Pred); | |||
2864 | } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) && | |||
2865 | (A == LHS || B == LHS)) { | |||
2866 | if (A != LHS) | |||
2867 | std::swap(A, B); // A pred smin(A, B). | |||
2868 | EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B". | |||
2869 | // We analyze this as smax(-A, -B) pred -A. | |||
2870 | // Note that we do not need to actually form -A or -B thanks to EqP. | |||
2871 | P = Pred; | |||
2872 | } | |||
2873 | if (P != CmpInst::BAD_ICMP_PREDICATE) { | |||
2874 | // Cases correspond to "max(A, B) p A". | |||
2875 | switch (P) { | |||
2876 | default: | |||
2877 | break; | |||
2878 | case CmpInst::ICMP_EQ: | |||
2879 | case CmpInst::ICMP_SLE: | |||
2880 | // Equivalent to "A EqP B". This may be the same as the condition tested | |||
2881 | // in the max/min; if so, we can just return that. | |||
2882 | if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B)) | |||
2883 | return V; | |||
2884 | if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B)) | |||
2885 | return V; | |||
2886 | // Otherwise, see if "A EqP B" simplifies. | |||
2887 | if (MaxRecurse) | |||
2888 | if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1)) | |||
2889 | return V; | |||
2890 | break; | |||
2891 | case CmpInst::ICMP_NE: | |||
2892 | case CmpInst::ICMP_SGT: { | |||
2893 | CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP); | |||
2894 | // Equivalent to "A InvEqP B". This may be the same as the condition | |||
2895 | // tested in the max/min; if so, we can just return that. | |||
2896 | if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B)) | |||
2897 | return V; | |||
2898 | if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B)) | |||
2899 | return V; | |||
2900 | // Otherwise, see if "A InvEqP B" simplifies. | |||
2901 | if (MaxRecurse) | |||
2902 | if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1)) | |||
2903 | return V; | |||
2904 | break; | |||
2905 | } | |||
2906 | case CmpInst::ICMP_SGE: | |||
2907 | // Always true. | |||
2908 | return getTrue(ITy); | |||
2909 | case CmpInst::ICMP_SLT: | |||
2910 | // Always false. | |||
2911 | return getFalse(ITy); | |||
2912 | } | |||
2913 | } | |||
2914 | ||||
2915 | // Unsigned variants on "max(a,b)>=a -> true". | |||
2916 | P = CmpInst::BAD_ICMP_PREDICATE; | |||
2917 | if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) { | |||
2918 | if (A != RHS) | |||
2919 | std::swap(A, B); // umax(A, B) pred A. | |||
2920 | EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B". | |||
2921 | // We analyze this as umax(A, B) pred A. | |||
2922 | P = Pred; | |||
2923 | } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) && | |||
2924 | (A == LHS || B == LHS)) { | |||
2925 | if (A != LHS) | |||
2926 | std::swap(A, B); // A pred umax(A, B). | |||
2927 | EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B". | |||
2928 | // We analyze this as umax(A, B) swapped-pred A. | |||
2929 | P = CmpInst::getSwappedPredicate(Pred); | |||
2930 | } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) && | |||
2931 | (A == RHS || B == RHS)) { | |||
2932 | if (A != RHS) | |||
2933 | std::swap(A, B); // umin(A, B) pred A. | |||
2934 | EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B". | |||
2935 | // We analyze this as umax(-A, -B) swapped-pred -A. | |||
2936 | // Note that we do not need to actually form -A or -B thanks to EqP. | |||
2937 | P = CmpInst::getSwappedPredicate(Pred); | |||
2938 | } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) && | |||
2939 | (A == LHS || B == LHS)) { | |||
2940 | if (A != LHS) | |||
2941 | std::swap(A, B); // A pred umin(A, B). | |||
2942 | EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B". | |||
2943 | // We analyze this as umax(-A, -B) pred -A. | |||
2944 | // Note that we do not need to actually form -A or -B thanks to EqP. | |||
2945 | P = Pred; | |||
2946 | } | |||
2947 | if (P != CmpInst::BAD_ICMP_PREDICATE) { | |||
2948 | // Cases correspond to "max(A, B) p A". | |||
2949 | switch (P) { | |||
2950 | default: | |||
2951 | break; | |||
2952 | case CmpInst::ICMP_EQ: | |||
2953 | case CmpInst::ICMP_ULE: | |||
2954 | // Equivalent to "A EqP B". This may be the same as the condition tested | |||
2955 | // in the max/min; if so, we can just return that. | |||
2956 | if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B)) | |||
2957 | return V; | |||
2958 | if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B)) | |||
2959 | return V; | |||
2960 | // Otherwise, see if "A EqP B" simplifies. | |||
2961 | if (MaxRecurse) | |||
2962 | if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1)) | |||
2963 | return V; | |||
2964 | break; | |||
2965 | case CmpInst::ICMP_NE: | |||
2966 | case CmpInst::ICMP_UGT: { | |||
2967 | CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP); | |||
2968 | // Equivalent to "A InvEqP B". This may be the same as the condition | |||
2969 | // tested in the max/min; if so, we can just return that. | |||
2970 | if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B)) | |||
2971 | return V; | |||
2972 | if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B)) | |||
2973 | return V; | |||
2974 | // Otherwise, see if "A InvEqP B" simplifies. | |||
2975 | if (MaxRecurse) | |||
2976 | if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1)) | |||
2977 | return V; | |||
2978 | break; | |||
2979 | } | |||
2980 | case CmpInst::ICMP_UGE: | |||
2981 | // Always true. | |||
2982 | return getTrue(ITy); | |||
2983 | case CmpInst::ICMP_ULT: | |||
2984 | // Always false. | |||
2985 | return getFalse(ITy); | |||
2986 | } | |||
2987 | } | |||
2988 | ||||
2989 | // Variants on "max(x,y) >= min(x,z)". | |||
2990 | Value *C, *D; | |||
2991 | if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && | |||
2992 | match(RHS, m_SMin(m_Value(C), m_Value(D))) && | |||
2993 | (A == C || A == D || B == C || B == D)) { | |||
2994 | // max(x, ?) pred min(x, ?). | |||
2995 | if (Pred == CmpInst::ICMP_SGE) | |||
2996 | // Always true. | |||
2997 | return getTrue(ITy); | |||
2998 | if (Pred == CmpInst::ICMP_SLT) | |||
2999 | // Always false. | |||
3000 | return getFalse(ITy); | |||
3001 | } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) && | |||
3002 | match(RHS, m_SMax(m_Value(C), m_Value(D))) && | |||
3003 | (A == C || A == D || B == C || B == D)) { | |||
3004 | // min(x, ?) pred max(x, ?). | |||
3005 | if (Pred == CmpInst::ICMP_SLE) | |||
3006 | // Always true. | |||
3007 | return getTrue(ITy); | |||
3008 | if (Pred == CmpInst::ICMP_SGT) | |||
3009 | // Always false. | |||
3010 | return getFalse(ITy); | |||
3011 | } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && | |||
3012 | match(RHS, m_UMin(m_Value(C), m_Value(D))) && | |||
3013 | (A == C || A == D || B == C || B == D)) { | |||
3014 | // max(x, ?) pred min(x, ?). | |||
3015 | if (Pred == CmpInst::ICMP_UGE) | |||
3016 | // Always true. | |||
3017 | return getTrue(ITy); | |||
3018 | if (Pred == CmpInst::ICMP_ULT) | |||
3019 | // Always false. | |||
3020 | return getFalse(ITy); | |||
3021 | } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) && | |||
3022 | match(RHS, m_UMax(m_Value(C), m_Value(D))) && | |||
3023 | (A == C || A == D || B == C || B == D)) { | |||
3024 | // min(x, ?) pred max(x, ?). | |||
3025 | if (Pred == CmpInst::ICMP_ULE) | |||
3026 | // Always true. | |||
3027 | return getTrue(ITy); | |||
3028 | if (Pred == CmpInst::ICMP_UGT) | |||
3029 | // Always false. | |||
3030 | return getFalse(ITy); | |||
3031 | } | |||
3032 | ||||
3033 | return nullptr; | |||
3034 | } | |||
3035 | ||||
3036 | /// Given operands for an ICmpInst, see if we can fold the result. | |||
3037 | /// If not, this returns null. | |||
3038 | static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS, | |||
3039 | const SimplifyQuery &Q, unsigned MaxRecurse) { | |||
3040 | CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate; | |||
3041 | assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!")((CmpInst::isIntPredicate(Pred) && "Not an integer compare!" ) ? static_cast<void> (0) : __assert_fail ("CmpInst::isIntPredicate(Pred) && \"Not an integer compare!\"" , "/build/llvm-toolchain-snapshot-9~svn360825/lib/Analysis/InstructionSimplify.cpp" , 3041, __PRETTY_FUNCTION__)); | |||
3042 | ||||
3043 | if (Constant *CLHS = dyn_cast<Constant>(LHS)) { | |||
3044 | if (Constant *CRHS = dyn_cast<Constant>(RHS)) | |||
3045 | return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI); | |||
3046 | ||||
3047 | // If we have a constant, make sure it is on the RHS. | |||
3048 | std::swap(LHS, RHS); | |||
3049 | Pred = CmpInst::getSwappedPredicate(Pred); | |||
3050 | } | |||
3051 | assert(!isa<UndefValue>(LHS) && "Unexpected icmp undef,%X")((!isa<UndefValue>(LHS) && "Unexpected icmp undef,%X" ) ? static_cast<void> (0) : __assert_fail ("!isa<UndefValue>(LHS) && \"Unexpected icmp undef,%X\"" , "/build/llvm-toolchain-snapshot-9~svn360825/lib/Analysis/InstructionSimplify.cpp" , 3051, __PRETTY_FUNCTION__)); | |||
3052 | ||||
3053 | Type *ITy = GetCompareTy(LHS); // The return type. | |||
3054 | ||||
3055 | // For EQ and NE, we can always pick a value for the undef to make the | |||
3056 | // predicate pass or fail, so we can return undef. | |||
3057 | // Matches behavior in llvm::ConstantFoldCompareInstruction. | |||
3058 | if (isa<UndefValue>(RHS) && ICmpInst::isEquality(Pred)) | |||
3059 | return UndefValue::get(ITy); | |||
3060 | ||||
3061 | // icmp X, X -> true/false | |||
3062 | // icmp X, undef -> true/false because undef could be X. | |||
3063 | if (LHS == RHS || isa<UndefValue>(RHS)) | |||
3064 | return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred)); | |||
3065 | ||||
3066 | if (Value *V = simplifyICmpOfBools(Pred, LHS, RHS, Q)) | |||
3067 | return V; | |||
3068 | ||||
3069 | if (Value *V = simplifyICmpWithZero(Pred, LHS, RHS, Q)) | |||
3070 | return V; | |||
3071 | ||||
3072 | if (Value *V = simplifyICmpWithConstant(Pred, LHS, RHS, Q.IIQ)) | |||
3073 | return V; | |||
3074 | ||||
3075 | // If both operands have range metadata, use the metadata | |||
3076 | // to simplify the comparison. | |||
3077 | if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) { | |||
3078 | auto RHS_Instr = cast<Instruction>(RHS); | |||
3079 | auto LHS_Instr = cast<Instruction>(LHS); | |||
3080 | ||||
3081 | if (Q.IIQ.getMetadata(RHS_Instr, LLVMContext::MD_range) && | |||
3082 | Q.IIQ.getMetadata(LHS_Instr, LLVMContext::MD_range)) { | |||
3083 | auto RHS_CR = getConstantRangeFromMetadata( | |||
3084 | *RHS_Instr->getMetadata(LLVMContext::MD_range)); | |||
3085 | auto LHS_CR = getConstantRangeFromMetadata( | |||
3086 | *LHS_Instr->getMetadata(LLVMContext::MD_range)); | |||
3087 | ||||
3088 | auto Satisfied_CR = ConstantRange::makeSatisfyingICmpRegion(Pred, RHS_CR); | |||
3089 | if (Satisfied_CR.contains(LHS_CR)) | |||
3090 | return ConstantInt::getTrue(RHS->getContext()); | |||
3091 | ||||
3092 | auto InversedSatisfied_CR = ConstantRange::makeSatisfyingICmpRegion( | |||
3093 | CmpInst::getInversePredicate(Pred), RHS_CR); | |||
3094 | if (InversedSatisfied_CR.contains(LHS_CR)) | |||
3095 | return ConstantInt::getFalse(RHS->getContext()); | |||
3096 | } | |||
3097 | } | |||
3098 | ||||
3099 | // Compare of cast, for example (zext X) != 0 -> X != 0 | |||
3100 | if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) { | |||
3101 | Instruction *LI = cast<CastInst>(LHS); | |||
3102 | Value *SrcOp = LI->getOperand(0); | |||
3103 | Type *SrcTy = SrcOp->getType(); | |||
3104 | Type *DstTy = LI->getType(); | |||
3105 | ||||
3106 | // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input | |||
3107 | // if the integer type is the same size as the pointer type. | |||
3108 | if (MaxRecurse && isa<PtrToIntInst>(LI) && | |||
3109 | Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) { | |||
3110 | if (Constant *RHSC = dyn_cast<Constant>(RHS)) { | |||
3111 | // Transfer the cast to the constant. | |||
3112 | if (Value *V = SimplifyICmpInst(Pred, SrcOp, | |||
3113 | ConstantExpr::getIntToPtr(RHSC, SrcTy), | |||
3114 | Q, MaxRecurse-1)) | |||
3115 | return V; | |||
3116 | } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) { | |||
3117 | if (RI->getOperand(0)->getType() == SrcTy) | |||
3118 | // Compare without the cast. | |||
3119 | if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0), | |||
3120 | Q, MaxRecurse-1)) | |||
3121 | return V; | |||
3122 | } | |||
3123 | } | |||
3124 | ||||
3125 | if (isa<ZExtInst>(LHS)) { | |||
3126 | // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the | |||
3127 | // same type. | |||
3128 | if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) { | |||
3129 | if (MaxRecurse && SrcTy == RI->getOperand(0)->getType()) | |||
3130 | // Compare X and Y. Note that signed predicates become unsigned. | |||
3131 | if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred), | |||
3132 | SrcOp, RI->getOperand(0), Q, | |||
3133 | MaxRecurse-1)) | |||
3134 | return V; | |||
3135 | } | |||
3136 | // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended | |||
3137 | // too. If not, then try to deduce the result of the comparison. | |||
3138 | else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) { | |||
3139 | // Compute the constant that would happen if we truncated to SrcTy then | |||
3140 | // reextended to DstTy. | |||
3141 | Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy); | |||
3142 | Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy); | |||
3143 | ||||
3144 | // If the re-extended constant didn't change then this is effectively | |||
3145 | // also a case of comparing two zero-extended values. | |||
3146 | if (RExt == CI && MaxRecurse) | |||
3147 | if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred), | |||
3148 | SrcOp, Trunc, Q, MaxRecurse-1)) | |||
3149 | return V; | |||
3150 | ||||
3151 | // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit | |||
3152 | // there. Use this to work out the result of the comparison. | |||
3153 | if (RExt != CI) { | |||
3154 | switch (Pred) { | |||
3155 | default: llvm_unreachable("Unknown ICmp predicate!")::llvm::llvm_unreachable_internal("Unknown ICmp predicate!", "/build/llvm-toolchain-snapshot-9~svn360825/lib/Analysis/InstructionSimplify.cpp" , 3155); | |||
3156 | // LHS <u RHS. | |||
3157 | case ICmpInst::ICMP_EQ: | |||
3158 | case ICmpInst::ICMP_UGT: | |||
3159 | case ICmpInst::ICMP_UGE: | |||
3160 | return ConstantInt::getFalse(CI->getContext()); | |||
3161 | ||||
3162 | case ICmpInst::ICMP_NE: | |||
3163 | case ICmpInst::ICMP_ULT: | |||
3164 | case ICmpInst::ICMP_ULE: | |||
3165 | return ConstantInt::getTrue(CI->getContext()); | |||
3166 | ||||
3167 | // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS | |||
3168 | // is non-negative then LHS <s RHS. | |||
3169 | case ICmpInst::ICMP_SGT: | |||
3170 | case ICmpInst::ICMP_SGE: | |||
3171 | return CI->getValue().isNegative() ? | |||
3172 | ConstantInt::getTrue(CI->getContext()) : | |||
3173 | ConstantInt::getFalse(CI->getContext()); | |||
3174 | ||||
3175 | case ICmpInst::ICMP_SLT: | |||
3176 | case ICmpInst::ICMP_SLE: | |||
3177 | return CI->getValue().isNegative() ? | |||
3178 | ConstantInt::getFalse(CI->getContext()) : | |||
3179 | ConstantInt::getTrue(CI->getContext()); | |||
3180 | } | |||
3181 | } | |||
3182 | } | |||
3183 | } | |||
3184 | ||||
3185 | if (isa<SExtInst>(LHS)) { | |||
3186 | // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the | |||
3187 | // same type. | |||
3188 | if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) { | |||
3189 | if (MaxRecurse && SrcTy == RI->getOperand(0)->getType()) | |||
3190 | // Compare X and Y. Note that the predicate does not change. | |||
3191 | if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0), | |||
3192 | Q, MaxRecurse-1)) | |||
3193 | return V; | |||
3194 | } | |||
3195 | // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended | |||
3196 | // too. If not, then try to deduce the result of the comparison. | |||
3197 | else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) { | |||
3198 | // Compute the constant that would happen if we truncated to SrcTy then | |||
3199 | // reextended to DstTy. | |||
3200 | Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy); | |||
3201 | Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy); | |||
3202 | ||||
3203 | // If the re-extended constant didn't change then this is effectively | |||
3204 | // also a case of comparing two sign-extended values. | |||
3205 | if (RExt == CI && MaxRecurse) | |||
3206 | if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1)) | |||
3207 | return V; | |||
3208 | ||||
3209 | // Otherwise the upper bits of LHS are all equal, while RHS has varying | |||
3210 | // bits there. Use this to work out the result of the comparison. | |||
3211 | if (RExt != CI) { | |||
3212 | switch (Pred) { | |||
3213 | default: llvm_unreachable("Unknown ICmp predicate!")::llvm::llvm_unreachable_internal("Unknown ICmp predicate!", "/build/llvm-toolchain-snapshot-9~svn360825/lib/Analysis/InstructionSimplify.cpp" , 3213); | |||
3214 | case ICmpInst::ICMP_EQ: | |||
3215 | return ConstantInt::getFalse(CI->getContext()); | |||
3216 | case ICmpInst::ICMP_NE: | |||
3217 | return ConstantInt::getTrue(CI->getContext()); | |||
3218 | ||||
3219 | // If RHS is non-negative then LHS <s RHS. If RHS is negative then | |||
3220 | // LHS >s RHS. | |||
3221 | case ICmpInst::ICMP_SGT: | |||
3222 | case ICmpInst::ICMP_SGE: | |||
3223 | return CI->getValue().isNegative() ? | |||
3224 | ConstantInt::getTrue(CI->getContext()) : | |||
3225 | ConstantInt::getFalse(CI->getContext()); | |||
3226 | case ICmpInst::ICMP_SLT: | |||
3227 | case ICmpInst::ICMP_SLE: | |||
3228 | return CI->getValue().isNegative() ? | |||
3229 | ConstantInt::getFalse(CI->getContext()) : | |||
3230 | ConstantInt::getTrue(CI->getContext()); | |||
3231 | ||||
3232 | // If LHS is non-negative then LHS <u RHS. If LHS is negative then | |||
3233 | // LHS >u RHS. | |||
3234 | case ICmpInst::ICMP_UGT: | |||
3235 | case ICmpInst::ICMP_UGE: | |||
3236 | // Comparison is true iff the LHS <s 0. | |||
3237 | if (MaxRecurse) | |||
3238 | if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp, | |||
3239 | Constant::getNullValue(SrcTy), | |||
3240 | Q, MaxRecurse-1)) | |||
3241 | return V; | |||
3242 | break; | |||
3243 | case ICmpInst::ICMP_ULT: | |||
3244 | case ICmpInst::ICMP_ULE: | |||
3245 | // Comparison is true iff the LHS >=s 0. | |||
3246 | if (MaxRecurse) | |||
3247 | if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp, | |||
3248 | Constant::getNullValue(SrcTy), | |||
3249 | Q, MaxRecurse-1)) | |||
3250 | return V; | |||
3251 | break; | |||
3252 | } | |||
3253 | } | |||
3254 | } | |||
3255 | } | |||
3256 | } | |||
3257 | ||||
3258 | // icmp eq|ne X, Y -> false|true if X != Y | |||
3259 | if (ICmpInst::isEquality(Pred) && | |||
3260 | isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo)) { | |||
3261 | return Pred == ICmpInst::ICMP_NE ? getTrue(ITy) : getFalse(ITy); | |||
3262 | } | |||
3263 | ||||
3264 | if (Value *V = simplifyICmpWithBinOp(Pred, LHS, RHS, Q, MaxRecurse)) | |||
3265 | return V; | |||
3266 | ||||
3267 | if (Value *V = simplifyICmpWithMinMax(Pred, LHS, RHS, Q, MaxRecurse)) | |||
3268 | return V; | |||
3269 | ||||
3270 | // Simplify comparisons of related pointers using a powerful, recursive | |||
3271 | // GEP-walk when we have target data available.. | |||
3272 | if (LHS->getType()->isPointerTy()) | |||
3273 | if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.AC, Q.CxtI, | |||
3274 | Q.IIQ, LHS, RHS)) | |||
3275 | return C; | |||
3276 | if (auto *CLHS = dyn_cast<PtrToIntOperator>(LHS)) | |||
3277 | if (auto *CRHS = dyn_cast<PtrToIntOperator>(RHS)) | |||
3278 | if (Q.DL.getTypeSizeInBits(CLHS->getPointerOperandType()) == | |||
3279 | Q.DL.getTypeSizeInBits(CLHS->getType()) && | |||
3280 | Q.DL.getTypeSizeInBits(CRHS->getPointerOperandType()) == | |||
3281 | Q.DL.getTypeSizeInBits(CRHS->getType())) | |||
3282 | if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.AC, Q.CxtI, | |||
3283 | Q.IIQ, CLHS->getPointerOperand(), | |||
3284 | CRHS->getPointerOperand())) | |||
3285 | return C; | |||
3286 | ||||
3287 | if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) { | |||
3288 | if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) { | |||
3289 | if (GLHS->getPointerOperand() == GRHS->getPointerOperand() && | |||
3290 | GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() && | |||
3291 | (ICmpInst::isEquality(Pred) || | |||
3292 | (GLHS->isInBounds() && GRHS->isInBounds() && | |||
3293 | Pred == ICmpInst::getSignedPredicate(Pred)))) { | |||
3294 | // The bases are equal and the indices are constant. Build a constant | |||
3295 | // expression GEP with the same indices and a null base pointer to see | |||
3296 | // what constant folding can make out of it. | |||
3297 | Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType()); | |||
3298 | SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end()); | |||
3299 | Constant *NewLHS = ConstantExpr::getGetElementPtr( | |||
3300 | GLHS->getSourceElementType(), Null, IndicesLHS); | |||
3301 | ||||
3302 | SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end()); | |||
3303 | Constant *NewRHS = ConstantExpr::getGetElementPtr( | |||
3304 | GLHS->getSourceElementType(), Null, IndicesRHS); | |||
3305 | return ConstantExpr::getICmp(Pred, NewLHS, NewRHS); | |||
3306 | } | |||
3307 | } | |||
3308 | } | |||
3309 | ||||
3310 | // If the comparison is with the result of a select instruction, check whether | |||
3311 | // comparing with either branch of the select always yields the same value. | |||
3312 | if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)) | |||
3313 | if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse)) | |||
3314 | return V; | |||
3315 | ||||
3316 | // If the comparison is with the result of a phi instruction, check whether | |||
3317 | // doing the compare with each incoming phi value yields a common result. | |||
3318 | if (isa<PHINode>(LHS) || isa<PHINode>(RHS)) | |||
3319 | if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse)) | |||
3320 | return V; | |||
3321 | ||||
3322 | return nullptr; | |||
3323 | } | |||
3324 | ||||
3325 | Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS, | |||
3326 | const SimplifyQuery &Q) { | |||
3327 | return ::SimplifyICmpInst(Predicate, LHS, RHS, Q, RecursionLimit); | |||
3328 | } | |||
3329 | ||||
3330 | /// Given operands for an FCmpInst, see if we can fold the result. | |||
3331 | /// If not, this returns null. | |||
3332 | static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS, | |||
3333 | FastMathFlags FMF, const SimplifyQuery &Q, | |||
3334 | unsigned MaxRecurse) { | |||
3335 | CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate; | |||
3336 | assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!")((CmpInst::isFPPredicate(Pred) && "Not an FP compare!" ) ? static_cast<void> (0) : __assert_fail ("CmpInst::isFPPredicate(Pred) && \"Not an FP compare!\"" , "/build/llvm-toolchain-snapshot-9~svn360825/lib/Analysis/InstructionSimplify.cpp" , 3336, __PRETTY_FUNCTION__)); | |||
3337 | ||||
3338 | if (Constant *CLHS = dyn_cast<Constant>(LHS)) { | |||
3339 | if (Constant *CRHS = dyn_cast<Constant>(RHS)) | |||
3340 | return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI); | |||
3341 | ||||
3342 | // If we have a constant, make sure it is on the RHS. | |||
3343 | std::swap(LHS, RHS); | |||
3344 | Pred = CmpInst::getSwappedPredicate(Pred); | |||
3345 | } | |||
3346 | ||||
3347 | // Fold trivial predicates. | |||
3348 | Type *RetTy = GetCompareTy(LHS); | |||
3349 | if (Pred == FCmpInst::FCMP_FALSE) | |||
3350 | return getFalse(RetTy); | |||
3351 | if (Pred == FCmpInst::FCMP_TRUE) | |||
3352 | return getTrue(RetTy); | |||
3353 | ||||
3354 | // Fold (un)ordered comparison if we can determine there are no NaNs. | |||
3355 | if (Pred == FCmpInst::FCMP_UNO || Pred == FCmpInst::FCMP_ORD) | |||
3356 | if (FMF.noNaNs() || | |||
3357 | (isKnownNeverNaN(LHS, Q.TLI) && isKnownNeverNaN(RHS, Q.TLI))) | |||
3358 | return ConstantInt::get(RetTy, Pred == FCmpInst::FCMP_ORD); | |||
3359 | ||||
3360 | // NaN is unordered; NaN is not ordered. | |||
3361 | assert((FCmpInst::isOrdered(Pred) || FCmpInst::isUnordered(Pred)) &&(((FCmpInst::isOrdered(Pred) || FCmpInst::isUnordered(Pred)) && "Comparison must be either ordered or unordered") ? static_cast <void> (0) : __assert_fail ("(FCmpInst::isOrdered(Pred) || FCmpInst::isUnordered(Pred)) && \"Comparison must be either ordered or unordered\"" , "/build/llvm-toolchain-snapshot-9~svn360825/lib/Analysis/InstructionSimplify.cpp" , 3362, __PRETTY_FUNCTION__)) | |||
3362 | "Comparison must be either ordered or unordered")(((FCmpInst::isOrdered(Pred) || FCmpInst::isUnordered(Pred)) && "Comparison must be either ordered or unordered") ? static_cast <void> (0) : __assert_fail ("(FCmpInst::isOrdered(Pred) || FCmpInst::isUnordered(Pred)) && \"Comparison must be either ordered or unordered\"" , "/build/llvm-toolchain-snapshot-9~svn360825/lib/Analysis/InstructionSimplify.cpp" , 3362, __PRETTY_FUNCTION__)); | |||
3363 | if (match(RHS, m_NaN())) | |||
3364 | return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred)); | |||
3365 | ||||
3366 | // fcmp pred x, undef and fcmp pred undef, x | |||
3367 | // fold to true if unordered, false if ordered | |||
3368 | if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS)) { | |||
3369 | // Choosing NaN for the undef will always make unordered comparison succeed | |||
3370 | // and ordered comparison fail. | |||
3371 | return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred)); | |||
3372 | } | |||
3373 | ||||
3374 | // fcmp x,x -> true/false. Not all compares are foldable. | |||
3375 | if (LHS == RHS) { | |||
3376 | if (CmpInst::isTrueWhenEqual(Pred)) | |||
3377 | return getTrue(RetTy); | |||
3378 | if (CmpInst::isFalseWhenEqual(Pred)) | |||
3379 | return getFalse(RetTy); | |||
3380 | } | |||
3381 | ||||
3382 | // Handle fcmp with constant RHS. | |||
3383 | // TODO: Use match with a specific FP value, so these work with vectors with | |||
3384 | // undef lanes. | |||
3385 | const APFloat *C; | |||
3386 | if (match(RHS, m_APFloat(C))) { | |||
3387 | // Check whether the constant is an infinity. | |||
3388 | if (C->isInfinity()) { | |||
3389 | if (C->isNegative()) { | |||
3390 | switch (Pred) { | |||
3391 | case FCmpInst::FCMP_OLT: | |||
3392 | // No value is ordered and less than negative infinity. | |||
3393 | return getFalse(RetTy); | |||
3394 | case FCmpInst::FCMP_UGE: | |||
3395 | // All values are unordered with or at least negative infinity. | |||
3396 | return getTrue(RetTy); | |||
3397 | default: | |||
3398 | break; | |||
3399 | } | |||
3400 | } else { | |||
3401 | switch (Pred) { | |||
3402 | case FCmpInst::FCMP_OGT: | |||
3403 | // No value is ordered and greater than infinity. | |||
3404 | return getFalse(RetTy); | |||
3405 | case FCmpInst::FCMP_ULE: | |||
3406 | // All values are unordered with and at most infinity. | |||
3407 | return getTrue(RetTy); | |||
3408 | default: | |||
3409 | break; | |||
3410 | } | |||
3411 | } | |||
3412 | } | |||
3413 | if (C->isNegative() && !C->isNegZero()) { | |||
3414 | assert(!C->isNaN() && "Unexpected NaN constant!")((!C->isNaN() && "Unexpected NaN constant!") ? static_cast <void> (0) : __assert_fail ("!C->isNaN() && \"Unexpected NaN constant!\"" , "/build/llvm-toolchain-snapshot-9~svn360825/lib/Analysis/InstructionSimplify.cpp" , 3414, __PRETTY_FUNCTION__)); | |||
3415 | // TODO: We can catch more cases by using a range check rather than | |||
3416 | // relying on CannotBeOrderedLessThanZero. | |||
3417 | switch (Pred) { | |||
3418 | case FCmpInst::FCMP_UGE: | |||
3419 | case FCmpInst::FCMP_UGT: | |||
3420 | case FCmpInst::FCMP_UNE: | |||
3421 | // (X >= 0) implies (X > C) when (C < 0) | |||
3422 | if (CannotBeOrderedLessThanZero(LHS, Q.TLI)) | |||
3423 | return getTrue(RetTy); | |||
3424 | break; | |||
3425 | case FCmpInst::FCMP_OEQ: | |||
3426 | case FCmpInst::FCMP_OLE: | |||
3427 | case FCmpInst::FCMP_OLT: | |||
3428 | // (X >= 0) implies !(X < C) when (C < 0) | |||
3429 | if (CannotBeOrderedLessThanZero(LHS, Q.TLI)) | |||
3430 | return getFalse(RetTy); | |||
3431 | break; | |||
3432 | default: | |||
3433 | break; | |||
3434 | } | |||
3435 | } | |||
3436 | } | |||
3437 | if (match(RHS, m_AnyZeroFP())) { | |||
3438 | switch (Pred) { | |||
3439 | case FCmpInst::FCMP_OGE: | |||
3440 | if (FMF.noNaNs() && CannotBeOrderedLessThanZero(LHS, Q.TLI)) | |||
3441 | return getTrue(RetTy); | |||
3442 | break; | |||
3443 | case FCmpInst::FCMP_UGE: | |||
3444 | if (CannotBeOrderedLessThanZero(LHS, Q.TLI)) | |||
3445 | return getTrue(RetTy); | |||
3446 | break; | |||
3447 | case FCmpInst::FCMP_ULT: | |||
3448 | if (FMF.noNaNs() && CannotBeOrderedLessThanZero(LHS, Q.TLI)) | |||
3449 | return getFalse(RetTy); | |||
3450 | break; | |||
3451 | case FCmpInst::FCMP_OLT: | |||
3452 | if (CannotBeOrderedLessThanZero(LHS, Q.TLI)) | |||
3453 | return getFalse(RetTy); | |||
3454 | break; | |||
3455 | default: | |||
3456 | break; | |||
3457 | } | |||
3458 | } | |||
3459 | ||||
3460 | // If the comparison is with the result of a select instruction, check whether | |||
3461 | // comparing with either branch of the select always yields the same value. | |||
3462 | if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)) | |||
3463 | if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse)) | |||
3464 | return V; | |||
3465 | ||||
3466 | // If the comparison is with the result of a phi instruction, check whether | |||
3467 | // doing the compare with each incoming phi value yields a common result. | |||
3468 | if (isa<PHINode>(LHS) || isa<PHINode>(RHS)) | |||
3469 | if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse)) | |||
3470 | return V; | |||
3471 | ||||
3472 | return nullptr; | |||
3473 | } | |||
3474 | ||||
3475 | Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS, | |||
3476 | FastMathFlags FMF, const SimplifyQuery &Q) { | |||
3477 | return ::SimplifyFCmpInst(Predicate, LHS, RHS, FMF, Q, RecursionLimit); | |||
3478 | } | |||
3479 | ||||
3480 | /// See if V simplifies when its operand Op is replaced with RepOp. | |||
3481 | static const Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp, | |||
3482 | const SimplifyQuery &Q, | |||
3483 | unsigned MaxRecurse) { | |||
3484 | // Trivial replacement. | |||
3485 | if (V == Op) | |||
3486 | return RepOp; | |||
3487 | ||||
3488 | // We cannot replace a constant, and shouldn't even try. | |||
3489 | if (isa<Constant>(Op)) | |||
3490 | return nullptr; | |||
3491 | ||||
3492 | auto *I = dyn_cast<Instruction>(V); | |||
3493 | if (!I) | |||
3494 | return nullptr; | |||
3495 | ||||
3496 | // If this is a binary operator, try to simplify it with the replaced op. | |||
3497 | if (auto *B = dyn_cast<BinaryOperator>(I)) { | |||
3498 | // Consider: | |||
3499 | // %cmp = icmp eq i32 %x, 2147483647 | |||
3500 | // %add = add nsw i32 %x, 1 | |||
3501 | // %sel = select i1 %cmp, i32 -2147483648, i32 %add | |||
3502 | // | |||
3503 | // We can't replace %sel with %add unless we strip away the flags. | |||
3504 | if (isa<OverflowingBinaryOperator>(B)) | |||
3505 | if (Q.IIQ.hasNoSignedWrap(B) || Q.IIQ.hasNoUnsignedWrap(B)) | |||
3506 | return nullptr; | |||
3507 | if (isa<PossiblyExactOperator>(B) && Q.IIQ.isExact(B)) | |||
3508 | return nullptr; | |||
3509 | ||||
3510 | if (MaxRecurse) { | |||
3511 | if (B->getOperand(0) == Op) | |||
3512 | return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), Q, | |||
3513 | MaxRecurse - 1); | |||
3514 | if (B->getOperand(1) == Op) | |||
3515 | return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, Q, | |||
3516 | MaxRecurse - 1); | |||
3517 | } | |||
3518 | } | |||
3519 | ||||
3520 | // Same for CmpInsts. | |||
3521 | if (CmpInst *C = dyn_cast<CmpInst>(I)) { | |||
3522 | if (MaxRecurse) { | |||
3523 | if (C->getOperand(0) == Op) | |||
3524 | return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), Q, | |||
3525 | MaxRecurse - 1); | |||
3526 | if (C->getOperand(1) == Op) | |||
3527 | return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, Q, | |||
3528 | MaxRecurse - 1); | |||
3529 | } | |||
3530 | } | |||
3531 | ||||
3532 | // Same for GEPs. | |||
3533 | if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) { | |||
3534 | if (MaxRecurse) { | |||
3535 | SmallVector<Value *, 8> NewOps(GEP->getNumOperands()); | |||
3536 | transform(GEP->operands(), NewOps.begin(), | |||
3537 | [&](Value *V) { return V == Op ? RepOp : V; }); | |||
3538 | return SimplifyGEPInst(GEP->getSourceElementType(), NewOps, Q, | |||
3539 | MaxRecurse - 1); | |||
3540 | } | |||
3541 | } | |||
3542 | ||||
3543 | // TODO: We could hand off more cases to instsimplify here. | |||
3544 | ||||
3545 | // If all operands are constant after substituting Op for RepOp then we can | |||
3546 | // constant fold the instruction. | |||
3547 | if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) { | |||
3548 | // Build a list of all constant operands. | |||
3549 | SmallVector<Constant *, 8> ConstOps; | |||
3550 | for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { | |||
3551 | if (I->getOperand(i) == Op) | |||
3552 | ConstOps.push_back(CRepOp); | |||
3553 | else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i))) | |||
3554 | ConstOps.push_back(COp); | |||
3555 | else | |||
3556 | break; | |||
3557 | } | |||
3558 | ||||
3559 | // All operands were constants, fold it. | |||
3560 | if (ConstOps.size() == I->getNumOperands()) { | |||
3561 | if (CmpInst *C = dyn_cast<CmpInst>(I)) | |||
3562 | return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0], | |||
3563 | ConstOps[1], Q.DL, Q.TLI); | |||
3564 | ||||
3565 | if (LoadInst *LI = dyn_cast<LoadInst>(I)) | |||
3566 | if (!LI->isVolatile()) | |||
3567 | return ConstantFoldLoadFromConstPtr(ConstOps[0], LI->getType(), Q.DL); | |||
3568 | ||||
3569 | return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI); | |||
3570 | } | |||
3571 | } | |||
3572 | ||||
3573 | return nullptr; | |||
3574 | } | |||
3575 | ||||
3576 | /// Try to simplify a select instruction when its condition operand is an | |||
3577 | /// integer comparison where one operand of the compare is a constant. | |||
3578 | static Value *simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X, | |||
3579 | const APInt *Y, bool TrueWhenUnset) { | |||
3580 | const APInt *C; | |||
3581 | ||||
3582 | // (X & Y) == 0 ? X & ~Y : X --> X | |||
3583 | // (X & Y) != 0 ? X & ~Y : X --> X & ~Y | |||
3584 | if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) && | |||
3585 | *Y == ~*C) | |||
3586 | return TrueWhenUnset ? FalseVal : TrueVal; | |||
3587 | ||||
3588 | // (X & Y) == 0 ? X : X & ~Y --> X & ~Y | |||
3589 | // (X & Y) != 0 ? X : X & ~Y --> X | |||
3590 | if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) && | |||
3591 | *Y == ~*C) | |||
3592 | return TrueWhenUnset ? FalseVal : TrueVal; | |||
3593 | ||||
3594 | if (Y->isPowerOf2()) { | |||
3595 | // (X & Y) == 0 ? X | Y : X --> X | Y | |||
3596 | // (X & Y) != 0 ? X | Y : X --> X | |||
3597 | if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) && | |||
3598 | *Y == *C) | |||
3599 | return TrueWhenUnset ? TrueVal : FalseVal; | |||
3600 | ||||
3601 | // (X & Y) == 0 ? X : X | Y --> X | |||
3602 | // (X & Y) != 0 ? X : X | Y --> X | Y | |||
3603 | if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) && | |||
3604 | *Y == *C) | |||
3605 | return TrueWhenUnset ? TrueVal : FalseVal; | |||
3606 | } | |||
3607 | ||||
3608 | return nullptr; | |||
3609 | } | |||
3610 | ||||
3611 | /// An alternative way to test if a bit is set or not uses sgt/slt instead of | |||
3612 | /// eq/ne. | |||
3613 | static Value *simplifySelectWithFakeICmpEq(Value *CmpLHS, Value *CmpRHS, | |||
3614 | ICmpInst::Predicate Pred, | |||
3615 | Value *TrueVal, Value *FalseVal) { | |||
3616 | Value *X; | |||
3617 | APInt Mask; | |||
3618 | if (!decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, X, Mask)) | |||
3619 | return nullptr; | |||
3620 | ||||
3621 | return simplifySelectBitTest(TrueVal, FalseVal, X, &Mask, | |||
3622 | Pred == ICmpInst::ICMP_EQ); | |||
3623 | } | |||
3624 | ||||
3625 | /// Try to simplify a select instruction when its condition operand is an | |||
3626 | /// integer comparison. | |||
3627 | static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal, | |||
3628 | Value *FalseVal, const SimplifyQuery &Q, | |||
3629 | unsigned MaxRecurse) { | |||
3630 | ICmpInst::Predicate Pred; | |||
3631 | Value *CmpLHS, *CmpRHS; | |||
3632 | if (!match(CondVal, m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS)))) | |||
3633 | return nullptr; | |||
3634 | ||||
3635 | if (ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero())) { | |||
3636 | Value *X; | |||
3637 | const APInt *Y; | |||
3638 | if (match(CmpLHS, m_And(m_Value(X), m_APInt(Y)))) | |||
3639 | if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, Y, | |||
3640 | Pred == ICmpInst::ICMP_EQ)) | |||
3641 | return V; | |||
3642 | ||||
3643 | // Test for a bogus zero-shift-guard-op around funnel-shift or rotate. | |||
3644 | Value *ShAmt; | |||
3645 | auto isFsh = m_CombineOr(m_Intrinsic<Intrinsic::fshl>(m_Value(X), m_Value(), | |||
3646 | m_Value(ShAmt)), | |||
3647 | m_Intrinsic<Intrinsic::fshr>(m_Value(), m_Value(X), | |||
3648 | m_Value(ShAmt))); | |||
3649 | // (ShAmt == 0) ? fshl(X, *, ShAmt) : X --> X | |||
3650 | // (ShAmt == 0) ? fshr(*, X, ShAmt) : X --> X | |||
3651 | if (match(TrueVal, isFsh) && FalseVal == X && CmpLHS == ShAmt && | |||
3652 | Pred == ICmpInst::ICMP_EQ) | |||
3653 | return X; | |||
3654 | // (ShAmt != 0) ? X : fshl(X, *, ShAmt) --> X | |||
3655 | // (ShAmt != 0) ? X : fshr(*, X, ShAmt) --> X | |||
3656 | if (match(FalseVal, isFsh) && TrueVal == X && CmpLHS == ShAmt && | |||
3657 | Pred == ICmpInst::ICMP_NE) | |||
3658 | return X; | |||
3659 | ||||
3660 | // Test for a zero-shift-guard-op around rotates. These are used to | |||
3661 | // avoid UB from oversized shifts in raw IR rotate patterns, but the | |||
3662 | // intrinsics do not have that problem. | |||
3663 | // We do not allow this transform for the general funnel shift case because | |||
3664 | // that would not preserve the poison safety of the original code. | |||
3665 | auto isRotate = m_CombineOr(m_Intrinsic<Intrinsic::fshl>(m_Value(X), | |||
3666 | m_Deferred(X), | |||
3667 | m_Value(ShAmt)), | |||
3668 | m_Intrinsic<Intrinsic::fshr>(m_Value(X), | |||
3669 | m_Deferred(X), | |||
3670 | m_Value(ShAmt))); | |||
3671 | // (ShAmt != 0) ? fshl(X, X, ShAmt) : X --> fshl(X, X, ShAmt) | |||
3672 | // (ShAmt != 0) ? fshr(X, X, ShAmt) : X --> fshr(X, X, ShAmt) | |||
3673 | if (match(TrueVal, isRotate) && FalseVal == X && CmpLHS == ShAmt && | |||
3674 | Pred == ICmpInst::ICMP_NE) | |||
3675 | return TrueVal; | |||
3676 | // (ShAmt == 0) ? X : fshl(X, X, ShAmt) --> fshl(X, X, ShAmt) | |||
3677 | // (ShAmt == 0) ? X : fshr(X, X, ShAmt) --> fshr(X, X, ShAmt) | |||
3678 | if (match(FalseVal, isRotate) && TrueVal == X && CmpLHS == ShAmt && | |||
3679 | Pred == ICmpInst::ICMP_EQ) | |||
3680 | return FalseVal; | |||
3681 | } | |||
3682 | ||||
3683 | // Check for other compares that behave like bit test. | |||
3684 | if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, CmpRHS, Pred, | |||
3685 | TrueVal, FalseVal)) | |||
3686 | return V; | |||
3687 | ||||
3688 | // If we have an equality comparison, then we know the value in one of the | |||
3689 | // arms of the select. See if substituting this value into the arm and | |||
3690 | // simplifying the result yields the same value as the other arm. | |||
3691 | if (Pred == ICmpInst::ICMP_EQ) { | |||
3692 | if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) == | |||
3693 | TrueVal || | |||
3694 | SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) == | |||
3695 | TrueVal) | |||
3696 | return FalseVal; | |||
3697 | if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) == | |||
3698 | FalseVal || | |||
3699 | SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) == | |||
3700 | FalseVal) | |||
3701 | return FalseVal; | |||
3702 | } else if (Pred == ICmpInst::ICMP_NE) { | |||
3703 | if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) == | |||
3704 | FalseVal || | |||
3705 | SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) == | |||
3706 | FalseVal) | |||
3707 | return TrueVal; | |||
3708 | if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) == | |||
3709 | TrueVal || | |||
3710 | SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) == | |||
3711 | TrueVal) | |||
3712 | return TrueVal; | |||
3713 | } | |||
3714 | ||||
3715 | return nullptr; | |||
3716 | } | |||
3717 | ||||
3718 | /// Try to simplify a select instruction when its condition operand is a | |||
3719 | /// floating-point comparison. | |||
3720 | static Value *simplifySelectWithFCmp(Value *Cond, Value *T, Value *F) { | |||
3721 | FCmpInst::Predicate Pred; | |||
3722 | if (!match(Cond, m_FCmp(Pred, m_Specific(T), m_Specific(F))) && | |||
3723 | !match(Cond, m_FCmp(Pred, m_Specific(F), m_Specific(T)))) | |||
3724 | return nullptr; | |||
3725 | ||||
3726 | // TODO: The transform may not be valid with -0.0. An incomplete way of | |||
3727 | // testing for that possibility is to check if at least one operand is a | |||
3728 | // non-zero constant. | |||
3729 | const APFloat *C; | |||
3730 | if ((match(T, m_APFloat(C)) && C->isNonZero()) || | |||
3731 | (match(F, m_APFloat(C)) && C->isNonZero())) { | |||
3732 | // (T == F) ? T : F --> F | |||
3733 | // (F == T) ? T : F --> F | |||
3734 | if (Pred == FCmpInst::FCMP_OEQ) | |||
3735 | return F; | |||
3736 | ||||
3737 | // (T != F) ? T : F --> T | |||
3738 | // (F != T) ? T : F --> T | |||
3739 | if (Pred == FCmpInst::FCMP_UNE) | |||
3740 | return T; | |||
3741 | } | |||
3742 | ||||
3743 | return nullptr; | |||
3744 | } | |||
3745 | ||||
3746 | /// Given operands for a SelectInst, see if we can fold the result. | |||
3747 | /// If not, this returns null. | |||
3748 | static Value *SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal, | |||
3749 | const SimplifyQuery &Q, unsigned MaxRecurse) { | |||
3750 | if (auto *CondC = dyn_cast<Constant>(Cond)) { | |||
3751 | if (auto *TrueC = dyn_cast<Constant>(TrueVal)) | |||
3752 | if (auto *FalseC = dyn_cast<Constant>(FalseVal)) | |||
3753 | return ConstantFoldSelectInstruction(CondC, TrueC, FalseC); | |||
3754 | ||||
3755 | // select undef, X, Y -> X or Y | |||
3756 | if (isa<UndefValue>(CondC)) | |||
3757 | return isa<Constant>(FalseVal) ? FalseVal : TrueVal; | |||
3758 | ||||
3759 | // TODO: Vector constants with undef elements don't simplify. | |||
3760 | ||||
3761 | // select true, X, Y -> X | |||
3762 | if (CondC->isAllOnesValue()) | |||
3763 | return TrueVal; | |||
3764 | // select false, X, Y -> Y | |||
3765 | if (CondC->isNullValue()) | |||
3766 | return FalseVal; | |||
3767 | } | |||
3768 | ||||
3769 | // select ?, X, X -> X | |||
3770 | if (TrueVal == FalseVal) | |||
3771 | return TrueVal; | |||
3772 | ||||
3773 | if (isa<UndefValue>(TrueVal)) // select ?, undef, X -> X | |||
3774 | return FalseVal; | |||
3775 | if (isa<UndefValue>(FalseVal)) // select ?, X, undef -> X | |||
3776 | return TrueVal; | |||
3777 | ||||
3778 | if (Value *V = | |||
3779 | simplifySelectWithICmpCond(Cond, TrueVal, FalseVal, Q, MaxRecurse)) | |||
3780 | return V; | |||
3781 | ||||
3782 | if (Value *V = simplifySelectWithFCmp(Cond, TrueVal, FalseVal)) | |||
3783 | return V; | |||
3784 | ||||
3785 | if (Value *V = foldSelectWithBinaryOp(Cond, TrueVal, FalseVal)) | |||
3786 | return V; | |||
3787 | ||||
3788 | Optional<bool> Imp = isImpliedByDomCondition(Cond, Q.CxtI, Q.DL); | |||
3789 | if (Imp) | |||
3790 | return *Imp ? TrueVal : FalseVal; | |||
3791 | ||||
3792 | return nullptr; | |||
3793 | } | |||
3794 | ||||
3795 | Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal, | |||
3796 | const SimplifyQuery &Q) { | |||
3797 | return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Q, RecursionLimit); | |||
3798 | } | |||
3799 | ||||
3800 | /// Given operands for an GetElementPtrInst, see if we can fold the result. | |||
3801 | /// If not, this returns null. | |||
3802 | static Value *SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops, | |||
3803 | const SimplifyQuery &Q, unsigned) { | |||
3804 | // The type of the GEP pointer operand. | |||
3805 | unsigned AS = | |||
3806 | cast<PointerType>(Ops[0]->getType()->getScalarType())->getAddressSpace(); | |||
3807 | ||||
3808 | // getelementptr P -> P. | |||
3809 | if (Ops.size() == 1) | |||
3810 | return Ops[0]; | |||
3811 | ||||
3812 | // Compute the (pointer) type returned by the GEP instruction. | |||
3813 | Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Ops.slice(1)); | |||
3814 | Type *GEPTy = PointerType::get(LastType, AS); | |||
3815 | if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType())) | |||
3816 | GEPTy = VectorType::get(GEPTy, VT->getNumElements()); | |||
3817 | else if (VectorType *VT = dyn_cast<VectorType>(Ops[1]->getType())) | |||
3818 | GEPTy = VectorType::get(GEPTy, VT->getNumElements()); | |||
3819 | ||||
3820 | if (isa<UndefValue>(Ops[0])) | |||
3821 | return UndefValue::get(GEPTy); | |||
3822 | ||||
3823 | if (Ops.size() == 2) { | |||
3824 | // getelementptr P, 0 -> P. | |||
3825 | if (match(Ops[1], m_Zero()) && Ops[0]->getType() == GEPTy) | |||
3826 | return Ops[0]; | |||
3827 | ||||
3828 | Type *Ty = SrcTy; | |||
3829 | if (Ty->isSized()) { | |||
3830 | Value *P; | |||
3831 | uint64_t C; | |||
3832 | uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty); | |||
3833 | // getelementptr P, N -> P if P points to a type of zero size. | |||
3834 | if (TyAllocSize == 0 && Ops[0]->getType() == GEPTy) | |||
3835 | return Ops[0]; | |||
3836 | ||||
3837 | // The following transforms are only safe if the ptrtoint cast | |||
3838 | // doesn't truncate the pointers. | |||
3839 | if (Ops[1]->getType()->getScalarSizeInBits() == | |||
3840 | Q.DL.getIndexSizeInBits(AS)) { | |||
3841 | auto PtrToIntOrZero = [GEPTy](Value *P) -> Value * { | |||
3842 | if (match(P, m_Zero())) | |||
3843 | return Constant::getNullValue(GEPTy); | |||
3844 | Value *Temp; | |||
3845 | if (match(P, m_PtrToInt(m_Value(Temp)))) | |||
3846 | if (Temp->getType() == GEPTy) | |||
3847 | return Temp; | |||
3848 | return nullptr; | |||
3849 | }; | |||
3850 | ||||
3851 | // getelementptr V, (sub P, V) -> P if P points to a type of size 1. | |||
3852 | if (TyAllocSize == 1 && | |||
3853 | match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))))) | |||
3854 | if (Value *R = PtrToIntOrZero(P)) | |||
3855 | return R; | |||
3856 | ||||
3857 | // getelementptr V, (ashr (sub P, V), C) -> Q | |||
3858 | // if P points to a type of size 1 << C. | |||
3859 | if (match(Ops[1], | |||
3860 | m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))), | |||
3861 | m_ConstantInt(C))) && | |||
3862 | TyAllocSize == 1ULL << C) | |||
3863 | if (Value *R = PtrToIntOrZero(P)) | |||
3864 | return R; | |||
3865 | ||||
3866 | // getelementptr V, (sdiv (sub P, V), C) -> Q | |||
3867 | // if P points to a type of size C. | |||
3868 | if (match(Ops[1], | |||
3869 | m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))), | |||
3870 | m_SpecificInt(TyAllocSize)))) | |||
3871 | if (Value *R = PtrToIntOrZero(P)) | |||
3872 | return R; | |||
3873 | } | |||
3874 | } | |||
3875 | } | |||
3876 | ||||
3877 | if (Q.DL.getTypeAllocSize(LastType) == 1 && | |||
3878 | all_of(Ops.slice(1).drop_back(1), | |||
3879 | [](Value *Idx) { return match(Idx, m_Zero()); })) { | |||
3880 | unsigned IdxWidth = | |||
3881 | Q.DL.getIndexSizeInBits(Ops[0]->getType()->getPointerAddressSpace()); | |||
3882 | if (Q.DL.getTypeSizeInBits(Ops.back()->getType()) == IdxWidth) { | |||
3883 | APInt BasePtrOffset(IdxWidth, 0); | |||
3884 | Value *StrippedBasePtr = | |||
3885 | Ops[0]->stripAndAccumulateInBoundsConstantOffsets(Q.DL, | |||
3886 | BasePtrOffset); | |||
3887 | ||||
3888 | // gep (gep V, C), (sub 0, V) -> C | |||
3889 | if (match(Ops.back(), | |||
3890 | m_Sub(m_Zero(), m_PtrToInt(m_Specific(StrippedBasePtr))))) { | |||
3891 | auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset); | |||
3892 | return ConstantExpr::getIntToPtr(CI, GEPTy); | |||
3893 | } | |||
3894 | // gep (gep V, C), (xor V, -1) -> C-1 | |||
3895 | if (match(Ops.back(), | |||
3896 | m_Xor(m_PtrToInt(m_Specific(StrippedBasePtr)), m_AllOnes()))) { | |||
3897 | auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset - 1); | |||
3898 | return ConstantExpr::getIntToPtr(CI, GEPTy); | |||
3899 | } | |||
3900 | } | |||
3901 | } | |||
3902 | ||||
3903 | // Check to see if this is constant foldable. | |||
3904 | if (!all_of(Ops, [](Value *V) { return isa<Constant>(V); })) | |||
3905 | return nullptr; | |||
3906 | ||||
3907 | auto *CE = ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ops[0]), | |||
3908 | Ops.slice(1)); | |||
3909 | if (auto *CEFolded = ConstantFoldConstant(CE, Q.DL)) | |||
3910 | return CEFolded; | |||
3911 | return CE; | |||
3912 | } | |||
3913 | ||||
3914 | Value *llvm::SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops, | |||
3915 | const SimplifyQuery &Q) { | |||
3916 | return ::SimplifyGEPInst(SrcTy, Ops, Q, RecursionLimit); | |||
3917 | } | |||
3918 | ||||
3919 | /// Given operands for an InsertValueInst, see if we can fold the result. | |||
3920 | /// If not, this returns null. | |||
3921 | static Value *SimplifyInsertValueInst(Value *Agg, Value *Val, | |||
3922 | ArrayRef<unsigned> Idxs, const SimplifyQuery &Q, | |||
3923 | unsigned) { | |||
3924 | if (Constant *CAgg = dyn_cast<Constant>(Agg)) | |||
3925 | if (Constant *CVal = dyn_cast<Constant>(Val)) | |||
3926 | return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs); | |||
3927 | ||||
3928 | // insertvalue x, undef, n -> x | |||
3929 | if (match(Val, m_Undef())) | |||
3930 | return Agg; | |||
3931 | ||||
3932 | // insertvalue x, (extractvalue y, n), n | |||
3933 | if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val)) | |||
3934 | if (EV->getAggregateOperand()->getType() == Agg->getType() && | |||
3935 | EV->getIndices() == Idxs) { | |||
3936 | // insertvalue undef, (extractvalue y, n), n -> y | |||
3937 | if (match(Agg, m_Undef())) | |||
3938 | return EV->getAggregateOperand(); | |||
3939 | ||||
3940 | // insertvalue y, (extractvalue y, n), n -> y | |||
3941 | if (Agg == EV->getAggregateOperand()) | |||
3942 | return Agg; | |||
3943 | } | |||
3944 | ||||
3945 | return nullptr; | |||
3946 | } | |||
3947 | ||||
3948 | Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val, | |||
3949 | ArrayRef<unsigned> Idxs, | |||
3950 | const SimplifyQuery &Q) { | |||
3951 | return ::SimplifyInsertValueInst(Agg, Val, Idxs, Q, RecursionLimit); | |||
3952 | } | |||
3953 | ||||
3954 | Value *llvm::SimplifyInsertElementInst(Value *Vec, Value *Val, Value *Idx, | |||
3955 | const SimplifyQuery &Q) { | |||
3956 | // Try to constant fold. | |||
3957 | auto *VecC = dyn_cast<Constant>(Vec); | |||
3958 | auto *ValC = dyn_cast<Constant>(Val); | |||
3959 | auto *IdxC = dyn_cast<Constant>(Idx); | |||
3960 | if (VecC && ValC && IdxC) | |||
3961 | return ConstantFoldInsertElementInstruction(VecC, ValC, IdxC); | |||
3962 | ||||
3963 | // Fold into undef if index is out of bounds. | |||
3964 | if (auto *CI = dyn_cast<ConstantInt>(Idx)) { | |||
3965 | uint64_t NumElements = cast<VectorType>(Vec->getType())->getNumElements(); | |||
3966 | if (CI->uge(NumElements)) | |||
3967 | return UndefValue::get(Vec->getType()); | |||
3968 | } | |||
3969 | ||||
3970 | // If index is undef, it might be out of bounds (see above case) | |||
3971 | if (isa<UndefValue>(Idx)) | |||
3972 | return UndefValue::get(Vec->getType()); | |||
3973 | ||||
3974 | return nullptr; | |||
3975 | } | |||
3976 | ||||
3977 | /// Given operands for an ExtractValueInst, see if we can fold the result. | |||
3978 | /// If not, this returns null. | |||
3979 | static Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs, | |||
3980 | const SimplifyQuery &, unsigned) { | |||
3981 | if (auto *CAgg = dyn_cast<Constant>(Agg)) | |||
3982 | return ConstantFoldExtractValueInstruction(CAgg, Idxs); | |||
3983 | ||||
3984 | // extractvalue x, (insertvalue y, elt, n), n -> elt | |||
3985 | unsigned NumIdxs = Idxs.size(); | |||
3986 | for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr; | |||
3987 | IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) { | |||
3988 | ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices(); | |||
3989 | unsigned NumInsertValueIdxs = InsertValueIdxs.size(); | |||
3990 | unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs); | |||
3991 | if (InsertValueIdxs.slice(0, NumCommonIdxs) == | |||
3992 | Idxs.slice(0, NumCommonIdxs)) { | |||
3993 | if (NumIdxs == NumInsertValueIdxs) | |||
3994 | return IVI->getInsertedValueOperand(); | |||
3995 | break; | |||
3996 | } | |||
3997 | } | |||
3998 | ||||
3999 | return nullptr; | |||
4000 | } | |||
4001 | ||||
4002 | Value *llvm::SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs, | |||
4003 | const SimplifyQuery &Q) { | |||
4004 | return ::SimplifyExtractValueInst(Agg, Idxs, Q, RecursionLimit); | |||
4005 | } | |||
4006 | ||||
4007 | /// Given operands for an ExtractElementInst, see if we can fold the result. | |||
4008 | /// If not, this returns null. | |||
4009 | static Value *SimplifyExtractElementInst(Value *Vec, Value *Idx, const SimplifyQuery &, | |||
4010 | unsigned) { | |||
4011 | if (auto *CVec = dyn_cast<Constant>(Vec)) { | |||
4012 | if (auto *CIdx = dyn_cast<Constant>(Idx)) | |||
4013 | return ConstantFoldExtractElementInstruction(CVec, CIdx); | |||
4014 | ||||
4015 | // The index is not relevant if our vector is a splat. | |||
4016 | if (auto *Splat = CVec->getSplatValue()) | |||
4017 | return Splat; | |||
4018 | ||||
4019 | if (isa<UndefValue>(Vec)) | |||
4020 | return UndefValue::get(Vec->getType()->getVectorElementType()); | |||
4021 | } | |||
4022 | ||||
4023 | // If extracting a specified index from the vector, see if we can recursively | |||
4024 | // find a previously computed scalar that was inserted into the vector. | |||
4025 | if (auto *IdxC = dyn_cast<ConstantInt>(Idx)) { | |||
4026 | if (IdxC->getValue().uge(Vec->getType()->getVectorNumElements())) | |||
4027 | // definitely out of bounds, thus undefined result | |||
4028 | return UndefValue::get(Vec->getType()->getVectorElementType()); | |||
4029 | if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue())) | |||
4030 | return Elt; | |||
4031 | } | |||
4032 | ||||
4033 | // An undef extract index can be arbitrarily chosen to be an out-of-range | |||
4034 | // index value, which would result in the instruction being undef. | |||
4035 | if (isa<UndefValue>(Idx)) | |||
4036 | return UndefValue::get(Vec->getType()->getVectorElementType()); | |||
4037 | ||||
4038 | return nullptr; | |||
4039 | } | |||
4040 | ||||
4041 | Value *llvm::SimplifyExtractElementInst(Value *Vec, Value *Idx, | |||
4042 | const SimplifyQuery &Q) { | |||
4043 | return ::SimplifyExtractElementInst(Vec, Idx, Q, RecursionLimit); | |||
4044 | } | |||
4045 | ||||
4046 | /// See if we can fold the given phi. If not, returns null. | |||
4047 | static Value *SimplifyPHINode(PHINode *PN, const SimplifyQuery &Q) { | |||
4048 | // If all of the PHI's incoming values are the same then replace the PHI node | |||
4049 | // with the common value. | |||
4050 | Value *CommonValue = nullptr; | |||
4051 | bool HasUndefInput = false; | |||
4052 | for (Value *Incoming : PN->incoming_values()) { | |||
4053 | // If the incoming value is the phi node itself, it can safely be skipped. | |||
4054 | if (Incoming == PN) continue; | |||
4055 | if (isa<UndefValue>(Incoming)) { | |||
4056 | // Remember that we saw an undef value, but otherwise ignore them. | |||
4057 | HasUndefInput = true; | |||
4058 | continue; | |||
4059 | } | |||
4060 | if (CommonValue && Incoming != CommonValue) | |||
4061 | return nullptr; // Not the same, bail out. | |||
4062 | CommonValue = Incoming; | |||
4063 | } | |||
4064 | ||||
4065 | // If CommonValue is null then all of the incoming values were either undef or | |||
4066 | // equal to the phi node itself. | |||
4067 | if (!CommonValue) | |||
4068 | return UndefValue::get(PN->getType()); | |||
4069 | ||||
4070 | // If we have a PHI node like phi(X, undef, X), where X is defined by some | |||
4071 | // instruction, we cannot return X as the result of the PHI node unless it | |||
4072 | // dominates the PHI block. | |||
4073 | if (HasUndefInput) | |||
4074 | return valueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr; | |||
4075 | ||||
4076 | return CommonValue; | |||
4077 | } | |||
4078 | ||||
4079 | static Value *SimplifyCastInst(unsigned CastOpc, Value *Op, | |||
4080 | Type *Ty, const SimplifyQuery &Q, unsigned MaxRecurse) { | |||
4081 | if (auto *C = dyn_cast<Constant>(Op)) | |||
4082 | return ConstantFoldCastOperand(CastOpc, C, Ty, Q.DL); | |||
4083 | ||||
4084 | if (auto *CI = dyn_cast<CastInst>(Op)) { | |||
4085 | auto *Src = CI->getOperand(0); | |||
4086 | Type *SrcTy = Src->getType(); | |||
4087 | Type *MidTy = CI->getType(); | |||
4088 | Type *DstTy = Ty; | |||
4089 | if (Src->getType() == Ty) { | |||
4090 | auto FirstOp = static_cast<Instruction::CastOps>(CI->getOpcode()); | |||
4091 | auto SecondOp = static_cast<Instruction::CastOps>(CastOpc); | |||
4092 | Type *SrcIntPtrTy = | |||
4093 | SrcTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(SrcTy) : nullptr; | |||
4094 | Type *MidIntPtrTy = | |||
4095 | MidTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(MidTy) : nullptr; | |||
4096 | Type *DstIntPtrTy = | |||
4097 | DstTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(DstTy) : nullptr; | |||
4098 | if (CastInst::isEliminableCastPair(FirstOp, SecondOp, SrcTy, MidTy, DstTy, | |||
4099 | SrcIntPtrTy, MidIntPtrTy, | |||
4100 | DstIntPtrTy) == Instruction::BitCast) | |||
4101 | return Src; | |||
4102 | } | |||
4103 | } | |||
4104 | ||||
4105 | // bitcast x -> x | |||
4106 | if (CastOpc == Instruction::BitCast) | |||
4107 | if (Op->getType() == Ty) | |||
4108 | return Op; | |||
4109 | ||||
4110 | return nullptr; | |||
4111 | } | |||
4112 | ||||
4113 | Value *llvm::SimplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty, | |||
4114 | const SimplifyQuery &Q) { | |||
4115 | return ::SimplifyCastInst(CastOpc, Op, Ty, Q, RecursionLimit); | |||
4116 | } | |||
4117 | ||||
4118 | /// For the given destination element of a shuffle, peek through shuffles to | |||
4119 | /// match a root vector source operand that contains that element in the same | |||
4120 | /// vector lane (ie, the same mask index), so we can eliminate the shuffle(s). | |||
4121 | static Value *foldIdentityShuffles(int DestElt, Value *Op0, Value *Op1, | |||
4122 | int MaskVal, Value *RootVec, | |||
4123 | unsigned MaxRecurse) { | |||
4124 | if (!MaxRecurse--) | |||
4125 | return nullptr; | |||
4126 | ||||
4127 | // Bail out if any mask value is undefined. That kind of shuffle may be | |||
4128 | // simplified further based on demanded bits or other folds. | |||
4129 | if (MaskVal == -1) | |||
4130 | return nullptr; | |||
4131 | ||||
4132 | // The mask value chooses which source operand we need to look at next. | |||
4133 | int InVecNumElts = Op0->getType()->getVectorNumElements(); | |||
4134 | int RootElt = MaskVal; | |||
4135 | Value *SourceOp = Op0; | |||
4136 | if (MaskVal >= InVecNumElts) { | |||
4137 | RootElt = MaskVal - InVecNumElts; | |||
4138 | SourceOp = Op1; | |||
4139 | } | |||
4140 | ||||
4141 | // If the source operand is a shuffle itself, look through it to find the | |||
4142 | // matching root vector. | |||
4143 | if (auto *SourceShuf = dyn_cast<ShuffleVectorInst>(SourceOp)) { | |||
4144 | return foldIdentityShuffles( | |||
4145 | DestElt, SourceShuf->getOperand(0), SourceShuf->getOperand(1), | |||
4146 | SourceShuf->getMaskValue(RootElt), RootVec, MaxRecurse); | |||
4147 | } | |||
4148 | ||||
4149 | // TODO: Look through bitcasts? What if the bitcast changes the vector element | |||
4150 | // size? | |||
4151 | ||||
4152 | // The source operand is not a shuffle. Initialize the root vector value for | |||
4153 | // this shuffle if that has not been done yet. | |||
4154 | if (!RootVec) | |||
4155 | RootVec = SourceOp; | |||
4156 | ||||
4157 | // Give up as soon as a source operand does not match the existing root value. | |||
4158 | if (RootVec != SourceOp) | |||
4159 | return nullptr; | |||
4160 | ||||
4161 | // The element must be coming from the same lane in the source vector | |||
4162 | // (although it may have crossed lanes in intermediate shuffles). | |||
4163 | if (RootElt != DestElt) | |||
4164 | return nullptr; | |||
4165 | ||||
4166 | return RootVec; | |||
4167 | } | |||
4168 | ||||
4169 | static Value *SimplifyShuffleVectorInst(Value *Op0, Value *Op1, Constant *Mask, | |||
4170 | Type *RetTy, const SimplifyQuery &Q, | |||
4171 | unsigned MaxRecurse) { | |||
4172 | if (isa<UndefValue>(Mask)) | |||
4173 | return UndefValue::get(RetTy); | |||
4174 | ||||
4175 | Type *InVecTy = Op0->getType(); | |||
4176 | unsigned MaskNumElts = Mask->getType()->getVectorNumElements(); | |||
4177 | unsigned InVecNumElts = InVecTy->getVectorNumElements(); | |||
4178 | ||||
4179 | SmallVector<int, 32> Indices; | |||
4180 | ShuffleVectorInst::getShuffleMask(Mask, Indices); | |||
4181 | assert(MaskNumElts == Indices.size() &&((MaskNumElts == Indices.size() && "Size of Indices not same as number of mask elements?" ) ? static_cast<void> (0) : __assert_fail ("MaskNumElts == Indices.size() && \"Size of Indices not same as number of mask elements?\"" , "/build/llvm-toolchain-snapshot-9~svn360825/lib/Analysis/InstructionSimplify.cpp" , 4182, __PRETTY_FUNCTION__)) | |||
4182 | "Size of Indices not same as number of mask elements?")((MaskNumElts == Indices.size() && "Size of Indices not same as number of mask elements?" ) ? static_cast<void> (0) : __assert_fail ("MaskNumElts == Indices.size() && \"Size of Indices not same as number of mask elements?\"" , "/build/llvm-toolchain-snapshot-9~svn360825/lib/Analysis/InstructionSimplify.cpp" , 4182, __PRETTY_FUNCTION__)); | |||
4183 | ||||
4184 | // Canonicalization: If mask does not select elements from an input vector, | |||
4185 | // replace that input vector with undef. | |||
4186 | bool MaskSelects0 = false, MaskSelects1 = false; | |||
4187 | for (unsigned i = 0; i != MaskNumElts; ++i) { | |||
4188 | if (Indices[i] == -1) | |||
4189 | continue; | |||
4190 | if ((unsigned)Indices[i] < InVecNumElts) | |||
4191 | MaskSelects0 = true; | |||
4192 | else | |||
4193 | MaskSelects1 = true; | |||
4194 | } | |||
4195 | if (!MaskSelects0) | |||
4196 | Op0 = UndefValue::get(InVecTy); | |||
4197 | if (!MaskSelects1) | |||
4198 | Op1 = UndefValue::get(InVecTy); | |||
4199 | ||||
4200 | auto *Op0Const = dyn_cast<Constant>(Op0); | |||
4201 | auto *Op1Const = dyn_cast<Constant>(Op1); | |||
4202 | ||||
4203 | // If all operands are constant, constant fold the shuffle. | |||
4204 | if (Op0Const && Op1Const) | |||
4205 | return ConstantFoldShuffleVectorInstruction(Op0Const, Op1Const, Mask); | |||
4206 | ||||
4207 | // Canonicalization: if only one input vector is constant, it shall be the | |||
4208 | // second one. | |||
4209 | if (Op0Const && !Op1Const) { | |||
4210 | std::swap(Op0, Op1); | |||
4211 | ShuffleVectorInst::commuteShuffleMask(Indices, InVecNumElts); | |||
4212 | } | |||
4213 | ||||
4214 | // A shuffle of a splat is always the splat itself. Legal if the shuffle's | |||
4215 | // value type is same as the input vectors' type. | |||
4216 | if (auto *OpShuf = dyn_cast<ShuffleVectorInst>(Op0)) | |||
4217 | if (isa<UndefValue>(Op1) && RetTy == InVecTy && | |||
4218 | OpShuf->getMask()->getSplatValue()) | |||
4219 | return Op0; | |||
4220 | ||||
4221 | // Don't fold a shuffle with undef mask elements. This may get folded in a | |||
4222 | // better way using demanded bits or other analysis. | |||
4223 | // TODO: Should we allow this? | |||
4224 | if (find(Indices, -1) != Indices.end()) | |||
4225 | return nullptr; | |||
4226 | ||||
4227 | // Check if every element of this shuffle can be mapped back to the | |||
4228 | // corresponding element of a single root vector. If so, we don't need this | |||
4229 | // shuffle. This handles simple identity shuffles as well as chains of | |||
4230 | // shuffles that may widen/narrow and/or move elements across lanes and back. | |||
4231 | Value *RootVec = nullptr; | |||
4232 | for (unsigned i = 0; i != MaskNumElts; ++i) { | |||
4233 | // Note that recursion is limited for each vector element, so if any element | |||
4234 | // exceeds the limit, this will fail to simplify. | |||
4235 | RootVec = | |||
4236 | foldIdentityShuffles(i, Op0, Op1, Indices[i], RootVec, MaxRecurse); | |||
4237 | ||||
4238 | // We can't replace a widening/narrowing shuffle with one of its operands. | |||
4239 | if (!RootVec || RootVec->getType() != RetTy) | |||
4240 | return nullptr; | |||
4241 | } | |||
4242 | return RootVec; | |||
4243 | } | |||
4244 | ||||
4245 | /// Given operands for a ShuffleVectorInst, fold the result or return null. | |||
4246 | Value *llvm::SimplifyShuffleVectorInst(Value *Op0, Value *Op1, Constant *Mask, | |||
4247 | Type *RetTy, const SimplifyQuery &Q) { | |||
4248 | return ::SimplifyShuffleVectorInst(Op0, Op1, Mask, RetTy, Q, RecursionLimit); | |||
4249 | } | |||
4250 | ||||
4251 | static Constant *foldConstant(Instruction::UnaryOps Opcode, | |||
4252 | Value *&Op, const SimplifyQuery &Q) { | |||
4253 | if (auto *C = dyn_cast<Constant>(Op)) | |||
4254 | return ConstantFoldUnaryOpOperand(Opcode, C, Q.DL); | |||
4255 | return nullptr; | |||
4256 | } | |||
4257 | ||||
4258 | /// Given the operand for an FNeg, see if we can fold the result. If not, this | |||
4259 | /// returns null. | |||
4260 | static Value *simplifyFNegInst(Value *Op, FastMathFlags FMF, | |||
4261 | const SimplifyQuery &Q, unsigned MaxRecurse) { | |||
4262 | if (Constant *C = foldConstant(Instruction::FNeg, Op, Q)) | |||
4263 | return C; | |||
4264 | ||||
4265 | Value *X; | |||
4266 | // fneg (fneg X) ==> X | |||
4267 | if (match(Op, m_FNeg(m_Value(X)))) | |||
4268 | return X; | |||
4269 | ||||
4270 | return nullptr; | |||
4271 | } | |||
4272 | ||||
4273 | Value *llvm::SimplifyFNegInst(Value *Op, FastMathFlags FMF, | |||
4274 | const SimplifyQuery &Q) { | |||
4275 | return ::simplifyFNegInst(Op, FMF, Q, RecursionLimit); | |||
4276 | } | |||
4277 | ||||
4278 | static Constant *propagateNaN(Constant *In) { | |||
4279 | // If the input is a vector with undef elements, just return a default NaN. | |||
4280 | if (!In->isNaN()) | |||
4281 | return ConstantFP::getNaN(In->getType()); | |||
4282 | ||||
4283 | // Propagate the existing NaN constant when possible. | |||
4284 | // TODO: Should we quiet a signaling NaN? | |||
4285 | return In; | |||
4286 | } | |||
4287 | ||||
4288 | static Constant *simplifyFPBinop(Value *Op0, Value *Op1) { | |||
4289 | if (isa<UndefValue>(Op0) || isa<UndefValue>(Op1)) | |||
4290 | return ConstantFP::getNaN(Op0->getType()); | |||
4291 | ||||
4292 | if (match(Op0, m_NaN())) | |||
4293 | return propagateNaN(cast<Constant>(Op0)); | |||
4294 | if (match(Op1, m_NaN())) | |||
4295 | return propagateNaN(cast<Constant>(Op1)); | |||
4296 | ||||
4297 | return nullptr; | |||
4298 | } | |||
4299 | ||||
4300 | /// Given operands for an FAdd, see if we can fold the result. If not, this | |||
4301 | /// returns null. | |||
4302 | static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF, | |||
4303 | const SimplifyQuery &Q, unsigned MaxRecurse) { | |||
4304 | if (Constant *C = foldOrCommuteConstant(Instruction::FAdd, Op0, Op1, Q)) | |||
4305 | return C; | |||
4306 | ||||
4307 | if (Constant *C = simplifyFPBinop(Op0, Op1)) | |||
4308 | return C; | |||
4309 | ||||
4310 | // fadd X, -0 ==> X | |||
4311 | if (match(Op1, m_NegZeroFP())) | |||
4312 | return Op0; | |||
4313 | ||||
4314 | // fadd X, 0 ==> X, when we know X is not -0 | |||
4315 | if (match(Op1, m_PosZeroFP()) && | |||
4316 | (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI))) | |||
4317 | return Op0; | |||
4318 | ||||
4319 | // With nnan: -X + X --> 0.0 (and commuted variant) | |||
4320 | // We don't have to explicitly exclude infinities (ninf): INF + -INF == NaN. | |||
4321 | // Negative zeros are allowed because we always end up with positive zero: | |||
4322 | // X = -0.0: (-0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0 | |||
4323 | // X = -0.0: ( 0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0 | |||
4324 | // X = 0.0: (-0.0 - ( 0.0)) + ( 0.0) == (-0.0) + ( 0.0) == 0.0 | |||
4325 | // X = 0.0: ( 0.0 - ( 0.0)) + ( 0.0) == ( 0.0) + ( 0.0) == 0.0 | |||
4326 | if (FMF.noNaNs()) { | |||
4327 | if (match(Op0, m_FSub(m_AnyZeroFP(), m_Specific(Op1))) || | |||
4328 | match(Op1, m_FSub(m_AnyZeroFP(), m_Specific(Op0)))) | |||
4329 | return ConstantFP::getNullValue(Op0->getType()); | |||
4330 | ||||
4331 | if (match(Op0, m_FNeg(m_Specific(Op1))) || | |||
4332 | match(Op1, m_FNeg(m_Specific(Op0)))) | |||
4333 | return ConstantFP::getNullValue(Op0->getType()); | |||
4334 | } | |||
4335 | ||||
4336 | // (X - Y) + Y --> X | |||
4337 | // Y + (X - Y) --> X | |||
4338 | Value *X; | |||
4339 | if (FMF.noSignedZeros() && FMF.allowReassoc() && | |||
4340 | (match(Op0, m_FSub(m_Value(X), m_Specific(Op1))) || | |||
4341 | match(Op1, m_FSub(m_Value(X), m_Specific(Op0))))) | |||
4342 | return X; | |||
4343 | ||||
4344 | return nullptr; | |||
4345 | } | |||
4346 | ||||
4347 | /// Given operands for an FSub, see if we can fold the result. If not, this | |||
4348 | /// returns null. | |||
4349 | static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF, | |||
4350 | const SimplifyQuery &Q, unsigned MaxRecurse) { | |||
4351 | if (Constant *C = foldOrCommuteConstant(Instruction::FSub, Op0, Op1, Q)) | |||
4352 | return C; | |||
4353 | ||||
4354 | if (Constant *C = simplifyFPBinop(Op0, Op1)) | |||
4355 | return C; | |||
4356 | ||||
4357 | // fsub X, +0 ==> X | |||
4358 | if (match(Op1, m_PosZeroFP())) | |||
4359 | return Op0; | |||
4360 | ||||
4361 | // fsub X, -0 ==> X, when we know X is not -0 | |||
4362 | if (match(Op1, m_NegZeroFP()) && | |||
4363 | (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI))) | |||
4364 | return Op0; | |||
4365 | ||||
4366 | // fsub -0.0, (fsub -0.0, X) ==> X | |||
4367 | Value *X; | |||
4368 | if (match(Op0, m_NegZeroFP()) && | |||
4369 | match(Op1, m_FSub(m_NegZeroFP(), m_Value(X)))) | |||
4370 | return X; | |||
4371 | ||||
4372 | // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored. | |||
4373 | if (FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()) && | |||
4374 | match(Op1, m_FSub(m_AnyZeroFP(), m_Value(X)))) | |||
4375 | return X; | |||
4376 | ||||
4377 | // fsub nnan x, x ==> 0.0 | |||
4378 | if (FMF.noNaNs() && Op0 == Op1) | |||
4379 | return Constant::getNullValue(Op0->getType()); | |||
4380 | ||||
4381 | // Y - (Y - X) --> X | |||
4382 | // (X + Y) - Y --> X | |||
4383 | if (FMF.noSignedZeros() && FMF.allowReassoc() && | |||
4384 | (match(Op1, m_FSub(m_Specific(Op0), m_Value(X))) || | |||
4385 | match(Op0, m_c_FAdd(m_Specific(Op1), m_Value(X))))) | |||
4386 | return X; | |||
4387 | ||||
4388 | return nullptr; | |||
4389 | } | |||
4390 | ||||
4391 | /// Given the operands for an FMul, see if we can fold the result | |||
4392 | static Value *SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF, | |||
4393 | const SimplifyQuery &Q, unsigned MaxRecurse) { | |||
4394 | if (Constant *C = foldOrCommuteConstant(Instruction::FMul, Op0, Op1, Q)) | |||
4395 | return C; | |||
4396 | ||||
4397 | if (Constant *C = simplifyFPBinop(Op0, Op1)) | |||
4398 | return C; | |||
4399 | ||||
4400 | // fmul X, 1.0 ==> X | |||
4401 | if (match(Op1, m_FPOne())) | |||
4402 | return Op0; | |||
4403 | ||||
4404 | // fmul nnan nsz X, 0 ==> 0 | |||
4405 | if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZeroFP())) | |||
4406 | return ConstantFP::getNullValue(Op0->getType()); | |||
4407 | ||||
4408 | // sqrt(X) * sqrt(X) --> X, if we can: | |||
4409 | // 1. Remove the intermediate rounding (reassociate). | |||
4410 | // 2. Ignore non-zero negative numbers because sqrt would produce NAN. | |||
4411 | // 3. Ignore -0.0 because sqrt(-0.0) == -0.0, but -0.0 * -0.0 == 0.0. | |||
4412 | Value *X; | |||
4413 | if (Op0 == Op1 && match(Op0, m_Intrinsic<Intrinsic::sqrt>(m_Value(X))) && | |||
4414 | FMF.allowReassoc() && FMF.noNaNs() && FMF.noSignedZeros()) | |||
4415 | return X; | |||
4416 | ||||
4417 | return nullptr; | |||
4418 | } | |||
4419 | ||||
4420 | Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF, | |||
4421 | const SimplifyQuery &Q) { | |||
4422 | return ::SimplifyFAddInst(Op0, Op1, FMF, Q, RecursionLimit); | |||
4423 | } | |||
4424 | ||||
4425 | ||||
4426 | Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF, | |||
4427 | const SimplifyQuery &Q) { | |||
4428 | return ::SimplifyFSubInst(Op0, Op1, FMF, Q, RecursionLimit); | |||
4429 | } | |||
4430 | ||||
4431 | Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF, | |||
4432 | const SimplifyQuery &Q) { | |||
4433 | return ::SimplifyFMulInst(Op0, Op1, FMF, Q, RecursionLimit); | |||
4434 | } | |||
4435 | ||||
4436 | static Value *SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF, | |||
4437 | const SimplifyQuery &Q, unsigned) { | |||
4438 | if (Constant *C = foldOrCommuteConstant(Instruction::FDiv, Op0, Op1, Q)) | |||
4439 | return C; | |||
4440 | ||||
4441 | if (Constant *C = simplifyFPBinop(Op0, Op1)) | |||
4442 | return C; | |||
4443 | ||||
4444 | // X / 1.0 -> X | |||
4445 | if (match(Op1, m_FPOne())) | |||
4446 | return Op0; | |||
4447 | ||||
4448 | // 0 / X -> 0 | |||
4449 | // Requires that NaNs are off (X could be zero) and signed zeroes are | |||
4450 | // ignored (X could be positive or negative, so the output sign is unknown). | |||
4451 | if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZeroFP())) | |||
4452 | return ConstantFP::getNullValue(Op0->getType()); | |||
4453 | ||||
4454 | if (FMF.noNaNs()) { | |||
4455 | // X / X -> 1.0 is legal when NaNs are ignored. | |||
4456 | // We can ignore infinities because INF/INF is NaN. | |||
4457 | if (Op0 == Op1) | |||
4458 | return ConstantFP::get(Op0->getType(), 1.0); | |||
4459 | ||||
4460 | // (X * Y) / Y --> X if we can reassociate to the above form. | |||
4461 | Value *X; | |||
4462 | if (FMF.allowReassoc() && match(Op0, m_c_FMul(m_Value(X), m_Specific(Op1)))) | |||
4463 | return X; | |||
4464 | ||||
4465 | // -X / X -> -1.0 and | |||
4466 | // X / -X -> -1.0 are legal when NaNs are ignored. | |||
4467 | // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored. | |||
4468 | if (match(Op0, m_FNegNSZ(m_Specific(Op1))) || | |||
4469 | match(Op1, m_FNegNSZ(m_Specific(Op0)))) | |||
4470 | return ConstantFP::get(Op0->getType(), -1.0); | |||
4471 | } | |||
4472 | ||||
4473 | return nullptr; | |||
4474 | } | |||
4475 | ||||
4476 | Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF, | |||
4477 | const SimplifyQuery &Q) { | |||
4478 | return ::SimplifyFDivInst(Op0, Op1, FMF, Q, RecursionLimit); | |||
4479 | } | |||
4480 | ||||
4481 | static Value *SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF, | |||
4482 | const SimplifyQuery &Q, unsigned) { | |||
4483 | if (Constant *C = foldOrCommuteConstant(Instruction::FRem, Op0, Op1, Q)) | |||
4484 | return C; | |||
4485 | ||||
4486 | if (Constant *C = simplifyFPBinop(Op0, Op1)) | |||
4487 | return C; | |||
4488 | ||||
4489 | // Unlike fdiv, the result of frem always matches the sign of the dividend. | |||
4490 | // The constant match may include undef elements in a vector, so return a full | |||
4491 | // zero constant as the result. | |||
4492 | if (FMF.noNaNs()) { | |||
4493 | // +0 % X -> 0 | |||
4494 | if (match(Op0, m_PosZeroFP())) | |||
4495 | return ConstantFP::getNullValue(Op0->getType()); | |||
4496 | // -0 % X -> -0 | |||
4497 | if (match(Op0, m_NegZeroFP())) | |||
4498 | return ConstantFP::getNegativeZero(Op0->getType()); | |||
4499 | } | |||
4500 | ||||
4501 | return nullptr; | |||
4502 | } | |||
4503 | ||||
4504 | Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF, | |||
4505 | const SimplifyQuery &Q) { | |||
4506 | return ::SimplifyFRemInst(Op0, Op1, FMF, Q, RecursionLimit); | |||
4507 | } | |||
4508 | ||||
4509 | //=== Helper functions for higher up the class hierarchy. | |||
4510 | ||||
4511 | /// Given the operand for a UnaryOperator, see if we can fold the result. | |||
4512 | /// If not, this returns null. | |||
4513 | static Value *simplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q, | |||
4514 | unsigned MaxRecurse) { | |||
4515 | switch (Opcode) { | |||
4516 | case Instruction::FNeg: | |||
4517 | return simplifyFNegInst(Op, FastMathFlags(), Q, MaxRecurse); | |||
4518 | default: | |||
4519 | llvm_unreachable("Unexpected opcode")::llvm::llvm_unreachable_internal("Unexpected opcode", "/build/llvm-toolchain-snapshot-9~svn360825/lib/Analysis/InstructionSimplify.cpp" , 4519); | |||
4520 | } | |||
4521 | } | |||
4522 | ||||
4523 | /// Given the operand for a UnaryOperator, see if we can fold the result. | |||
4524 | /// If not, this returns null. | |||
4525 | /// In contrast to SimplifyUnOp, try to use FastMathFlag when folding the | |||
4526 | /// result. In case we don't need FastMathFlags, simply fall to SimplifyUnOp. | |||
4527 | static Value *simplifyFPUnOp(unsigned Opcode, Value *Op, | |||
4528 | const FastMathFlags &FMF, | |||
4529 | const SimplifyQuery &Q, unsigned MaxRecurse) { | |||
4530 | switch (Opcode) { | |||
4531 | case Instruction::FNeg: | |||
4532 | return simplifyFNegInst(Op, FMF, Q, MaxRecurse); | |||
4533 | default: | |||
4534 | return simplifyUnOp(Opcode, Op, Q, MaxRecurse); | |||
4535 | } | |||
4536 | } | |||
4537 | ||||
4538 | Value *llvm::SimplifyFPUnOp(unsigned Opcode, Value *Op, FastMathFlags FMF, | |||
4539 | const SimplifyQuery &Q) { | |||
4540 | return ::simplifyFPUnOp(Opcode, Op, FMF, Q, RecursionLimit); | |||
4541 | } | |||
4542 | ||||
4543 | /// Given operands for a BinaryOperator, see if we can fold the result. | |||
4544 | /// If not, this returns null. | |||
4545 | static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, | |||
4546 | const SimplifyQuery &Q, unsigned MaxRecurse) { | |||
4547 | switch (Opcode) { | |||
4548 | case Instruction::Add: | |||
4549 | return SimplifyAddInst(LHS, RHS, false, false, Q, MaxRecurse); | |||
4550 | case Instruction::Sub: | |||
4551 | return SimplifySubInst(LHS, RHS, false, false, Q, MaxRecurse); | |||
4552 | case Instruction::Mul: | |||
4553 | return SimplifyMulInst(LHS, RHS, Q, MaxRecurse); | |||
4554 | case Instruction::SDiv: | |||
4555 | return SimplifySDivInst(LHS, RHS, Q, MaxRecurse); | |||
4556 | case Instruction::UDiv: | |||
4557 | return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse); | |||
4558 | case Instruction::SRem: | |||
4559 | return SimplifySRemInst(LHS, RHS, Q, MaxRecurse); | |||
4560 | case Instruction::URem: | |||
4561 | return SimplifyURemInst(LHS, RHS, Q, MaxRecurse); | |||
4562 | case Instruction::Shl: | |||
4563 | return SimplifyShlInst(LHS, RHS, false, false, Q, MaxRecurse); | |||
4564 | case Instruction::LShr: | |||
4565 | return SimplifyLShrInst(LHS, RHS, false, Q, MaxRecurse); | |||
4566 | case Instruction::AShr: | |||
4567 | return SimplifyAShrInst(LHS, RHS, false, Q, MaxRecurse); | |||
4568 | case Instruction::And: | |||
4569 | return SimplifyAndInst(LHS, RHS, Q, MaxRecurse); | |||
4570 | case Instruction::Or: | |||
4571 | return SimplifyOrInst(LHS, RHS, Q, MaxRecurse); | |||
4572 | case Instruction::Xor: | |||
4573 | return SimplifyXorInst(LHS, RHS, Q, MaxRecurse); | |||
4574 | case Instruction::FAdd: | |||
4575 | return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse); | |||
4576 | case Instruction::FSub: | |||
4577 | return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse); | |||
4578 | case Instruction::FMul: | |||
4579 | return SimplifyFMulInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse); | |||
4580 | case Instruction::FDiv: | |||
4581 | return SimplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse); | |||
4582 | case Instruction::FRem: | |||
4583 | return SimplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse); | |||
4584 | default: | |||
4585 | llvm_unreachable("Unexpected opcode")::llvm::llvm_unreachable_internal("Unexpected opcode", "/build/llvm-toolchain-snapshot-9~svn360825/lib/Analysis/InstructionSimplify.cpp" , 4585); | |||
4586 | } | |||
4587 | } | |||
4588 | ||||
4589 | /// Given operands for a BinaryOperator, see if we can fold the result. | |||
4590 | /// If not, this returns null. | |||
4591 | /// In contrast to SimplifyBinOp, try to use FastMathFlag when folding the | |||
4592 | /// result. In case we don't need FastMathFlags, simply fall to SimplifyBinOp. | |||
4593 | static Value *SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS, | |||
4594 | const FastMathFlags &FMF, const SimplifyQuery &Q, | |||
4595 | unsigned MaxRecurse) { | |||
4596 | switch (Opcode) { | |||
4597 | case Instruction::FAdd: | |||
4598 | return SimplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse); | |||
4599 | case Instruction::FSub: | |||
4600 | return SimplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse); | |||
4601 | case Instruction::FMul: | |||
4602 | return SimplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse); | |||
4603 | case Instruction::FDiv: | |||
4604 | return SimplifyFDivInst(LHS, RHS, FMF, Q, MaxRecurse); | |||
4605 | default: | |||
4606 | return SimplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse); | |||
4607 | } | |||
4608 | } | |||
4609 | ||||
4610 | Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, | |||
4611 | const SimplifyQuery &Q) { | |||
4612 | return ::SimplifyBinOp(Opcode, LHS, RHS, Q, RecursionLimit); | |||
4613 | } | |||
4614 | ||||
4615 | Value *llvm::SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS, | |||
4616 | FastMathFlags FMF, const SimplifyQuery &Q) { | |||
4617 | return ::SimplifyFPBinOp(Opcode, LHS, RHS, FMF, Q, RecursionLimit); | |||
4618 | } | |||
4619 | ||||
4620 | /// Given operands for a CmpInst, see if we can fold the result. | |||
4621 | static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS, | |||
4622 | const SimplifyQuery &Q, unsigned MaxRecurse) { | |||
4623 | if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate)) | |||
4624 | return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse); | |||
4625 | return SimplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse); | |||
4626 | } | |||
4627 | ||||
4628 | Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS, | |||
4629 | const SimplifyQuery &Q) { | |||
4630 | return ::SimplifyCmpInst(Predicate, LHS, RHS, Q, RecursionLimit); | |||
| ||||
4631 | } | |||
4632 | ||||
4633 | static bool IsIdempotent(Intrinsic::ID ID) { | |||
4634 | switch (ID) { | |||
4635 | default: return false; | |||
4636 | ||||
4637 | // Unary idempotent: f(f(x)) = f(x) | |||
4638 | case Intrinsic::fabs: | |||
4639 | case Intrinsic::floor: | |||
4640 | case Intrinsic::ceil: | |||
4641 | case Intrinsic::trunc: | |||
4642 | case Intrinsic::rint: | |||
4643 | case Intrinsic::nearbyint: | |||
4644 | case Intrinsic::round: | |||
4645 | case Intrinsic::canonicalize: | |||
4646 | return true; | |||
4647 | } | |||
4648 | } | |||
4649 | ||||
4650 | static Value *SimplifyRelativeLoad(Constant *Ptr, Constant *Offset, | |||
4651 | const DataLayout &DL) { | |||
4652 | GlobalValue *PtrSym; | |||
4653 | APInt PtrOffset; | |||
4654 | if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL)) | |||
4655 | return nullptr; | |||
4656 | ||||
4657 | Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext()); | |||
4658 | Type *Int32Ty = Type::getInt32Ty(Ptr->getContext()); | |||
4659 | Type *Int32PtrTy = Int32Ty->getPointerTo(); | |||
4660 | Type *Int64Ty = Type::getInt64Ty(Ptr->getContext()); | |||
4661 | ||||
4662 | auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset); | |||
4663 | if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64) | |||
4664 | return nullptr; | |||
4665 | ||||
4666 | uint64_t OffsetInt = OffsetConstInt->getSExtValue(); | |||
4667 | if (OffsetInt % 4 != 0) | |||
4668 | return nullptr; | |||
4669 | ||||
4670 | Constant *C = ConstantExpr::getGetElementPtr( | |||
4671 | Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy), | |||
4672 | ConstantInt::get(Int64Ty, OffsetInt / 4)); | |||
4673 | Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL); | |||
4674 | if (!Loaded) | |||
4675 | return nullptr; | |||
4676 | ||||
4677 | auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded); | |||
4678 | if (!LoadedCE) | |||
4679 | return nullptr; | |||
4680 | ||||
4681 | if (LoadedCE->getOpcode() == Instruction::Trunc) { | |||
4682 | LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0)); | |||
4683 | if (!LoadedCE) | |||
4684 | return nullptr; | |||
4685 | } | |||
4686 | ||||
4687 | if (LoadedCE->getOpcode() != Instruction::Sub) | |||
4688 | return nullptr; | |||
4689 | ||||
4690 | auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0)); | |||
4691 | if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt) | |||
4692 | return nullptr; | |||
4693 | auto *LoadedLHSPtr = LoadedLHS->getOperand(0); | |||
4694 | ||||
4695 | Constant *LoadedRHS = LoadedCE->getOperand(1); | |||
4696 | GlobalValue *LoadedRHSSym; | |||
4697 | APInt LoadedRHSOffset; | |||
4698 | if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset, | |||
4699 | DL) || | |||
4700 | PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset) | |||
4701 | return nullptr; | |||
4702 | ||||
4703 | return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy); | |||
4704 | } | |||
4705 | ||||
4706 | static Value *simplifyUnaryIntrinsic(Function *F, Value *Op0, | |||
4707 | const SimplifyQuery &Q) { | |||
4708 | // Idempotent functions return the same result when called repeatedly. | |||
4709 | Intrinsic::ID IID = F->getIntrinsicID(); | |||
4710 | if (IsIdempotent(IID)) | |||
4711 | if (auto *II = dyn_cast<IntrinsicInst>(Op0)) | |||
4712 | if (II->getIntrinsicID() == IID) | |||
4713 | return II; | |||
4714 | ||||
4715 | Value *X; | |||
4716 | switch (IID) { | |||
4717 | case Intrinsic::fabs: | |||
4718 | if (SignBitMustBeZero(Op0, Q.TLI)) return Op0; | |||
4719 | break; | |||
4720 | case Intrinsic::bswap: | |||
4721 | // bswap(bswap(x)) -> x | |||
4722 | if (match(Op0, m_BSwap(m_Value(X)))) return X; | |||
4723 | break; | |||
4724 | case Intrinsic::bitreverse: | |||
4725 | // bitreverse(bitreverse(x)) -> x | |||
4726 | if (match(Op0, m_BitReverse(m_Value(X)))) return X; | |||
4727 | break; | |||
4728 | case Intrinsic::exp: | |||
4729 | // exp(log(x)) -> x | |||
4730 | if (Q.CxtI->hasAllowReassoc() && | |||
4731 | match(Op0, m_Intrinsic<Intrinsic::log>(m_Value(X)))) return X; | |||
4732 | break; | |||
4733 | case Intrinsic::exp2: | |||
4734 | // exp2(log2(x)) -> x | |||
4735 | if (Q.CxtI->hasAllowReassoc() && | |||
4736 | match(Op0, m_Intrinsic<Intrinsic::log2>(m_Value(X)))) return X; | |||
4737 | break; | |||
4738 | case Intrinsic::log: | |||
4739 | // log(exp(x)) -> x | |||
4740 | if (Q.CxtI->hasAllowReassoc() && | |||
4741 | match(Op0, m_Intrinsic<Intrinsic::exp>(m_Value(X)))) return X; | |||
4742 | break; | |||
4743 | case Intrinsic::log2: | |||
4744 | // log2(exp2(x)) -> x | |||
4745 | if (Q.CxtI->hasAllowReassoc() && | |||
4746 | (match(Op0, m_Intrinsic<Intrinsic::exp2>(m_Value(X))) || | |||
4747 | match(Op0, m_Intrinsic<Intrinsic::pow>(m_SpecificFP(2.0), | |||
4748 | m_Value(X))))) return X; | |||
4749 | break; | |||
4750 | case Intrinsic::log10: | |||
4751 | // log10(pow(10.0, x)) -> x | |||
4752 | if (Q.CxtI->hasAllowReassoc() && | |||
4753 | match(Op0, m_Intrinsic<Intrinsic::pow>(m_SpecificFP(10.0), | |||
4754 | m_Value(X)))) return X; | |||
4755 | break; | |||
4756 | case Intrinsic::floor: | |||
4757 | case Intrinsic::trunc: | |||
4758 | case Intrinsic::ceil: | |||
4759 | case Intrinsic::round: | |||
4760 | case Intrinsic::nearbyint: | |||
4761 | case Intrinsic::rint: { | |||
4762 | // floor (sitofp x) -> sitofp x | |||
4763 | // floor (uitofp x) -> uitofp x | |||
4764 | // | |||
4765 | // Converting from int always results in a finite integral number or | |||
4766 | // infinity. For either of those inputs, these rounding functions always | |||
4767 | // return the same value, so the rounding can be eliminated. | |||
4768 | if (match(Op0, m_SIToFP(m_Value())) || match(Op0, m_UIToFP(m_Value()))) | |||
4769 | return Op0; | |||
4770 | break; | |||
4771 | } | |||
4772 | default: | |||
4773 | break; | |||
4774 | } | |||
4775 | ||||
4776 | return nullptr; | |||
4777 | } | |||
4778 | ||||
4779 | static Value *simplifyBinaryIntrinsic(Function *F, Value *Op0, Value *Op1, | |||
4780 | const SimplifyQuery &Q) { | |||
4781 | Intrinsic::ID IID = F->getIntrinsicID(); | |||
4782 | Type *ReturnType = F->getReturnType(); | |||
4783 | switch (IID) { | |||
4784 | case Intrinsic::usub_with_overflow: | |||
4785 | case Intrinsic::ssub_with_overflow: | |||
4786 | // X - X -> { 0, false } | |||
4787 | if (Op0 == Op1) | |||
4788 | return Constant::getNullValue(ReturnType); | |||
4789 | // X - undef -> undef | |||
4790 | // undef - X -> undef | |||
4791 | if (isa<UndefValue>(Op0) || isa<UndefValue>(Op1)) | |||
4792 | return UndefValue::get(ReturnType); | |||
4793 | break; | |||
4794 | case Intrinsic::uadd_with_overflow: | |||
4795 | case Intrinsic::sadd_with_overflow: | |||
4796 | // X + undef -> undef | |||
4797 | if (isa<UndefValue>(Op0) || isa<UndefValue>(Op1)) | |||
4798 | return UndefValue::get(ReturnType); | |||
4799 | break; | |||
4800 | case Intrinsic::umul_with_overflow: | |||
4801 | case Intrinsic::smul_with_overflow: | |||
4802 | // 0 * X -> { 0, false } | |||
4803 | // X * 0 -> { 0, false } | |||
4804 | if (match(Op0, m_Zero()) || match(Op1, m_Zero())) | |||
4805 | return Constant::getNullValue(ReturnType); | |||
4806 | // undef * X -> { 0, false } | |||
4807 | // X * undef -> { 0, false } | |||
4808 | if (match(Op0, m_Undef()) || match(Op1, m_Undef())) | |||
4809 | return Constant::getNullValue(ReturnType); | |||
4810 | break; | |||
4811 | case Intrinsic::uadd_sat: | |||
4812 | // sat(MAX + X) -> MAX | |||
4813 | // sat(X + MAX) -> MAX | |||
4814 | if (match(Op0, m_AllOnes()) || match(Op1, m_AllOnes())) | |||
4815 | return Constant::getAllOnesValue(ReturnType); | |||
4816 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
4817 | case Intrinsic::sadd_sat: | |||
4818 | // sat(X + undef) -> -1 | |||
4819 | // sat(undef + X) -> -1 | |||
4820 | // For unsigned: Assume undef is MAX, thus we saturate to MAX (-1). | |||
4821 | // For signed: Assume undef is ~X, in which case X + ~X = -1. | |||
4822 | if (match(Op0, m_Undef()) || match(Op1, m_Undef())) | |||
4823 | return Constant::getAllOnesValue(ReturnType); | |||
4824 | ||||
4825 | // X + 0 -> X | |||
4826 | if (match(Op1, m_Zero())) | |||
4827 | return Op0; | |||
4828 | // 0 + X -> X | |||
4829 | if (match(Op0, m_Zero())) | |||
4830 | return Op1; | |||
4831 | break; | |||
4832 | case Intrinsic::usub_sat: | |||
4833 | // sat(0 - X) -> 0, sat(X - MAX) -> 0 | |||
4834 | if (match(Op0, m_Zero()) || match(Op1, m_AllOnes())) | |||
4835 | return Constant::getNullValue(ReturnType); | |||
4836 | LLVM_FALLTHROUGH[[clang::fallthrough]]; | |||
4837 | case Intrinsic::ssub_sat: | |||
4838 | // X - X -> 0, X - undef -> 0, undef - X -> 0 | |||
4839 | if (Op0 == Op1 || match(Op0, m_Undef()) || match(Op1, m_Undef())) | |||
4840 | return Constant::getNullValue(ReturnType); | |||
4841 | // X - 0 -> X | |||
4842 | if (match(Op1, m_Zero())) | |||
4843 | return Op0; | |||
4844 | break; | |||
4845 | case Intrinsic::load_relative: | |||
4846 | if (auto *C0 = dyn_cast<Constant>(Op0)) | |||
4847 | if (auto *C1 = dyn_cast<Constant>(Op1)) | |||
4848 | return SimplifyRelativeLoad(C0, C1, Q.DL); | |||
4849 | break; | |||
4850 | case Intrinsic::powi: | |||
4851 | if (auto *Power = dyn_cast<ConstantInt>(Op1)) { | |||
4852 | // powi(x, 0) -> 1.0 | |||
4853 | if (Power->isZero()) | |||
4854 | return ConstantFP::get(Op0->getType(), 1.0); | |||
4855 | // powi(x, 1) -> x | |||
4856 | if (Power->isOne()) | |||
4857 | return Op0; | |||
4858 | } | |||
4859 | break; | |||
4860 | case Intrinsic::maxnum: | |||
4861 | case Intrinsic::minnum: | |||
4862 | case Intrinsic::maximum: | |||
4863 | case Intrinsic::minimum: { | |||
4864 | // If the arguments are the same, this is a no-op. | |||
4865 | if (Op0 == Op1) return Op0; | |||
4866 | ||||
4867 | // If one argument is undef, return the other argument. | |||
4868 | if (match(Op0, m_Undef())) | |||
4869 | return Op1; | |||
4870 | if (match(Op1, m_Undef())) | |||
4871 | return Op0; | |||
4872 | ||||
4873 | // If one argument is NaN, return other or NaN appropriately. | |||
4874 | bool PropagateNaN = IID == Intrinsic::minimum || IID == Intrinsic::maximum; | |||
4875 | if (match(Op0, m_NaN())) | |||
4876 | return PropagateNaN ? Op0 : Op1; | |||
4877 | if (match(Op1, m_NaN())) | |||
4878 | return PropagateNaN ? Op1 : Op0; | |||
4879 | ||||
4880 | // Min/max of the same operation with common operand: | |||
4881 | // m(m(X, Y)), X --> m(X, Y) (4 commuted variants) | |||
4882 | if (auto *M0 = dyn_cast<IntrinsicInst>(Op0)) | |||
4883 | if (M0->getIntrinsicID() == IID && | |||
4884 | (M0->getOperand(0) == Op1 || M0->getOperand(1) == Op1)) | |||
4885 | return Op0; | |||
4886 | if (auto *M1 = dyn_cast<IntrinsicInst>(Op1)) | |||
4887 | if (M1->getIntrinsicID() == IID && | |||
4888 | (M1->getOperand(0) == Op0 || M1->getOperand(1) == Op0)) | |||
4889 | return Op1; | |||
4890 | ||||
4891 | // min(X, -Inf) --> -Inf (and commuted variant) | |||
4892 | // max(X, +Inf) --> +Inf (and commuted variant) | |||
4893 | bool UseNegInf = IID == Intrinsic::minnum || IID == Intrinsic::minimum; | |||
4894 | const APFloat *C; | |||
4895 | if ((match(Op0, m_APFloat(C)) && C->isInfinity() && | |||
4896 | C->isNegative() == UseNegInf) || | |||
4897 | (match(Op1, m_APFloat(C)) && C->isInfinity() && | |||
4898 | C->isNegative() == UseNegInf)) | |||
4899 | return ConstantFP::getInfinity(ReturnType, UseNegInf); | |||
4900 | ||||
4901 | // TODO: minnum(nnan x, inf) -> x | |||
4902 | // TODO: minnum(nnan ninf x, flt_max) -> x | |||
4903 | // TODO: maxnum(nnan x, -inf) -> x | |||
4904 | // TODO: maxnum(nnan ninf x, -flt_max) -> x | |||
4905 | break; | |||
4906 | } | |||
4907 | default: | |||
4908 | break; | |||
4909 | } | |||
4910 | ||||
4911 | return nullptr; | |||
4912 | } | |||
4913 | ||||
4914 | template <typename IterTy> | |||
4915 | static Value *simplifyIntrinsic(Function *F, IterTy ArgBegin, IterTy ArgEnd, | |||
4916 | const SimplifyQuery &Q) { | |||
4917 | // Intrinsics with no operands have some kind of side effect. Don't simplify. | |||
4918 | unsigned NumOperands = std::distance(ArgBegin, ArgEnd); | |||
4919 | if (NumOperands == 0) | |||
4920 | return nullptr; | |||
4921 | ||||
4922 | Intrinsic::ID IID = F->getIntrinsicID(); | |||
4923 | if (NumOperands == 1) | |||
4924 | return simplifyUnaryIntrinsic(F, ArgBegin[0], Q); | |||
4925 | ||||
4926 | if (NumOperands == 2) | |||
4927 | return simplifyBinaryIntrinsic(F, ArgBegin[0], ArgBegin[1], Q); | |||
4928 | ||||
4929 | // Handle intrinsics with 3 or more arguments. | |||
4930 | switch (IID) { | |||
4931 | case Intrinsic::masked_load: | |||
4932 | case Intrinsic::masked_gather: { | |||
4933 | Value *MaskArg = ArgBegin[2]; | |||
4934 | Value *PassthruArg = ArgBegin[3]; | |||
4935 | // If the mask is all zeros or undef, the "passthru" argument is the result. | |||
4936 | if (maskIsAllZeroOrUndef(MaskArg)) | |||
4937 | return PassthruArg; | |||
4938 | return nullptr; | |||
4939 | } | |||
4940 | case Intrinsic::fshl: | |||
4941 | case Intrinsic::fshr: { | |||
4942 | Value *Op0 = ArgBegin[0], *Op1 = ArgBegin[1], *ShAmtArg = ArgBegin[2]; | |||
4943 | ||||
4944 | // If both operands are undef, the result is undef. | |||
4945 | if (match(Op0, m_Undef()) && match(Op1, m_Undef())) | |||
4946 | return UndefValue::get(F->getReturnType()); | |||
4947 | ||||
4948 | // If shift amount is undef, assume it is zero. | |||
4949 | if (match(ShAmtArg, m_Undef())) | |||
4950 | return ArgBegin[IID == Intrinsic::fshl ? 0 : 1]; | |||
4951 | ||||
4952 | const APInt *ShAmtC; | |||
4953 | if (match(ShAmtArg, m_APInt(ShAmtC))) { | |||
4954 | // If there's effectively no shift, return the 1st arg or 2nd arg. | |||
4955 | APInt BitWidth = APInt(ShAmtC->getBitWidth(), ShAmtC->getBitWidth()); | |||
4956 | if (ShAmtC->urem(BitWidth).isNullValue()) | |||
4957 | return ArgBegin[IID == Intrinsic::fshl ? 0 : 1]; | |||
4958 | } | |||
4959 | return nullptr; | |||
4960 | } | |||
4961 | default: | |||
4962 | return nullptr; | |||
4963 | } | |||
4964 | } | |||
4965 | ||||
4966 | template <typename IterTy> | |||
4967 | static Value *SimplifyCall(CallBase *Call, Value *V, IterTy ArgBegin, | |||
4968 | IterTy ArgEnd, const SimplifyQuery &Q, | |||
4969 | unsigned MaxRecurse) { | |||
4970 | Type *Ty = V->getType(); | |||
4971 | if (PointerType *PTy = dyn_cast<PointerType>(Ty)) | |||
4972 | Ty = PTy->getElementType(); | |||
4973 | FunctionType *FTy = cast<FunctionType>(Ty); | |||
4974 | ||||
4975 | // call undef -> undef | |||
4976 | // call null -> undef | |||
4977 | if (isa<UndefValue>(V) || isa<ConstantPointerNull>(V)) | |||
4978 | return UndefValue::get(FTy->getReturnType()); | |||
4979 | ||||
4980 | Function *F = dyn_cast<Function>(V); | |||
4981 | if (!F) | |||
4982 | return nullptr; | |||
4983 | ||||
4984 | if (F->isIntrinsic()) | |||
4985 | if (Value *Ret = simplifyIntrinsic(F, ArgBegin, ArgEnd, Q)) | |||
4986 | return Ret; | |||
4987 | ||||
4988 | if (!canConstantFoldCallTo(Call, F)) | |||
4989 | return nullptr; | |||
4990 | ||||
4991 | SmallVector<Constant *, 4> ConstantArgs; | |||
4992 | ConstantArgs.reserve(ArgEnd - ArgBegin); | |||
4993 | for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) { | |||
4994 | Constant *C = dyn_cast<Constant>(*I); | |||
4995 | if (!C) | |||
4996 | return nullptr; | |||
4997 | ConstantArgs.push_back(C); | |||
4998 | } | |||
4999 | ||||
5000 | return ConstantFoldCall(Call, F, ConstantArgs, Q.TLI); | |||
5001 | } | |||
5002 | ||||
5003 | Value *llvm::SimplifyCall(CallBase *Call, Value *V, User::op_iterator ArgBegin, | |||
5004 | User::op_iterator ArgEnd, const SimplifyQuery &Q) { | |||
5005 | return ::SimplifyCall(Call, V, ArgBegin, ArgEnd, Q, RecursionLimit); | |||
5006 | } | |||
5007 | ||||
5008 | Value *llvm::SimplifyCall(CallBase *Call, Value *V, ArrayRef<Value *> Args, | |||
5009 | const SimplifyQuery &Q) { | |||
5010 | return ::SimplifyCall(Call, V, Args.begin(), Args.end(), Q, RecursionLimit); | |||
5011 | } | |||
5012 | ||||
5013 | Value *llvm::SimplifyCall(CallBase *Call, const SimplifyQuery &Q) { | |||
5014 | return ::SimplifyCall(Call, Call->getCalledValue(), Call->arg_begin(), | |||
5015 | Call->arg_end(), Q, RecursionLimit); | |||
5016 | } | |||
5017 | ||||
5018 | /// See if we can compute a simplified version of this instruction. | |||
5019 | /// If not, this returns null. | |||
5020 | ||||
5021 | Value *llvm::SimplifyInstruction(Instruction *I, const SimplifyQuery &SQ, | |||
5022 | OptimizationRemarkEmitter *ORE) { | |||
5023 | const SimplifyQuery Q = SQ.CxtI ? SQ : SQ.getWithInstruction(I); | |||
5024 | Value *Result; | |||
5025 | ||||
5026 | switch (I->getOpcode()) { | |||
5027 | default: | |||
5028 | Result = ConstantFoldInstruction(I, Q.DL, Q.TLI); | |||
5029 | break; | |||
5030 | case Instruction::FNeg: | |||
5031 | Result = SimplifyFNegInst(I->getOperand(0), I->getFastMathFlags(), Q); | |||
5032 | break; | |||
5033 | case Instruction::FAdd: | |||
5034 | Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1), | |||
5035 | I->getFastMathFlags(), Q); | |||
5036 | break; | |||
5037 | case Instruction::Add: | |||
5038 | Result = | |||
5039 | SimplifyAddInst(I->getOperand(0), I->getOperand(1), | |||
5040 | Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)), | |||
5041 | Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q); | |||
5042 | break; | |||
5043 | case Instruction::FSub: | |||
5044 | Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1), | |||
5045 | I->getFastMathFlags(), Q); | |||
5046 | break; | |||
5047 | case Instruction::Sub: | |||
5048 | Result = | |||
5049 | SimplifySubInst(I->getOperand(0), I->getOperand(1), | |||
5050 | Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)), | |||
5051 | Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q); | |||
5052 | break; | |||
5053 | case Instruction::FMul: | |||
5054 | Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1), | |||
5055 | I->getFastMathFlags(), Q); | |||
5056 | break; | |||
5057 | case Instruction::Mul: | |||
5058 | Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), Q); | |||
5059 | break; | |||
5060 | case Instruction::SDiv: | |||
5061 | Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), Q); | |||
5062 | break; | |||
5063 | case Instruction::UDiv: | |||
5064 | Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), Q); | |||
5065 | break; | |||
5066 | case Instruction::FDiv: | |||
5067 | Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), | |||
5068 | I->getFastMathFlags(), Q); | |||
5069 | break; | |||
5070 | case Instruction::SRem: | |||
5071 | Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), Q); | |||
5072 | break; | |||
5073 | case Instruction::URem: | |||
5074 | Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), Q); | |||
5075 | break; | |||
5076 | case Instruction::FRem: | |||
5077 | Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1), | |||
5078 | I->getFastMathFlags(), Q); | |||
5079 | break; | |||
5080 | case Instruction::Shl: | |||
5081 | Result = | |||
5082 | SimplifyShlInst(I->getOperand(0), I->getOperand(1), | |||
5083 | Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)), | |||
5084 | Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q); | |||
5085 | break; | |||
5086 | case Instruction::LShr: | |||
5087 | Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1), | |||
5088 | Q.IIQ.isExact(cast<BinaryOperator>(I)), Q); | |||
5089 | break; | |||
5090 | case Instruction::AShr: | |||
5091 | Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1), | |||
5092 | Q.IIQ.isExact(cast<BinaryOperator>(I)), Q); | |||
5093 | break; | |||
5094 | case Instruction::And: | |||
5095 | Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), Q); | |||
5096 | break; | |||
5097 | case Instruction::Or: | |||
5098 | Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), Q); | |||
5099 | break; | |||
5100 | case Instruction::Xor: | |||
5101 | Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), Q); | |||
5102 | break; | |||
5103 | case Instruction::ICmp: | |||
5104 | Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(), | |||
5105 | I->getOperand(0), I->getOperand(1), Q); | |||
5106 | break; | |||
5107 | case Instruction::FCmp: | |||
5108 | Result = | |||
5109 | SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(), I->getOperand(0), | |||
5110 | I->getOperand(1), I->getFastMathFlags(), Q); | |||
5111 | break; | |||
5112 | case Instruction::Select: | |||
5113 | Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1), | |||
5114 | I->getOperand(2), Q); | |||
5115 | break; | |||
5116 | case Instruction::GetElementPtr: { | |||
5117 | SmallVector<Value *, 8> Ops(I->op_begin(), I->op_end()); | |||
5118 | Result = SimplifyGEPInst(cast<GetElementPtrInst>(I)->getSourceElementType(), | |||
5119 | Ops, Q); | |||
5120 | break; | |||
5121 | } | |||
5122 | case Instruction::InsertValue: { | |||
5123 | InsertValueInst *IV = cast<InsertValueInst>(I); | |||
5124 | Result = SimplifyInsertValueInst(IV->getAggregateOperand(), | |||
5125 | IV->getInsertedValueOperand(), | |||
5126 | IV->getIndices(), Q); | |||
5127 | break; | |||
5128 | } | |||
5129 | case Instruction::InsertElement: { | |||
5130 | auto *IE = cast<InsertElementInst>(I); | |||
5131 | Result = SimplifyInsertElementInst(IE->getOperand(0), IE->getOperand(1), | |||
5132 | IE->getOperand(2), Q); | |||
5133 | break; | |||
5134 | } | |||
5135 | case Instruction::ExtractValue: { | |||
5136 | auto *EVI = cast<ExtractValueInst>(I); | |||
5137 | Result = SimplifyExtractValueInst(EVI->getAggregateOperand(), | |||
5138 | EVI->getIndices(), Q); | |||
5139 | break; | |||
5140 | } | |||
5141 | case Instruction::ExtractElement: { | |||
5142 | auto *EEI = cast<ExtractElementInst>(I); | |||
5143 | Result = SimplifyExtractElementInst(EEI->getVectorOperand(), | |||
5144 | EEI->getIndexOperand(), Q); | |||
5145 | break; | |||
5146 | } | |||
5147 | case Instruction::ShuffleVector: { | |||
5148 | auto *SVI = cast<ShuffleVectorInst>(I); | |||
5149 | Result = SimplifyShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1), | |||
5150 | SVI->getMask(), SVI->getType(), Q); | |||
5151 | break; | |||
5152 | } | |||
5153 | case Instruction::PHI: | |||
5154 | Result = SimplifyPHINode(cast<PHINode>(I), Q); | |||
5155 | break; | |||
5156 | case Instruction::Call: { | |||
5157 | Result = SimplifyCall(cast<CallInst>(I), Q); | |||
5158 | break; | |||
5159 | } | |||
5160 | #define HANDLE_CAST_INST(num, opc, clas) case Instruction::opc: | |||
5161 | #include "llvm/IR/Instruction.def" | |||
5162 | #undef HANDLE_CAST_INST | |||
5163 | Result = | |||
5164 | SimplifyCastInst(I->getOpcode(), I->getOperand(0), I->getType(), Q); | |||
5165 | break; | |||
5166 | case Instruction::Alloca: | |||
5167 | // No simplifications for Alloca and it can't be constant folded. | |||
5168 | Result = nullptr; | |||
5169 | break; | |||
5170 | } | |||
5171 | ||||
5172 | // In general, it is possible for computeKnownBits to determine all bits in a | |||
5173 | // value even when the operands are not all constants. | |||
5174 | if (!Result && I->getType()->isIntOrIntVectorTy()) { | |||
5175 | KnownBits Known = computeKnownBits(I, Q.DL, /*Depth*/ 0, Q.AC, I, Q.DT, ORE); | |||
5176 | if (Known.isConstant()) | |||
5177 | Result = ConstantInt::get(I->getType(), Known.getConstant()); | |||
5178 | } | |||
5179 | ||||
5180 | /// If called on unreachable code, the above logic may report that the | |||
5181 | /// instruction simplified to itself. Make life easier for users by | |||
5182 | /// detecting that case here, returning a safe value instead. | |||
5183 | return Result == I ? UndefValue::get(I->getType()) : Result; | |||
5184 | } | |||
5185 | ||||
5186 | /// Implementation of recursive simplification through an instruction's | |||
5187 | /// uses. | |||
5188 | /// | |||
5189 | /// This is the common implementation of the recursive simplification routines. | |||
5190 | /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to | |||
5191 | /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of | |||
5192 | /// instructions to process and attempt to simplify it using | |||
5193 | /// InstructionSimplify. | |||
5194 | /// | |||
5195 | /// This routine returns 'true' only when *it* simplifies something. The passed | |||
5196 | /// in simplified value does not count toward this. | |||
5197 | static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV, | |||
5198 | const TargetLibraryInfo *TLI, | |||
5199 | const DominatorTree *DT, | |||
5200 | AssumptionCache *AC) { | |||
5201 | bool Simplified = false; | |||
5202 | SmallSetVector<Instruction *, 8> Worklist; | |||
5203 | const DataLayout &DL = I->getModule()->getDataLayout(); | |||
5204 | ||||
5205 | // If we have an explicit value to collapse to, do that round of the | |||
5206 | // simplification loop by hand initially. | |||
5207 | if (SimpleV) { | |||
5208 | for (User *U : I->users()) | |||
5209 | if (U != I) | |||
5210 | Worklist.insert(cast<Instruction>(U)); | |||
5211 | ||||
5212 | // Replace the instruction with its simplified value. | |||
5213 | I->replaceAllUsesWith(SimpleV); | |||
5214 | ||||
5215 | // Gracefully handle edge cases where the instruction is not wired into any | |||
5216 | // parent block. | |||
5217 | if (I->getParent() && !I->isEHPad() && !I->isTerminator() && | |||
5218 | !I->mayHaveSideEffects()) | |||
5219 | I->eraseFromParent(); | |||
5220 | } else { | |||
5221 | Worklist.insert(I); | |||
5222 | } | |||
5223 | ||||
5224 | // Note that we must test the size on each iteration, the worklist can grow. | |||
5225 | for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) { | |||
5226 | I = Worklist[Idx]; | |||
5227 | ||||
5228 | // See if this instruction simplifies. | |||
5229 | SimpleV = SimplifyInstruction(I, {DL, TLI, DT, AC}); | |||
5230 | if (!SimpleV) | |||
5231 | continue; | |||
5232 | ||||
5233 | Simplified = true; | |||
5234 | ||||
5235 | // Stash away all the uses of the old instruction so we can check them for | |||
5236 | // recursive simplifications after a RAUW. This is cheaper than checking all | |||
5237 | // uses of To on the recursive step in most cases. | |||
5238 | for (User *U : I->users()) | |||
5239 | Worklist.insert(cast<Instruction>(U)); | |||
5240 | ||||
5241 | // Replace the instruction with its simplified value. | |||
5242 | I->replaceAllUsesWith(SimpleV); | |||
5243 | ||||
5244 | // Gracefully handle edge cases where the instruction is not wired into any | |||
5245 | // parent block. | |||
5246 | if (I->getParent() && !I->isEHPad() && !I->isTerminator() && | |||
5247 | !I->mayHaveSideEffects()) | |||
5248 | I->eraseFromParent(); | |||
5249 | } | |||
5250 | return Simplified; | |||
5251 | } | |||
5252 | ||||
5253 | bool llvm::recursivelySimplifyInstruction(Instruction *I, | |||
5254 | const TargetLibraryInfo *TLI, | |||
5255 | const DominatorTree *DT, | |||
5256 | AssumptionCache *AC) { | |||
5257 | return replaceAndRecursivelySimplifyImpl(I, nullptr, TLI, DT, AC); | |||
5258 | } | |||
5259 | ||||
5260 | bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV, | |||
5261 | const TargetLibraryInfo *TLI, | |||
5262 | const DominatorTree *DT, | |||
5263 | AssumptionCache *AC) { | |||
5264 | assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!")((I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!" ) ? static_cast<void> (0) : __assert_fail ("I != SimpleV && \"replaceAndRecursivelySimplify(X,X) is not valid!\"" , "/build/llvm-toolchain-snapshot-9~svn360825/lib/Analysis/InstructionSimplify.cpp" , 5264, __PRETTY_FUNCTION__)); | |||
5265 | assert(SimpleV && "Must provide a simplified value.")((SimpleV && "Must provide a simplified value.") ? static_cast <void> (0) : __assert_fail ("SimpleV && \"Must provide a simplified value.\"" , "/build/llvm-toolchain-snapshot-9~svn360825/lib/Analysis/InstructionSimplify.cpp" , 5265, __PRETTY_FUNCTION__)); | |||
5266 | return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC); | |||
5267 | } | |||
5268 | ||||
5269 | namespace llvm { | |||
5270 | const SimplifyQuery getBestSimplifyQuery(Pass &P, Function &F) { | |||
5271 | auto *DTWP = P.getAnalysisIfAvailable<DominatorTreeWrapperPass>(); | |||
5272 | auto *DT = DTWP ? &DTWP->getDomTree() : nullptr; | |||
5273 | auto *TLIWP = P.getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>(); | |||
5274 | auto *TLI = TLIWP ? &TLIWP->getTLI() : nullptr; | |||
5275 | auto *ACWP = P.getAnalysisIfAvailable<AssumptionCacheTracker>(); | |||
5276 | auto *AC = ACWP ? &ACWP->getAssumptionCache(F) : nullptr; | |||
5277 | return {F.getParent()->getDataLayout(), TLI, DT, AC}; | |||
5278 | } | |||
5279 | ||||
5280 | const SimplifyQuery getBestSimplifyQuery(LoopStandardAnalysisResults &AR, | |||
5281 | const DataLayout &DL) { | |||
5282 | return {DL, &AR.TLI, &AR.DT, &AR.AC}; | |||
5283 | } | |||
5284 | ||||
5285 | template <class T, class... TArgs> | |||
5286 | const SimplifyQuery getBestSimplifyQuery(AnalysisManager<T, TArgs...> &AM, | |||
5287 | Function &F) { | |||
5288 | auto *DT = AM.template getCachedResult<DominatorTreeAnalysis>(F); | |||
5289 | auto *TLI = AM.template getCachedResult<TargetLibraryAnalysis>(F); | |||
5290 | auto *AC = AM.template getCachedResult<AssumptionAnalysis>(F); | |||
5291 | return {F.getParent()->getDataLayout(), TLI, DT, AC}; | |||
5292 | } | |||
5293 | template const SimplifyQuery getBestSimplifyQuery(AnalysisManager<Function> &, | |||
5294 | Function &); | |||
5295 | } |
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/InstrTypes.h" |
36 | #include "llvm/IR/Instruction.h" |
37 | #include "llvm/IR/Instructions.h" |
38 | #include "llvm/IR/Intrinsics.h" |
39 | #include "llvm/IR/Operator.h" |
40 | #include "llvm/IR/Value.h" |
41 | #include "llvm/Support/Casting.h" |
42 | #include <cstdint> |
43 | |
44 | namespace llvm { |
45 | namespace PatternMatch { |
46 | |
47 | template <typename Val, typename Pattern> bool match(Val *V, const Pattern &P) { |
48 | return const_cast<Pattern &>(P).match(V); |
49 | } |
50 | |
51 | template <typename SubPattern_t> struct OneUse_match { |
52 | SubPattern_t SubPattern; |
53 | |
54 | OneUse_match(const SubPattern_t &SP) : SubPattern(SP) {} |
55 | |
56 | template <typename OpTy> bool match(OpTy *V) { |
57 | return V->hasOneUse() && SubPattern.match(V); |
58 | } |
59 | }; |
60 | |
61 | template <typename T> inline OneUse_match<T> m_OneUse(const T &SubPattern) { |
62 | return SubPattern; |
63 | } |
64 | |
65 | template <typename Class> struct class_match { |
66 | template <typename ITy> bool match(ITy *V) { return isa<Class>(V); } |
67 | }; |
68 | |
69 | /// Match an arbitrary value and ignore it. |
70 | inline class_match<Value> m_Value() { return class_match<Value>(); } |
71 | |
72 | /// Match an arbitrary binary operation and ignore it. |
73 | inline class_match<BinaryOperator> m_BinOp() { |
74 | return class_match<BinaryOperator>(); |
75 | } |
76 | |
77 | /// Matches any compare instruction and ignore it. |
78 | inline class_match<CmpInst> m_Cmp() { return class_match<CmpInst>(); } |
79 | |
80 | /// Match an arbitrary ConstantInt and ignore it. |
81 | inline class_match<ConstantInt> m_ConstantInt() { |
82 | return class_match<ConstantInt>(); |
83 | } |
84 | |
85 | /// Match an arbitrary undef constant. |
86 | inline class_match<UndefValue> m_Undef() { return class_match<UndefValue>(); } |
87 | |
88 | /// Match an arbitrary Constant and ignore it. |
89 | inline class_match<Constant> m_Constant() { return class_match<Constant>(); } |
90 | |
91 | /// Matching combinators |
92 | template <typename LTy, typename RTy> struct match_combine_or { |
93 | LTy L; |
94 | RTy R; |
95 | |
96 | match_combine_or(const LTy &Left, const RTy &Right) : L(Left), R(Right) {} |
97 | |
98 | template <typename ITy> bool match(ITy *V) { |
99 | if (L.match(V)) |
100 | return true; |
101 | if (R.match(V)) |
102 | return true; |
103 | return false; |
104 | } |
105 | }; |
106 | |
107 | template <typename LTy, typename RTy> struct match_combine_and { |
108 | LTy L; |
109 | RTy R; |
110 | |
111 | match_combine_and(const LTy &Left, const RTy &Right) : L(Left), R(Right) {} |
112 | |
113 | template <typename ITy> bool match(ITy *V) { |
114 | if (L.match(V)) |
115 | if (R.match(V)) |
116 | return true; |
117 | return false; |
118 | } |
119 | }; |
120 | |
121 | /// Combine two pattern matchers matching L || R |
122 | template <typename LTy, typename RTy> |
123 | inline match_combine_or<LTy, RTy> m_CombineOr(const LTy &L, const RTy &R) { |
124 | return match_combine_or<LTy, RTy>(L, R); |
125 | } |
126 | |
127 | /// Combine two pattern matchers matching L && R |
128 | template <typename LTy, typename RTy> |
129 | inline match_combine_and<LTy, RTy> m_CombineAnd(const LTy &L, const RTy &R) { |
130 | return match_combine_and<LTy, RTy>(L, R); |
131 | } |
132 | |
133 | struct apint_match { |
134 | const APInt *&Res; |
135 | |
136 | apint_match(const APInt *&R) : Res(R) {} |
137 | |
138 | template <typename ITy> bool match(ITy *V) { |
139 | if (auto *CI = dyn_cast<ConstantInt>(V)) { |
140 | Res = &CI->getValue(); |
141 | return true; |
142 | } |
143 | if (V->getType()->isVectorTy()) |
144 | if (const auto *C = dyn_cast<Constant>(V)) |
145 | if (auto *CI = dyn_cast_or_null<ConstantInt>(C->getSplatValue())) { |
146 | Res = &CI->getValue(); |
147 | return true; |
148 | } |
149 | return false; |
150 | } |
151 | }; |
152 | // Either constexpr if or renaming ConstantFP::getValueAPF to |
153 | // ConstantFP::getValue is needed to do it via single template |
154 | // function for both apint/apfloat. |
155 | struct apfloat_match { |
156 | const APFloat *&Res; |
157 | apfloat_match(const APFloat *&R) : Res(R) {} |
158 | template <typename ITy> bool match(ITy *V) { |
159 | if (auto *CI = dyn_cast<ConstantFP>(V)) { |
160 | Res = &CI->getValueAPF(); |
161 | return true; |
162 | } |
163 | if (V->getType()->isVectorTy()) |
164 | if (const auto *C = dyn_cast<Constant>(V)) |
165 | if (auto *CI = dyn_cast_or_null<ConstantFP>(C->getSplatValue())) { |
166 | Res = &CI->getValueAPF(); |
167 | return true; |
168 | } |
169 | return false; |
170 | } |
171 | }; |
172 | |
173 | /// Match a ConstantInt or splatted ConstantVector, binding the |
174 | /// specified pointer to the contained APInt. |
175 | inline apint_match m_APInt(const APInt *&Res) { return Res; } |
176 | |
177 | /// Match a ConstantFP or splatted ConstantVector, binding the |
178 | /// specified pointer to the contained APFloat. |
179 | inline apfloat_match m_APFloat(const APFloat *&Res) { return Res; } |
180 | |
181 | template <int64_t Val> struct constantint_match { |
182 | template <typename ITy> bool match(ITy *V) { |
183 | if (const auto *CI = dyn_cast<ConstantInt>(V)) { |
184 | const APInt &CIV = CI->getValue(); |
185 | if (Val >= 0) |
186 | return CIV == static_cast<uint64_t>(Val); |
187 | // If Val is negative, and CI is shorter than it, truncate to the right |
188 | // number of bits. If it is larger, then we have to sign extend. Just |
189 | // compare their negated values. |
190 | return -CIV == -Val; |
191 | } |
192 | return false; |
193 | } |
194 | }; |
195 | |
196 | /// Match a ConstantInt with a specific value. |
197 | template <int64_t Val> inline constantint_match<Val> m_ConstantInt() { |
198 | return constantint_match<Val>(); |
199 | } |
200 | |
201 | /// This helper class is used to match scalar and vector integer constants that |
202 | /// satisfy a specified predicate. |
203 | /// For vector constants, undefined elements are ignored. |
204 | template <typename Predicate> struct cst_pred_ty : public Predicate { |
205 | template <typename ITy> bool match(ITy *V) { |
206 | if (const auto *CI = dyn_cast<ConstantInt>(V)) |
207 | return this->isValue(CI->getValue()); |
208 | if (V->getType()->isVectorTy()) { |
209 | if (const auto *C = dyn_cast<Constant>(V)) { |
210 | if (const auto *CI = dyn_cast_or_null<ConstantInt>(C->getSplatValue())) |
211 | return this->isValue(CI->getValue()); |
212 | |
213 | // Non-splat vector constant: check each element for a match. |
214 | unsigned NumElts = V->getType()->getVectorNumElements(); |
215 | 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-9~svn360825/include/llvm/IR/PatternMatch.h" , 215, __PRETTY_FUNCTION__)); |
216 | bool HasNonUndefElements = false; |
217 | for (unsigned i = 0; i != NumElts; ++i) { |
218 | Constant *Elt = C->getAggregateElement(i); |
219 | if (!Elt) |
220 | return false; |
221 | if (isa<UndefValue>(Elt)) |
222 | continue; |
223 | auto *CI = dyn_cast<ConstantInt>(Elt); |
224 | if (!CI || !this->isValue(CI->getValue())) |
225 | return false; |
226 | HasNonUndefElements = true; |
227 | } |
228 | return HasNonUndefElements; |
229 | } |
230 | } |
231 | return false; |
232 | } |
233 | }; |
234 | |
235 | /// This helper class is used to match scalar and vector constants that |
236 | /// satisfy a specified predicate, and bind them to an APInt. |
237 | template <typename Predicate> struct api_pred_ty : public Predicate { |
238 | const APInt *&Res; |
239 | |
240 | api_pred_ty(const APInt *&R) : Res(R) {} |
241 | |
242 | template <typename ITy> bool match(ITy *V) { |
243 | if (const auto *CI = dyn_cast<ConstantInt>(V)) |
244 | if (this->isValue(CI->getValue())) { |
245 | Res = &CI->getValue(); |
246 | return true; |
247 | } |
248 | if (V->getType()->isVectorTy()) |
249 | if (const auto *C = dyn_cast<Constant>(V)) |
250 | if (auto *CI = dyn_cast_or_null<ConstantInt>(C->getSplatValue())) |
251 | if (this->isValue(CI->getValue())) { |
252 | Res = &CI->getValue(); |
253 | return true; |
254 | } |
255 | |
256 | return false; |
257 | } |
258 | }; |
259 | |
260 | /// This helper class is used to match scalar and vector floating-point |
261 | /// constants that satisfy a specified predicate. |
262 | /// For vector constants, undefined elements are ignored. |
263 | template <typename Predicate> struct cstfp_pred_ty : public Predicate { |
264 | template <typename ITy> bool match(ITy *V) { |
265 | if (const auto *CF = dyn_cast<ConstantFP>(V)) |
266 | return this->isValue(CF->getValueAPF()); |
267 | if (V->getType()->isVectorTy()) { |
268 | if (const auto *C = dyn_cast<Constant>(V)) { |
269 | if (const auto *CF = dyn_cast_or_null<ConstantFP>(C->getSplatValue())) |
270 | return this->isValue(CF->getValueAPF()); |
271 | |
272 | // Non-splat vector constant: check each element for a match. |
273 | unsigned NumElts = V->getType()->getVectorNumElements(); |
274 | 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-9~svn360825/include/llvm/IR/PatternMatch.h" , 274, __PRETTY_FUNCTION__)); |
275 | bool HasNonUndefElements = false; |
276 | for (unsigned i = 0; i != NumElts; ++i) { |
277 | Constant *Elt = C->getAggregateElement(i); |
278 | if (!Elt) |
279 | return false; |
280 | if (isa<UndefValue>(Elt)) |
281 | continue; |
282 | auto *CF = dyn_cast<ConstantFP>(Elt); |
283 | if (!CF || !this->isValue(CF->getValueAPF())) |
284 | return false; |
285 | HasNonUndefElements = true; |
286 | } |
287 | return HasNonUndefElements; |
288 | } |
289 | } |
290 | return false; |
291 | } |
292 | }; |
293 | |
294 | /////////////////////////////////////////////////////////////////////////////// |
295 | // |
296 | // Encapsulate constant value queries for use in templated predicate matchers. |
297 | // This allows checking if constants match using compound predicates and works |
298 | // with vector constants, possibly with relaxed constraints. For example, ignore |
299 | // undef values. |
300 | // |
301 | /////////////////////////////////////////////////////////////////////////////// |
302 | |
303 | struct is_all_ones { |
304 | bool isValue(const APInt &C) { return C.isAllOnesValue(); } |
305 | }; |
306 | /// Match an integer or vector with all bits set. |
307 | /// For vectors, this includes constants with undefined elements. |
308 | inline cst_pred_ty<is_all_ones> m_AllOnes() { |
309 | return cst_pred_ty<is_all_ones>(); |
310 | } |
311 | |
312 | struct is_maxsignedvalue { |
313 | bool isValue(const APInt &C) { return C.isMaxSignedValue(); } |
314 | }; |
315 | /// Match an integer or vector with values having all bits except for the high |
316 | /// bit set (0x7f...). |
317 | /// For vectors, this includes constants with undefined elements. |
318 | inline cst_pred_ty<is_maxsignedvalue> m_MaxSignedValue() { |
319 | return cst_pred_ty<is_maxsignedvalue>(); |
320 | } |
321 | inline api_pred_ty<is_maxsignedvalue> m_MaxSignedValue(const APInt *&V) { |
322 | return V; |
323 | } |
324 | |
325 | struct is_negative { |
326 | bool isValue(const APInt &C) { return C.isNegative(); } |
327 | }; |
328 | /// Match an integer or vector of negative values. |
329 | /// For vectors, this includes constants with undefined elements. |
330 | inline cst_pred_ty<is_negative> m_Negative() { |
331 | return cst_pred_ty<is_negative>(); |
332 | } |
333 | inline api_pred_ty<is_negative> m_Negative(const APInt *&V) { |
334 | return V; |
335 | } |
336 | |
337 | struct is_nonnegative { |
338 | bool isValue(const APInt &C) { return C.isNonNegative(); } |
339 | }; |
340 | /// Match an integer or vector of nonnegative values. |
341 | /// For vectors, this includes constants with undefined elements. |
342 | inline cst_pred_ty<is_nonnegative> m_NonNegative() { |
343 | return cst_pred_ty<is_nonnegative>(); |
344 | } |
345 | inline api_pred_ty<is_nonnegative> m_NonNegative(const APInt *&V) { |
346 | return V; |
347 | } |
348 | |
349 | struct is_one { |
350 | bool isValue(const APInt &C) { return C.isOneValue(); } |
351 | }; |
352 | /// Match an integer 1 or a vector with all elements equal to 1. |
353 | /// For vectors, this includes constants with undefined elements. |
354 | inline cst_pred_ty<is_one> m_One() { |
355 | return cst_pred_ty<is_one>(); |
356 | } |
357 | |
358 | struct is_zero_int { |
359 | bool isValue(const APInt &C) { return C.isNullValue(); } |
360 | }; |
361 | /// Match an integer 0 or a vector with all elements equal to 0. |
362 | /// For vectors, this includes constants with undefined elements. |
363 | inline cst_pred_ty<is_zero_int> m_ZeroInt() { |
364 | return cst_pred_ty<is_zero_int>(); |
365 | } |
366 | |
367 | struct is_zero { |
368 | template <typename ITy> bool match(ITy *V) { |
369 | auto *C = dyn_cast<Constant>(V); |
370 | return C && (C->isNullValue() || cst_pred_ty<is_zero_int>().match(C)); |
371 | } |
372 | }; |
373 | /// Match any null constant or a vector with all elements equal to 0. |
374 | /// For vectors, this includes constants with undefined elements. |
375 | inline is_zero m_Zero() { |
376 | return is_zero(); |
377 | } |
378 | |
379 | struct is_power2 { |
380 | bool isValue(const APInt &C) { return C.isPowerOf2(); } |
381 | }; |
382 | /// Match an integer or vector power-of-2. |
383 | /// For vectors, this includes constants with undefined elements. |
384 | inline cst_pred_ty<is_power2> m_Power2() { |
385 | return cst_pred_ty<is_power2>(); |
386 | } |
387 | inline api_pred_ty<is_power2> m_Power2(const APInt *&V) { |
388 | return V; |
389 | } |
390 | |
391 | struct is_power2_or_zero { |
392 | bool isValue(const APInt &C) { return !C || C.isPowerOf2(); } |
393 | }; |
394 | /// Match an integer or vector of 0 or power-of-2 values. |
395 | /// For vectors, this includes constants with undefined elements. |
396 | inline cst_pred_ty<is_power2_or_zero> m_Power2OrZero() { |
397 | return cst_pred_ty<is_power2_or_zero>(); |
398 | } |
399 | inline api_pred_ty<is_power2_or_zero> m_Power2OrZero(const APInt *&V) { |
400 | return V; |
401 | } |
402 | |
403 | struct is_sign_mask { |
404 | bool isValue(const APInt &C) { return C.isSignMask(); } |
405 | }; |
406 | /// Match an integer or vector with only the sign bit(s) set. |
407 | /// For vectors, this includes constants with undefined elements. |
408 | inline cst_pred_ty<is_sign_mask> m_SignMask() { |
409 | return cst_pred_ty<is_sign_mask>(); |
410 | } |
411 | |
412 | struct is_lowbit_mask { |
413 | bool isValue(const APInt &C) { return C.isMask(); } |
414 | }; |
415 | /// Match an integer or vector with only the low bit(s) set. |
416 | /// For vectors, this includes constants with undefined elements. |
417 | inline cst_pred_ty<is_lowbit_mask> m_LowBitMask() { |
418 | return cst_pred_ty<is_lowbit_mask>(); |
419 | } |
420 | |
421 | struct is_nan { |
422 | bool isValue(const APFloat &C) { return C.isNaN(); } |
423 | }; |
424 | /// Match an arbitrary NaN constant. This includes quiet and signalling nans. |
425 | /// For vectors, this includes constants with undefined elements. |
426 | inline cstfp_pred_ty<is_nan> m_NaN() { |
427 | return cstfp_pred_ty<is_nan>(); |
428 | } |
429 | |
430 | struct is_any_zero_fp { |
431 | bool isValue(const APFloat &C) { return C.isZero(); } |
432 | }; |
433 | /// Match a floating-point negative zero or positive zero. |
434 | /// For vectors, this includes constants with undefined elements. |
435 | inline cstfp_pred_ty<is_any_zero_fp> m_AnyZeroFP() { |
436 | return cstfp_pred_ty<is_any_zero_fp>(); |
437 | } |
438 | |
439 | struct is_pos_zero_fp { |
440 | bool isValue(const APFloat &C) { return C.isPosZero(); } |
441 | }; |
442 | /// Match a floating-point positive zero. |
443 | /// For vectors, this includes constants with undefined elements. |
444 | inline cstfp_pred_ty<is_pos_zero_fp> m_PosZeroFP() { |
445 | return cstfp_pred_ty<is_pos_zero_fp>(); |
446 | } |
447 | |
448 | struct is_neg_zero_fp { |
449 | bool isValue(const APFloat &C) { return C.isNegZero(); } |
450 | }; |
451 | /// Match a floating-point negative zero. |
452 | /// For vectors, this includes constants with undefined elements. |
453 | inline cstfp_pred_ty<is_neg_zero_fp> m_NegZeroFP() { |
454 | return cstfp_pred_ty<is_neg_zero_fp>(); |
455 | } |
456 | |
457 | /////////////////////////////////////////////////////////////////////////////// |
458 | |
459 | template <typename Class> struct bind_ty { |
460 | Class *&VR; |
461 | |
462 | bind_ty(Class *&V) : VR(V) {} |
463 | |
464 | template <typename ITy> bool match(ITy *V) { |
465 | if (auto *CV = dyn_cast<Class>(V)) { |
466 | VR = CV; |
467 | return true; |
468 | } |
469 | return false; |
470 | } |
471 | }; |
472 | |
473 | /// Match a value, capturing it if we match. |
474 | inline bind_ty<Value> m_Value(Value *&V) { return V; } |
475 | inline bind_ty<const Value> m_Value(const Value *&V) { return V; } |
476 | |
477 | /// Match an instruction, capturing it if we match. |
478 | inline bind_ty<Instruction> m_Instruction(Instruction *&I) { return I; } |
479 | /// Match a binary operator, capturing it if we match. |
480 | inline bind_ty<BinaryOperator> m_BinOp(BinaryOperator *&I) { return I; } |
481 | |
482 | /// Match a ConstantInt, capturing the value if we match. |
483 | inline bind_ty<ConstantInt> m_ConstantInt(ConstantInt *&CI) { return CI; } |
484 | |
485 | /// Match a Constant, capturing the value if we match. |
486 | inline bind_ty<Constant> m_Constant(Constant *&C) { return C; } |
487 | |
488 | /// Match a ConstantFP, capturing the value if we match. |
489 | inline bind_ty<ConstantFP> m_ConstantFP(ConstantFP *&C) { return C; } |
490 | |
491 | /// Match a specified Value*. |
492 | struct specificval_ty { |
493 | const Value *Val; |
494 | |
495 | specificval_ty(const Value *V) : Val(V) {} |
496 | |
497 | template <typename ITy> bool match(ITy *V) { return V == Val; } |
498 | }; |
499 | |
500 | /// Match if we have a specific specified value. |
501 | inline specificval_ty m_Specific(const Value *V) { return V; } |
502 | |
503 | /// Stores a reference to the Value *, not the Value * itself, |
504 | /// thus can be used in commutative matchers. |
505 | template <typename Class> struct deferredval_ty { |
506 | Class *const &Val; |
507 | |
508 | deferredval_ty(Class *const &V) : Val(V) {} |
509 | |
510 | template <typename ITy> bool match(ITy *const V) { return V == Val; } |
511 | }; |
512 | |
513 | /// A commutative-friendly version of m_Specific(). |
514 | inline deferredval_ty<Value> m_Deferred(Value *const &V) { return V; } |
515 | inline deferredval_ty<const Value> m_Deferred(const Value *const &V) { |
516 | return V; |
517 | } |
518 | |
519 | /// Match a specified floating point value or vector of all elements of |
520 | /// that value. |
521 | struct specific_fpval { |
522 | double Val; |
523 | |
524 | specific_fpval(double V) : Val(V) {} |
525 | |
526 | template <typename ITy> bool match(ITy *V) { |
527 | if (const auto *CFP = dyn_cast<ConstantFP>(V)) |
528 | return CFP->isExactlyValue(Val); |
529 | if (V->getType()->isVectorTy()) |
530 | if (const auto *C = dyn_cast<Constant>(V)) |
531 | if (auto *CFP = dyn_cast_or_null<ConstantFP>(C->getSplatValue())) |
532 | return CFP->isExactlyValue(Val); |
533 | return false; |
534 | } |
535 | }; |
536 | |
537 | /// Match a specific floating point value or vector with all elements |
538 | /// equal to the value. |
539 | inline specific_fpval m_SpecificFP(double V) { return specific_fpval(V); } |
540 | |
541 | /// Match a float 1.0 or vector with all elements equal to 1.0. |
542 | inline specific_fpval m_FPOne() { return m_SpecificFP(1.0); } |
543 | |
544 | struct bind_const_intval_ty { |
545 | uint64_t &VR; |
546 | |
547 | bind_const_intval_ty(uint64_t &V) : VR(V) {} |
548 | |
549 | template <typename ITy> bool match(ITy *V) { |
550 | if (const auto *CV = dyn_cast<ConstantInt>(V)) |
551 | if (CV->getValue().ule(UINT64_MAX(18446744073709551615UL))) { |
552 | VR = CV->getZExtValue(); |
553 | return true; |
554 | } |
555 | return false; |
556 | } |
557 | }; |
558 | |
559 | /// Match a specified integer value or vector of all elements of that |
560 | // value. |
561 | struct specific_intval { |
562 | uint64_t Val; |
563 | |
564 | specific_intval(uint64_t V) : Val(V) {} |
565 | |
566 | template <typename ITy> bool match(ITy *V) { |
567 | const auto *CI = dyn_cast<ConstantInt>(V); |
568 | if (!CI && V->getType()->isVectorTy()) |
569 | if (const auto *C = dyn_cast<Constant>(V)) |
570 | CI = dyn_cast_or_null<ConstantInt>(C->getSplatValue()); |
571 | |
572 | return CI && CI->getValue() == Val; |
573 | } |
574 | }; |
575 | |
576 | /// Match a specific integer value or vector with all elements equal to |
577 | /// the value. |
578 | inline specific_intval m_SpecificInt(uint64_t V) { return specific_intval(V); } |
579 | |
580 | /// Match a ConstantInt and bind to its value. This does not match |
581 | /// ConstantInts wider than 64-bits. |
582 | inline bind_const_intval_ty m_ConstantInt(uint64_t &V) { return V; } |
583 | |
584 | //===----------------------------------------------------------------------===// |
585 | // Matcher for any binary operator. |
586 | // |
587 | template <typename LHS_t, typename RHS_t, bool Commutable = false> |
588 | struct AnyBinaryOp_match { |
589 | LHS_t L; |
590 | RHS_t R; |
591 | |
592 | // The evaluation order is always stable, regardless of Commutability. |
593 | // The LHS is always matched first. |
594 | AnyBinaryOp_match(const LHS_t &LHS, const RHS_t &RHS) : L(LHS), R(RHS) {} |
595 | |
596 | template <typename OpTy> bool match(OpTy *V) { |
597 | if (auto *I = dyn_cast<BinaryOperator>(V)) |
598 | return (L.match(I->getOperand(0)) && R.match(I->getOperand(1))) || |
599 | (Commutable && L.match(I->getOperand(1)) && |
600 | R.match(I->getOperand(0))); |
601 | return false; |
602 | } |
603 | }; |
604 | |
605 | template <typename LHS, typename RHS> |
606 | inline AnyBinaryOp_match<LHS, RHS> m_BinOp(const LHS &L, const RHS &R) { |
607 | return AnyBinaryOp_match<LHS, RHS>(L, R); |
608 | } |
609 | |
610 | //===----------------------------------------------------------------------===// |
611 | // Matchers for specific binary operators. |
612 | // |
613 | |
614 | template <typename LHS_t, typename RHS_t, unsigned Opcode, |
615 | bool Commutable = false> |
616 | struct BinaryOp_match { |
617 | LHS_t L; |
618 | RHS_t R; |
619 | |
620 | // The evaluation order is always stable, regardless of Commutability. |
621 | // The LHS is always matched first. |
622 | BinaryOp_match(const LHS_t &LHS, const RHS_t &RHS) : L(LHS), R(RHS) {} |
623 | |
624 | template <typename OpTy> bool match(OpTy *V) { |
625 | if (V->getValueID() == Value::InstructionVal + Opcode) { |
626 | auto *I = cast<BinaryOperator>(V); |
627 | return (L.match(I->getOperand(0)) && R.match(I->getOperand(1))) || |
628 | (Commutable && L.match(I->getOperand(1)) && |
629 | R.match(I->getOperand(0))); |
630 | } |
631 | if (auto *CE = dyn_cast<ConstantExpr>(V)) |
632 | return CE->getOpcode() == Opcode && |
633 | ((L.match(CE->getOperand(0)) && R.match(CE->getOperand(1))) || |
634 | (Commutable && L.match(CE->getOperand(1)) && |
635 | R.match(CE->getOperand(0)))); |
636 | return false; |
637 | } |
638 | }; |
639 | |
640 | template <typename LHS, typename RHS> |
641 | inline BinaryOp_match<LHS, RHS, Instruction::Add> m_Add(const LHS &L, |
642 | const RHS &R) { |
643 | return BinaryOp_match<LHS, RHS, Instruction::Add>(L, R); |
644 | } |
645 | |
646 | template <typename LHS, typename RHS> |
647 | inline BinaryOp_match<LHS, RHS, Instruction::FAdd> m_FAdd(const LHS &L, |
648 | const RHS &R) { |
649 | return BinaryOp_match<LHS, RHS, Instruction::FAdd>(L, R); |
650 | } |
651 | |
652 | template <typename LHS, typename RHS> |
653 | inline BinaryOp_match<LHS, RHS, Instruction::Sub> m_Sub(const LHS &L, |
654 | const RHS &R) { |
655 | return BinaryOp_match<LHS, RHS, Instruction::Sub>(L, R); |
656 | } |
657 | |
658 | template <typename LHS, typename RHS> |
659 | inline BinaryOp_match<LHS, RHS, Instruction::FSub> m_FSub(const LHS &L, |
660 | const RHS &R) { |
661 | return BinaryOp_match<LHS, RHS, Instruction::FSub>(L, R); |
662 | } |
663 | |
664 | template <typename Op_t> struct FNeg_match { |
665 | Op_t X; |
666 | |
667 | FNeg_match(const Op_t &Op) : X(Op) {} |
668 | template <typename OpTy> bool match(OpTy *V) { |
669 | auto *FPMO = dyn_cast<FPMathOperator>(V); |
670 | if (!FPMO) return false; |
671 | |
672 | if (FPMO->getOpcode() == Instruction::FNeg) |
673 | return X.match(FPMO->getOperand(0)); |
674 | |
675 | if (FPMO->getOpcode() == Instruction::FSub) { |
676 | if (FPMO->hasNoSignedZeros()) { |
677 | // With 'nsz', any zero goes. |
678 | if (!cstfp_pred_ty<is_any_zero_fp>().match(FPMO->getOperand(0))) |
679 | return false; |
680 | } else { |
681 | // Without 'nsz', we need fsub -0.0, X exactly. |
682 | if (!cstfp_pred_ty<is_neg_zero_fp>().match(FPMO->getOperand(0))) |
683 | return false; |
684 | } |
685 | |
686 | return X.match(FPMO->getOperand(1)); |
687 | } |
688 | |
689 | return false; |
690 | } |
691 | }; |
692 | |
693 | /// Match 'fneg X' as 'fsub -0.0, X'. |
694 | template <typename OpTy> |
695 | inline FNeg_match<OpTy> |
696 | m_FNeg(const OpTy &X) { |
697 | return FNeg_match<OpTy>(X); |
698 | } |
699 | |
700 | /// Match 'fneg X' as 'fsub +-0.0, X'. |
701 | template <typename RHS> |
702 | inline BinaryOp_match<cstfp_pred_ty<is_any_zero_fp>, RHS, Instruction::FSub> |
703 | m_FNegNSZ(const RHS &X) { |
704 | return m_FSub(m_AnyZeroFP(), X); |
705 | } |
706 | |
707 | template <typename LHS, typename RHS> |
708 | inline BinaryOp_match<LHS, RHS, Instruction::Mul> m_Mul(const LHS &L, |
709 | const RHS &R) { |
710 | return BinaryOp_match<LHS, RHS, Instruction::Mul>(L, R); |
711 | } |
712 | |
713 | template <typename LHS, typename RHS> |
714 | inline BinaryOp_match<LHS, RHS, Instruction::FMul> m_FMul(const LHS &L, |
715 | const RHS &R) { |
716 | return BinaryOp_match<LHS, RHS, Instruction::FMul>(L, R); |
717 | } |
718 | |
719 | template <typename LHS, typename RHS> |
720 | inline BinaryOp_match<LHS, RHS, Instruction::UDiv> m_UDiv(const LHS &L, |
721 | const RHS &R) { |
722 | return BinaryOp_match<LHS, RHS, Instruction::UDiv>(L, R); |
723 | } |
724 | |
725 | template <typename LHS, typename RHS> |
726 | inline BinaryOp_match<LHS, RHS, Instruction::SDiv> m_SDiv(const LHS &L, |
727 | const RHS &R) { |
728 | return BinaryOp_match<LHS, RHS, Instruction::SDiv>(L, R); |
729 | } |
730 | |
731 | template <typename LHS, typename RHS> |
732 | inline BinaryOp_match<LHS, RHS, Instruction::FDiv> m_FDiv(const LHS &L, |
733 | const RHS &R) { |
734 | return BinaryOp_match<LHS, RHS, Instruction::FDiv>(L, R); |
735 | } |
736 | |
737 | template <typename LHS, typename RHS> |
738 | inline BinaryOp_match<LHS, RHS, Instruction::URem> m_URem(const LHS &L, |
739 | const RHS &R) { |
740 | return BinaryOp_match<LHS, RHS, Instruction::URem>(L, R); |
741 | } |
742 | |
743 | template <typename LHS, typename RHS> |
744 | inline BinaryOp_match<LHS, RHS, Instruction::SRem> m_SRem(const LHS &L, |
745 | const RHS &R) { |
746 | return BinaryOp_match<LHS, RHS, Instruction::SRem>(L, R); |
747 | } |
748 | |
749 | template <typename LHS, typename RHS> |
750 | inline BinaryOp_match<LHS, RHS, Instruction::FRem> m_FRem(const LHS &L, |
751 | const RHS &R) { |
752 | return BinaryOp_match<LHS, RHS, Instruction::FRem>(L, R); |
753 | } |
754 | |
755 | template <typename LHS, typename RHS> |
756 | inline BinaryOp_match<LHS, RHS, Instruction::And> m_And(const LHS &L, |
757 | const RHS &R) { |
758 | return BinaryOp_match<LHS, RHS, Instruction::And>(L, R); |
759 | } |
760 | |
761 | template <typename LHS, typename RHS> |
762 | inline BinaryOp_match<LHS, RHS, Instruction::Or> m_Or(const LHS &L, |
763 | const RHS &R) { |
764 | return BinaryOp_match<LHS, RHS, Instruction::Or>(L, R); |
765 | } |
766 | |
767 | template <typename LHS, typename RHS> |
768 | inline BinaryOp_match<LHS, RHS, Instruction::Xor> m_Xor(const LHS &L, |
769 | const RHS &R) { |
770 | return BinaryOp_match<LHS, RHS, Instruction::Xor>(L, R); |
771 | } |
772 | |
773 | template <typename LHS, typename RHS> |
774 | inline BinaryOp_match<LHS, RHS, Instruction::Shl> m_Shl(const LHS &L, |
775 | const RHS &R) { |
776 | return BinaryOp_match<LHS, RHS, Instruction::Shl>(L, R); |
777 | } |
778 | |
779 | template <typename LHS, typename RHS> |
780 | inline BinaryOp_match<LHS, RHS, Instruction::LShr> m_LShr(const LHS &L, |
781 | const RHS &R) { |
782 | return BinaryOp_match<LHS, RHS, Instruction::LShr>(L, R); |
783 | } |
784 | |
785 | template <typename LHS, typename RHS> |
786 | inline BinaryOp_match<LHS, RHS, Instruction::AShr> m_AShr(const LHS &L, |
787 | const RHS &R) { |
788 | return BinaryOp_match<LHS, RHS, Instruction::AShr>(L, R); |
789 | } |
790 | |
791 | template <typename LHS_t, typename RHS_t, unsigned Opcode, |
792 | unsigned WrapFlags = 0> |
793 | struct OverflowingBinaryOp_match { |
794 | LHS_t L; |
795 | RHS_t R; |
796 | |
797 | OverflowingBinaryOp_match(const LHS_t &LHS, const RHS_t &RHS) |
798 | : L(LHS), R(RHS) {} |
799 | |
800 | template <typename OpTy> bool match(OpTy *V) { |
801 | if (auto *Op = dyn_cast<OverflowingBinaryOperator>(V)) { |
802 | if (Op->getOpcode() != Opcode) |
803 | return false; |
804 | if (WrapFlags & OverflowingBinaryOperator::NoUnsignedWrap && |
805 | !Op->hasNoUnsignedWrap()) |
806 | return false; |
807 | if (WrapFlags & OverflowingBinaryOperator::NoSignedWrap && |
808 | !Op->hasNoSignedWrap()) |
809 | return false; |
810 | return L.match(Op->getOperand(0)) && R.match(Op->getOperand(1)); |
811 | } |
812 | return false; |
813 | } |
814 | }; |
815 | |
816 | template <typename LHS, typename RHS> |
817 | inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Add, |
818 | OverflowingBinaryOperator::NoSignedWrap> |
819 | m_NSWAdd(const LHS &L, const RHS &R) { |
820 | return OverflowingBinaryOp_match<LHS, RHS, Instruction::Add, |
821 | OverflowingBinaryOperator::NoSignedWrap>( |
822 | L, R); |
823 | } |
824 | template <typename LHS, typename RHS> |
825 | inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Sub, |
826 | OverflowingBinaryOperator::NoSignedWrap> |
827 | m_NSWSub(const LHS &L, const RHS &R) { |
828 | return OverflowingBinaryOp_match<LHS, RHS, Instruction::Sub, |
829 | OverflowingBinaryOperator::NoSignedWrap>( |
830 | L, R); |
831 | } |
832 | template <typename LHS, typename RHS> |
833 | inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Mul, |
834 | OverflowingBinaryOperator::NoSignedWrap> |
835 | m_NSWMul(const LHS &L, const RHS &R) { |
836 | return OverflowingBinaryOp_match<LHS, RHS, Instruction::Mul, |
837 | OverflowingBinaryOperator::NoSignedWrap>( |
838 | L, R); |
839 | } |
840 | template <typename LHS, typename RHS> |
841 | inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Shl, |
842 | OverflowingBinaryOperator::NoSignedWrap> |
843 | m_NSWShl(const LHS &L, const RHS &R) { |
844 | return OverflowingBinaryOp_match<LHS, RHS, Instruction::Shl, |
845 | OverflowingBinaryOperator::NoSignedWrap>( |
846 | L, R); |
847 | } |
848 | |
849 | template <typename LHS, typename RHS> |
850 | inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Add, |
851 | OverflowingBinaryOperator::NoUnsignedWrap> |
852 | m_NUWAdd(const LHS &L, const RHS &R) { |
853 | return OverflowingBinaryOp_match<LHS, RHS, Instruction::Add, |
854 | OverflowingBinaryOperator::NoUnsignedWrap>( |
855 | L, R); |
856 | } |
857 | template <typename LHS, typename RHS> |
858 | inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Sub, |
859 | OverflowingBinaryOperator::NoUnsignedWrap> |
860 | m_NUWSub(const LHS &L, const RHS &R) { |
861 | return OverflowingBinaryOp_match<LHS, RHS, Instruction::Sub, |
862 | OverflowingBinaryOperator::NoUnsignedWrap>( |
863 | L, R); |
864 | } |
865 | template <typename LHS, typename RHS> |
866 | inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Mul, |
867 | OverflowingBinaryOperator::NoUnsignedWrap> |
868 | m_NUWMul(const LHS &L, const RHS &R) { |
869 | return OverflowingBinaryOp_match<LHS, RHS, Instruction::Mul, |
870 | OverflowingBinaryOperator::NoUnsignedWrap>( |
871 | L, R); |
872 | } |
873 | template <typename LHS, typename RHS> |
874 | inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Shl, |
875 | OverflowingBinaryOperator::NoUnsignedWrap> |
876 | m_NUWShl(const LHS &L, const RHS &R) { |
877 | return OverflowingBinaryOp_match<LHS, RHS, Instruction::Shl, |
878 | OverflowingBinaryOperator::NoUnsignedWrap>( |
879 | L, R); |
880 | } |
881 | |
882 | //===----------------------------------------------------------------------===// |
883 | // Class that matches a group of binary opcodes. |
884 | // |
885 | template <typename LHS_t, typename RHS_t, typename Predicate> |
886 | struct BinOpPred_match : Predicate { |
887 | LHS_t L; |
888 | RHS_t R; |
889 | |
890 | BinOpPred_match(const LHS_t &LHS, const RHS_t &RHS) : L(LHS), R(RHS) {} |
891 | |
892 | template <typename OpTy> bool match(OpTy *V) { |
893 | if (auto *I = dyn_cast<Instruction>(V)) |
894 | return this->isOpType(I->getOpcode()) && L.match(I->getOperand(0)) && |
895 | R.match(I->getOperand(1)); |
896 | if (auto *CE = dyn_cast<ConstantExpr>(V)) |
897 | return this->isOpType(CE->getOpcode()) && L.match(CE->getOperand(0)) && |
898 | R.match(CE->getOperand(1)); |
899 | return false; |
900 | } |
901 | }; |
902 | |
903 | struct is_shift_op { |
904 | bool isOpType(unsigned Opcode) { return Instruction::isShift(Opcode); } |
905 | }; |
906 | |
907 | struct is_right_shift_op { |
908 | bool isOpType(unsigned Opcode) { |
909 | return Opcode == Instruction::LShr || Opcode == Instruction::AShr; |
910 | } |
911 | }; |
912 | |
913 | struct is_logical_shift_op { |
914 | bool isOpType(unsigned Opcode) { |
915 | return Opcode == Instruction::LShr || Opcode == Instruction::Shl; |
916 | } |
917 | }; |
918 | |
919 | struct is_bitwiselogic_op { |
920 | bool isOpType(unsigned Opcode) { |
921 | return Instruction::isBitwiseLogicOp(Opcode); |
922 | } |
923 | }; |
924 | |
925 | struct is_idiv_op { |
926 | bool isOpType(unsigned Opcode) { |
927 | return Opcode == Instruction::SDiv || Opcode == Instruction::UDiv; |
928 | } |
929 | }; |
930 | |
931 | /// Matches shift operations. |
932 | template <typename LHS, typename RHS> |
933 | inline BinOpPred_match<LHS, RHS, is_shift_op> m_Shift(const LHS &L, |
934 | const RHS &R) { |
935 | return BinOpPred_match<LHS, RHS, is_shift_op>(L, R); |
936 | } |
937 | |
938 | /// Matches logical shift operations. |
939 | template <typename LHS, typename RHS> |
940 | inline BinOpPred_match<LHS, RHS, is_right_shift_op> m_Shr(const LHS &L, |
941 | const RHS &R) { |
942 | return BinOpPred_match<LHS, RHS, is_right_shift_op>(L, R); |
943 | } |
944 | |
945 | /// Matches logical shift operations. |
946 | template <typename LHS, typename RHS> |
947 | inline BinOpPred_match<LHS, RHS, is_logical_shift_op> |
948 | m_LogicalShift(const LHS &L, const RHS &R) { |
949 | return BinOpPred_match<LHS, RHS, is_logical_shift_op>(L, R); |
950 | } |
951 | |
952 | /// Matches bitwise logic operations. |
953 | template <typename LHS, typename RHS> |
954 | inline BinOpPred_match<LHS, RHS, is_bitwiselogic_op> |
955 | m_BitwiseLogic(const LHS &L, const RHS &R) { |
956 | return BinOpPred_match<LHS, RHS, is_bitwiselogic_op>(L, R); |
957 | } |
958 | |
959 | /// Matches integer division operations. |
960 | template <typename LHS, typename RHS> |
961 | inline BinOpPred_match<LHS, RHS, is_idiv_op> m_IDiv(const LHS &L, |
962 | const RHS &R) { |
963 | return BinOpPred_match<LHS, RHS, is_idiv_op>(L, R); |
964 | } |
965 | |
966 | //===----------------------------------------------------------------------===// |
967 | // Class that matches exact binary ops. |
968 | // |
969 | template <typename SubPattern_t> struct Exact_match { |
970 | SubPattern_t SubPattern; |
971 | |
972 | Exact_match(const SubPattern_t &SP) : SubPattern(SP) {} |
973 | |
974 | template <typename OpTy> bool match(OpTy *V) { |
975 | if (auto *PEO = dyn_cast<PossiblyExactOperator>(V)) |
976 | return PEO->isExact() && SubPattern.match(V); |
977 | return false; |
978 | } |
979 | }; |
980 | |
981 | template <typename T> inline Exact_match<T> m_Exact(const T &SubPattern) { |
982 | return SubPattern; |
983 | } |
984 | |
985 | //===----------------------------------------------------------------------===// |
986 | // Matchers for CmpInst classes |
987 | // |
988 | |
989 | template <typename LHS_t, typename RHS_t, typename Class, typename PredicateTy, |
990 | bool Commutable = false> |
991 | struct CmpClass_match { |
992 | PredicateTy &Predicate; |
993 | LHS_t L; |
994 | RHS_t R; |
995 | |
996 | // The evaluation order is always stable, regardless of Commutability. |
997 | // The LHS is always matched first. |
998 | CmpClass_match(PredicateTy &Pred, const LHS_t &LHS, const RHS_t &RHS) |
999 | : Predicate(Pred), L(LHS), R(RHS) {} |
1000 | |
1001 | template <typename OpTy> bool match(OpTy *V) { |
1002 | if (auto *I = dyn_cast<Class>(V)) |
1003 | if ((L.match(I->getOperand(0)) && R.match(I->getOperand(1))) || |
1004 | (Commutable && L.match(I->getOperand(1)) && |
1005 | R.match(I->getOperand(0)))) { |
1006 | Predicate = I->getPredicate(); |
1007 | return true; |
1008 | } |
1009 | return false; |
1010 | } |
1011 | }; |
1012 | |
1013 | template <typename LHS, typename RHS> |
1014 | inline CmpClass_match<LHS, RHS, CmpInst, CmpInst::Predicate> |
1015 | m_Cmp(CmpInst::Predicate &Pred, const LHS &L, const RHS &R) { |
1016 | return CmpClass_match<LHS, RHS, CmpInst, CmpInst::Predicate>(Pred, L, R); |
1017 | } |
1018 | |
1019 | template <typename LHS, typename RHS> |
1020 | inline CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate> |
1021 | m_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R) { |
1022 | return CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>(Pred, L, R); |
1023 | } |
1024 | |
1025 | template <typename LHS, typename RHS> |
1026 | inline CmpClass_match<LHS, RHS, FCmpInst, FCmpInst::Predicate> |
1027 | m_FCmp(FCmpInst::Predicate &Pred, const LHS &L, const RHS &R) { |
1028 | return CmpClass_match<LHS, RHS, FCmpInst, FCmpInst::Predicate>(Pred, L, R); |
1029 | } |
1030 | |
1031 | //===----------------------------------------------------------------------===// |
1032 | // Matchers for instructions with a given opcode and number of operands. |
1033 | // |
1034 | |
1035 | /// Matches instructions with Opcode and three operands. |
1036 | template <typename T0, unsigned Opcode> struct OneOps_match { |
1037 | T0 Op1; |
1038 | |
1039 | OneOps_match(const T0 &Op1) : Op1(Op1) {} |
1040 | |
1041 | template <typename OpTy> bool match(OpTy *V) { |
1042 | if (V->getValueID() == Value::InstructionVal + Opcode) { |
1043 | auto *I = cast<Instruction>(V); |
1044 | return Op1.match(I->getOperand(0)); |
1045 | } |
1046 | return false; |
1047 | } |
1048 | }; |
1049 | |
1050 | /// Matches instructions with Opcode and three operands. |
1051 | template <typename T0, typename T1, unsigned Opcode> struct TwoOps_match { |
1052 | T0 Op1; |
1053 | T1 Op2; |
1054 | |
1055 | TwoOps_match(const T0 &Op1, const T1 &Op2) : Op1(Op1), Op2(Op2) {} |
1056 | |
1057 | template <typename OpTy> bool match(OpTy *V) { |
1058 | if (V->getValueID() == Value::InstructionVal + Opcode) { |
1059 | auto *I = cast<Instruction>(V); |
1060 | return Op1.match(I->getOperand(0)) && Op2.match(I->getOperand(1)); |
1061 | } |
1062 | return false; |
1063 | } |
1064 | }; |
1065 | |
1066 | /// Matches instructions with Opcode and three operands. |
1067 | template <typename T0, typename T1, typename T2, unsigned Opcode> |
1068 | struct ThreeOps_match { |
1069 | T0 Op1; |
1070 | T1 Op2; |
1071 | T2 Op3; |
1072 | |
1073 | ThreeOps_match(const T0 &Op1, const T1 &Op2, const T2 &Op3) |
1074 | : Op1(Op1), Op2(Op2), Op3(Op3) {} |
1075 | |
1076 | template <typename OpTy> bool match(OpTy *V) { |
1077 | if (V->getValueID() == Value::InstructionVal + Opcode) { |
1078 | auto *I = cast<Instruction>(V); |
1079 | return Op1.match(I->getOperand(0)) && Op2.match(I->getOperand(1)) && |
1080 | Op3.match(I->getOperand(2)); |
1081 | } |
1082 | return false; |
1083 | } |
1084 | }; |
1085 | |
1086 | /// Matches SelectInst. |
1087 | template <typename Cond, typename LHS, typename RHS> |
1088 | inline ThreeOps_match<Cond, LHS, RHS, Instruction::Select> |
1089 | m_Select(const Cond &C, const LHS &L, const RHS &R) { |
1090 | return ThreeOps_match<Cond, LHS, RHS, Instruction::Select>(C, L, R); |
1091 | } |
1092 | |
1093 | /// This matches a select of two constants, e.g.: |
1094 | /// m_SelectCst<-1, 0>(m_Value(V)) |
1095 | template <int64_t L, int64_t R, typename Cond> |
1096 | inline ThreeOps_match<Cond, constantint_match<L>, constantint_match<R>, |
1097 | Instruction::Select> |
1098 | m_SelectCst(const Cond &C) { |
1099 | return m_Select(C, m_ConstantInt<L>(), m_ConstantInt<R>()); |
1100 | } |
1101 | |
1102 | /// Matches InsertElementInst. |
1103 | template <typename Val_t, typename Elt_t, typename Idx_t> |
1104 | inline ThreeOps_match<Val_t, Elt_t, Idx_t, Instruction::InsertElement> |
1105 | m_InsertElement(const Val_t &Val, const Elt_t &Elt, const Idx_t &Idx) { |
1106 | return ThreeOps_match<Val_t, Elt_t, Idx_t, Instruction::InsertElement>( |
1107 | Val, Elt, Idx); |
1108 | } |
1109 | |
1110 | /// Matches ExtractElementInst. |
1111 | template <typename Val_t, typename Idx_t> |
1112 | inline TwoOps_match<Val_t, Idx_t, Instruction::ExtractElement> |
1113 | m_ExtractElement(const Val_t &Val, const Idx_t &Idx) { |
1114 | return TwoOps_match<Val_t, Idx_t, Instruction::ExtractElement>(Val, Idx); |
1115 | } |
1116 | |
1117 | /// Matches ShuffleVectorInst. |
1118 | template <typename V1_t, typename V2_t, typename Mask_t> |
1119 | inline ThreeOps_match<V1_t, V2_t, Mask_t, Instruction::ShuffleVector> |
1120 | m_ShuffleVector(const V1_t &v1, const V2_t &v2, const Mask_t &m) { |
1121 | return ThreeOps_match<V1_t, V2_t, Mask_t, Instruction::ShuffleVector>(v1, v2, |
1122 | m); |
1123 | } |
1124 | |
1125 | /// Matches LoadInst. |
1126 | template <typename OpTy> |
1127 | inline OneOps_match<OpTy, Instruction::Load> m_Load(const OpTy &Op) { |
1128 | return OneOps_match<OpTy, Instruction::Load>(Op); |
1129 | } |
1130 | |
1131 | /// Matches StoreInst. |
1132 | template <typename ValueOpTy, typename PointerOpTy> |
1133 | inline TwoOps_match<ValueOpTy, PointerOpTy, Instruction::Store> |
1134 | m_Store(const ValueOpTy &ValueOp, const PointerOpTy &PointerOp) { |
1135 | return TwoOps_match<ValueOpTy, PointerOpTy, Instruction::Store>(ValueOp, |
1136 | PointerOp); |
1137 | } |
1138 | |
1139 | //===----------------------------------------------------------------------===// |
1140 | // Matchers for CastInst classes |
1141 | // |
1142 | |
1143 | template <typename Op_t, unsigned Opcode> struct CastClass_match { |
1144 | Op_t Op; |
1145 | |
1146 | CastClass_match(const Op_t &OpMatch) : Op(OpMatch) {} |
1147 | |
1148 | template <typename OpTy> bool match(OpTy *V) { |
1149 | if (auto *O = dyn_cast<Operator>(V)) |
1150 | return O->getOpcode() == Opcode && Op.match(O->getOperand(0)); |
1151 | return false; |
1152 | } |
1153 | }; |
1154 | |
1155 | /// Matches BitCast. |
1156 | template <typename OpTy> |
1157 | inline CastClass_match<OpTy, Instruction::BitCast> m_BitCast(const OpTy &Op) { |
1158 | return CastClass_match<OpTy, Instruction::BitCast>(Op); |
1159 | } |
1160 | |
1161 | /// Matches PtrToInt. |
1162 | template <typename OpTy> |
1163 | inline CastClass_match<OpTy, Instruction::PtrToInt> m_PtrToInt(const OpTy &Op) { |
1164 | return CastClass_match<OpTy, Instruction::PtrToInt>(Op); |
1165 | } |
1166 | |
1167 | /// Matches Trunc. |
1168 | template <typename OpTy> |
1169 | inline CastClass_match<OpTy, Instruction::Trunc> m_Trunc(const OpTy &Op) { |
1170 | return CastClass_match<OpTy, Instruction::Trunc>(Op); |
1171 | } |
1172 | |
1173 | /// Matches SExt. |
1174 | template <typename OpTy> |
1175 | inline CastClass_match<OpTy, Instruction::SExt> m_SExt(const OpTy &Op) { |
1176 | return CastClass_match<OpTy, Instruction::SExt>(Op); |
1177 | } |
1178 | |
1179 | /// Matches ZExt. |
1180 | template <typename OpTy> |
1181 | inline CastClass_match<OpTy, Instruction::ZExt> m_ZExt(const OpTy &Op) { |
1182 | return CastClass_match<OpTy, Instruction::ZExt>(Op); |
1183 | } |
1184 | |
1185 | template <typename OpTy> |
1186 | inline match_combine_or<CastClass_match<OpTy, Instruction::ZExt>, |
1187 | CastClass_match<OpTy, Instruction::SExt>> |
1188 | m_ZExtOrSExt(const OpTy &Op) { |
1189 | return m_CombineOr(m_ZExt(Op), m_SExt(Op)); |
1190 | } |
1191 | |
1192 | /// Matches UIToFP. |
1193 | template <typename OpTy> |
1194 | inline CastClass_match<OpTy, Instruction::UIToFP> m_UIToFP(const OpTy &Op) { |
1195 | return CastClass_match<OpTy, Instruction::UIToFP>(Op); |
1196 | } |
1197 | |
1198 | /// Matches SIToFP. |
1199 | template <typename OpTy> |
1200 | inline CastClass_match<OpTy, Instruction::SIToFP> m_SIToFP(const OpTy &Op) { |
1201 | return CastClass_match<OpTy, Instruction::SIToFP>(Op); |
1202 | } |
1203 | |
1204 | /// Matches FPTrunc |
1205 | template <typename OpTy> |
1206 | inline CastClass_match<OpTy, Instruction::FPTrunc> m_FPTrunc(const OpTy &Op) { |
1207 | return CastClass_match<OpTy, Instruction::FPTrunc>(Op); |
1208 | } |
1209 | |
1210 | /// Matches FPExt |
1211 | template <typename OpTy> |
1212 | inline CastClass_match<OpTy, Instruction::FPExt> m_FPExt(const OpTy &Op) { |
1213 | return CastClass_match<OpTy, Instruction::FPExt>(Op); |
1214 | } |
1215 | |
1216 | //===----------------------------------------------------------------------===// |
1217 | // Matchers for control flow. |
1218 | // |
1219 | |
1220 | struct br_match { |
1221 | BasicBlock *&Succ; |
1222 | |
1223 | br_match(BasicBlock *&Succ) : Succ(Succ) {} |
1224 | |
1225 | template <typename OpTy> bool match(OpTy *V) { |
1226 | if (auto *BI = dyn_cast<BranchInst>(V)) |
1227 | if (BI->isUnconditional()) { |
1228 | Succ = BI->getSuccessor(0); |
1229 | return true; |
1230 | } |
1231 | return false; |
1232 | } |
1233 | }; |
1234 | |
1235 | inline br_match m_UnconditionalBr(BasicBlock *&Succ) { return br_match(Succ); } |
1236 | |
1237 | template <typename Cond_t> struct brc_match { |
1238 | Cond_t Cond; |
1239 | BasicBlock *&T, *&F; |
1240 | |
1241 | brc_match(const Cond_t &C, BasicBlock *&t, BasicBlock *&f) |
1242 | : Cond(C), T(t), F(f) {} |
1243 | |
1244 | template <typename OpTy> bool match(OpTy *V) { |
1245 | if (auto *BI = dyn_cast<BranchInst>(V)) |
1246 | if (BI->isConditional() && Cond.match(BI->getCondition())) { |
1247 | T = BI->getSuccessor(0); |
1248 | F = BI->getSuccessor(1); |
1249 | return true; |
1250 | } |
1251 | return false; |
1252 | } |
1253 | }; |
1254 | |
1255 | template <typename Cond_t> |
1256 | inline brc_match<Cond_t> m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F) { |
1257 | return brc_match<Cond_t>(C, T, F); |
1258 | } |
1259 | |
1260 | //===----------------------------------------------------------------------===// |
1261 | // Matchers for max/min idioms, eg: "select (sgt x, y), x, y" -> smax(x,y). |
1262 | // |
1263 | |
1264 | template <typename CmpInst_t, typename LHS_t, typename RHS_t, typename Pred_t, |
1265 | bool Commutable = false> |
1266 | struct MaxMin_match { |
1267 | LHS_t L; |
1268 | RHS_t R; |
1269 | |
1270 | // The evaluation order is always stable, regardless of Commutability. |
1271 | // The LHS is always matched first. |
1272 | MaxMin_match(const LHS_t &LHS, const RHS_t &RHS) : L(LHS), R(RHS) {} |
1273 | |
1274 | template <typename OpTy> bool match(OpTy *V) { |
1275 | // Look for "(x pred y) ? x : y" or "(x pred y) ? y : x". |
1276 | auto *SI = dyn_cast<SelectInst>(V); |
1277 | if (!SI) |
1278 | return false; |
1279 | auto *Cmp = dyn_cast<CmpInst_t>(SI->getCondition()); |
1280 | if (!Cmp) |
1281 | return false; |
1282 | // At this point we have a select conditioned on a comparison. Check that |
1283 | // it is the values returned by the select that are being compared. |
1284 | Value *TrueVal = SI->getTrueValue(); |
1285 | Value *FalseVal = SI->getFalseValue(); |
1286 | Value *LHS = Cmp->getOperand(0); |
1287 | Value *RHS = Cmp->getOperand(1); |
1288 | if ((TrueVal != LHS || FalseVal != RHS) && |
1289 | (TrueVal != RHS || FalseVal != LHS)) |
1290 | return false; |
1291 | typename CmpInst_t::Predicate Pred = |
1292 | LHS == TrueVal ? Cmp->getPredicate() : Cmp->getInversePredicate(); |
1293 | // Does "(x pred y) ? x : y" represent the desired max/min operation? |
1294 | if (!Pred_t::match(Pred)) |
1295 | return false; |
1296 | // It does! Bind the operands. |
1297 | return (L.match(LHS) && R.match(RHS)) || |
1298 | (Commutable && L.match(RHS) && R.match(LHS)); |
1299 | } |
1300 | }; |
1301 | |
1302 | /// Helper class for identifying signed max predicates. |
1303 | struct smax_pred_ty { |
1304 | static bool match(ICmpInst::Predicate Pred) { |
1305 | return Pred == CmpInst::ICMP_SGT || Pred == CmpInst::ICMP_SGE; |
1306 | } |
1307 | }; |
1308 | |
1309 | /// Helper class for identifying signed min predicates. |
1310 | struct smin_pred_ty { |
1311 | static bool match(ICmpInst::Predicate Pred) { |
1312 | return Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_SLE; |
1313 | } |
1314 | }; |
1315 | |
1316 | /// Helper class for identifying unsigned max predicates. |
1317 | struct umax_pred_ty { |
1318 | static bool match(ICmpInst::Predicate Pred) { |
1319 | return Pred == CmpInst::ICMP_UGT || Pred == CmpInst::ICMP_UGE; |
1320 | } |
1321 | }; |
1322 | |
1323 | /// Helper class for identifying unsigned min predicates. |
1324 | struct umin_pred_ty { |
1325 | static bool match(ICmpInst::Predicate Pred) { |
1326 | return Pred == CmpInst::ICMP_ULT || Pred == CmpInst::ICMP_ULE; |
1327 | } |
1328 | }; |
1329 | |
1330 | /// Helper class for identifying ordered max predicates. |
1331 | struct ofmax_pred_ty { |
1332 | static bool match(FCmpInst::Predicate Pred) { |
1333 | return Pred == CmpInst::FCMP_OGT || Pred == CmpInst::FCMP_OGE; |
1334 | } |
1335 | }; |
1336 | |
1337 | /// Helper class for identifying ordered min predicates. |
1338 | struct ofmin_pred_ty { |
1339 | static bool match(FCmpInst::Predicate Pred) { |
1340 | return Pred == CmpInst::FCMP_OLT || Pred == CmpInst::FCMP_OLE; |
1341 | } |
1342 | }; |
1343 | |
1344 | /// Helper class for identifying unordered max predicates. |
1345 | struct ufmax_pred_ty { |
1346 | static bool match(FCmpInst::Predicate Pred) { |
1347 | return Pred == CmpInst::FCMP_UGT || Pred == CmpInst::FCMP_UGE; |
1348 | } |
1349 | }; |
1350 | |
1351 | /// Helper class for identifying unordered min predicates. |
1352 | struct ufmin_pred_ty { |
1353 | static bool match(FCmpInst::Predicate Pred) { |
1354 | return Pred == CmpInst::FCMP_ULT || Pred == CmpInst::FCMP_ULE; |
1355 | } |
1356 | }; |
1357 | |
1358 | template <typename LHS, typename RHS> |
1359 | inline MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty> m_SMax(const LHS &L, |
1360 | const RHS &R) { |
1361 | return MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty>(L, R); |
1362 | } |
1363 | |
1364 | template <typename LHS, typename RHS> |
1365 | inline MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty> m_SMin(const LHS &L, |
1366 | const RHS &R) { |
1367 | return MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty>(L, R); |
1368 | } |
1369 | |
1370 | template <typename LHS, typename RHS> |
1371 | inline MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty> m_UMax(const LHS &L, |
1372 | const RHS &R) { |
1373 | return MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty>(L, R); |
1374 | } |
1375 | |
1376 | template <typename LHS, typename RHS> |
1377 | inline MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty> m_UMin(const LHS &L, |
1378 | const RHS &R) { |
1379 | return MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty>(L, R); |
1380 | } |
1381 | |
1382 | /// Match an 'ordered' floating point maximum function. |
1383 | /// Floating point has one special value 'NaN'. Therefore, there is no total |
1384 | /// order. However, if we can ignore the 'NaN' value (for example, because of a |
1385 | /// 'no-nans-float-math' flag) a combination of a fcmp and select has 'maximum' |
1386 | /// semantics. In the presence of 'NaN' we have to preserve the original |
1387 | /// select(fcmp(ogt/ge, L, R), L, R) semantics matched by this predicate. |
1388 | /// |
1389 | /// max(L, R) iff L and R are not NaN |
1390 | /// m_OrdFMax(L, R) = R iff L or R are NaN |
1391 | template <typename LHS, typename RHS> |
1392 | inline MaxMin_match<FCmpInst, LHS, RHS, ofmax_pred_ty> m_OrdFMax(const LHS &L, |
1393 | const RHS &R) { |
1394 | return MaxMin_match<FCmpInst, LHS, RHS, ofmax_pred_ty>(L, R); |
1395 | } |
1396 | |
1397 | /// Match an 'ordered' floating point minimum function. |
1398 | /// Floating point has one special value 'NaN'. Therefore, there is no total |
1399 | /// order. However, if we can ignore the 'NaN' value (for example, because of a |
1400 | /// 'no-nans-float-math' flag) a combination of a fcmp and select has 'minimum' |
1401 | /// semantics. In the presence of 'NaN' we have to preserve the original |
1402 | /// select(fcmp(olt/le, L, R), L, R) semantics matched by this predicate. |
1403 | /// |
1404 | /// min(L, R) iff L and R are not NaN |
1405 | /// m_OrdFMin(L, R) = R iff L or R are NaN |
1406 | template <typename LHS, typename RHS> |
1407 | inline MaxMin_match<FCmpInst, LHS, RHS, ofmin_pred_ty> m_OrdFMin(const LHS &L, |
1408 | const RHS &R) { |
1409 | return MaxMin_match<FCmpInst, LHS, RHS, ofmin_pred_ty>(L, R); |
1410 | } |
1411 | |
1412 | /// Match an 'unordered' floating point maximum function. |
1413 | /// Floating point has one special value 'NaN'. Therefore, there is no total |
1414 | /// order. However, if we can ignore the 'NaN' value (for example, because of a |
1415 | /// 'no-nans-float-math' flag) a combination of a fcmp and select has 'maximum' |
1416 | /// semantics. In the presence of 'NaN' we have to preserve the original |
1417 | /// select(fcmp(ugt/ge, L, R), L, R) semantics matched by this predicate. |
1418 | /// |
1419 | /// max(L, R) iff L and R are not NaN |
1420 | /// m_UnordFMax(L, R) = L iff L or R are NaN |
1421 | template <typename LHS, typename RHS> |
1422 | inline MaxMin_match<FCmpInst, LHS, RHS, ufmax_pred_ty> |
1423 | m_UnordFMax(const LHS &L, const RHS &R) { |
1424 | return MaxMin_match<FCmpInst, LHS, RHS, ufmax_pred_ty>(L, R); |
1425 | } |
1426 | |
1427 | /// Match an 'unordered' floating point minimum function. |
1428 | /// Floating point has one special value 'NaN'. Therefore, there is no total |
1429 | /// order. However, if we can ignore the 'NaN' value (for example, because of a |
1430 | /// 'no-nans-float-math' flag) a combination of a fcmp and select has 'minimum' |
1431 | /// semantics. In the presence of 'NaN' we have to preserve the original |
1432 | /// select(fcmp(ult/le, L, R), L, R) semantics matched by this predicate. |
1433 | /// |
1434 | /// min(L, R) iff L and R are not NaN |
1435 | /// m_UnordFMin(L, R) = L iff L or R are NaN |
1436 | template <typename LHS, typename RHS> |
1437 | inline MaxMin_match<FCmpInst, LHS, RHS, ufmin_pred_ty> |
1438 | m_UnordFMin(const LHS &L, const RHS &R) { |
1439 | return MaxMin_match<FCmpInst, LHS, RHS, ufmin_pred_ty>(L, R); |
1440 | } |
1441 | |
1442 | //===----------------------------------------------------------------------===// |
1443 | // Matchers for overflow check patterns: e.g. (a + b) u< a |
1444 | // |
1445 | |
1446 | template <typename LHS_t, typename RHS_t, typename Sum_t> |
1447 | struct UAddWithOverflow_match { |
1448 | LHS_t L; |
1449 | RHS_t R; |
1450 | Sum_t S; |
1451 | |
1452 | UAddWithOverflow_match(const LHS_t &L, const RHS_t &R, const Sum_t &S) |
1453 | : L(L), R(R), S(S) {} |
1454 | |
1455 | template <typename OpTy> bool match(OpTy *V) { |
1456 | Value *ICmpLHS, *ICmpRHS; |
1457 | ICmpInst::Predicate Pred; |
1458 | if (!m_ICmp(Pred, m_Value(ICmpLHS), m_Value(ICmpRHS)).match(V)) |
1459 | return false; |
1460 | |
1461 | Value *AddLHS, *AddRHS; |
1462 | auto AddExpr = m_Add(m_Value(AddLHS), m_Value(AddRHS)); |
1463 | |
1464 | // (a + b) u< a, (a + b) u< b |
1465 | if (Pred == ICmpInst::ICMP_ULT) |
1466 | if (AddExpr.match(ICmpLHS) && (ICmpRHS == AddLHS || ICmpRHS == AddRHS)) |
1467 | return L.match(AddLHS) && R.match(AddRHS) && S.match(ICmpLHS); |
1468 | |
1469 | // a >u (a + b), b >u (a + b) |
1470 | if (Pred == ICmpInst::ICMP_UGT) |
1471 | if (AddExpr.match(ICmpRHS) && (ICmpLHS == AddLHS || ICmpLHS == AddRHS)) |
1472 | return L.match(AddLHS) && R.match(AddRHS) && S.match(ICmpRHS); |
1473 | |
1474 | // Match special-case for increment-by-1. |
1475 | if (Pred == ICmpInst::ICMP_EQ) { |
1476 | // (a + 1) == 0 |
1477 | // (1 + a) == 0 |
1478 | if (AddExpr.match(ICmpLHS) && m_ZeroInt().match(ICmpRHS) && |
1479 | (m_One().match(AddLHS) || m_One().match(AddRHS))) |
1480 | return L.match(AddLHS) && R.match(AddRHS) && S.match(ICmpLHS); |
1481 | // 0 == (a + 1) |
1482 | // 0 == (1 + a) |
1483 | if (m_ZeroInt().match(ICmpLHS) && AddExpr.match(ICmpRHS) && |
1484 | (m_One().match(AddLHS) || m_One().match(AddRHS))) |
1485 | return L.match(AddLHS) && R.match(AddRHS) && S.match(ICmpRHS); |
1486 | } |
1487 | |
1488 | return false; |
1489 | } |
1490 | }; |
1491 | |
1492 | /// Match an icmp instruction checking for unsigned overflow on addition. |
1493 | /// |
1494 | /// S is matched to the addition whose result is being checked for overflow, and |
1495 | /// L and R are matched to the LHS and RHS of S. |
1496 | template <typename LHS_t, typename RHS_t, typename Sum_t> |
1497 | UAddWithOverflow_match<LHS_t, RHS_t, Sum_t> |
1498 | m_UAddWithOverflow(const LHS_t &L, const RHS_t &R, const Sum_t &S) { |
1499 | return UAddWithOverflow_match<LHS_t, RHS_t, Sum_t>(L, R, S); |
1500 | } |
1501 | |
1502 | template <typename Opnd_t> struct Argument_match { |
1503 | unsigned OpI; |
1504 | Opnd_t Val; |
1505 | |
1506 | Argument_match(unsigned OpIdx, const Opnd_t &V) : OpI(OpIdx), Val(V) {} |
1507 | |
1508 | template <typename OpTy> bool match(OpTy *V) { |
1509 | // FIXME: Should likely be switched to use `CallBase`. |
1510 | if (const auto *CI = dyn_cast<CallInst>(V)) |
1511 | return Val.match(CI->getArgOperand(OpI)); |
1512 | return false; |
1513 | } |
1514 | }; |
1515 | |
1516 | /// Match an argument. |
1517 | template <unsigned OpI, typename Opnd_t> |
1518 | inline Argument_match<Opnd_t> m_Argument(const Opnd_t &Op) { |
1519 | return Argument_match<Opnd_t>(OpI, Op); |
1520 | } |
1521 | |
1522 | /// Intrinsic matchers. |
1523 | struct IntrinsicID_match { |
1524 | unsigned ID; |
1525 | |
1526 | IntrinsicID_match(Intrinsic::ID IntrID) : ID(IntrID) {} |
1527 | |
1528 | template <typename OpTy> bool match(OpTy *V) { |
1529 | if (const auto *CI = dyn_cast<CallInst>(V)) |
1530 | if (const auto *F = CI->getCalledFunction()) |
1531 | return F->getIntrinsicID() == ID; |
1532 | return false; |
1533 | } |
1534 | }; |
1535 | |
1536 | /// Intrinsic matches are combinations of ID matchers, and argument |
1537 | /// matchers. Higher arity matcher are defined recursively in terms of and-ing |
1538 | /// them with lower arity matchers. Here's some convenient typedefs for up to |
1539 | /// several arguments, and more can be added as needed |
1540 | template <typename T0 = void, typename T1 = void, typename T2 = void, |
1541 | typename T3 = void, typename T4 = void, typename T5 = void, |
1542 | typename T6 = void, typename T7 = void, typename T8 = void, |
1543 | typename T9 = void, typename T10 = void> |
1544 | struct m_Intrinsic_Ty; |
1545 | template <typename T0> struct m_Intrinsic_Ty<T0> { |
1546 | using Ty = match_combine_and<IntrinsicID_match, Argument_match<T0>>; |
1547 | }; |
1548 | template <typename T0, typename T1> struct m_Intrinsic_Ty<T0, T1> { |
1549 | using Ty = |
1550 | match_combine_and<typename m_Intrinsic_Ty<T0>::Ty, Argument_match<T1>>; |
1551 | }; |
1552 | template <typename T0, typename T1, typename T2> |
1553 | struct m_Intrinsic_Ty<T0, T1, T2> { |
1554 | using Ty = |
1555 | match_combine_and<typename m_Intrinsic_Ty<T0, T1>::Ty, |
1556 | Argument_match<T2>>; |
1557 | }; |
1558 | template <typename T0, typename T1, typename T2, typename T3> |
1559 | struct m_Intrinsic_Ty<T0, T1, T2, T3> { |
1560 | using Ty = |
1561 | match_combine_and<typename m_Intrinsic_Ty<T0, T1, T2>::Ty, |
1562 | Argument_match<T3>>; |
1563 | }; |
1564 | |
1565 | /// Match intrinsic calls like this: |
1566 | /// m_Intrinsic<Intrinsic::fabs>(m_Value(X)) |
1567 | template <Intrinsic::ID IntrID> inline IntrinsicID_match m_Intrinsic() { |
1568 | return IntrinsicID_match(IntrID); |
1569 | } |
1570 | |
1571 | template <Intrinsic::ID IntrID, typename T0> |
1572 | inline typename m_Intrinsic_Ty<T0>::Ty m_Intrinsic(const T0 &Op0) { |
1573 | return m_CombineAnd(m_Intrinsic<IntrID>(), m_Argument<0>(Op0)); |
1574 | } |
1575 | |
1576 | template <Intrinsic::ID IntrID, typename T0, typename T1> |
1577 | inline typename m_Intrinsic_Ty<T0, T1>::Ty m_Intrinsic(const T0 &Op0, |
1578 | const T1 &Op1) { |
1579 | return m_CombineAnd(m_Intrinsic<IntrID>(Op0), m_Argument<1>(Op1)); |
1580 | } |
1581 | |
1582 | template <Intrinsic::ID IntrID, typename T0, typename T1, typename T2> |
1583 | inline typename m_Intrinsic_Ty<T0, T1, T2>::Ty |
1584 | m_Intrinsic(const T0 &Op0, const T1 &Op1, const T2 &Op2) { |
1585 | return m_CombineAnd(m_Intrinsic<IntrID>(Op0, Op1), m_Argument<2>(Op2)); |
1586 | } |
1587 | |
1588 | template <Intrinsic::ID IntrID, typename T0, typename T1, typename T2, |
1589 | typename T3> |
1590 | inline typename m_Intrinsic_Ty<T0, T1, T2, T3>::Ty |
1591 | m_Intrinsic(const T0 &Op0, const T1 &Op1, const T2 &Op2, const T3 &Op3) { |
1592 | return m_CombineAnd(m_Intrinsic<IntrID>(Op0, Op1, Op2), m_Argument<3>(Op3)); |
1593 | } |
1594 | |
1595 | // Helper intrinsic matching specializations. |
1596 | template <typename Opnd0> |
1597 | inline typename m_Intrinsic_Ty<Opnd0>::Ty m_BitReverse(const Opnd0 &Op0) { |
1598 | return m_Intrinsic<Intrinsic::bitreverse>(Op0); |
1599 | } |
1600 | |
1601 | template <typename Opnd0> |
1602 | inline typename m_Intrinsic_Ty<Opnd0>::Ty m_BSwap(const Opnd0 &Op0) { |
1603 | return m_Intrinsic<Intrinsic::bswap>(Op0); |
1604 | } |
1605 | |
1606 | template <typename Opnd0> |
1607 | inline typename m_Intrinsic_Ty<Opnd0>::Ty m_FAbs(const Opnd0 &Op0) { |
1608 | return m_Intrinsic<Intrinsic::fabs>(Op0); |
1609 | } |
1610 | |
1611 | template <typename Opnd0> |
1612 | inline typename m_Intrinsic_Ty<Opnd0>::Ty m_FCanonicalize(const Opnd0 &Op0) { |
1613 | return m_Intrinsic<Intrinsic::canonicalize>(Op0); |
1614 | } |
1615 | |
1616 | template <typename Opnd0, typename Opnd1> |
1617 | inline typename m_Intrinsic_Ty<Opnd0, Opnd1>::Ty m_FMin(const Opnd0 &Op0, |
1618 | const Opnd1 &Op1) { |
1619 | return m_Intrinsic<Intrinsic::minnum>(Op0, Op1); |
1620 | } |
1621 | |
1622 | template <typename Opnd0, typename Opnd1> |
1623 | inline typename m_Intrinsic_Ty<Opnd0, Opnd1>::Ty m_FMax(const Opnd0 &Op0, |
1624 | const Opnd1 &Op1) { |
1625 | return m_Intrinsic<Intrinsic::maxnum>(Op0, Op1); |
1626 | } |
1627 | |
1628 | //===----------------------------------------------------------------------===// |
1629 | // Matchers for two-operands operators with the operators in either order |
1630 | // |
1631 | |
1632 | /// Matches a BinaryOperator with LHS and RHS in either order. |
1633 | template <typename LHS, typename RHS> |
1634 | inline AnyBinaryOp_match<LHS, RHS, true> m_c_BinOp(const LHS &L, const RHS &R) { |
1635 | return AnyBinaryOp_match<LHS, RHS, true>(L, R); |
1636 | } |
1637 | |
1638 | /// Matches an ICmp with a predicate over LHS and RHS in either order. |
1639 | /// Does not swap the predicate. |
1640 | template <typename LHS, typename RHS> |
1641 | inline CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate, true> |
1642 | m_c_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R) { |
1643 | return CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate, true>(Pred, L, |
1644 | R); |
1645 | } |
1646 | |
1647 | /// Matches a Add with LHS and RHS in either order. |
1648 | template <typename LHS, typename RHS> |
1649 | inline BinaryOp_match<LHS, RHS, Instruction::Add, true> m_c_Add(const LHS &L, |
1650 | const RHS &R) { |
1651 | return BinaryOp_match<LHS, RHS, Instruction::Add, true>(L, R); |
1652 | } |
1653 | |
1654 | /// Matches a Mul with LHS and RHS in either order. |
1655 | template <typename LHS, typename RHS> |
1656 | inline BinaryOp_match<LHS, RHS, Instruction::Mul, true> m_c_Mul(const LHS &L, |
1657 | const RHS &R) { |
1658 | return BinaryOp_match<LHS, RHS, Instruction::Mul, true>(L, R); |
1659 | } |
1660 | |
1661 | /// Matches an And with LHS and RHS in either order. |
1662 | template <typename LHS, typename RHS> |
1663 | inline BinaryOp_match<LHS, RHS, Instruction::And, true> m_c_And(const LHS &L, |
1664 | const RHS &R) { |
1665 | return BinaryOp_match<LHS, RHS, Instruction::And, true>(L, R); |
1666 | } |
1667 | |
1668 | /// Matches an Or with LHS and RHS in either order. |
1669 | template <typename LHS, typename RHS> |
1670 | inline BinaryOp_match<LHS, RHS, Instruction::Or, true> m_c_Or(const LHS &L, |
1671 | const RHS &R) { |
1672 | return BinaryOp_match<LHS, RHS, Instruction::Or, true>(L, R); |
1673 | } |
1674 | |
1675 | /// Matches an Xor with LHS and RHS in either order. |
1676 | template <typename LHS, typename RHS> |
1677 | inline BinaryOp_match<LHS, RHS, Instruction::Xor, true> m_c_Xor(const LHS &L, |
1678 | const RHS &R) { |
1679 | return BinaryOp_match<LHS, RHS, Instruction::Xor, true>(L, R); |
1680 | } |
1681 | |
1682 | /// Matches a 'Neg' as 'sub 0, V'. |
1683 | template <typename ValTy> |
1684 | inline BinaryOp_match<cst_pred_ty<is_zero_int>, ValTy, Instruction::Sub> |
1685 | m_Neg(const ValTy &V) { |
1686 | return m_Sub(m_ZeroInt(), V); |
1687 | } |
1688 | |
1689 | /// Matches a 'Not' as 'xor V, -1' or 'xor -1, V'. |
1690 | template <typename ValTy> |
1691 | inline BinaryOp_match<ValTy, cst_pred_ty<is_all_ones>, Instruction::Xor, true> |
1692 | m_Not(const ValTy &V) { |
1693 | return m_c_Xor(V, m_AllOnes()); |
1694 | } |
1695 | |
1696 | /// Matches an SMin with LHS and RHS in either order. |
1697 | template <typename LHS, typename RHS> |
1698 | inline MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty, true> |
1699 | m_c_SMin(const LHS &L, const RHS &R) { |
1700 | return MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty, true>(L, R); |
1701 | } |
1702 | /// Matches an SMax with LHS and RHS in either order. |
1703 | template <typename LHS, typename RHS> |
1704 | inline MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty, true> |
1705 | m_c_SMax(const LHS &L, const RHS &R) { |
1706 | return MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty, true>(L, R); |
1707 | } |
1708 | /// Matches a UMin with LHS and RHS in either order. |
1709 | template <typename LHS, typename RHS> |
1710 | inline MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty, true> |
1711 | m_c_UMin(const LHS &L, const RHS &R) { |
1712 | return MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty, true>(L, R); |
1713 | } |
1714 | /// Matches a UMax with LHS and RHS in either order. |
1715 | template <typename LHS, typename RHS> |
1716 | inline MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty, true> |
1717 | m_c_UMax(const LHS &L, const RHS &R) { |
1718 | return MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty, true>(L, R); |
1719 | } |
1720 | |
1721 | /// Matches FAdd with LHS and RHS in either order. |
1722 | template <typename LHS, typename RHS> |
1723 | inline BinaryOp_match<LHS, RHS, Instruction::FAdd, true> |
1724 | m_c_FAdd(const LHS &L, const RHS &R) { |
1725 | return BinaryOp_match<LHS, RHS, Instruction::FAdd, true>(L, R); |
1726 | } |
1727 | |
1728 | /// Matches FMul with LHS and RHS in either order. |
1729 | template <typename LHS, typename RHS> |
1730 | inline BinaryOp_match<LHS, RHS, Instruction::FMul, true> |
1731 | m_c_FMul(const LHS &L, const RHS &R) { |
1732 | return BinaryOp_match<LHS, RHS, Instruction::FMul, true>(L, R); |
1733 | } |
1734 | |
1735 | template <typename Opnd_t> struct Signum_match { |
1736 | Opnd_t Val; |
1737 | Signum_match(const Opnd_t &V) : Val(V) {} |
1738 | |
1739 | template <typename OpTy> bool match(OpTy *V) { |
1740 | unsigned TypeSize = V->getType()->getScalarSizeInBits(); |
1741 | if (TypeSize == 0) |
1742 | return false; |
1743 | |
1744 | unsigned ShiftWidth = TypeSize - 1; |
1745 | Value *OpL = nullptr, *OpR = nullptr; |
1746 | |
1747 | // This is the representation of signum we match: |
1748 | // |
1749 | // signum(x) == (x >> 63) | (-x >>u 63) |
1750 | // |
1751 | // An i1 value is its own signum, so it's correct to match |
1752 | // |
1753 | // signum(x) == (x >> 0) | (-x >>u 0) |
1754 | // |
1755 | // for i1 values. |
1756 | |
1757 | auto LHS = m_AShr(m_Value(OpL), m_SpecificInt(ShiftWidth)); |
1758 | auto RHS = m_LShr(m_Neg(m_Value(OpR)), m_SpecificInt(ShiftWidth)); |
1759 | auto Signum = m_Or(LHS, RHS); |
1760 | |
1761 | return Signum.match(V) && OpL == OpR && Val.match(OpL); |
1762 | } |
1763 | }; |
1764 | |
1765 | /// Matches a signum pattern. |
1766 | /// |
1767 | /// signum(x) = |
1768 | /// x > 0 -> 1 |
1769 | /// x == 0 -> 0 |
1770 | /// x < 0 -> -1 |
1771 | template <typename Val_t> inline Signum_match<Val_t> m_Signum(const Val_t &V) { |
1772 | return Signum_match<Val_t>(V); |
1773 | } |
1774 | |
1775 | } // end namespace PatternMatch |
1776 | } // end namespace llvm |
1777 | |
1778 | #endif // LLVM_IR_PATTERNMATCH_H |
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/None.h" |
20 | #include "llvm/ADT/STLExtras.h" |
21 | #include "llvm/ADT/SmallVector.h" |
22 | #include "llvm/ADT/StringRef.h" |
23 | #include "llvm/ADT/Twine.h" |
24 | #include "llvm/ADT/iterator.h" |
25 | #include "llvm/ADT/iterator_range.h" |
26 | #include "llvm/IR/Attributes.h" |
27 | #include "llvm/IR/BasicBlock.h" |
28 | #include "llvm/IR/CallingConv.h" |
29 | #include "llvm/IR/Constant.h" |
30 | #include "llvm/IR/DerivedTypes.h" |
31 | #include "llvm/IR/Function.h" |
32 | #include "llvm/IR/InstrTypes.h" |
33 | #include "llvm/IR/Instruction.h" |
34 | #include "llvm/IR/OperandTraits.h" |
35 | #include "llvm/IR/Type.h" |
36 | #include "llvm/IR/Use.h" |
37 | #include "llvm/IR/User.h" |
38 | #include "llvm/IR/Value.h" |
39 | #include "llvm/Support/AtomicOrdering.h" |
40 | #include "llvm/Support/Casting.h" |
41 | #include "llvm/Support/ErrorHandling.h" |
42 | #include <cassert> |
43 | #include <cstddef> |
44 | #include <cstdint> |
45 | #include <iterator> |
46 | |
47 | namespace llvm { |
48 | |
49 | class APInt; |
50 | class ConstantInt; |
51 | class DataLayout; |
52 | class LLVMContext; |
53 | |
54 | //===----------------------------------------------------------------------===// |
55 | // AllocaInst Class |
56 | //===----------------------------------------------------------------------===// |
57 | |
58 | /// an instruction to allocate memory on the stack |
59 | class AllocaInst : public UnaryInstruction { |
60 | Type *AllocatedType; |
61 | |
62 | protected: |
63 | // Note: Instruction needs to be a friend here to call cloneImpl. |
64 | friend class Instruction; |
65 | |
66 | AllocaInst *cloneImpl() const; |
67 | |
68 | public: |
69 | explicit AllocaInst(Type *Ty, unsigned AddrSpace, |
70 | Value *ArraySize = nullptr, |
71 | const Twine &Name = "", |
72 | Instruction *InsertBefore = nullptr); |
73 | AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, |
74 | const Twine &Name, BasicBlock *InsertAtEnd); |
75 | |
76 | AllocaInst(Type *Ty, unsigned AddrSpace, |
77 | const Twine &Name, Instruction *InsertBefore = nullptr); |
78 | AllocaInst(Type *Ty, unsigned AddrSpace, |
79 | const Twine &Name, BasicBlock *InsertAtEnd); |
80 | |
81 | AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, unsigned Align, |
82 | const Twine &Name = "", Instruction *InsertBefore = nullptr); |
83 | AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, unsigned Align, |
84 | const Twine &Name, BasicBlock *InsertAtEnd); |
85 | |
86 | /// Return true if there is an allocation size parameter to the allocation |
87 | /// instruction that is not 1. |
88 | bool isArrayAllocation() const; |
89 | |
90 | /// Get the number of elements allocated. For a simple allocation of a single |
91 | /// element, this will return a constant 1 value. |
92 | const Value *getArraySize() const { return getOperand(0); } |
93 | Value *getArraySize() { return getOperand(0); } |
94 | |
95 | /// Overload to return most specific pointer type. |
96 | PointerType *getType() const { |
97 | return cast<PointerType>(Instruction::getType()); |
98 | } |
99 | |
100 | /// Get allocation size in bits. Returns None if size can't be determined, |
101 | /// e.g. in case of a VLA. |
102 | Optional<uint64_t> getAllocationSizeInBits(const DataLayout &DL) const; |
103 | |
104 | /// Return the type that is being allocated by the instruction. |
105 | Type *getAllocatedType() const { return AllocatedType; } |
106 | /// for use only in special circumstances that need to generically |
107 | /// transform a whole instruction (eg: IR linking and vectorization). |
108 | void setAllocatedType(Type *Ty) { AllocatedType = Ty; } |
109 | |
110 | /// Return the alignment of the memory that is being allocated by the |
111 | /// instruction. |
112 | unsigned getAlignment() const { |
113 | return (1u << (getSubclassDataFromInstruction() & 31)) >> 1; |
114 | } |
115 | void setAlignment(unsigned Align); |
116 | |
117 | /// Return true if this alloca is in the entry block of the function and is a |
118 | /// constant size. If so, the code generator will fold it into the |
119 | /// prolog/epilog code, so it is basically free. |
120 | bool isStaticAlloca() const; |
121 | |
122 | /// Return true if this alloca is used as an inalloca argument to a call. Such |
123 | /// allocas are never considered static even if they are in the entry block. |
124 | bool isUsedWithInAlloca() const { |
125 | return getSubclassDataFromInstruction() & 32; |
126 | } |
127 | |
128 | /// Specify whether this alloca is used to represent the arguments to a call. |
129 | void setUsedWithInAlloca(bool V) { |
130 | setInstructionSubclassData((getSubclassDataFromInstruction() & ~32) | |
131 | (V ? 32 : 0)); |
132 | } |
133 | |
134 | /// Return true if this alloca is used as a swifterror argument to a call. |
135 | bool isSwiftError() const { |
136 | return getSubclassDataFromInstruction() & 64; |
137 | } |
138 | |
139 | /// Specify whether this alloca is used to represent a swifterror. |
140 | void setSwiftError(bool V) { |
141 | setInstructionSubclassData((getSubclassDataFromInstruction() & ~64) | |
142 | (V ? 64 : 0)); |
143 | } |
144 | |
145 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
146 | static bool classof(const Instruction *I) { |
147 | return (I->getOpcode() == Instruction::Alloca); |
148 | } |
149 | static bool classof(const Value *V) { |
150 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
151 | } |
152 | |
153 | private: |
154 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
155 | // method so that subclasses cannot accidentally use it. |
156 | void setInstructionSubclassData(unsigned short D) { |
157 | Instruction::setInstructionSubclassData(D); |
158 | } |
159 | }; |
160 | |
161 | //===----------------------------------------------------------------------===// |
162 | // LoadInst Class |
163 | //===----------------------------------------------------------------------===// |
164 | |
165 | /// An instruction for reading from memory. This uses the SubclassData field in |
166 | /// Value to store whether or not the load is volatile. |
167 | class LoadInst : public UnaryInstruction { |
168 | void AssertOK(); |
169 | |
170 | protected: |
171 | // Note: Instruction needs to be a friend here to call cloneImpl. |
172 | friend class Instruction; |
173 | |
174 | LoadInst *cloneImpl() const; |
175 | |
176 | public: |
177 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr = "", |
178 | Instruction *InsertBefore = nullptr); |
179 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd); |
180 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile, |
181 | Instruction *InsertBefore = nullptr); |
182 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile, |
183 | BasicBlock *InsertAtEnd); |
184 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile, |
185 | unsigned Align, Instruction *InsertBefore = nullptr); |
186 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile, |
187 | unsigned Align, BasicBlock *InsertAtEnd); |
188 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile, |
189 | unsigned Align, AtomicOrdering Order, |
190 | SyncScope::ID SSID = SyncScope::System, |
191 | Instruction *InsertBefore = nullptr); |
192 | LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile, |
193 | unsigned Align, AtomicOrdering Order, SyncScope::ID SSID, |
194 | BasicBlock *InsertAtEnd); |
195 | |
196 | // Deprecated [opaque pointer types] |
197 | explicit LoadInst(Value *Ptr, const Twine &NameStr = "", |
198 | Instruction *InsertBefore = nullptr) |
199 | : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr, |
200 | InsertBefore) {} |
201 | LoadInst(Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd) |
202 | : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr, |
203 | InsertAtEnd) {} |
204 | LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, |
205 | Instruction *InsertBefore = nullptr) |
206 | : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr, |
207 | isVolatile, InsertBefore) {} |
208 | LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, |
209 | BasicBlock *InsertAtEnd) |
210 | : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr, |
211 | isVolatile, InsertAtEnd) {} |
212 | LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, unsigned Align, |
213 | Instruction *InsertBefore = nullptr) |
214 | : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr, |
215 | isVolatile, Align, InsertBefore) {} |
216 | LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, unsigned Align, |
217 | BasicBlock *InsertAtEnd) |
218 | : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr, |
219 | isVolatile, Align, InsertAtEnd) {} |
220 | LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, unsigned Align, |
221 | AtomicOrdering Order, SyncScope::ID SSID = SyncScope::System, |
222 | Instruction *InsertBefore = nullptr) |
223 | : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr, |
224 | isVolatile, Align, Order, SSID, InsertBefore) {} |
225 | LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, unsigned Align, |
226 | AtomicOrdering Order, SyncScope::ID SSID, BasicBlock *InsertAtEnd) |
227 | : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr, |
228 | isVolatile, Align, Order, SSID, InsertAtEnd) {} |
229 | |
230 | /// Return true if this is a load from a volatile memory location. |
231 | bool isVolatile() const { return getSubclassDataFromInstruction() & 1; } |
232 | |
233 | /// Specify whether this is a volatile load or not. |
234 | void setVolatile(bool V) { |
235 | setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) | |
236 | (V ? 1 : 0)); |
237 | } |
238 | |
239 | /// Return the alignment of the access that is being performed. |
240 | unsigned getAlignment() const { |
241 | return (1 << ((getSubclassDataFromInstruction() >> 1) & 31)) >> 1; |
242 | } |
243 | |
244 | void setAlignment(unsigned Align); |
245 | |
246 | /// Returns the ordering constraint of this load instruction. |
247 | AtomicOrdering getOrdering() const { |
248 | return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7); |
249 | } |
250 | |
251 | /// Sets the ordering constraint of this load instruction. May not be Release |
252 | /// or AcquireRelease. |
253 | void setOrdering(AtomicOrdering Ordering) { |
254 | setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) | |
255 | ((unsigned)Ordering << 7)); |
256 | } |
257 | |
258 | /// Returns the synchronization scope ID of this load instruction. |
259 | SyncScope::ID getSyncScopeID() const { |
260 | return SSID; |
261 | } |
262 | |
263 | /// Sets the synchronization scope ID of this load instruction. |
264 | void setSyncScopeID(SyncScope::ID SSID) { |
265 | this->SSID = SSID; |
266 | } |
267 | |
268 | /// Sets the ordering constraint and the synchronization scope ID of this load |
269 | /// instruction. |
270 | void setAtomic(AtomicOrdering Ordering, |
271 | SyncScope::ID SSID = SyncScope::System) { |
272 | setOrdering(Ordering); |
273 | setSyncScopeID(SSID); |
274 | } |
275 | |
276 | bool isSimple() const { return !isAtomic() && !isVolatile(); } |
277 | |
278 | bool isUnordered() const { |
279 | return (getOrdering() == AtomicOrdering::NotAtomic || |
280 | getOrdering() == AtomicOrdering::Unordered) && |
281 | !isVolatile(); |
282 | } |
283 | |
284 | Value *getPointerOperand() { return getOperand(0); } |
285 | const Value *getPointerOperand() const { return getOperand(0); } |
286 | static unsigned getPointerOperandIndex() { return 0U; } |
287 | Type *getPointerOperandType() const { return getPointerOperand()->getType(); } |
288 | |
289 | /// Returns the address space of the pointer operand. |
290 | unsigned getPointerAddressSpace() const { |
291 | return getPointerOperandType()->getPointerAddressSpace(); |
292 | } |
293 | |
294 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
295 | static bool classof(const Instruction *I) { |
296 | return I->getOpcode() == Instruction::Load; |
297 | } |
298 | static bool classof(const Value *V) { |
299 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
300 | } |
301 | |
302 | private: |
303 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
304 | // method so that subclasses cannot accidentally use it. |
305 | void setInstructionSubclassData(unsigned short D) { |
306 | Instruction::setInstructionSubclassData(D); |
307 | } |
308 | |
309 | /// The synchronization scope ID of this load instruction. Not quite enough |
310 | /// room in SubClassData for everything, so synchronization scope ID gets its |
311 | /// own field. |
312 | SyncScope::ID SSID; |
313 | }; |
314 | |
315 | //===----------------------------------------------------------------------===// |
316 | // StoreInst Class |
317 | //===----------------------------------------------------------------------===// |
318 | |
319 | /// An instruction for storing to memory. |
320 | class StoreInst : public Instruction { |
321 | void AssertOK(); |
322 | |
323 | protected: |
324 | // Note: Instruction needs to be a friend here to call cloneImpl. |
325 | friend class Instruction; |
326 | |
327 | StoreInst *cloneImpl() const; |
328 | |
329 | public: |
330 | StoreInst(Value *Val, Value *Ptr, Instruction *InsertBefore); |
331 | StoreInst(Value *Val, Value *Ptr, BasicBlock *InsertAtEnd); |
332 | StoreInst(Value *Val, Value *Ptr, bool isVolatile = false, |
333 | Instruction *InsertBefore = nullptr); |
334 | StoreInst(Value *Val, Value *Ptr, bool isVolatile, BasicBlock *InsertAtEnd); |
335 | StoreInst(Value *Val, Value *Ptr, bool isVolatile, |
336 | unsigned Align, Instruction *InsertBefore = nullptr); |
337 | StoreInst(Value *Val, Value *Ptr, bool isVolatile, |
338 | unsigned Align, BasicBlock *InsertAtEnd); |
339 | StoreInst(Value *Val, Value *Ptr, bool isVolatile, |
340 | unsigned Align, AtomicOrdering Order, |
341 | SyncScope::ID SSID = SyncScope::System, |
342 | Instruction *InsertBefore = nullptr); |
343 | StoreInst(Value *Val, Value *Ptr, bool isVolatile, |
344 | unsigned Align, AtomicOrdering Order, SyncScope::ID SSID, |
345 | BasicBlock *InsertAtEnd); |
346 | |
347 | // allocate space for exactly two operands |
348 | void *operator new(size_t s) { |
349 | return User::operator new(s, 2); |
350 | } |
351 | |
352 | /// Return true if this is a store to a volatile memory location. |
353 | bool isVolatile() const { return getSubclassDataFromInstruction() & 1; } |
354 | |
355 | /// Specify whether this is a volatile store or not. |
356 | void setVolatile(bool V) { |
357 | setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) | |
358 | (V ? 1 : 0)); |
359 | } |
360 | |
361 | /// Transparently provide more efficient getOperand methods. |
362 | 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; |
363 | |
364 | /// Return the alignment of the access that is being performed |
365 | unsigned getAlignment() const { |
366 | return (1 << ((getSubclassDataFromInstruction() >> 1) & 31)) >> 1; |
367 | } |
368 | |
369 | void setAlignment(unsigned Align); |
370 | |
371 | /// Returns the ordering constraint of this store instruction. |
372 | AtomicOrdering getOrdering() const { |
373 | return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7); |
374 | } |
375 | |
376 | /// Sets the ordering constraint of this store instruction. May not be |
377 | /// Acquire or AcquireRelease. |
378 | void setOrdering(AtomicOrdering Ordering) { |
379 | setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) | |
380 | ((unsigned)Ordering << 7)); |
381 | } |
382 | |
383 | /// Returns the synchronization scope ID of this store instruction. |
384 | SyncScope::ID getSyncScopeID() const { |
385 | return SSID; |
386 | } |
387 | |
388 | /// Sets the synchronization scope ID of this store instruction. |
389 | void setSyncScopeID(SyncScope::ID SSID) { |
390 | this->SSID = SSID; |
391 | } |
392 | |
393 | /// Sets the ordering constraint and the synchronization scope ID of this |
394 | /// store instruction. |
395 | void setAtomic(AtomicOrdering Ordering, |
396 | SyncScope::ID SSID = SyncScope::System) { |
397 | setOrdering(Ordering); |
398 | setSyncScopeID(SSID); |
399 | } |
400 | |
401 | bool isSimple() const { return !isAtomic() && !isVolatile(); } |
402 | |
403 | bool isUnordered() const { |
404 | return (getOrdering() == AtomicOrdering::NotAtomic || |
405 | getOrdering() == AtomicOrdering::Unordered) && |
406 | !isVolatile(); |
407 | } |
408 | |
409 | Value *getValueOperand() { return getOperand(0); } |
410 | const Value *getValueOperand() const { return getOperand(0); } |
411 | |
412 | Value *getPointerOperand() { return getOperand(1); } |
413 | const Value *getPointerOperand() const { return getOperand(1); } |
414 | static unsigned getPointerOperandIndex() { return 1U; } |
415 | Type *getPointerOperandType() const { return getPointerOperand()->getType(); } |
416 | |
417 | /// Returns the address space of the pointer operand. |
418 | unsigned getPointerAddressSpace() const { |
419 | return getPointerOperandType()->getPointerAddressSpace(); |
420 | } |
421 | |
422 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
423 | static bool classof(const Instruction *I) { |
424 | return I->getOpcode() == Instruction::Store; |
425 | } |
426 | static bool classof(const Value *V) { |
427 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
428 | } |
429 | |
430 | private: |
431 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
432 | // method so that subclasses cannot accidentally use it. |
433 | void setInstructionSubclassData(unsigned short D) { |
434 | Instruction::setInstructionSubclassData(D); |
435 | } |
436 | |
437 | /// The synchronization scope ID of this store instruction. Not quite enough |
438 | /// room in SubClassData for everything, so synchronization scope ID gets its |
439 | /// own field. |
440 | SyncScope::ID SSID; |
441 | }; |
442 | |
443 | template <> |
444 | struct OperandTraits<StoreInst> : public FixedNumOperandTraits<StoreInst, 2> { |
445 | }; |
446 | |
447 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 447, __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-9~svn360825/include/llvm/IR/Instructions.h" , 447, __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 ); } |
448 | |
449 | //===----------------------------------------------------------------------===// |
450 | // FenceInst Class |
451 | //===----------------------------------------------------------------------===// |
452 | |
453 | /// An instruction for ordering other memory operations. |
454 | class FenceInst : public Instruction { |
455 | void Init(AtomicOrdering Ordering, SyncScope::ID SSID); |
456 | |
457 | protected: |
458 | // Note: Instruction needs to be a friend here to call cloneImpl. |
459 | friend class Instruction; |
460 | |
461 | FenceInst *cloneImpl() const; |
462 | |
463 | public: |
464 | // Ordering may only be Acquire, Release, AcquireRelease, or |
465 | // SequentiallyConsistent. |
466 | FenceInst(LLVMContext &C, AtomicOrdering Ordering, |
467 | SyncScope::ID SSID = SyncScope::System, |
468 | Instruction *InsertBefore = nullptr); |
469 | FenceInst(LLVMContext &C, AtomicOrdering Ordering, SyncScope::ID SSID, |
470 | BasicBlock *InsertAtEnd); |
471 | |
472 | // allocate space for exactly zero operands |
473 | void *operator new(size_t s) { |
474 | return User::operator new(s, 0); |
475 | } |
476 | |
477 | /// Returns the ordering constraint of this fence instruction. |
478 | AtomicOrdering getOrdering() const { |
479 | return AtomicOrdering(getSubclassDataFromInstruction() >> 1); |
480 | } |
481 | |
482 | /// Sets the ordering constraint of this fence instruction. May only be |
483 | /// Acquire, Release, AcquireRelease, or SequentiallyConsistent. |
484 | void setOrdering(AtomicOrdering Ordering) { |
485 | setInstructionSubclassData((getSubclassDataFromInstruction() & 1) | |
486 | ((unsigned)Ordering << 1)); |
487 | } |
488 | |
489 | /// Returns the synchronization scope ID of this fence instruction. |
490 | SyncScope::ID getSyncScopeID() const { |
491 | return SSID; |
492 | } |
493 | |
494 | /// Sets the synchronization scope ID of this fence instruction. |
495 | void setSyncScopeID(SyncScope::ID SSID) { |
496 | this->SSID = SSID; |
497 | } |
498 | |
499 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
500 | static bool classof(const Instruction *I) { |
501 | return I->getOpcode() == Instruction::Fence; |
502 | } |
503 | static bool classof(const Value *V) { |
504 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
505 | } |
506 | |
507 | private: |
508 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
509 | // method so that subclasses cannot accidentally use it. |
510 | void setInstructionSubclassData(unsigned short D) { |
511 | Instruction::setInstructionSubclassData(D); |
512 | } |
513 | |
514 | /// The synchronization scope ID of this fence instruction. Not quite enough |
515 | /// room in SubClassData for everything, so synchronization scope ID gets its |
516 | /// own field. |
517 | SyncScope::ID SSID; |
518 | }; |
519 | |
520 | //===----------------------------------------------------------------------===// |
521 | // AtomicCmpXchgInst Class |
522 | //===----------------------------------------------------------------------===// |
523 | |
524 | /// an instruction that atomically checks whether a |
525 | /// specified value is in a memory location, and, if it is, stores a new value |
526 | /// there. Returns the value that was loaded. |
527 | /// |
528 | class AtomicCmpXchgInst : public Instruction { |
529 | void Init(Value *Ptr, Value *Cmp, Value *NewVal, |
530 | AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering, |
531 | SyncScope::ID SSID); |
532 | |
533 | protected: |
534 | // Note: Instruction needs to be a friend here to call cloneImpl. |
535 | friend class Instruction; |
536 | |
537 | AtomicCmpXchgInst *cloneImpl() const; |
538 | |
539 | public: |
540 | AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal, |
541 | AtomicOrdering SuccessOrdering, |
542 | AtomicOrdering FailureOrdering, |
543 | SyncScope::ID SSID, Instruction *InsertBefore = nullptr); |
544 | AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal, |
545 | AtomicOrdering SuccessOrdering, |
546 | AtomicOrdering FailureOrdering, |
547 | SyncScope::ID SSID, BasicBlock *InsertAtEnd); |
548 | |
549 | // allocate space for exactly three operands |
550 | void *operator new(size_t s) { |
551 | return User::operator new(s, 3); |
552 | } |
553 | |
554 | /// Return true if this is a cmpxchg from a volatile memory |
555 | /// location. |
556 | /// |
557 | bool isVolatile() const { |
558 | return getSubclassDataFromInstruction() & 1; |
559 | } |
560 | |
561 | /// Specify whether this is a volatile cmpxchg. |
562 | /// |
563 | void setVolatile(bool V) { |
564 | setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) | |
565 | (unsigned)V); |
566 | } |
567 | |
568 | /// Return true if this cmpxchg may spuriously fail. |
569 | bool isWeak() const { |
570 | return getSubclassDataFromInstruction() & 0x100; |
571 | } |
572 | |
573 | void setWeak(bool IsWeak) { |
574 | setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x100) | |
575 | (IsWeak << 8)); |
576 | } |
577 | |
578 | /// Transparently provide more efficient getOperand methods. |
579 | 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; |
580 | |
581 | /// Returns the success ordering constraint of this cmpxchg instruction. |
582 | AtomicOrdering getSuccessOrdering() const { |
583 | return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7); |
584 | } |
585 | |
586 | /// Sets the success ordering constraint of this cmpxchg instruction. |
587 | void setSuccessOrdering(AtomicOrdering Ordering) { |
588 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 589, __PRETTY_FUNCTION__)) |
589 | "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-9~svn360825/include/llvm/IR/Instructions.h" , 589, __PRETTY_FUNCTION__)); |
590 | setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x1c) | |
591 | ((unsigned)Ordering << 2)); |
592 | } |
593 | |
594 | /// Returns the failure ordering constraint of this cmpxchg instruction. |
595 | AtomicOrdering getFailureOrdering() const { |
596 | return AtomicOrdering((getSubclassDataFromInstruction() >> 5) & 7); |
597 | } |
598 | |
599 | /// Sets the failure ordering constraint of this cmpxchg instruction. |
600 | void setFailureOrdering(AtomicOrdering Ordering) { |
601 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 602, __PRETTY_FUNCTION__)) |
602 | "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-9~svn360825/include/llvm/IR/Instructions.h" , 602, __PRETTY_FUNCTION__)); |
603 | setInstructionSubclassData((getSubclassDataFromInstruction() & ~0xe0) | |
604 | ((unsigned)Ordering << 5)); |
605 | } |
606 | |
607 | /// Returns the synchronization scope ID of this cmpxchg instruction. |
608 | SyncScope::ID getSyncScopeID() const { |
609 | return SSID; |
610 | } |
611 | |
612 | /// Sets the synchronization scope ID of this cmpxchg instruction. |
613 | void setSyncScopeID(SyncScope::ID SSID) { |
614 | this->SSID = SSID; |
615 | } |
616 | |
617 | Value *getPointerOperand() { return getOperand(0); } |
618 | const Value *getPointerOperand() const { return getOperand(0); } |
619 | static unsigned getPointerOperandIndex() { return 0U; } |
620 | |
621 | Value *getCompareOperand() { return getOperand(1); } |
622 | const Value *getCompareOperand() const { return getOperand(1); } |
623 | |
624 | Value *getNewValOperand() { return getOperand(2); } |
625 | const Value *getNewValOperand() const { return getOperand(2); } |
626 | |
627 | /// Returns the address space of the pointer operand. |
628 | unsigned getPointerAddressSpace() const { |
629 | return getPointerOperand()->getType()->getPointerAddressSpace(); |
630 | } |
631 | |
632 | /// Returns the strongest permitted ordering on failure, given the |
633 | /// desired ordering on success. |
634 | /// |
635 | /// If the comparison in a cmpxchg operation fails, there is no atomic store |
636 | /// so release semantics cannot be provided. So this function drops explicit |
637 | /// Release requests from the AtomicOrdering. A SequentiallyConsistent |
638 | /// operation would remain SequentiallyConsistent. |
639 | static AtomicOrdering |
640 | getStrongestFailureOrdering(AtomicOrdering SuccessOrdering) { |
641 | switch (SuccessOrdering) { |
642 | default: |
643 | llvm_unreachable("invalid cmpxchg success ordering")::llvm::llvm_unreachable_internal("invalid cmpxchg success ordering" , "/build/llvm-toolchain-snapshot-9~svn360825/include/llvm/IR/Instructions.h" , 643); |
644 | case AtomicOrdering::Release: |
645 | case AtomicOrdering::Monotonic: |
646 | return AtomicOrdering::Monotonic; |
647 | case AtomicOrdering::AcquireRelease: |
648 | case AtomicOrdering::Acquire: |
649 | return AtomicOrdering::Acquire; |
650 | case AtomicOrdering::SequentiallyConsistent: |
651 | return AtomicOrdering::SequentiallyConsistent; |
652 | } |
653 | } |
654 | |
655 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
656 | static bool classof(const Instruction *I) { |
657 | return I->getOpcode() == Instruction::AtomicCmpXchg; |
658 | } |
659 | static bool classof(const Value *V) { |
660 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
661 | } |
662 | |
663 | private: |
664 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
665 | // method so that subclasses cannot accidentally use it. |
666 | void setInstructionSubclassData(unsigned short D) { |
667 | Instruction::setInstructionSubclassData(D); |
668 | } |
669 | |
670 | /// The synchronization scope ID of this cmpxchg instruction. Not quite |
671 | /// enough room in SubClassData for everything, so synchronization scope ID |
672 | /// gets its own field. |
673 | SyncScope::ID SSID; |
674 | }; |
675 | |
676 | template <> |
677 | struct OperandTraits<AtomicCmpXchgInst> : |
678 | public FixedNumOperandTraits<AtomicCmpXchgInst, 3> { |
679 | }; |
680 | |
681 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 681, __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-9~svn360825/include/llvm/IR/Instructions.h" , 681, __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); } |
682 | |
683 | //===----------------------------------------------------------------------===// |
684 | // AtomicRMWInst Class |
685 | //===----------------------------------------------------------------------===// |
686 | |
687 | /// an instruction that atomically reads a memory location, |
688 | /// combines it with another value, and then stores the result back. Returns |
689 | /// the old value. |
690 | /// |
691 | class AtomicRMWInst : public Instruction { |
692 | protected: |
693 | // Note: Instruction needs to be a friend here to call cloneImpl. |
694 | friend class Instruction; |
695 | |
696 | AtomicRMWInst *cloneImpl() const; |
697 | |
698 | public: |
699 | /// This enumeration lists the possible modifications atomicrmw can make. In |
700 | /// the descriptions, 'p' is the pointer to the instruction's memory location, |
701 | /// 'old' is the initial value of *p, and 'v' is the other value passed to the |
702 | /// instruction. These instructions always return 'old'. |
703 | enum BinOp { |
704 | /// *p = v |
705 | Xchg, |
706 | /// *p = old + v |
707 | Add, |
708 | /// *p = old - v |
709 | Sub, |
710 | /// *p = old & v |
711 | And, |
712 | /// *p = ~(old & v) |
713 | Nand, |
714 | /// *p = old | v |
715 | Or, |
716 | /// *p = old ^ v |
717 | Xor, |
718 | /// *p = old >signed v ? old : v |
719 | Max, |
720 | /// *p = old <signed v ? old : v |
721 | Min, |
722 | /// *p = old >unsigned v ? old : v |
723 | UMax, |
724 | /// *p = old <unsigned v ? old : v |
725 | UMin, |
726 | |
727 | /// *p = old + v |
728 | FAdd, |
729 | |
730 | /// *p = old - v |
731 | FSub, |
732 | |
733 | FIRST_BINOP = Xchg, |
734 | LAST_BINOP = FSub, |
735 | BAD_BINOP |
736 | }; |
737 | |
738 | AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val, |
739 | AtomicOrdering Ordering, SyncScope::ID SSID, |
740 | Instruction *InsertBefore = nullptr); |
741 | AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val, |
742 | AtomicOrdering Ordering, SyncScope::ID SSID, |
743 | BasicBlock *InsertAtEnd); |
744 | |
745 | // allocate space for exactly two operands |
746 | void *operator new(size_t s) { |
747 | return User::operator new(s, 2); |
748 | } |
749 | |
750 | BinOp getOperation() const { |
751 | return static_cast<BinOp>(getSubclassDataFromInstruction() >> 5); |
752 | } |
753 | |
754 | static StringRef getOperationName(BinOp Op); |
755 | |
756 | static bool isFPOperation(BinOp Op) { |
757 | switch (Op) { |
758 | case AtomicRMWInst::FAdd: |
759 | case AtomicRMWInst::FSub: |
760 | return true; |
761 | default: |
762 | return false; |
763 | } |
764 | } |
765 | |
766 | void setOperation(BinOp Operation) { |
767 | unsigned short SubclassData = getSubclassDataFromInstruction(); |
768 | setInstructionSubclassData((SubclassData & 31) | |
769 | (Operation << 5)); |
770 | } |
771 | |
772 | /// Return true if this is a RMW on a volatile memory location. |
773 | /// |
774 | bool isVolatile() const { |
775 | return getSubclassDataFromInstruction() & 1; |
776 | } |
777 | |
778 | /// Specify whether this is a volatile RMW or not. |
779 | /// |
780 | void setVolatile(bool V) { |
781 | setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) | |
782 | (unsigned)V); |
783 | } |
784 | |
785 | /// Transparently provide more efficient getOperand methods. |
786 | 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; |
787 | |
788 | /// Returns the ordering constraint of this rmw instruction. |
789 | AtomicOrdering getOrdering() const { |
790 | return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7); |
791 | } |
792 | |
793 | /// Sets the ordering constraint of this rmw instruction. |
794 | void setOrdering(AtomicOrdering Ordering) { |
795 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 796, __PRETTY_FUNCTION__)) |
796 | "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-9~svn360825/include/llvm/IR/Instructions.h" , 796, __PRETTY_FUNCTION__)); |
797 | setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 2)) | |
798 | ((unsigned)Ordering << 2)); |
799 | } |
800 | |
801 | /// Returns the synchronization scope ID of this rmw instruction. |
802 | SyncScope::ID getSyncScopeID() const { |
803 | return SSID; |
804 | } |
805 | |
806 | /// Sets the synchronization scope ID of this rmw instruction. |
807 | void setSyncScopeID(SyncScope::ID SSID) { |
808 | this->SSID = SSID; |
809 | } |
810 | |
811 | Value *getPointerOperand() { return getOperand(0); } |
812 | const Value *getPointerOperand() const { return getOperand(0); } |
813 | static unsigned getPointerOperandIndex() { return 0U; } |
814 | |
815 | Value *getValOperand() { return getOperand(1); } |
816 | const Value *getValOperand() const { return getOperand(1); } |
817 | |
818 | /// Returns the address space of the pointer operand. |
819 | unsigned getPointerAddressSpace() const { |
820 | return getPointerOperand()->getType()->getPointerAddressSpace(); |
821 | } |
822 | |
823 | bool isFloatingPointOperation() const { |
824 | return isFPOperation(getOperation()); |
825 | } |
826 | |
827 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
828 | static bool classof(const Instruction *I) { |
829 | return I->getOpcode() == Instruction::AtomicRMW; |
830 | } |
831 | static bool classof(const Value *V) { |
832 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
833 | } |
834 | |
835 | private: |
836 | void Init(BinOp Operation, Value *Ptr, Value *Val, |
837 | AtomicOrdering Ordering, SyncScope::ID SSID); |
838 | |
839 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
840 | // method so that subclasses cannot accidentally use it. |
841 | void setInstructionSubclassData(unsigned short D) { |
842 | Instruction::setInstructionSubclassData(D); |
843 | } |
844 | |
845 | /// The synchronization scope ID of this rmw instruction. Not quite enough |
846 | /// room in SubClassData for everything, so synchronization scope ID gets its |
847 | /// own field. |
848 | SyncScope::ID SSID; |
849 | }; |
850 | |
851 | template <> |
852 | struct OperandTraits<AtomicRMWInst> |
853 | : public FixedNumOperandTraits<AtomicRMWInst,2> { |
854 | }; |
855 | |
856 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 856, __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-9~svn360825/include/llvm/IR/Instructions.h" , 856, __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); } |
857 | |
858 | //===----------------------------------------------------------------------===// |
859 | // GetElementPtrInst Class |
860 | //===----------------------------------------------------------------------===// |
861 | |
862 | // checkGEPType - Simple wrapper function to give a better assertion failure |
863 | // message on bad indexes for a gep instruction. |
864 | // |
865 | inline Type *checkGEPType(Type *Ty) { |
866 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 866, __PRETTY_FUNCTION__)); |
867 | return Ty; |
868 | } |
869 | |
870 | /// an instruction for type-safe pointer arithmetic to |
871 | /// access elements of arrays and structs |
872 | /// |
873 | class GetElementPtrInst : public Instruction { |
874 | Type *SourceElementType; |
875 | Type *ResultElementType; |
876 | |
877 | GetElementPtrInst(const GetElementPtrInst &GEPI); |
878 | |
879 | /// Constructors - Create a getelementptr instruction with a base pointer an |
880 | /// list of indices. The first ctor can optionally insert before an existing |
881 | /// instruction, the second appends the new instruction to the specified |
882 | /// BasicBlock. |
883 | inline GetElementPtrInst(Type *PointeeType, Value *Ptr, |
884 | ArrayRef<Value *> IdxList, unsigned Values, |
885 | const Twine &NameStr, Instruction *InsertBefore); |
886 | inline GetElementPtrInst(Type *PointeeType, Value *Ptr, |
887 | ArrayRef<Value *> IdxList, unsigned Values, |
888 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
889 | |
890 | void init(Value *Ptr, ArrayRef<Value *> IdxList, const Twine &NameStr); |
891 | |
892 | protected: |
893 | // Note: Instruction needs to be a friend here to call cloneImpl. |
894 | friend class Instruction; |
895 | |
896 | GetElementPtrInst *cloneImpl() const; |
897 | |
898 | public: |
899 | static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr, |
900 | ArrayRef<Value *> IdxList, |
901 | const Twine &NameStr = "", |
902 | Instruction *InsertBefore = nullptr) { |
903 | unsigned Values = 1 + unsigned(IdxList.size()); |
904 | if (!PointeeType) |
905 | PointeeType = |
906 | cast<PointerType>(Ptr->getType()->getScalarType())->getElementType(); |
907 | else |
908 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 910, __PRETTY_FUNCTION__)) |
909 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 910, __PRETTY_FUNCTION__)) |
910 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 910, __PRETTY_FUNCTION__)); |
911 | return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values, |
912 | NameStr, InsertBefore); |
913 | } |
914 | |
915 | static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr, |
916 | ArrayRef<Value *> IdxList, |
917 | const Twine &NameStr, |
918 | BasicBlock *InsertAtEnd) { |
919 | unsigned Values = 1 + unsigned(IdxList.size()); |
920 | if (!PointeeType) |
921 | PointeeType = |
922 | cast<PointerType>(Ptr->getType()->getScalarType())->getElementType(); |
923 | else |
924 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 926, __PRETTY_FUNCTION__)) |
925 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 926, __PRETTY_FUNCTION__)) |
926 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 926, __PRETTY_FUNCTION__)); |
927 | return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values, |
928 | NameStr, InsertAtEnd); |
929 | } |
930 | |
931 | /// Create an "inbounds" getelementptr. See the documentation for the |
932 | /// "inbounds" flag in LangRef.html for details. |
933 | static GetElementPtrInst *CreateInBounds(Value *Ptr, |
934 | ArrayRef<Value *> IdxList, |
935 | const Twine &NameStr = "", |
936 | Instruction *InsertBefore = nullptr){ |
937 | return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertBefore); |
938 | } |
939 | |
940 | static GetElementPtrInst * |
941 | CreateInBounds(Type *PointeeType, Value *Ptr, ArrayRef<Value *> IdxList, |
942 | const Twine &NameStr = "", |
943 | Instruction *InsertBefore = nullptr) { |
944 | GetElementPtrInst *GEP = |
945 | Create(PointeeType, Ptr, IdxList, NameStr, InsertBefore); |
946 | GEP->setIsInBounds(true); |
947 | return GEP; |
948 | } |
949 | |
950 | static GetElementPtrInst *CreateInBounds(Value *Ptr, |
951 | ArrayRef<Value *> IdxList, |
952 | const Twine &NameStr, |
953 | BasicBlock *InsertAtEnd) { |
954 | return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertAtEnd); |
955 | } |
956 | |
957 | static GetElementPtrInst *CreateInBounds(Type *PointeeType, Value *Ptr, |
958 | ArrayRef<Value *> IdxList, |
959 | const Twine &NameStr, |
960 | BasicBlock *InsertAtEnd) { |
961 | GetElementPtrInst *GEP = |
962 | Create(PointeeType, Ptr, IdxList, NameStr, InsertAtEnd); |
963 | GEP->setIsInBounds(true); |
964 | return GEP; |
965 | } |
966 | |
967 | /// Transparently provide more efficient getOperand methods. |
968 | 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; |
969 | |
970 | Type *getSourceElementType() const { return SourceElementType; } |
971 | |
972 | void setSourceElementType(Type *Ty) { SourceElementType = Ty; } |
973 | void setResultElementType(Type *Ty) { ResultElementType = Ty; } |
974 | |
975 | Type *getResultElementType() const { |
976 | assert(ResultElementType ==((ResultElementType == cast<PointerType>(getType()-> getScalarType())->getElementType()) ? static_cast<void> (0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()" , "/build/llvm-toolchain-snapshot-9~svn360825/include/llvm/IR/Instructions.h" , 977, __PRETTY_FUNCTION__)) |
977 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 977, __PRETTY_FUNCTION__)); |
978 | return ResultElementType; |
979 | } |
980 | |
981 | /// Returns the address space of this instruction's pointer type. |
982 | unsigned getAddressSpace() const { |
983 | // Note that this is always the same as the pointer operand's address space |
984 | // and that is cheaper to compute, so cheat here. |
985 | return getPointerAddressSpace(); |
986 | } |
987 | |
988 | /// Returns the type of the element that would be loaded with |
989 | /// a load instruction with the specified parameters. |
990 | /// |
991 | /// Null is returned if the indices are invalid for the specified |
992 | /// pointer type. |
993 | /// |
994 | static Type *getIndexedType(Type *Ty, ArrayRef<Value *> IdxList); |
995 | static Type *getIndexedType(Type *Ty, ArrayRef<Constant *> IdxList); |
996 | static Type *getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList); |
997 | |
998 | inline op_iterator idx_begin() { return op_begin()+1; } |
999 | inline const_op_iterator idx_begin() const { return op_begin()+1; } |
1000 | inline op_iterator idx_end() { return op_end(); } |
1001 | inline const_op_iterator idx_end() const { return op_end(); } |
1002 | |
1003 | inline iterator_range<op_iterator> indices() { |
1004 | return make_range(idx_begin(), idx_end()); |
1005 | } |
1006 | |
1007 | inline iterator_range<const_op_iterator> indices() const { |
1008 | return make_range(idx_begin(), idx_end()); |
1009 | } |
1010 | |
1011 | Value *getPointerOperand() { |
1012 | return getOperand(0); |
1013 | } |
1014 | const Value *getPointerOperand() const { |
1015 | return getOperand(0); |
1016 | } |
1017 | static unsigned getPointerOperandIndex() { |
1018 | return 0U; // get index for modifying correct operand. |
1019 | } |
1020 | |
1021 | /// Method to return the pointer operand as a |
1022 | /// PointerType. |
1023 | Type *getPointerOperandType() const { |
1024 | return getPointerOperand()->getType(); |
1025 | } |
1026 | |
1027 | /// Returns the address space of the pointer operand. |
1028 | unsigned getPointerAddressSpace() const { |
1029 | return getPointerOperandType()->getPointerAddressSpace(); |
1030 | } |
1031 | |
1032 | /// Returns the pointer type returned by the GEP |
1033 | /// instruction, which may be a vector of pointers. |
1034 | static Type *getGEPReturnType(Value *Ptr, ArrayRef<Value *> IdxList) { |
1035 | return getGEPReturnType( |
1036 | cast<PointerType>(Ptr->getType()->getScalarType())->getElementType(), |
1037 | Ptr, IdxList); |
1038 | } |
1039 | static Type *getGEPReturnType(Type *ElTy, Value *Ptr, |
1040 | ArrayRef<Value *> IdxList) { |
1041 | Type *PtrTy = PointerType::get(checkGEPType(getIndexedType(ElTy, IdxList)), |
1042 | Ptr->getType()->getPointerAddressSpace()); |
1043 | // Vector GEP |
1044 | if (Ptr->getType()->isVectorTy()) { |
1045 | unsigned NumElem = Ptr->getType()->getVectorNumElements(); |
1046 | return VectorType::get(PtrTy, NumElem); |
1047 | } |
1048 | for (Value *Index : IdxList) |
1049 | if (Index->getType()->isVectorTy()) { |
1050 | unsigned NumElem = Index->getType()->getVectorNumElements(); |
1051 | return VectorType::get(PtrTy, NumElem); |
1052 | } |
1053 | // Scalar GEP |
1054 | return PtrTy; |
1055 | } |
1056 | |
1057 | unsigned getNumIndices() const { // Note: always non-negative |
1058 | return getNumOperands() - 1; |
1059 | } |
1060 | |
1061 | bool hasIndices() const { |
1062 | return getNumOperands() > 1; |
1063 | } |
1064 | |
1065 | /// Return true if all of the indices of this GEP are |
1066 | /// zeros. If so, the result pointer and the first operand have the same |
1067 | /// value, just potentially different types. |
1068 | bool hasAllZeroIndices() const; |
1069 | |
1070 | /// Return true if all of the indices of this GEP are |
1071 | /// constant integers. If so, the result pointer and the first operand have |
1072 | /// a constant offset between them. |
1073 | bool hasAllConstantIndices() const; |
1074 | |
1075 | /// Set or clear the inbounds flag on this GEP instruction. |
1076 | /// See LangRef.html for the meaning of inbounds on a getelementptr. |
1077 | void setIsInBounds(bool b = true); |
1078 | |
1079 | /// Determine whether the GEP has the inbounds flag. |
1080 | bool isInBounds() const; |
1081 | |
1082 | /// Accumulate the constant address offset of this GEP if possible. |
1083 | /// |
1084 | /// This routine accepts an APInt into which it will accumulate the constant |
1085 | /// offset of this GEP if the GEP is in fact constant. If the GEP is not |
1086 | /// all-constant, it returns false and the value of the offset APInt is |
1087 | /// undefined (it is *not* preserved!). The APInt passed into this routine |
1088 | /// must be at least as wide as the IntPtr type for the address space of |
1089 | /// the base GEP pointer. |
1090 | bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const; |
1091 | |
1092 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
1093 | static bool classof(const Instruction *I) { |
1094 | return (I->getOpcode() == Instruction::GetElementPtr); |
1095 | } |
1096 | static bool classof(const Value *V) { |
1097 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
1098 | } |
1099 | }; |
1100 | |
1101 | template <> |
1102 | struct OperandTraits<GetElementPtrInst> : |
1103 | public VariadicOperandTraits<GetElementPtrInst, 1> { |
1104 | }; |
1105 | |
1106 | GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr, |
1107 | ArrayRef<Value *> IdxList, unsigned Values, |
1108 | const Twine &NameStr, |
1109 | Instruction *InsertBefore) |
1110 | : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr, |
1111 | OperandTraits<GetElementPtrInst>::op_end(this) - Values, |
1112 | Values, InsertBefore), |
1113 | SourceElementType(PointeeType), |
1114 | ResultElementType(getIndexedType(PointeeType, IdxList)) { |
1115 | assert(ResultElementType ==((ResultElementType == cast<PointerType>(getType()-> getScalarType())->getElementType()) ? static_cast<void> (0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()" , "/build/llvm-toolchain-snapshot-9~svn360825/include/llvm/IR/Instructions.h" , 1116, __PRETTY_FUNCTION__)) |
1116 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 1116, __PRETTY_FUNCTION__)); |
1117 | init(Ptr, IdxList, NameStr); |
1118 | } |
1119 | |
1120 | GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr, |
1121 | ArrayRef<Value *> IdxList, unsigned Values, |
1122 | const Twine &NameStr, |
1123 | BasicBlock *InsertAtEnd) |
1124 | : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr, |
1125 | OperandTraits<GetElementPtrInst>::op_end(this) - Values, |
1126 | Values, InsertAtEnd), |
1127 | SourceElementType(PointeeType), |
1128 | ResultElementType(getIndexedType(PointeeType, IdxList)) { |
1129 | assert(ResultElementType ==((ResultElementType == cast<PointerType>(getType()-> getScalarType())->getElementType()) ? static_cast<void> (0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()" , "/build/llvm-toolchain-snapshot-9~svn360825/include/llvm/IR/Instructions.h" , 1130, __PRETTY_FUNCTION__)) |
1130 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 1130, __PRETTY_FUNCTION__)); |
1131 | init(Ptr, IdxList, NameStr); |
1132 | } |
1133 | |
1134 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 1134, __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-9~svn360825/include/llvm/IR/Instructions.h" , 1134, __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); } |
1135 | |
1136 | //===----------------------------------------------------------------------===// |
1137 | // ICmpInst Class |
1138 | //===----------------------------------------------------------------------===// |
1139 | |
1140 | /// This instruction compares its operands according to the predicate given |
1141 | /// to the constructor. It only operates on integers or pointers. The operands |
1142 | /// must be identical types. |
1143 | /// Represent an integer comparison operator. |
1144 | class ICmpInst: public CmpInst { |
1145 | void AssertOK() { |
1146 | assert(isIntPredicate() &&((isIntPredicate() && "Invalid ICmp predicate value") ? static_cast<void> (0) : __assert_fail ("isIntPredicate() && \"Invalid ICmp predicate value\"" , "/build/llvm-toolchain-snapshot-9~svn360825/include/llvm/IR/Instructions.h" , 1147, __PRETTY_FUNCTION__)) |
1147 | "Invalid ICmp predicate value")((isIntPredicate() && "Invalid ICmp predicate value") ? static_cast<void> (0) : __assert_fail ("isIntPredicate() && \"Invalid ICmp predicate value\"" , "/build/llvm-toolchain-snapshot-9~svn360825/include/llvm/IR/Instructions.h" , 1147, __PRETTY_FUNCTION__)); |
1148 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 1149, __PRETTY_FUNCTION__)) |
1149 | "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-9~svn360825/include/llvm/IR/Instructions.h" , 1149, __PRETTY_FUNCTION__)); |
1150 | // Check that the operands are the right type |
1151 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 1153, __PRETTY_FUNCTION__)) |
1152 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 1153, __PRETTY_FUNCTION__)) |
1153 | "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-9~svn360825/include/llvm/IR/Instructions.h" , 1153, __PRETTY_FUNCTION__)); |
1154 | } |
1155 | |
1156 | protected: |
1157 | // Note: Instruction needs to be a friend here to call cloneImpl. |
1158 | friend class Instruction; |
1159 | |
1160 | /// Clone an identical ICmpInst |
1161 | ICmpInst *cloneImpl() const; |
1162 | |
1163 | public: |
1164 | /// Constructor with insert-before-instruction semantics. |
1165 | ICmpInst( |
1166 | Instruction *InsertBefore, ///< Where to insert |
1167 | Predicate pred, ///< The predicate to use for the comparison |
1168 | Value *LHS, ///< The left-hand-side of the expression |
1169 | Value *RHS, ///< The right-hand-side of the expression |
1170 | const Twine &NameStr = "" ///< Name of the instruction |
1171 | ) : CmpInst(makeCmpResultType(LHS->getType()), |
1172 | Instruction::ICmp, pred, LHS, RHS, NameStr, |
1173 | InsertBefore) { |
1174 | #ifndef NDEBUG |
1175 | AssertOK(); |
1176 | #endif |
1177 | } |
1178 | |
1179 | /// Constructor with insert-at-end semantics. |
1180 | ICmpInst( |
1181 | BasicBlock &InsertAtEnd, ///< Block to insert into. |
1182 | Predicate pred, ///< The predicate to use for the comparison |
1183 | Value *LHS, ///< The left-hand-side of the expression |
1184 | Value *RHS, ///< The right-hand-side of the expression |
1185 | const Twine &NameStr = "" ///< Name of the instruction |
1186 | ) : CmpInst(makeCmpResultType(LHS->getType()), |
1187 | Instruction::ICmp, pred, LHS, RHS, NameStr, |
1188 | &InsertAtEnd) { |
1189 | #ifndef NDEBUG |
1190 | AssertOK(); |
1191 | #endif |
1192 | } |
1193 | |
1194 | /// Constructor with no-insertion semantics |
1195 | ICmpInst( |
1196 | Predicate pred, ///< The predicate to use for the comparison |
1197 | Value *LHS, ///< The left-hand-side of the expression |
1198 | Value *RHS, ///< The right-hand-side of the expression |
1199 | const Twine &NameStr = "" ///< Name of the instruction |
1200 | ) : CmpInst(makeCmpResultType(LHS->getType()), |
1201 | Instruction::ICmp, pred, LHS, RHS, NameStr) { |
1202 | #ifndef NDEBUG |
1203 | AssertOK(); |
1204 | #endif |
1205 | } |
1206 | |
1207 | /// For example, EQ->EQ, SLE->SLE, UGT->SGT, etc. |
1208 | /// @returns the predicate that would be the result if the operand were |
1209 | /// regarded as signed. |
1210 | /// Return the signed version of the predicate |
1211 | Predicate getSignedPredicate() const { |
1212 | return getSignedPredicate(getPredicate()); |
1213 | } |
1214 | |
1215 | /// This is a static version that you can use without an instruction. |
1216 | /// Return the signed version of the predicate. |
1217 | static Predicate getSignedPredicate(Predicate pred); |
1218 | |
1219 | /// For example, EQ->EQ, SLE->ULE, UGT->UGT, etc. |
1220 | /// @returns the predicate that would be the result if the operand were |
1221 | /// regarded as unsigned. |
1222 | /// Return the unsigned version of the predicate |
1223 | Predicate getUnsignedPredicate() const { |
1224 | return getUnsignedPredicate(getPredicate()); |
1225 | } |
1226 | |
1227 | /// This is a static version that you can use without an instruction. |
1228 | /// Return the unsigned version of the predicate. |
1229 | static Predicate getUnsignedPredicate(Predicate pred); |
1230 | |
1231 | /// Return true if this predicate is either EQ or NE. This also |
1232 | /// tests for commutativity. |
1233 | static bool isEquality(Predicate P) { |
1234 | return P == ICMP_EQ || P == ICMP_NE; |
1235 | } |
1236 | |
1237 | /// Return true if this predicate is either EQ or NE. This also |
1238 | /// tests for commutativity. |
1239 | bool isEquality() const { |
1240 | return isEquality(getPredicate()); |
1241 | } |
1242 | |
1243 | /// @returns true if the predicate of this ICmpInst is commutative |
1244 | /// Determine if this relation is commutative. |
1245 | bool isCommutative() const { return isEquality(); } |
1246 | |
1247 | /// Return true if the predicate is relational (not EQ or NE). |
1248 | /// |
1249 | bool isRelational() const { |
1250 | return !isEquality(); |
1251 | } |
1252 | |
1253 | /// Return true if the predicate is relational (not EQ or NE). |
1254 | /// |
1255 | static bool isRelational(Predicate P) { |
1256 | return !isEquality(P); |
1257 | } |
1258 | |
1259 | /// Exchange the two operands to this instruction in such a way that it does |
1260 | /// not modify the semantics of the instruction. The predicate value may be |
1261 | /// changed to retain the same result if the predicate is order dependent |
1262 | /// (e.g. ult). |
1263 | /// Swap operands and adjust predicate. |
1264 | void swapOperands() { |
1265 | setPredicate(getSwappedPredicate()); |
1266 | Op<0>().swap(Op<1>()); |
1267 | } |
1268 | |
1269 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
1270 | static bool classof(const Instruction *I) { |
1271 | return I->getOpcode() == Instruction::ICmp; |
1272 | } |
1273 | static bool classof(const Value *V) { |
1274 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
1275 | } |
1276 | }; |
1277 | |
1278 | //===----------------------------------------------------------------------===// |
1279 | // FCmpInst Class |
1280 | //===----------------------------------------------------------------------===// |
1281 | |
1282 | /// This instruction compares its operands according to the predicate given |
1283 | /// to the constructor. It only operates on floating point values or packed |
1284 | /// vectors of floating point values. The operands must be identical types. |
1285 | /// Represents a floating point comparison operator. |
1286 | class FCmpInst: public CmpInst { |
1287 | void AssertOK() { |
1288 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 1288, __PRETTY_FUNCTION__)); |
1289 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 1290, __PRETTY_FUNCTION__)) |
1290 | "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-9~svn360825/include/llvm/IR/Instructions.h" , 1290, __PRETTY_FUNCTION__)); |
1291 | // Check that the operands are the right type |
1292 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 1293, __PRETTY_FUNCTION__)) |
1293 | "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-9~svn360825/include/llvm/IR/Instructions.h" , 1293, __PRETTY_FUNCTION__)); |
1294 | } |
1295 | |
1296 | protected: |
1297 | // Note: Instruction needs to be a friend here to call cloneImpl. |
1298 | friend class Instruction; |
1299 | |
1300 | /// Clone an identical FCmpInst |
1301 | FCmpInst *cloneImpl() const; |
1302 | |
1303 | public: |
1304 | /// Constructor with insert-before-instruction semantics. |
1305 | FCmpInst( |
1306 | Instruction *InsertBefore, ///< Where to insert |
1307 | Predicate pred, ///< The predicate to use for the comparison |
1308 | Value *LHS, ///< The left-hand-side of the expression |
1309 | Value *RHS, ///< The right-hand-side of the expression |
1310 | const Twine &NameStr = "" ///< Name of the instruction |
1311 | ) : CmpInst(makeCmpResultType(LHS->getType()), |
1312 | Instruction::FCmp, pred, LHS, RHS, NameStr, |
1313 | InsertBefore) { |
1314 | AssertOK(); |
1315 | } |
1316 | |
1317 | /// Constructor with insert-at-end semantics. |
1318 | FCmpInst( |
1319 | BasicBlock &InsertAtEnd, ///< Block to insert into. |
1320 | Predicate pred, ///< The predicate to use for the comparison |
1321 | Value *LHS, ///< The left-hand-side of the expression |
1322 | Value *RHS, ///< The right-hand-side of the expression |
1323 | const Twine &NameStr = "" ///< Name of the instruction |
1324 | ) : CmpInst(makeCmpResultType(LHS->getType()), |
1325 | Instruction::FCmp, pred, LHS, RHS, NameStr, |
1326 | &InsertAtEnd) { |
1327 | AssertOK(); |
1328 | } |
1329 | |
1330 | /// Constructor with no-insertion semantics |
1331 | FCmpInst( |
1332 | Predicate Pred, ///< The predicate to use for the comparison |
1333 | Value *LHS, ///< The left-hand-side of the expression |
1334 | Value *RHS, ///< The right-hand-side of the expression |
1335 | const Twine &NameStr = "", ///< Name of the instruction |
1336 | Instruction *FlagsSource = nullptr |
1337 | ) : CmpInst(makeCmpResultType(LHS->getType()), Instruction::FCmp, Pred, LHS, |
1338 | RHS, NameStr, nullptr, FlagsSource) { |
1339 | AssertOK(); |
1340 | } |
1341 | |
1342 | /// @returns true if the predicate of this instruction is EQ or NE. |
1343 | /// Determine if this is an equality predicate. |
1344 | static bool isEquality(Predicate Pred) { |
1345 | return Pred == FCMP_OEQ || Pred == FCMP_ONE || Pred == FCMP_UEQ || |
1346 | Pred == FCMP_UNE; |
1347 | } |
1348 | |
1349 | /// @returns true if the predicate of this instruction is EQ or NE. |
1350 | /// Determine if this is an equality predicate. |
1351 | bool isEquality() const { return isEquality(getPredicate()); } |
1352 | |
1353 | /// @returns true if the predicate of this instruction is commutative. |
1354 | /// Determine if this is a commutative predicate. |
1355 | bool isCommutative() const { |
1356 | return isEquality() || |
1357 | getPredicate() == FCMP_FALSE || |
1358 | getPredicate() == FCMP_TRUE || |
1359 | getPredicate() == FCMP_ORD || |
1360 | getPredicate() == FCMP_UNO; |
1361 | } |
1362 | |
1363 | /// @returns true if the predicate is relational (not EQ or NE). |
1364 | /// Determine if this a relational predicate. |
1365 | bool isRelational() const { return !isEquality(); } |
1366 | |
1367 | /// Exchange the two operands to this instruction in such a way that it does |
1368 | /// not modify the semantics of the instruction. The predicate value may be |
1369 | /// changed to retain the same result if the predicate is order dependent |
1370 | /// (e.g. ult). |
1371 | /// Swap operands and adjust predicate. |
1372 | void swapOperands() { |
1373 | setPredicate(getSwappedPredicate()); |
1374 | Op<0>().swap(Op<1>()); |
1375 | } |
1376 | |
1377 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
1378 | static bool classof(const Instruction *I) { |
1379 | return I->getOpcode() == Instruction::FCmp; |
1380 | } |
1381 | static bool classof(const Value *V) { |
1382 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
1383 | } |
1384 | }; |
1385 | |
1386 | //===----------------------------------------------------------------------===// |
1387 | /// This class represents a function call, abstracting a target |
1388 | /// machine's calling convention. This class uses low bit of the SubClassData |
1389 | /// field to indicate whether or not this is a tail call. The rest of the bits |
1390 | /// hold the calling convention of the call. |
1391 | /// |
1392 | class CallInst : public CallBase { |
1393 | CallInst(const CallInst &CI); |
1394 | |
1395 | /// Construct a CallInst given a range of arguments. |
1396 | /// Construct a CallInst from a range of arguments |
1397 | inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1398 | ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr, |
1399 | Instruction *InsertBefore); |
1400 | |
1401 | inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1402 | const Twine &NameStr, Instruction *InsertBefore) |
1403 | : CallInst(Ty, Func, Args, None, NameStr, InsertBefore) {} |
1404 | |
1405 | /// Construct a CallInst given a range of arguments. |
1406 | /// Construct a CallInst from a range of arguments |
1407 | inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1408 | ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr, |
1409 | BasicBlock *InsertAtEnd); |
1410 | |
1411 | explicit CallInst(FunctionType *Ty, Value *F, const Twine &NameStr, |
1412 | Instruction *InsertBefore); |
1413 | |
1414 | CallInst(FunctionType *ty, Value *F, const Twine &NameStr, |
1415 | BasicBlock *InsertAtEnd); |
1416 | |
1417 | void init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args, |
1418 | ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr); |
1419 | void init(FunctionType *FTy, Value *Func, const Twine &NameStr); |
1420 | |
1421 | /// Compute the number of operands to allocate. |
1422 | static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) { |
1423 | // We need one operand for the called function, plus the input operand |
1424 | // counts provided. |
1425 | return 1 + NumArgs + NumBundleInputs; |
1426 | } |
1427 | |
1428 | protected: |
1429 | // Note: Instruction needs to be a friend here to call cloneImpl. |
1430 | friend class Instruction; |
1431 | |
1432 | CallInst *cloneImpl() const; |
1433 | |
1434 | public: |
1435 | static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr = "", |
1436 | Instruction *InsertBefore = nullptr) { |
1437 | return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertBefore); |
1438 | } |
1439 | |
1440 | static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1441 | const Twine &NameStr, |
1442 | Instruction *InsertBefore = nullptr) { |
1443 | return new (ComputeNumOperands(Args.size())) |
1444 | CallInst(Ty, Func, Args, None, NameStr, InsertBefore); |
1445 | } |
1446 | |
1447 | static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1448 | ArrayRef<OperandBundleDef> Bundles = None, |
1449 | const Twine &NameStr = "", |
1450 | Instruction *InsertBefore = nullptr) { |
1451 | const int NumOperands = |
1452 | ComputeNumOperands(Args.size(), CountBundleInputs(Bundles)); |
1453 | const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo); |
1454 | |
1455 | return new (NumOperands, DescriptorBytes) |
1456 | CallInst(Ty, Func, Args, Bundles, NameStr, InsertBefore); |
1457 | } |
1458 | |
1459 | static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr, |
1460 | BasicBlock *InsertAtEnd) { |
1461 | return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertAtEnd); |
1462 | } |
1463 | |
1464 | static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1465 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
1466 | return new (ComputeNumOperands(Args.size())) |
1467 | CallInst(Ty, Func, Args, None, NameStr, InsertAtEnd); |
1468 | } |
1469 | |
1470 | static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1471 | ArrayRef<OperandBundleDef> Bundles, |
1472 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
1473 | const int NumOperands = |
1474 | ComputeNumOperands(Args.size(), CountBundleInputs(Bundles)); |
1475 | const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo); |
1476 | |
1477 | return new (NumOperands, DescriptorBytes) |
1478 | CallInst(Ty, Func, Args, Bundles, NameStr, InsertAtEnd); |
1479 | } |
1480 | |
1481 | static CallInst *Create(FunctionCallee Func, const Twine &NameStr = "", |
1482 | Instruction *InsertBefore = nullptr) { |
1483 | return Create(Func.getFunctionType(), Func.getCallee(), NameStr, |
1484 | InsertBefore); |
1485 | } |
1486 | |
1487 | static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args, |
1488 | ArrayRef<OperandBundleDef> Bundles = None, |
1489 | const Twine &NameStr = "", |
1490 | Instruction *InsertBefore = nullptr) { |
1491 | return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles, |
1492 | NameStr, InsertBefore); |
1493 | } |
1494 | |
1495 | static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args, |
1496 | const Twine &NameStr, |
1497 | Instruction *InsertBefore = nullptr) { |
1498 | return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr, |
1499 | InsertBefore); |
1500 | } |
1501 | |
1502 | static CallInst *Create(FunctionCallee Func, const Twine &NameStr, |
1503 | BasicBlock *InsertAtEnd) { |
1504 | return Create(Func.getFunctionType(), Func.getCallee(), NameStr, |
1505 | InsertAtEnd); |
1506 | } |
1507 | |
1508 | static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args, |
1509 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
1510 | return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr, |
1511 | InsertAtEnd); |
1512 | } |
1513 | |
1514 | static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args, |
1515 | ArrayRef<OperandBundleDef> Bundles, |
1516 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
1517 | return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles, |
1518 | NameStr, InsertAtEnd); |
1519 | } |
1520 | |
1521 | // Deprecated [opaque pointer types] |
1522 | static CallInst *Create(Value *Func, const Twine &NameStr = "", |
1523 | Instruction *InsertBefore = nullptr) { |
1524 | return Create(cast<FunctionType>( |
1525 | cast<PointerType>(Func->getType())->getElementType()), |
1526 | Func, NameStr, InsertBefore); |
1527 | } |
1528 | |
1529 | // Deprecated [opaque pointer types] |
1530 | static CallInst *Create(Value *Func, ArrayRef<Value *> Args, |
1531 | const Twine &NameStr, |
1532 | Instruction *InsertBefore = nullptr) { |
1533 | return Create(cast<FunctionType>( |
1534 | cast<PointerType>(Func->getType())->getElementType()), |
1535 | Func, Args, NameStr, InsertBefore); |
1536 | } |
1537 | |
1538 | // Deprecated [opaque pointer types] |
1539 | static CallInst *Create(Value *Func, ArrayRef<Value *> Args, |
1540 | ArrayRef<OperandBundleDef> Bundles = None, |
1541 | const Twine &NameStr = "", |
1542 | Instruction *InsertBefore = nullptr) { |
1543 | return Create(cast<FunctionType>( |
1544 | cast<PointerType>(Func->getType())->getElementType()), |
1545 | Func, Args, Bundles, NameStr, InsertBefore); |
1546 | } |
1547 | |
1548 | // Deprecated [opaque pointer types] |
1549 | static CallInst *Create(Value *Func, const Twine &NameStr, |
1550 | BasicBlock *InsertAtEnd) { |
1551 | return Create(cast<FunctionType>( |
1552 | cast<PointerType>(Func->getType())->getElementType()), |
1553 | Func, NameStr, InsertAtEnd); |
1554 | } |
1555 | |
1556 | // Deprecated [opaque pointer types] |
1557 | static CallInst *Create(Value *Func, ArrayRef<Value *> Args, |
1558 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
1559 | return Create(cast<FunctionType>( |
1560 | cast<PointerType>(Func->getType())->getElementType()), |
1561 | Func, Args, NameStr, InsertAtEnd); |
1562 | } |
1563 | |
1564 | // Deprecated [opaque pointer types] |
1565 | static CallInst *Create(Value *Func, ArrayRef<Value *> Args, |
1566 | ArrayRef<OperandBundleDef> Bundles, |
1567 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
1568 | return Create(cast<FunctionType>( |
1569 | cast<PointerType>(Func->getType())->getElementType()), |
1570 | Func, Args, Bundles, NameStr, InsertAtEnd); |
1571 | } |
1572 | |
1573 | /// Create a clone of \p CI with a different set of operand bundles and |
1574 | /// insert it before \p InsertPt. |
1575 | /// |
1576 | /// The returned call instruction is identical \p CI in every way except that |
1577 | /// the operand bundles for the new instruction are set to the operand bundles |
1578 | /// in \p Bundles. |
1579 | static CallInst *Create(CallInst *CI, ArrayRef<OperandBundleDef> Bundles, |
1580 | Instruction *InsertPt = nullptr); |
1581 | |
1582 | /// Generate the IR for a call to malloc: |
1583 | /// 1. Compute the malloc call's argument as the specified type's size, |
1584 | /// possibly multiplied by the array size if the array size is not |
1585 | /// constant 1. |
1586 | /// 2. Call malloc with that argument. |
1587 | /// 3. Bitcast the result of the malloc call to the specified type. |
1588 | static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy, |
1589 | Type *AllocTy, Value *AllocSize, |
1590 | Value *ArraySize = nullptr, |
1591 | Function *MallocF = nullptr, |
1592 | const Twine &Name = ""); |
1593 | static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy, |
1594 | Type *AllocTy, Value *AllocSize, |
1595 | Value *ArraySize = nullptr, |
1596 | Function *MallocF = nullptr, |
1597 | const Twine &Name = ""); |
1598 | static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy, |
1599 | Type *AllocTy, Value *AllocSize, |
1600 | Value *ArraySize = nullptr, |
1601 | ArrayRef<OperandBundleDef> Bundles = None, |
1602 | Function *MallocF = nullptr, |
1603 | const Twine &Name = ""); |
1604 | static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, 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 | /// Generate the IR for a call to the builtin free function. |
1611 | static Instruction *CreateFree(Value *Source, Instruction *InsertBefore); |
1612 | static Instruction *CreateFree(Value *Source, BasicBlock *InsertAtEnd); |
1613 | static Instruction *CreateFree(Value *Source, |
1614 | ArrayRef<OperandBundleDef> Bundles, |
1615 | Instruction *InsertBefore); |
1616 | static Instruction *CreateFree(Value *Source, |
1617 | ArrayRef<OperandBundleDef> Bundles, |
1618 | BasicBlock *InsertAtEnd); |
1619 | |
1620 | // Note that 'musttail' implies 'tail'. |
1621 | enum TailCallKind { |
1622 | TCK_None = 0, |
1623 | TCK_Tail = 1, |
1624 | TCK_MustTail = 2, |
1625 | TCK_NoTail = 3 |
1626 | }; |
1627 | TailCallKind getTailCallKind() const { |
1628 | return TailCallKind(getSubclassDataFromInstruction() & 3); |
1629 | } |
1630 | |
1631 | bool isTailCall() const { |
1632 | unsigned Kind = getSubclassDataFromInstruction() & 3; |
1633 | return Kind == TCK_Tail || Kind == TCK_MustTail; |
1634 | } |
1635 | |
1636 | bool isMustTailCall() const { |
1637 | return (getSubclassDataFromInstruction() & 3) == TCK_MustTail; |
1638 | } |
1639 | |
1640 | bool isNoTailCall() const { |
1641 | return (getSubclassDataFromInstruction() & 3) == TCK_NoTail; |
1642 | } |
1643 | |
1644 | void setTailCall(bool isTC = true) { |
1645 | setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) | |
1646 | unsigned(isTC ? TCK_Tail : TCK_None)); |
1647 | } |
1648 | |
1649 | void setTailCallKind(TailCallKind TCK) { |
1650 | setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) | |
1651 | unsigned(TCK)); |
1652 | } |
1653 | |
1654 | /// Return true if the call can return twice |
1655 | bool canReturnTwice() const { return hasFnAttr(Attribute::ReturnsTwice); } |
1656 | void setCanReturnTwice() { |
1657 | addAttribute(AttributeList::FunctionIndex, Attribute::ReturnsTwice); |
1658 | } |
1659 | |
1660 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
1661 | static bool classof(const Instruction *I) { |
1662 | return I->getOpcode() == Instruction::Call; |
1663 | } |
1664 | static bool classof(const Value *V) { |
1665 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
1666 | } |
1667 | |
1668 | /// Updates profile metadata by scaling it by \p S / \p T. |
1669 | void updateProfWeight(uint64_t S, uint64_t T); |
1670 | |
1671 | private: |
1672 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
1673 | // method so that subclasses cannot accidentally use it. |
1674 | void setInstructionSubclassData(unsigned short D) { |
1675 | Instruction::setInstructionSubclassData(D); |
1676 | } |
1677 | }; |
1678 | |
1679 | CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1680 | ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr, |
1681 | BasicBlock *InsertAtEnd) |
1682 | : CallBase(Ty->getReturnType(), Instruction::Call, |
1683 | OperandTraits<CallBase>::op_end(this) - |
1684 | (Args.size() + CountBundleInputs(Bundles) + 1), |
1685 | unsigned(Args.size() + CountBundleInputs(Bundles) + 1), |
1686 | InsertAtEnd) { |
1687 | init(Ty, Func, Args, Bundles, NameStr); |
1688 | } |
1689 | |
1690 | CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args, |
1691 | ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr, |
1692 | Instruction *InsertBefore) |
1693 | : CallBase(Ty->getReturnType(), Instruction::Call, |
1694 | OperandTraits<CallBase>::op_end(this) - |
1695 | (Args.size() + CountBundleInputs(Bundles) + 1), |
1696 | unsigned(Args.size() + CountBundleInputs(Bundles) + 1), |
1697 | InsertBefore) { |
1698 | init(Ty, Func, Args, Bundles, NameStr); |
1699 | } |
1700 | |
1701 | //===----------------------------------------------------------------------===// |
1702 | // SelectInst Class |
1703 | //===----------------------------------------------------------------------===// |
1704 | |
1705 | /// This class represents the LLVM 'select' instruction. |
1706 | /// |
1707 | class SelectInst : public Instruction { |
1708 | SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr, |
1709 | Instruction *InsertBefore) |
1710 | : Instruction(S1->getType(), Instruction::Select, |
1711 | &Op<0>(), 3, InsertBefore) { |
1712 | init(C, S1, S2); |
1713 | setName(NameStr); |
1714 | } |
1715 | |
1716 | SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr, |
1717 | BasicBlock *InsertAtEnd) |
1718 | : Instruction(S1->getType(), Instruction::Select, |
1719 | &Op<0>(), 3, InsertAtEnd) { |
1720 | init(C, S1, S2); |
1721 | setName(NameStr); |
1722 | } |
1723 | |
1724 | void init(Value *C, Value *S1, Value *S2) { |
1725 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 1725, __PRETTY_FUNCTION__)); |
1726 | Op<0>() = C; |
1727 | Op<1>() = S1; |
1728 | Op<2>() = S2; |
1729 | } |
1730 | |
1731 | protected: |
1732 | // Note: Instruction needs to be a friend here to call cloneImpl. |
1733 | friend class Instruction; |
1734 | |
1735 | SelectInst *cloneImpl() const; |
1736 | |
1737 | public: |
1738 | static SelectInst *Create(Value *C, Value *S1, Value *S2, |
1739 | const Twine &NameStr = "", |
1740 | Instruction *InsertBefore = nullptr, |
1741 | Instruction *MDFrom = nullptr) { |
1742 | SelectInst *Sel = new(3) SelectInst(C, S1, S2, NameStr, InsertBefore); |
1743 | if (MDFrom) |
1744 | Sel->copyMetadata(*MDFrom); |
1745 | return Sel; |
1746 | } |
1747 | |
1748 | static SelectInst *Create(Value *C, Value *S1, Value *S2, |
1749 | const Twine &NameStr, |
1750 | BasicBlock *InsertAtEnd) { |
1751 | return new(3) SelectInst(C, S1, S2, NameStr, InsertAtEnd); |
1752 | } |
1753 | |
1754 | const Value *getCondition() const { return Op<0>(); } |
1755 | const Value *getTrueValue() const { return Op<1>(); } |
1756 | const Value *getFalseValue() const { return Op<2>(); } |
1757 | Value *getCondition() { return Op<0>(); } |
1758 | Value *getTrueValue() { return Op<1>(); } |
1759 | Value *getFalseValue() { return Op<2>(); } |
1760 | |
1761 | void setCondition(Value *V) { Op<0>() = V; } |
1762 | void setTrueValue(Value *V) { Op<1>() = V; } |
1763 | void setFalseValue(Value *V) { Op<2>() = V; } |
1764 | |
1765 | /// Return a string if the specified operands are invalid |
1766 | /// for a select operation, otherwise return null. |
1767 | static const char *areInvalidOperands(Value *Cond, Value *True, Value *False); |
1768 | |
1769 | /// Transparently provide more efficient getOperand methods. |
1770 | 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; |
1771 | |
1772 | OtherOps getOpcode() const { |
1773 | return static_cast<OtherOps>(Instruction::getOpcode()); |
1774 | } |
1775 | |
1776 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
1777 | static bool classof(const Instruction *I) { |
1778 | return I->getOpcode() == Instruction::Select; |
1779 | } |
1780 | static bool classof(const Value *V) { |
1781 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
1782 | } |
1783 | }; |
1784 | |
1785 | template <> |
1786 | struct OperandTraits<SelectInst> : public FixedNumOperandTraits<SelectInst, 3> { |
1787 | }; |
1788 | |
1789 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 1789, __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-9~svn360825/include/llvm/IR/Instructions.h" , 1789, __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); } |
1790 | |
1791 | //===----------------------------------------------------------------------===// |
1792 | // VAArgInst Class |
1793 | //===----------------------------------------------------------------------===// |
1794 | |
1795 | /// This class represents the va_arg llvm instruction, which returns |
1796 | /// an argument of the specified type given a va_list and increments that list |
1797 | /// |
1798 | class VAArgInst : public UnaryInstruction { |
1799 | protected: |
1800 | // Note: Instruction needs to be a friend here to call cloneImpl. |
1801 | friend class Instruction; |
1802 | |
1803 | VAArgInst *cloneImpl() const; |
1804 | |
1805 | public: |
1806 | VAArgInst(Value *List, Type *Ty, const Twine &NameStr = "", |
1807 | Instruction *InsertBefore = nullptr) |
1808 | : UnaryInstruction(Ty, VAArg, List, InsertBefore) { |
1809 | setName(NameStr); |
1810 | } |
1811 | |
1812 | VAArgInst(Value *List, Type *Ty, const Twine &NameStr, |
1813 | BasicBlock *InsertAtEnd) |
1814 | : UnaryInstruction(Ty, VAArg, List, InsertAtEnd) { |
1815 | setName(NameStr); |
1816 | } |
1817 | |
1818 | Value *getPointerOperand() { return getOperand(0); } |
1819 | const Value *getPointerOperand() const { return getOperand(0); } |
1820 | static unsigned getPointerOperandIndex() { return 0U; } |
1821 | |
1822 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
1823 | static bool classof(const Instruction *I) { |
1824 | return I->getOpcode() == VAArg; |
1825 | } |
1826 | static bool classof(const Value *V) { |
1827 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
1828 | } |
1829 | }; |
1830 | |
1831 | //===----------------------------------------------------------------------===// |
1832 | // ExtractElementInst Class |
1833 | //===----------------------------------------------------------------------===// |
1834 | |
1835 | /// This instruction extracts a single (scalar) |
1836 | /// element from a VectorType value |
1837 | /// |
1838 | class ExtractElementInst : public Instruction { |
1839 | ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr = "", |
1840 | Instruction *InsertBefore = nullptr); |
1841 | ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr, |
1842 | BasicBlock *InsertAtEnd); |
1843 | |
1844 | protected: |
1845 | // Note: Instruction needs to be a friend here to call cloneImpl. |
1846 | friend class Instruction; |
1847 | |
1848 | ExtractElementInst *cloneImpl() const; |
1849 | |
1850 | public: |
1851 | static ExtractElementInst *Create(Value *Vec, Value *Idx, |
1852 | const Twine &NameStr = "", |
1853 | Instruction *InsertBefore = nullptr) { |
1854 | return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertBefore); |
1855 | } |
1856 | |
1857 | static ExtractElementInst *Create(Value *Vec, Value *Idx, |
1858 | const Twine &NameStr, |
1859 | BasicBlock *InsertAtEnd) { |
1860 | return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertAtEnd); |
1861 | } |
1862 | |
1863 | /// Return true if an extractelement instruction can be |
1864 | /// formed with the specified operands. |
1865 | static bool isValidOperands(const Value *Vec, const Value *Idx); |
1866 | |
1867 | Value *getVectorOperand() { return Op<0>(); } |
1868 | Value *getIndexOperand() { return Op<1>(); } |
1869 | const Value *getVectorOperand() const { return Op<0>(); } |
1870 | const Value *getIndexOperand() const { return Op<1>(); } |
1871 | |
1872 | VectorType *getVectorOperandType() const { |
1873 | return cast<VectorType>(getVectorOperand()->getType()); |
1874 | } |
1875 | |
1876 | /// Transparently provide more efficient getOperand methods. |
1877 | 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; |
1878 | |
1879 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
1880 | static bool classof(const Instruction *I) { |
1881 | return I->getOpcode() == Instruction::ExtractElement; |
1882 | } |
1883 | static bool classof(const Value *V) { |
1884 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
1885 | } |
1886 | }; |
1887 | |
1888 | template <> |
1889 | struct OperandTraits<ExtractElementInst> : |
1890 | public FixedNumOperandTraits<ExtractElementInst, 2> { |
1891 | }; |
1892 | |
1893 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 1893, __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-9~svn360825/include/llvm/IR/Instructions.h" , 1893, __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); } |
1894 | |
1895 | //===----------------------------------------------------------------------===// |
1896 | // InsertElementInst Class |
1897 | //===----------------------------------------------------------------------===// |
1898 | |
1899 | /// This instruction inserts a single (scalar) |
1900 | /// element into a VectorType value |
1901 | /// |
1902 | class InsertElementInst : public Instruction { |
1903 | InsertElementInst(Value *Vec, Value *NewElt, Value *Idx, |
1904 | const Twine &NameStr = "", |
1905 | Instruction *InsertBefore = nullptr); |
1906 | InsertElementInst(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr, |
1907 | BasicBlock *InsertAtEnd); |
1908 | |
1909 | protected: |
1910 | // Note: Instruction needs to be a friend here to call cloneImpl. |
1911 | friend class Instruction; |
1912 | |
1913 | InsertElementInst *cloneImpl() const; |
1914 | |
1915 | public: |
1916 | static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx, |
1917 | const Twine &NameStr = "", |
1918 | Instruction *InsertBefore = nullptr) { |
1919 | return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertBefore); |
1920 | } |
1921 | |
1922 | static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx, |
1923 | const Twine &NameStr, |
1924 | BasicBlock *InsertAtEnd) { |
1925 | return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertAtEnd); |
1926 | } |
1927 | |
1928 | /// Return true if an insertelement instruction can be |
1929 | /// formed with the specified operands. |
1930 | static bool isValidOperands(const Value *Vec, const Value *NewElt, |
1931 | const Value *Idx); |
1932 | |
1933 | /// Overload to return most specific vector type. |
1934 | /// |
1935 | VectorType *getType() const { |
1936 | return cast<VectorType>(Instruction::getType()); |
1937 | } |
1938 | |
1939 | /// Transparently provide more efficient getOperand methods. |
1940 | 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; |
1941 | |
1942 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
1943 | static bool classof(const Instruction *I) { |
1944 | return I->getOpcode() == Instruction::InsertElement; |
1945 | } |
1946 | static bool classof(const Value *V) { |
1947 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
1948 | } |
1949 | }; |
1950 | |
1951 | template <> |
1952 | struct OperandTraits<InsertElementInst> : |
1953 | public FixedNumOperandTraits<InsertElementInst, 3> { |
1954 | }; |
1955 | |
1956 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 1956, __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-9~svn360825/include/llvm/IR/Instructions.h" , 1956, __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); } |
1957 | |
1958 | //===----------------------------------------------------------------------===// |
1959 | // ShuffleVectorInst Class |
1960 | //===----------------------------------------------------------------------===// |
1961 | |
1962 | /// This instruction constructs a fixed permutation of two |
1963 | /// input vectors. |
1964 | /// |
1965 | class ShuffleVectorInst : public Instruction { |
1966 | protected: |
1967 | // Note: Instruction needs to be a friend here to call cloneImpl. |
1968 | friend class Instruction; |
1969 | |
1970 | ShuffleVectorInst *cloneImpl() const; |
1971 | |
1972 | public: |
1973 | ShuffleVectorInst(Value *V1, Value *V2, Value *Mask, |
1974 | const Twine &NameStr = "", |
1975 | Instruction *InsertBefor = nullptr); |
1976 | ShuffleVectorInst(Value *V1, Value *V2, Value *Mask, |
1977 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
1978 | |
1979 | // allocate space for exactly three operands |
1980 | void *operator new(size_t s) { |
1981 | return User::operator new(s, 3); |
1982 | } |
1983 | |
1984 | /// Swap the first 2 operands and adjust the mask to preserve the semantics |
1985 | /// of the instruction. |
1986 | void commute(); |
1987 | |
1988 | /// Return true if a shufflevector instruction can be |
1989 | /// formed with the specified operands. |
1990 | static bool isValidOperands(const Value *V1, const Value *V2, |
1991 | const Value *Mask); |
1992 | |
1993 | /// Overload to return most specific vector type. |
1994 | /// |
1995 | VectorType *getType() const { |
1996 | return cast<VectorType>(Instruction::getType()); |
1997 | } |
1998 | |
1999 | /// Transparently provide more efficient getOperand methods. |
2000 | 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; |
2001 | |
2002 | Constant *getMask() const { |
2003 | return cast<Constant>(getOperand(2)); |
2004 | } |
2005 | |
2006 | /// Return the shuffle mask value for the specified element of the mask. |
2007 | /// Return -1 if the element is undef. |
2008 | static int getMaskValue(const Constant *Mask, unsigned Elt); |
2009 | |
2010 | /// Return the shuffle mask value of this instruction for the given element |
2011 | /// index. Return -1 if the element is undef. |
2012 | int getMaskValue(unsigned Elt) const { |
2013 | return getMaskValue(getMask(), Elt); |
2014 | } |
2015 | |
2016 | /// Convert the input shuffle mask operand to a vector of integers. Undefined |
2017 | /// elements of the mask are returned as -1. |
2018 | static void getShuffleMask(const Constant *Mask, |
2019 | SmallVectorImpl<int> &Result); |
2020 | |
2021 | /// Return the mask for this instruction as a vector of integers. Undefined |
2022 | /// elements of the mask are returned as -1. |
2023 | void getShuffleMask(SmallVectorImpl<int> &Result) const { |
2024 | return getShuffleMask(getMask(), Result); |
2025 | } |
2026 | |
2027 | SmallVector<int, 16> getShuffleMask() const { |
2028 | SmallVector<int, 16> Mask; |
2029 | getShuffleMask(Mask); |
2030 | return Mask; |
2031 | } |
2032 | |
2033 | /// Return true if this shuffle returns a vector with a different number of |
2034 | /// elements than its source vectors. |
2035 | /// Examples: shufflevector <4 x n> A, <4 x n> B, <1,2,3> |
2036 | /// shufflevector <4 x n> A, <4 x n> B, <1,2,3,4,5> |
2037 | bool changesLength() const { |
2038 | unsigned NumSourceElts = Op<0>()->getType()->getVectorNumElements(); |
2039 | unsigned NumMaskElts = getMask()->getType()->getVectorNumElements(); |
2040 | return NumSourceElts != NumMaskElts; |
2041 | } |
2042 | |
2043 | /// Return true if this shuffle returns a vector with a greater number of |
2044 | /// elements than its source vectors. |
2045 | /// Example: shufflevector <2 x n> A, <2 x n> B, <1,2,3> |
2046 | bool increasesLength() const { |
2047 | unsigned NumSourceElts = Op<0>()->getType()->getVectorNumElements(); |
2048 | unsigned NumMaskElts = getMask()->getType()->getVectorNumElements(); |
2049 | return NumSourceElts < NumMaskElts; |
2050 | } |
2051 | |
2052 | /// Return true if this shuffle mask chooses elements from exactly one source |
2053 | /// vector. |
2054 | /// Example: <7,5,undef,7> |
2055 | /// This assumes that vector operands are the same length as the mask. |
2056 | static bool isSingleSourceMask(ArrayRef<int> Mask); |
2057 | static bool isSingleSourceMask(const Constant *Mask) { |
2058 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 2058, __PRETTY_FUNCTION__)); |
2059 | SmallVector<int, 16> MaskAsInts; |
2060 | getShuffleMask(Mask, MaskAsInts); |
2061 | return isSingleSourceMask(MaskAsInts); |
2062 | } |
2063 | |
2064 | /// Return true if this shuffle chooses elements from exactly one source |
2065 | /// vector without changing the length of that vector. |
2066 | /// Example: shufflevector <4 x n> A, <4 x n> B, <3,0,undef,3> |
2067 | /// TODO: Optionally allow length-changing shuffles. |
2068 | bool isSingleSource() const { |
2069 | return !changesLength() && isSingleSourceMask(getMask()); |
2070 | } |
2071 | |
2072 | /// Return true if this shuffle mask chooses elements from exactly one source |
2073 | /// vector without lane crossings. A shuffle using this mask is not |
2074 | /// necessarily a no-op because it may change the number of elements from its |
2075 | /// input vectors or it may provide demanded bits knowledge via undef lanes. |
2076 | /// Example: <undef,undef,2,3> |
2077 | static bool isIdentityMask(ArrayRef<int> Mask); |
2078 | static bool isIdentityMask(const Constant *Mask) { |
2079 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 2079, __PRETTY_FUNCTION__)); |
2080 | SmallVector<int, 16> MaskAsInts; |
2081 | getShuffleMask(Mask, MaskAsInts); |
2082 | return isIdentityMask(MaskAsInts); |
2083 | } |
2084 | |
2085 | /// Return true if this shuffle chooses elements from exactly one source |
2086 | /// vector without lane crossings and does not change the number of elements |
2087 | /// from its input vectors. |
2088 | /// Example: shufflevector <4 x n> A, <4 x n> B, <4,undef,6,undef> |
2089 | bool isIdentity() const { |
2090 | return !changesLength() && isIdentityMask(getShuffleMask()); |
2091 | } |
2092 | |
2093 | /// Return true if this shuffle lengthens exactly one source vector with |
2094 | /// undefs in the high elements. |
2095 | bool isIdentityWithPadding() const; |
2096 | |
2097 | /// Return true if this shuffle extracts the first N elements of exactly one |
2098 | /// source vector. |
2099 | bool isIdentityWithExtract() const; |
2100 | |
2101 | /// Return true if this shuffle concatenates its 2 source vectors. This |
2102 | /// returns false if either input is undefined. In that case, the shuffle is |
2103 | /// is better classified as an identity with padding operation. |
2104 | bool isConcat() const; |
2105 | |
2106 | /// Return true if this shuffle mask chooses elements from its source vectors |
2107 | /// without lane crossings. A shuffle using this mask would be |
2108 | /// equivalent to a vector select with a constant condition operand. |
2109 | /// Example: <4,1,6,undef> |
2110 | /// This returns false if the mask does not choose from both input vectors. |
2111 | /// In that case, the shuffle is better classified as an identity shuffle. |
2112 | /// This assumes that vector operands are the same length as the mask |
2113 | /// (a length-changing shuffle can never be equivalent to a vector select). |
2114 | static bool isSelectMask(ArrayRef<int> Mask); |
2115 | static bool isSelectMask(const Constant *Mask) { |
2116 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 2116, __PRETTY_FUNCTION__)); |
2117 | SmallVector<int, 16> MaskAsInts; |
2118 | getShuffleMask(Mask, MaskAsInts); |
2119 | return isSelectMask(MaskAsInts); |
2120 | } |
2121 | |
2122 | /// Return true if this shuffle chooses elements from its source vectors |
2123 | /// without lane crossings and all operands have the same number of elements. |
2124 | /// In other words, this shuffle is equivalent to a vector select with a |
2125 | /// constant condition operand. |
2126 | /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,1,6,3> |
2127 | /// This returns false if the mask does not choose from both input vectors. |
2128 | /// In that case, the shuffle is better classified as an identity shuffle. |
2129 | /// TODO: Optionally allow length-changing shuffles. |
2130 | bool isSelect() const { |
2131 | return !changesLength() && isSelectMask(getMask()); |
2132 | } |
2133 | |
2134 | /// Return true if this shuffle mask swaps the order of elements from exactly |
2135 | /// one source vector. |
2136 | /// Example: <7,6,undef,4> |
2137 | /// This assumes that vector operands are the same length as the mask. |
2138 | static bool isReverseMask(ArrayRef<int> Mask); |
2139 | static bool isReverseMask(const Constant *Mask) { |
2140 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 2140, __PRETTY_FUNCTION__)); |
2141 | SmallVector<int, 16> MaskAsInts; |
2142 | getShuffleMask(Mask, MaskAsInts); |
2143 | return isReverseMask(MaskAsInts); |
2144 | } |
2145 | |
2146 | /// Return true if this shuffle swaps the order of elements from exactly |
2147 | /// one source vector. |
2148 | /// Example: shufflevector <4 x n> A, <4 x n> B, <3,undef,1,undef> |
2149 | /// TODO: Optionally allow length-changing shuffles. |
2150 | bool isReverse() const { |
2151 | return !changesLength() && isReverseMask(getMask()); |
2152 | } |
2153 | |
2154 | /// Return true if this shuffle mask chooses all elements with the same value |
2155 | /// as the first element of exactly one source vector. |
2156 | /// Example: <4,undef,undef,4> |
2157 | /// This assumes that vector operands are the same length as the mask. |
2158 | static bool isZeroEltSplatMask(ArrayRef<int> Mask); |
2159 | static bool isZeroEltSplatMask(const Constant *Mask) { |
2160 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 2160, __PRETTY_FUNCTION__)); |
2161 | SmallVector<int, 16> MaskAsInts; |
2162 | getShuffleMask(Mask, MaskAsInts); |
2163 | return isZeroEltSplatMask(MaskAsInts); |
2164 | } |
2165 | |
2166 | /// Return true if all elements of this shuffle are the same value as the |
2167 | /// first element of exactly one source vector without changing the length |
2168 | /// of that vector. |
2169 | /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,0,undef,0> |
2170 | /// TODO: Optionally allow length-changing shuffles. |
2171 | /// TODO: Optionally allow splats from other elements. |
2172 | bool isZeroEltSplat() const { |
2173 | return !changesLength() && isZeroEltSplatMask(getMask()); |
2174 | } |
2175 | |
2176 | /// Return true if this shuffle mask is a transpose mask. |
2177 | /// Transpose vector masks transpose a 2xn matrix. They read corresponding |
2178 | /// even- or odd-numbered vector elements from two n-dimensional source |
2179 | /// vectors and write each result into consecutive elements of an |
2180 | /// n-dimensional destination vector. Two shuffles are necessary to complete |
2181 | /// the transpose, one for the even elements and another for the odd elements. |
2182 | /// This description closely follows how the TRN1 and TRN2 AArch64 |
2183 | /// instructions operate. |
2184 | /// |
2185 | /// For example, a simple 2x2 matrix can be transposed with: |
2186 | /// |
2187 | /// ; Original matrix |
2188 | /// m0 = < a, b > |
2189 | /// m1 = < c, d > |
2190 | /// |
2191 | /// ; Transposed matrix |
2192 | /// t0 = < a, c > = shufflevector m0, m1, < 0, 2 > |
2193 | /// t1 = < b, d > = shufflevector m0, m1, < 1, 3 > |
2194 | /// |
2195 | /// For matrices having greater than n columns, the resulting nx2 transposed |
2196 | /// matrix is stored in two result vectors such that one vector contains |
2197 | /// interleaved elements from all the even-numbered rows and the other vector |
2198 | /// contains interleaved elements from all the odd-numbered rows. For example, |
2199 | /// a 2x4 matrix can be transposed with: |
2200 | /// |
2201 | /// ; Original matrix |
2202 | /// m0 = < a, b, c, d > |
2203 | /// m1 = < e, f, g, h > |
2204 | /// |
2205 | /// ; Transposed matrix |
2206 | /// t0 = < a, e, c, g > = shufflevector m0, m1 < 0, 4, 2, 6 > |
2207 | /// t1 = < b, f, d, h > = shufflevector m0, m1 < 1, 5, 3, 7 > |
2208 | static bool isTransposeMask(ArrayRef<int> Mask); |
2209 | static bool isTransposeMask(const Constant *Mask) { |
2210 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 2210, __PRETTY_FUNCTION__)); |
2211 | SmallVector<int, 16> MaskAsInts; |
2212 | getShuffleMask(Mask, MaskAsInts); |
2213 | return isTransposeMask(MaskAsInts); |
2214 | } |
2215 | |
2216 | /// Return true if this shuffle transposes the elements of its inputs without |
2217 | /// changing the length of the vectors. This operation may also be known as a |
2218 | /// merge or interleave. See the description for isTransposeMask() for the |
2219 | /// exact specification. |
2220 | /// Example: shufflevector <4 x n> A, <4 x n> B, <0,4,2,6> |
2221 | bool isTranspose() const { |
2222 | return !changesLength() && isTransposeMask(getMask()); |
2223 | } |
2224 | |
2225 | /// Return true if this shuffle mask is an extract subvector mask. |
2226 | /// A valid extract subvector mask returns a smaller vector from a single |
2227 | /// source operand. The base extraction index is returned as well. |
2228 | static bool isExtractSubvectorMask(ArrayRef<int> Mask, int NumSrcElts, |
2229 | int &Index); |
2230 | static bool isExtractSubvectorMask(const Constant *Mask, int NumSrcElts, |
2231 | int &Index) { |
2232 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 2232, __PRETTY_FUNCTION__)); |
2233 | SmallVector<int, 16> MaskAsInts; |
2234 | getShuffleMask(Mask, MaskAsInts); |
2235 | return isExtractSubvectorMask(MaskAsInts, NumSrcElts, Index); |
2236 | } |
2237 | |
2238 | /// Return true if this shuffle mask is an extract subvector mask. |
2239 | bool isExtractSubvectorMask(int &Index) const { |
2240 | int NumSrcElts = Op<0>()->getType()->getVectorNumElements(); |
2241 | return isExtractSubvectorMask(getMask(), NumSrcElts, Index); |
2242 | } |
2243 | |
2244 | /// Change values in a shuffle permute mask assuming the two vector operands |
2245 | /// of length InVecNumElts have swapped position. |
2246 | static void commuteShuffleMask(MutableArrayRef<int> Mask, |
2247 | unsigned InVecNumElts) { |
2248 | for (int &Idx : Mask) { |
2249 | if (Idx == -1) |
2250 | continue; |
2251 | Idx = Idx < (int)InVecNumElts ? Idx + InVecNumElts : Idx - InVecNumElts; |
2252 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 2253, __PRETTY_FUNCTION__)) |
2253 | "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-9~svn360825/include/llvm/IR/Instructions.h" , 2253, __PRETTY_FUNCTION__)); |
2254 | } |
2255 | } |
2256 | |
2257 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
2258 | static bool classof(const Instruction *I) { |
2259 | return I->getOpcode() == Instruction::ShuffleVector; |
2260 | } |
2261 | static bool classof(const Value *V) { |
2262 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
2263 | } |
2264 | }; |
2265 | |
2266 | template <> |
2267 | struct OperandTraits<ShuffleVectorInst> : |
2268 | public FixedNumOperandTraits<ShuffleVectorInst, 3> { |
2269 | }; |
2270 | |
2271 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 2271, __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-9~svn360825/include/llvm/IR/Instructions.h" , 2271, __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); } |
2272 | |
2273 | //===----------------------------------------------------------------------===// |
2274 | // ExtractValueInst Class |
2275 | //===----------------------------------------------------------------------===// |
2276 | |
2277 | /// This instruction extracts a struct member or array |
2278 | /// element value from an aggregate value. |
2279 | /// |
2280 | class ExtractValueInst : public UnaryInstruction { |
2281 | SmallVector<unsigned, 4> Indices; |
2282 | |
2283 | ExtractValueInst(const ExtractValueInst &EVI); |
2284 | |
2285 | /// Constructors - Create a extractvalue instruction with a base aggregate |
2286 | /// value and a list of indices. The first ctor can optionally insert before |
2287 | /// an existing instruction, the second appends the new instruction to the |
2288 | /// specified BasicBlock. |
2289 | inline ExtractValueInst(Value *Agg, |
2290 | ArrayRef<unsigned> Idxs, |
2291 | const Twine &NameStr, |
2292 | Instruction *InsertBefore); |
2293 | inline ExtractValueInst(Value *Agg, |
2294 | ArrayRef<unsigned> Idxs, |
2295 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
2296 | |
2297 | void init(ArrayRef<unsigned> Idxs, const Twine &NameStr); |
2298 | |
2299 | protected: |
2300 | // Note: Instruction needs to be a friend here to call cloneImpl. |
2301 | friend class Instruction; |
2302 | |
2303 | ExtractValueInst *cloneImpl() const; |
2304 | |
2305 | public: |
2306 | static ExtractValueInst *Create(Value *Agg, |
2307 | ArrayRef<unsigned> Idxs, |
2308 | const Twine &NameStr = "", |
2309 | Instruction *InsertBefore = nullptr) { |
2310 | return new |
2311 | ExtractValueInst(Agg, Idxs, NameStr, InsertBefore); |
2312 | } |
2313 | |
2314 | static ExtractValueInst *Create(Value *Agg, |
2315 | ArrayRef<unsigned> Idxs, |
2316 | const Twine &NameStr, |
2317 | BasicBlock *InsertAtEnd) { |
2318 | return new ExtractValueInst(Agg, Idxs, NameStr, InsertAtEnd); |
2319 | } |
2320 | |
2321 | /// Returns the type of the element that would be extracted |
2322 | /// with an extractvalue instruction with the specified parameters. |
2323 | /// |
2324 | /// Null is returned if the indices are invalid for the specified type. |
2325 | static Type *getIndexedType(Type *Agg, ArrayRef<unsigned> Idxs); |
2326 | |
2327 | using idx_iterator = const unsigned*; |
2328 | |
2329 | inline idx_iterator idx_begin() const { return Indices.begin(); } |
2330 | inline idx_iterator idx_end() const { return Indices.end(); } |
2331 | inline iterator_range<idx_iterator> indices() const { |
2332 | return make_range(idx_begin(), idx_end()); |
2333 | } |
2334 | |
2335 | Value *getAggregateOperand() { |
2336 | return getOperand(0); |
2337 | } |
2338 | const Value *getAggregateOperand() const { |
2339 | return getOperand(0); |
2340 | } |
2341 | static unsigned getAggregateOperandIndex() { |
2342 | return 0U; // get index for modifying correct operand |
2343 | } |
2344 | |
2345 | ArrayRef<unsigned> getIndices() const { |
2346 | return Indices; |
2347 | } |
2348 | |
2349 | unsigned getNumIndices() const { |
2350 | return (unsigned)Indices.size(); |
2351 | } |
2352 | |
2353 | bool hasIndices() const { |
2354 | return true; |
2355 | } |
2356 | |
2357 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
2358 | static bool classof(const Instruction *I) { |
2359 | return I->getOpcode() == Instruction::ExtractValue; |
2360 | } |
2361 | static bool classof(const Value *V) { |
2362 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
2363 | } |
2364 | }; |
2365 | |
2366 | ExtractValueInst::ExtractValueInst(Value *Agg, |
2367 | ArrayRef<unsigned> Idxs, |
2368 | const Twine &NameStr, |
2369 | Instruction *InsertBefore) |
2370 | : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)), |
2371 | ExtractValue, Agg, InsertBefore) { |
2372 | init(Idxs, NameStr); |
2373 | } |
2374 | |
2375 | ExtractValueInst::ExtractValueInst(Value *Agg, |
2376 | ArrayRef<unsigned> Idxs, |
2377 | const Twine &NameStr, |
2378 | BasicBlock *InsertAtEnd) |
2379 | : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)), |
2380 | ExtractValue, Agg, InsertAtEnd) { |
2381 | init(Idxs, NameStr); |
2382 | } |
2383 | |
2384 | //===----------------------------------------------------------------------===// |
2385 | // InsertValueInst Class |
2386 | //===----------------------------------------------------------------------===// |
2387 | |
2388 | /// This instruction inserts a struct field of array element |
2389 | /// value into an aggregate value. |
2390 | /// |
2391 | class InsertValueInst : public Instruction { |
2392 | SmallVector<unsigned, 4> Indices; |
2393 | |
2394 | InsertValueInst(const InsertValueInst &IVI); |
2395 | |
2396 | /// Constructors - Create a insertvalue instruction with a base aggregate |
2397 | /// value, a value to insert, and a list of indices. The first ctor can |
2398 | /// optionally insert before an existing instruction, the second appends |
2399 | /// the new instruction to the specified BasicBlock. |
2400 | inline InsertValueInst(Value *Agg, Value *Val, |
2401 | ArrayRef<unsigned> Idxs, |
2402 | const Twine &NameStr, |
2403 | Instruction *InsertBefore); |
2404 | inline InsertValueInst(Value *Agg, Value *Val, |
2405 | ArrayRef<unsigned> Idxs, |
2406 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
2407 | |
2408 | /// Constructors - These two constructors are convenience methods because one |
2409 | /// and two index insertvalue instructions are so common. |
2410 | InsertValueInst(Value *Agg, Value *Val, unsigned Idx, |
2411 | const Twine &NameStr = "", |
2412 | Instruction *InsertBefore = nullptr); |
2413 | InsertValueInst(Value *Agg, Value *Val, unsigned Idx, const Twine &NameStr, |
2414 | BasicBlock *InsertAtEnd); |
2415 | |
2416 | void init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs, |
2417 | const Twine &NameStr); |
2418 | |
2419 | protected: |
2420 | // Note: Instruction needs to be a friend here to call cloneImpl. |
2421 | friend class Instruction; |
2422 | |
2423 | InsertValueInst *cloneImpl() const; |
2424 | |
2425 | public: |
2426 | // allocate space for exactly two operands |
2427 | void *operator new(size_t s) { |
2428 | return User::operator new(s, 2); |
2429 | } |
2430 | |
2431 | static InsertValueInst *Create(Value *Agg, Value *Val, |
2432 | ArrayRef<unsigned> Idxs, |
2433 | const Twine &NameStr = "", |
2434 | Instruction *InsertBefore = nullptr) { |
2435 | return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertBefore); |
2436 | } |
2437 | |
2438 | static InsertValueInst *Create(Value *Agg, Value *Val, |
2439 | ArrayRef<unsigned> Idxs, |
2440 | const Twine &NameStr, |
2441 | BasicBlock *InsertAtEnd) { |
2442 | return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertAtEnd); |
2443 | } |
2444 | |
2445 | /// Transparently provide more efficient getOperand methods. |
2446 | 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; |
2447 | |
2448 | using idx_iterator = const unsigned*; |
2449 | |
2450 | inline idx_iterator idx_begin() const { return Indices.begin(); } |
2451 | inline idx_iterator idx_end() const { return Indices.end(); } |
2452 | inline iterator_range<idx_iterator> indices() const { |
2453 | return make_range(idx_begin(), idx_end()); |
2454 | } |
2455 | |
2456 | Value *getAggregateOperand() { |
2457 | return getOperand(0); |
2458 | } |
2459 | const Value *getAggregateOperand() const { |
2460 | return getOperand(0); |
2461 | } |
2462 | static unsigned getAggregateOperandIndex() { |
2463 | return 0U; // get index for modifying correct operand |
2464 | } |
2465 | |
2466 | Value *getInsertedValueOperand() { |
2467 | return getOperand(1); |
2468 | } |
2469 | const Value *getInsertedValueOperand() const { |
2470 | return getOperand(1); |
2471 | } |
2472 | static unsigned getInsertedValueOperandIndex() { |
2473 | return 1U; // get index for modifying correct operand |
2474 | } |
2475 | |
2476 | ArrayRef<unsigned> getIndices() const { |
2477 | return Indices; |
2478 | } |
2479 | |
2480 | unsigned getNumIndices() const { |
2481 | return (unsigned)Indices.size(); |
2482 | } |
2483 | |
2484 | bool hasIndices() const { |
2485 | return true; |
2486 | } |
2487 | |
2488 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
2489 | static bool classof(const Instruction *I) { |
2490 | return I->getOpcode() == Instruction::InsertValue; |
2491 | } |
2492 | static bool classof(const Value *V) { |
2493 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
2494 | } |
2495 | }; |
2496 | |
2497 | template <> |
2498 | struct OperandTraits<InsertValueInst> : |
2499 | public FixedNumOperandTraits<InsertValueInst, 2> { |
2500 | }; |
2501 | |
2502 | InsertValueInst::InsertValueInst(Value *Agg, |
2503 | Value *Val, |
2504 | ArrayRef<unsigned> Idxs, |
2505 | const Twine &NameStr, |
2506 | Instruction *InsertBefore) |
2507 | : Instruction(Agg->getType(), InsertValue, |
2508 | OperandTraits<InsertValueInst>::op_begin(this), |
2509 | 2, InsertBefore) { |
2510 | init(Agg, Val, Idxs, NameStr); |
2511 | } |
2512 | |
2513 | InsertValueInst::InsertValueInst(Value *Agg, |
2514 | Value *Val, |
2515 | ArrayRef<unsigned> Idxs, |
2516 | const Twine &NameStr, |
2517 | BasicBlock *InsertAtEnd) |
2518 | : Instruction(Agg->getType(), InsertValue, |
2519 | OperandTraits<InsertValueInst>::op_begin(this), |
2520 | 2, InsertAtEnd) { |
2521 | init(Agg, Val, Idxs, NameStr); |
2522 | } |
2523 | |
2524 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 2524, __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-9~svn360825/include/llvm/IR/Instructions.h" , 2524, __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); } |
2525 | |
2526 | //===----------------------------------------------------------------------===// |
2527 | // PHINode Class |
2528 | //===----------------------------------------------------------------------===// |
2529 | |
2530 | // PHINode - The PHINode class is used to represent the magical mystical PHI |
2531 | // node, that can not exist in nature, but can be synthesized in a computer |
2532 | // scientist's overactive imagination. |
2533 | // |
2534 | class PHINode : public Instruction { |
2535 | /// The number of operands actually allocated. NumOperands is |
2536 | /// the number actually in use. |
2537 | unsigned ReservedSpace; |
2538 | |
2539 | PHINode(const PHINode &PN); |
2540 | |
2541 | explicit PHINode(Type *Ty, unsigned NumReservedValues, |
2542 | const Twine &NameStr = "", |
2543 | Instruction *InsertBefore = nullptr) |
2544 | : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertBefore), |
2545 | ReservedSpace(NumReservedValues) { |
2546 | setName(NameStr); |
2547 | allocHungoffUses(ReservedSpace); |
2548 | } |
2549 | |
2550 | PHINode(Type *Ty, unsigned NumReservedValues, const Twine &NameStr, |
2551 | BasicBlock *InsertAtEnd) |
2552 | : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertAtEnd), |
2553 | ReservedSpace(NumReservedValues) { |
2554 | setName(NameStr); |
2555 | allocHungoffUses(ReservedSpace); |
2556 | } |
2557 | |
2558 | protected: |
2559 | // Note: Instruction needs to be a friend here to call cloneImpl. |
2560 | friend class Instruction; |
2561 | |
2562 | PHINode *cloneImpl() const; |
2563 | |
2564 | // allocHungoffUses - this is more complicated than the generic |
2565 | // User::allocHungoffUses, because we have to allocate Uses for the incoming |
2566 | // values and pointers to the incoming blocks, all in one allocation. |
2567 | void allocHungoffUses(unsigned N) { |
2568 | User::allocHungoffUses(N, /* IsPhi */ true); |
2569 | } |
2570 | |
2571 | public: |
2572 | /// Constructors - NumReservedValues is a hint for the number of incoming |
2573 | /// edges that this phi node will have (use 0 if you really have no idea). |
2574 | static PHINode *Create(Type *Ty, unsigned NumReservedValues, |
2575 | const Twine &NameStr = "", |
2576 | Instruction *InsertBefore = nullptr) { |
2577 | return new PHINode(Ty, NumReservedValues, NameStr, InsertBefore); |
2578 | } |
2579 | |
2580 | static PHINode *Create(Type *Ty, unsigned NumReservedValues, |
2581 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
2582 | return new PHINode(Ty, NumReservedValues, NameStr, InsertAtEnd); |
2583 | } |
2584 | |
2585 | /// Provide fast operand accessors |
2586 | 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; |
2587 | |
2588 | // Block iterator interface. This provides access to the list of incoming |
2589 | // basic blocks, which parallels the list of incoming values. |
2590 | |
2591 | using block_iterator = BasicBlock **; |
2592 | using const_block_iterator = BasicBlock * const *; |
2593 | |
2594 | block_iterator block_begin() { |
2595 | Use::UserRef *ref = |
2596 | reinterpret_cast<Use::UserRef*>(op_begin() + ReservedSpace); |
2597 | return reinterpret_cast<block_iterator>(ref + 1); |
2598 | } |
2599 | |
2600 | const_block_iterator block_begin() const { |
2601 | const Use::UserRef *ref = |
2602 | reinterpret_cast<const Use::UserRef*>(op_begin() + ReservedSpace); |
2603 | return reinterpret_cast<const_block_iterator>(ref + 1); |
2604 | } |
2605 | |
2606 | block_iterator block_end() { |
2607 | return block_begin() + getNumOperands(); |
2608 | } |
2609 | |
2610 | const_block_iterator block_end() const { |
2611 | return block_begin() + getNumOperands(); |
2612 | } |
2613 | |
2614 | iterator_range<block_iterator> blocks() { |
2615 | return make_range(block_begin(), block_end()); |
2616 | } |
2617 | |
2618 | iterator_range<const_block_iterator> blocks() const { |
2619 | return make_range(block_begin(), block_end()); |
2620 | } |
2621 | |
2622 | op_range incoming_values() { return operands(); } |
2623 | |
2624 | const_op_range incoming_values() const { return operands(); } |
2625 | |
2626 | /// Return the number of incoming edges |
2627 | /// |
2628 | unsigned getNumIncomingValues() const { return getNumOperands(); } |
2629 | |
2630 | /// Return incoming value number x |
2631 | /// |
2632 | Value *getIncomingValue(unsigned i) const { |
2633 | return getOperand(i); |
2634 | } |
2635 | void setIncomingValue(unsigned i, Value *V) { |
2636 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 2636, __PRETTY_FUNCTION__)); |
2637 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 2638, __PRETTY_FUNCTION__)) |
2638 | "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-9~svn360825/include/llvm/IR/Instructions.h" , 2638, __PRETTY_FUNCTION__)); |
2639 | setOperand(i, V); |
2640 | } |
2641 | |
2642 | static unsigned getOperandNumForIncomingValue(unsigned i) { |
2643 | return i; |
2644 | } |
2645 | |
2646 | static unsigned getIncomingValueNumForOperand(unsigned i) { |
2647 | return i; |
2648 | } |
2649 | |
2650 | /// Return incoming basic block number @p i. |
2651 | /// |
2652 | BasicBlock *getIncomingBlock(unsigned i) const { |
2653 | return block_begin()[i]; |
2654 | } |
2655 | |
2656 | /// Return incoming basic block corresponding |
2657 | /// to an operand of the PHI. |
2658 | /// |
2659 | BasicBlock *getIncomingBlock(const Use &U) const { |
2660 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 2660, __PRETTY_FUNCTION__)); |
2661 | return getIncomingBlock(unsigned(&U - op_begin())); |
2662 | } |
2663 | |
2664 | /// Return incoming basic block corresponding |
2665 | /// to value use iterator. |
2666 | /// |
2667 | BasicBlock *getIncomingBlock(Value::const_user_iterator I) const { |
2668 | return getIncomingBlock(I.getUse()); |
2669 | } |
2670 | |
2671 | void setIncomingBlock(unsigned i, BasicBlock *BB) { |
2672 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 2672, __PRETTY_FUNCTION__)); |
2673 | block_begin()[i] = BB; |
2674 | } |
2675 | |
2676 | /// Replace every incoming basic block \p Old to basic block \p New. |
2677 | void replaceIncomingBlockWith(BasicBlock *Old, BasicBlock *New) { |
2678 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 2678, __PRETTY_FUNCTION__)); |
2679 | for (unsigned Op = 0, NumOps = getNumOperands(); Op != NumOps; ++Op) |
2680 | if (getIncomingBlock(Op) == Old) |
2681 | setIncomingBlock(Op, New); |
2682 | } |
2683 | |
2684 | /// Add an incoming value to the end of the PHI list |
2685 | /// |
2686 | void addIncoming(Value *V, BasicBlock *BB) { |
2687 | if (getNumOperands() == ReservedSpace) |
2688 | growOperands(); // Get more space! |
2689 | // Initialize some new operands. |
2690 | setNumHungOffUseOperands(getNumOperands() + 1); |
2691 | setIncomingValue(getNumOperands() - 1, V); |
2692 | setIncomingBlock(getNumOperands() - 1, BB); |
2693 | } |
2694 | |
2695 | /// Remove an incoming value. This is useful if a |
2696 | /// predecessor basic block is deleted. The value removed is returned. |
2697 | /// |
2698 | /// If the last incoming value for a PHI node is removed (and DeletePHIIfEmpty |
2699 | /// is true), the PHI node is destroyed and any uses of it are replaced with |
2700 | /// dummy values. The only time there should be zero incoming values to a PHI |
2701 | /// node is when the block is dead, so this strategy is sound. |
2702 | /// |
2703 | Value *removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty = true); |
2704 | |
2705 | Value *removeIncomingValue(const BasicBlock *BB, bool DeletePHIIfEmpty=true) { |
2706 | int Idx = getBasicBlockIndex(BB); |
2707 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 2707, __PRETTY_FUNCTION__)); |
2708 | return removeIncomingValue(Idx, DeletePHIIfEmpty); |
2709 | } |
2710 | |
2711 | /// Return the first index of the specified basic |
2712 | /// block in the value list for this PHI. Returns -1 if no instance. |
2713 | /// |
2714 | int getBasicBlockIndex(const BasicBlock *BB) const { |
2715 | for (unsigned i = 0, e = getNumOperands(); i != e; ++i) |
2716 | if (block_begin()[i] == BB) |
2717 | return i; |
2718 | return -1; |
2719 | } |
2720 | |
2721 | Value *getIncomingValueForBlock(const BasicBlock *BB) const { |
2722 | int Idx = getBasicBlockIndex(BB); |
2723 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 2723, __PRETTY_FUNCTION__)); |
2724 | return getIncomingValue(Idx); |
2725 | } |
2726 | |
2727 | /// If the specified PHI node always merges together the |
2728 | /// same value, return the value, otherwise return null. |
2729 | Value *hasConstantValue() const; |
2730 | |
2731 | /// Whether the specified PHI node always merges |
2732 | /// together the same value, assuming undefs are equal to a unique |
2733 | /// non-undef value. |
2734 | bool hasConstantOrUndefValue() const; |
2735 | |
2736 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
2737 | static bool classof(const Instruction *I) { |
2738 | return I->getOpcode() == Instruction::PHI; |
2739 | } |
2740 | static bool classof(const Value *V) { |
2741 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
2742 | } |
2743 | |
2744 | private: |
2745 | void growOperands(); |
2746 | }; |
2747 | |
2748 | template <> |
2749 | struct OperandTraits<PHINode> : public HungoffOperandTraits<2> { |
2750 | }; |
2751 | |
2752 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 2752, __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-9~svn360825/include/llvm/IR/Instructions.h" , 2752, __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 ); } |
2753 | |
2754 | //===----------------------------------------------------------------------===// |
2755 | // LandingPadInst Class |
2756 | //===----------------------------------------------------------------------===// |
2757 | |
2758 | //===--------------------------------------------------------------------------- |
2759 | /// The landingpad instruction holds all of the information |
2760 | /// necessary to generate correct exception handling. The landingpad instruction |
2761 | /// cannot be moved from the top of a landing pad block, which itself is |
2762 | /// accessible only from the 'unwind' edge of an invoke. This uses the |
2763 | /// SubclassData field in Value to store whether or not the landingpad is a |
2764 | /// cleanup. |
2765 | /// |
2766 | class LandingPadInst : public Instruction { |
2767 | /// The number of operands actually allocated. NumOperands is |
2768 | /// the number actually in use. |
2769 | unsigned ReservedSpace; |
2770 | |
2771 | LandingPadInst(const LandingPadInst &LP); |
2772 | |
2773 | public: |
2774 | enum ClauseType { Catch, Filter }; |
2775 | |
2776 | private: |
2777 | explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues, |
2778 | const Twine &NameStr, Instruction *InsertBefore); |
2779 | explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues, |
2780 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
2781 | |
2782 | // Allocate space for exactly zero operands. |
2783 | void *operator new(size_t s) { |
2784 | return User::operator new(s); |
2785 | } |
2786 | |
2787 | void growOperands(unsigned Size); |
2788 | void init(unsigned NumReservedValues, const Twine &NameStr); |
2789 | |
2790 | protected: |
2791 | // Note: Instruction needs to be a friend here to call cloneImpl. |
2792 | friend class Instruction; |
2793 | |
2794 | LandingPadInst *cloneImpl() const; |
2795 | |
2796 | public: |
2797 | /// Constructors - NumReservedClauses is a hint for the number of incoming |
2798 | /// clauses that this landingpad will have (use 0 if you really have no idea). |
2799 | static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses, |
2800 | const Twine &NameStr = "", |
2801 | Instruction *InsertBefore = nullptr); |
2802 | static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses, |
2803 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
2804 | |
2805 | /// Provide fast operand accessors |
2806 | 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; |
2807 | |
2808 | /// Return 'true' if this landingpad instruction is a |
2809 | /// cleanup. I.e., it should be run when unwinding even if its landing pad |
2810 | /// doesn't catch the exception. |
2811 | bool isCleanup() const { return getSubclassDataFromInstruction() & 1; } |
2812 | |
2813 | /// Indicate that this landingpad instruction is a cleanup. |
2814 | void setCleanup(bool V) { |
2815 | setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) | |
2816 | (V ? 1 : 0)); |
2817 | } |
2818 | |
2819 | /// Add a catch or filter clause to the landing pad. |
2820 | void addClause(Constant *ClauseVal); |
2821 | |
2822 | /// Get the value of the clause at index Idx. Use isCatch/isFilter to |
2823 | /// determine what type of clause this is. |
2824 | Constant *getClause(unsigned Idx) const { |
2825 | return cast<Constant>(getOperandList()[Idx]); |
2826 | } |
2827 | |
2828 | /// Return 'true' if the clause and index Idx is a catch clause. |
2829 | bool isCatch(unsigned Idx) const { |
2830 | return !isa<ArrayType>(getOperandList()[Idx]->getType()); |
2831 | } |
2832 | |
2833 | /// Return 'true' if the clause and index Idx is a filter clause. |
2834 | bool isFilter(unsigned Idx) const { |
2835 | return isa<ArrayType>(getOperandList()[Idx]->getType()); |
2836 | } |
2837 | |
2838 | /// Get the number of clauses for this landing pad. |
2839 | unsigned getNumClauses() const { return getNumOperands(); } |
2840 | |
2841 | /// Grow the size of the operand list to accommodate the new |
2842 | /// number of clauses. |
2843 | void reserveClauses(unsigned Size) { growOperands(Size); } |
2844 | |
2845 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
2846 | static bool classof(const Instruction *I) { |
2847 | return I->getOpcode() == Instruction::LandingPad; |
2848 | } |
2849 | static bool classof(const Value *V) { |
2850 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
2851 | } |
2852 | }; |
2853 | |
2854 | template <> |
2855 | struct OperandTraits<LandingPadInst> : public HungoffOperandTraits<1> { |
2856 | }; |
2857 | |
2858 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 2858, __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-9~svn360825/include/llvm/IR/Instructions.h" , 2858, __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); } |
2859 | |
2860 | //===----------------------------------------------------------------------===// |
2861 | // ReturnInst Class |
2862 | //===----------------------------------------------------------------------===// |
2863 | |
2864 | //===--------------------------------------------------------------------------- |
2865 | /// Return a value (possibly void), from a function. Execution |
2866 | /// does not continue in this function any longer. |
2867 | /// |
2868 | class ReturnInst : public Instruction { |
2869 | ReturnInst(const ReturnInst &RI); |
2870 | |
2871 | private: |
2872 | // ReturnInst constructors: |
2873 | // ReturnInst() - 'ret void' instruction |
2874 | // ReturnInst( null) - 'ret void' instruction |
2875 | // ReturnInst(Value* X) - 'ret X' instruction |
2876 | // ReturnInst( null, Inst *I) - 'ret void' instruction, insert before I |
2877 | // ReturnInst(Value* X, Inst *I) - 'ret X' instruction, insert before I |
2878 | // ReturnInst( null, BB *B) - 'ret void' instruction, insert @ end of B |
2879 | // ReturnInst(Value* X, BB *B) - 'ret X' instruction, insert @ end of B |
2880 | // |
2881 | // NOTE: If the Value* passed is of type void then the constructor behaves as |
2882 | // if it was passed NULL. |
2883 | explicit ReturnInst(LLVMContext &C, Value *retVal = nullptr, |
2884 | Instruction *InsertBefore = nullptr); |
2885 | ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd); |
2886 | explicit ReturnInst(LLVMContext &C, BasicBlock *InsertAtEnd); |
2887 | |
2888 | protected: |
2889 | // Note: Instruction needs to be a friend here to call cloneImpl. |
2890 | friend class Instruction; |
2891 | |
2892 | ReturnInst *cloneImpl() const; |
2893 | |
2894 | public: |
2895 | static ReturnInst* Create(LLVMContext &C, Value *retVal = nullptr, |
2896 | Instruction *InsertBefore = nullptr) { |
2897 | return new(!!retVal) ReturnInst(C, retVal, InsertBefore); |
2898 | } |
2899 | |
2900 | static ReturnInst* Create(LLVMContext &C, Value *retVal, |
2901 | BasicBlock *InsertAtEnd) { |
2902 | return new(!!retVal) ReturnInst(C, retVal, InsertAtEnd); |
2903 | } |
2904 | |
2905 | static ReturnInst* Create(LLVMContext &C, BasicBlock *InsertAtEnd) { |
2906 | return new(0) ReturnInst(C, InsertAtEnd); |
2907 | } |
2908 | |
2909 | /// Provide fast operand accessors |
2910 | 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; |
2911 | |
2912 | /// Convenience accessor. Returns null if there is no return value. |
2913 | Value *getReturnValue() const { |
2914 | return getNumOperands() != 0 ? getOperand(0) : nullptr; |
2915 | } |
2916 | |
2917 | unsigned getNumSuccessors() const { return 0; } |
2918 | |
2919 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
2920 | static bool classof(const Instruction *I) { |
2921 | return (I->getOpcode() == Instruction::Ret); |
2922 | } |
2923 | static bool classof(const Value *V) { |
2924 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
2925 | } |
2926 | |
2927 | private: |
2928 | BasicBlock *getSuccessor(unsigned idx) const { |
2929 | llvm_unreachable("ReturnInst has no successors!")::llvm::llvm_unreachable_internal("ReturnInst has no successors!" , "/build/llvm-toolchain-snapshot-9~svn360825/include/llvm/IR/Instructions.h" , 2929); |
2930 | } |
2931 | |
2932 | void setSuccessor(unsigned idx, BasicBlock *B) { |
2933 | llvm_unreachable("ReturnInst has no successors!")::llvm::llvm_unreachable_internal("ReturnInst has no successors!" , "/build/llvm-toolchain-snapshot-9~svn360825/include/llvm/IR/Instructions.h" , 2933); |
2934 | } |
2935 | }; |
2936 | |
2937 | template <> |
2938 | struct OperandTraits<ReturnInst> : public VariadicOperandTraits<ReturnInst> { |
2939 | }; |
2940 | |
2941 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 2941, __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-9~svn360825/include/llvm/IR/Instructions.h" , 2941, __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); } |
2942 | |
2943 | //===----------------------------------------------------------------------===// |
2944 | // BranchInst Class |
2945 | //===----------------------------------------------------------------------===// |
2946 | |
2947 | //===--------------------------------------------------------------------------- |
2948 | /// Conditional or Unconditional Branch instruction. |
2949 | /// |
2950 | class BranchInst : public Instruction { |
2951 | /// Ops list - Branches are strange. The operands are ordered: |
2952 | /// [Cond, FalseDest,] TrueDest. This makes some accessors faster because |
2953 | /// they don't have to check for cond/uncond branchness. These are mostly |
2954 | /// accessed relative from op_end(). |
2955 | BranchInst(const BranchInst &BI); |
2956 | // BranchInst constructors (where {B, T, F} are blocks, and C is a condition): |
2957 | // BranchInst(BB *B) - 'br B' |
2958 | // BranchInst(BB* T, BB *F, Value *C) - 'br C, T, F' |
2959 | // BranchInst(BB* B, Inst *I) - 'br B' insert before I |
2960 | // BranchInst(BB* T, BB *F, Value *C, Inst *I) - 'br C, T, F', insert before I |
2961 | // BranchInst(BB* B, BB *I) - 'br B' insert at end |
2962 | // BranchInst(BB* T, BB *F, Value *C, BB *I) - 'br C, T, F', insert at end |
2963 | explicit BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore = nullptr); |
2964 | BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond, |
2965 | Instruction *InsertBefore = nullptr); |
2966 | BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd); |
2967 | BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond, |
2968 | BasicBlock *InsertAtEnd); |
2969 | |
2970 | void AssertOK(); |
2971 | |
2972 | protected: |
2973 | // Note: Instruction needs to be a friend here to call cloneImpl. |
2974 | friend class Instruction; |
2975 | |
2976 | BranchInst *cloneImpl() const; |
2977 | |
2978 | public: |
2979 | /// Iterator type that casts an operand to a basic block. |
2980 | /// |
2981 | /// This only makes sense because the successors are stored as adjacent |
2982 | /// operands for branch instructions. |
2983 | struct succ_op_iterator |
2984 | : iterator_adaptor_base<succ_op_iterator, value_op_iterator, |
2985 | std::random_access_iterator_tag, BasicBlock *, |
2986 | ptrdiff_t, BasicBlock *, BasicBlock *> { |
2987 | explicit succ_op_iterator(value_op_iterator I) : iterator_adaptor_base(I) {} |
2988 | |
2989 | BasicBlock *operator*() const { return cast<BasicBlock>(*I); } |
2990 | BasicBlock *operator->() const { return operator*(); } |
2991 | }; |
2992 | |
2993 | /// The const version of `succ_op_iterator`. |
2994 | struct const_succ_op_iterator |
2995 | : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator, |
2996 | std::random_access_iterator_tag, |
2997 | const BasicBlock *, ptrdiff_t, const BasicBlock *, |
2998 | const BasicBlock *> { |
2999 | explicit const_succ_op_iterator(const_value_op_iterator I) |
3000 | : iterator_adaptor_base(I) {} |
3001 | |
3002 | const BasicBlock *operator*() const { return cast<BasicBlock>(*I); } |
3003 | const BasicBlock *operator->() const { return operator*(); } |
3004 | }; |
3005 | |
3006 | static BranchInst *Create(BasicBlock *IfTrue, |
3007 | Instruction *InsertBefore = nullptr) { |
3008 | return new(1) BranchInst(IfTrue, InsertBefore); |
3009 | } |
3010 | |
3011 | static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse, |
3012 | Value *Cond, Instruction *InsertBefore = nullptr) { |
3013 | return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertBefore); |
3014 | } |
3015 | |
3016 | static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) { |
3017 | return new(1) BranchInst(IfTrue, InsertAtEnd); |
3018 | } |
3019 | |
3020 | static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse, |
3021 | Value *Cond, BasicBlock *InsertAtEnd) { |
3022 | return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertAtEnd); |
3023 | } |
3024 | |
3025 | /// Transparently provide more efficient getOperand methods. |
3026 | 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; |
3027 | |
3028 | bool isUnconditional() const { return getNumOperands() == 1; } |
3029 | bool isConditional() const { return getNumOperands() == 3; } |
3030 | |
3031 | Value *getCondition() const { |
3032 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 3032, __PRETTY_FUNCTION__)); |
3033 | return Op<-3>(); |
3034 | } |
3035 | |
3036 | void setCondition(Value *V) { |
3037 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 3037, __PRETTY_FUNCTION__)); |
3038 | Op<-3>() = V; |
3039 | } |
3040 | |
3041 | unsigned getNumSuccessors() const { return 1+isConditional(); } |
3042 | |
3043 | BasicBlock *getSuccessor(unsigned i) const { |
3044 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 3044, __PRETTY_FUNCTION__)); |
3045 | return cast_or_null<BasicBlock>((&Op<-1>() - i)->get()); |
3046 | } |
3047 | |
3048 | void setSuccessor(unsigned idx, BasicBlock *NewSucc) { |
3049 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 3049, __PRETTY_FUNCTION__)); |
3050 | *(&Op<-1>() - idx) = NewSucc; |
3051 | } |
3052 | |
3053 | /// Swap the successors of this branch instruction. |
3054 | /// |
3055 | /// Swaps the successors of the branch instruction. This also swaps any |
3056 | /// branch weight metadata associated with the instruction so that it |
3057 | /// continues to map correctly to each operand. |
3058 | void swapSuccessors(); |
3059 | |
3060 | iterator_range<succ_op_iterator> successors() { |
3061 | return make_range( |
3062 | succ_op_iterator(std::next(value_op_begin(), isConditional() ? 1 : 0)), |
3063 | succ_op_iterator(value_op_end())); |
3064 | } |
3065 | |
3066 | iterator_range<const_succ_op_iterator> successors() const { |
3067 | return make_range(const_succ_op_iterator( |
3068 | std::next(value_op_begin(), isConditional() ? 1 : 0)), |
3069 | const_succ_op_iterator(value_op_end())); |
3070 | } |
3071 | |
3072 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
3073 | static bool classof(const Instruction *I) { |
3074 | return (I->getOpcode() == Instruction::Br); |
3075 | } |
3076 | static bool classof(const Value *V) { |
3077 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
3078 | } |
3079 | }; |
3080 | |
3081 | template <> |
3082 | struct OperandTraits<BranchInst> : public VariadicOperandTraits<BranchInst, 1> { |
3083 | }; |
3084 | |
3085 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 3085, __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-9~svn360825/include/llvm/IR/Instructions.h" , 3085, __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); } |
3086 | |
3087 | //===----------------------------------------------------------------------===// |
3088 | // SwitchInst Class |
3089 | //===----------------------------------------------------------------------===// |
3090 | |
3091 | //===--------------------------------------------------------------------------- |
3092 | /// Multiway switch |
3093 | /// |
3094 | class SwitchInst : public Instruction { |
3095 | unsigned ReservedSpace; |
3096 | |
3097 | // Operand[0] = Value to switch on |
3098 | // Operand[1] = Default basic block destination |
3099 | // Operand[2n ] = Value to match |
3100 | // Operand[2n+1] = BasicBlock to go to on match |
3101 | SwitchInst(const SwitchInst &SI); |
3102 | |
3103 | /// Create a new switch instruction, specifying a value to switch on and a |
3104 | /// default destination. The number of additional cases can be specified here |
3105 | /// to make memory allocation more efficient. This constructor can also |
3106 | /// auto-insert before another instruction. |
3107 | SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases, |
3108 | Instruction *InsertBefore); |
3109 | |
3110 | /// Create a new switch instruction, specifying a value to switch on and a |
3111 | /// default destination. The number of additional cases can be specified here |
3112 | /// to make memory allocation more efficient. This constructor also |
3113 | /// auto-inserts at the end of the specified BasicBlock. |
3114 | SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases, |
3115 | BasicBlock *InsertAtEnd); |
3116 | |
3117 | // allocate space for exactly zero operands |
3118 | void *operator new(size_t s) { |
3119 | return User::operator new(s); |
3120 | } |
3121 | |
3122 | void init(Value *Value, BasicBlock *Default, unsigned NumReserved); |
3123 | void growOperands(); |
3124 | |
3125 | protected: |
3126 | // Note: Instruction needs to be a friend here to call cloneImpl. |
3127 | friend class Instruction; |
3128 | |
3129 | SwitchInst *cloneImpl() const; |
3130 | |
3131 | public: |
3132 | // -2 |
3133 | static const unsigned DefaultPseudoIndex = static_cast<unsigned>(~0L-1); |
3134 | |
3135 | template <typename CaseHandleT> class CaseIteratorImpl; |
3136 | |
3137 | /// A handle to a particular switch case. It exposes a convenient interface |
3138 | /// to both the case value and the successor block. |
3139 | /// |
3140 | /// We define this as a template and instantiate it to form both a const and |
3141 | /// non-const handle. |
3142 | template <typename SwitchInstT, typename ConstantIntT, typename BasicBlockT> |
3143 | class CaseHandleImpl { |
3144 | // Directly befriend both const and non-const iterators. |
3145 | friend class SwitchInst::CaseIteratorImpl< |
3146 | CaseHandleImpl<SwitchInstT, ConstantIntT, BasicBlockT>>; |
3147 | |
3148 | protected: |
3149 | // Expose the switch type we're parameterized with to the iterator. |
3150 | using SwitchInstType = SwitchInstT; |
3151 | |
3152 | SwitchInstT *SI; |
3153 | ptrdiff_t Index; |
3154 | |
3155 | CaseHandleImpl() = default; |
3156 | CaseHandleImpl(SwitchInstT *SI, ptrdiff_t Index) : SI(SI), Index(Index) {} |
3157 | |
3158 | public: |
3159 | /// Resolves case value for current case. |
3160 | ConstantIntT *getCaseValue() const { |
3161 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 3162, __PRETTY_FUNCTION__)) |
3162 | "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-9~svn360825/include/llvm/IR/Instructions.h" , 3162, __PRETTY_FUNCTION__)); |
3163 | return reinterpret_cast<ConstantIntT *>(SI->getOperand(2 + Index * 2)); |
3164 | } |
3165 | |
3166 | /// Resolves successor for current case. |
3167 | BasicBlockT *getCaseSuccessor() const { |
3168 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 3170, __PRETTY_FUNCTION__)) |
3169 | (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-9~svn360825/include/llvm/IR/Instructions.h" , 3170, __PRETTY_FUNCTION__)) |
3170 | "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-9~svn360825/include/llvm/IR/Instructions.h" , 3170, __PRETTY_FUNCTION__)); |
3171 | return SI->getSuccessor(getSuccessorIndex()); |
3172 | } |
3173 | |
3174 | /// Returns number of current case. |
3175 | unsigned getCaseIndex() const { return Index; } |
3176 | |
3177 | /// Returns successor index for current case successor. |
3178 | unsigned getSuccessorIndex() const { |
3179 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 3181, __PRETTY_FUNCTION__)) |
3180 | (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-9~svn360825/include/llvm/IR/Instructions.h" , 3181, __PRETTY_FUNCTION__)) |
3181 | "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-9~svn360825/include/llvm/IR/Instructions.h" , 3181, __PRETTY_FUNCTION__)); |
3182 | return (unsigned)Index != DefaultPseudoIndex ? Index + 1 : 0; |
3183 | } |
3184 | |
3185 | bool operator==(const CaseHandleImpl &RHS) const { |
3186 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 3186, __PRETTY_FUNCTION__)); |
3187 | return Index == RHS.Index; |
3188 | } |
3189 | }; |
3190 | |
3191 | using ConstCaseHandle = |
3192 | CaseHandleImpl<const SwitchInst, const ConstantInt, const BasicBlock>; |
3193 | |
3194 | class CaseHandle |
3195 | : public CaseHandleImpl<SwitchInst, ConstantInt, BasicBlock> { |
3196 | friend class SwitchInst::CaseIteratorImpl<CaseHandle>; |
3197 | |
3198 | public: |
3199 | CaseHandle(SwitchInst *SI, ptrdiff_t Index) : CaseHandleImpl(SI, Index) {} |
3200 | |
3201 | /// Sets the new value for current case. |
3202 | void setValue(ConstantInt *V) { |
3203 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 3204, __PRETTY_FUNCTION__)) |
3204 | "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-9~svn360825/include/llvm/IR/Instructions.h" , 3204, __PRETTY_FUNCTION__)); |
3205 | SI->setOperand(2 + Index*2, reinterpret_cast<Value*>(V)); |
3206 | } |
3207 | |
3208 | /// Sets the new successor for current case. |
3209 | void setSuccessor(BasicBlock *S) { |
3210 | SI->setSuccessor(getSuccessorIndex(), S); |
3211 | } |
3212 | }; |
3213 | |
3214 | template <typename CaseHandleT> |
3215 | class CaseIteratorImpl |
3216 | : public iterator_facade_base<CaseIteratorImpl<CaseHandleT>, |
3217 | std::random_access_iterator_tag, |
3218 | CaseHandleT> { |
3219 | using SwitchInstT = typename CaseHandleT::SwitchInstType; |
3220 | |
3221 | CaseHandleT Case; |
3222 | |
3223 | public: |
3224 | /// Default constructed iterator is in an invalid state until assigned to |
3225 | /// a case for a particular switch. |
3226 | CaseIteratorImpl() = default; |
3227 | |
3228 | /// Initializes case iterator for given SwitchInst and for given |
3229 | /// case number. |
3230 | CaseIteratorImpl(SwitchInstT *SI, unsigned CaseNum) : Case(SI, CaseNum) {} |
3231 | |
3232 | /// Initializes case iterator for given SwitchInst and for given |
3233 | /// successor index. |
3234 | static CaseIteratorImpl fromSuccessorIndex(SwitchInstT *SI, |
3235 | unsigned SuccessorIndex) { |
3236 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 3237, __PRETTY_FUNCTION__)) |
3237 | "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-9~svn360825/include/llvm/IR/Instructions.h" , 3237, __PRETTY_FUNCTION__)); |
3238 | return SuccessorIndex != 0 ? CaseIteratorImpl(SI, SuccessorIndex - 1) |
3239 | : CaseIteratorImpl(SI, DefaultPseudoIndex); |
3240 | } |
3241 | |
3242 | /// Support converting to the const variant. This will be a no-op for const |
3243 | /// variant. |
3244 | operator CaseIteratorImpl<ConstCaseHandle>() const { |
3245 | return CaseIteratorImpl<ConstCaseHandle>(Case.SI, Case.Index); |
3246 | } |
3247 | |
3248 | CaseIteratorImpl &operator+=(ptrdiff_t N) { |
3249 | // Check index correctness after addition. |
3250 | // Note: Index == getNumCases() means end(). |
3251 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 3253, __PRETTY_FUNCTION__)) |
3252 | (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-9~svn360825/include/llvm/IR/Instructions.h" , 3253, __PRETTY_FUNCTION__)) |
3253 | "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-9~svn360825/include/llvm/IR/Instructions.h" , 3253, __PRETTY_FUNCTION__)); |
3254 | Case.Index += N; |
3255 | return *this; |
3256 | } |
3257 | CaseIteratorImpl &operator-=(ptrdiff_t N) { |
3258 | // Check index correctness after subtraction. |
3259 | // Note: Case.Index == getNumCases() means end(). |
3260 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 3262, __PRETTY_FUNCTION__)) |
3261 | (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-9~svn360825/include/llvm/IR/Instructions.h" , 3262, __PRETTY_FUNCTION__)) |
3262 | "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-9~svn360825/include/llvm/IR/Instructions.h" , 3262, __PRETTY_FUNCTION__)); |
3263 | Case.Index -= N; |
3264 | return *this; |
3265 | } |
3266 | ptrdiff_t operator-(const CaseIteratorImpl &RHS) const { |
3267 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 3267, __PRETTY_FUNCTION__)); |
3268 | return Case.Index - RHS.Case.Index; |
3269 | } |
3270 | bool operator==(const CaseIteratorImpl &RHS) const { |
3271 | return Case == RHS.Case; |
3272 | } |
3273 | bool operator<(const CaseIteratorImpl &RHS) const { |
3274 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 3274, __PRETTY_FUNCTION__)); |
3275 | return Case.Index < RHS.Case.Index; |
3276 | } |
3277 | CaseHandleT &operator*() { return Case; } |
3278 | const CaseHandleT &operator*() const { return Case; } |
3279 | }; |
3280 | |
3281 | using CaseIt = CaseIteratorImpl<CaseHandle>; |
3282 | using ConstCaseIt = CaseIteratorImpl<ConstCaseHandle>; |
3283 | |
3284 | static SwitchInst *Create(Value *Value, BasicBlock *Default, |
3285 | unsigned NumCases, |
3286 | Instruction *InsertBefore = nullptr) { |
3287 | return new SwitchInst(Value, Default, NumCases, InsertBefore); |
3288 | } |
3289 | |
3290 | static SwitchInst *Create(Value *Value, BasicBlock *Default, |
3291 | unsigned NumCases, BasicBlock *InsertAtEnd) { |
3292 | return new SwitchInst(Value, Default, NumCases, InsertAtEnd); |
3293 | } |
3294 | |
3295 | /// Provide fast operand accessors |
3296 | 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; |
3297 | |
3298 | // Accessor Methods for Switch stmt |
3299 | Value *getCondition() const { return getOperand(0); } |
3300 | void setCondition(Value *V) { setOperand(0, V); } |
3301 | |
3302 | BasicBlock *getDefaultDest() const { |
3303 | return cast<BasicBlock>(getOperand(1)); |
3304 | } |
3305 | |
3306 | void setDefaultDest(BasicBlock *DefaultCase) { |
3307 | setOperand(1, reinterpret_cast<Value*>(DefaultCase)); |
3308 | } |
3309 | |
3310 | /// Return the number of 'cases' in this switch instruction, excluding the |
3311 | /// default case. |
3312 | unsigned getNumCases() const { |
3313 | return getNumOperands()/2 - 1; |
3314 | } |
3315 | |
3316 | /// Returns a read/write iterator that points to the first case in the |
3317 | /// SwitchInst. |
3318 | CaseIt case_begin() { |
3319 | return CaseIt(this, 0); |
3320 | } |
3321 | |
3322 | /// Returns a read-only iterator that points to the first case in the |
3323 | /// SwitchInst. |
3324 | ConstCaseIt case_begin() const { |
3325 | return ConstCaseIt(this, 0); |
3326 | } |
3327 | |
3328 | /// Returns a read/write iterator that points one past the last in the |
3329 | /// SwitchInst. |
3330 | CaseIt case_end() { |
3331 | return CaseIt(this, getNumCases()); |
3332 | } |
3333 | |
3334 | /// Returns a read-only iterator that points one past the last in the |
3335 | /// SwitchInst. |
3336 | ConstCaseIt case_end() const { |
3337 | return ConstCaseIt(this, getNumCases()); |
3338 | } |
3339 | |
3340 | /// Iteration adapter for range-for loops. |
3341 | iterator_range<CaseIt> cases() { |
3342 | return make_range(case_begin(), case_end()); |
3343 | } |
3344 | |
3345 | /// Constant iteration adapter for range-for loops. |
3346 | iterator_range<ConstCaseIt> cases() const { |
3347 | return make_range(case_begin(), case_end()); |
3348 | } |
3349 | |
3350 | /// Returns an iterator that points to the default case. |
3351 | /// Note: this iterator allows to resolve successor only. Attempt |
3352 | /// to resolve case value causes an assertion. |
3353 | /// Also note, that increment and decrement also causes an assertion and |
3354 | /// makes iterator invalid. |
3355 | CaseIt case_default() { |
3356 | return CaseIt(this, DefaultPseudoIndex); |
3357 | } |
3358 | ConstCaseIt case_default() const { |
3359 | return ConstCaseIt(this, DefaultPseudoIndex); |
3360 | } |
3361 | |
3362 | /// Search all of the case values for the specified constant. If it is |
3363 | /// explicitly handled, return the case iterator of it, otherwise return |
3364 | /// default case iterator to indicate that it is handled by the default |
3365 | /// handler. |
3366 | CaseIt findCaseValue(const ConstantInt *C) { |
3367 | CaseIt I = llvm::find_if( |
3368 | cases(), [C](CaseHandle &Case) { return Case.getCaseValue() == C; }); |
3369 | if (I != case_end()) |
3370 | return I; |
3371 | |
3372 | return case_default(); |
3373 | } |
3374 | ConstCaseIt findCaseValue(const ConstantInt *C) const { |
3375 | ConstCaseIt I = llvm::find_if(cases(), [C](ConstCaseHandle &Case) { |
3376 | return Case.getCaseValue() == C; |
3377 | }); |
3378 | if (I != case_end()) |
3379 | return I; |
3380 | |
3381 | return case_default(); |
3382 | } |
3383 | |
3384 | /// Finds the unique case value for a given successor. Returns null if the |
3385 | /// successor is not found, not unique, or is the default case. |
3386 | ConstantInt *findCaseDest(BasicBlock *BB) { |
3387 | if (BB == getDefaultDest()) |
3388 | return nullptr; |
3389 | |
3390 | ConstantInt *CI = nullptr; |
3391 | for (auto Case : cases()) { |
3392 | if (Case.getCaseSuccessor() != BB) |
3393 | continue; |
3394 | |
3395 | if (CI) |
3396 | return nullptr; // Multiple cases lead to BB. |
3397 | |
3398 | CI = Case.getCaseValue(); |
3399 | } |
3400 | |
3401 | return CI; |
3402 | } |
3403 | |
3404 | /// Add an entry to the switch instruction. |
3405 | /// Note: |
3406 | /// This action invalidates case_end(). Old case_end() iterator will |
3407 | /// point to the added case. |
3408 | void addCase(ConstantInt *OnVal, BasicBlock *Dest); |
3409 | |
3410 | /// This method removes the specified case and its successor from the switch |
3411 | /// instruction. Note that this operation may reorder the remaining cases at |
3412 | /// index idx and above. |
3413 | /// Note: |
3414 | /// This action invalidates iterators for all cases following the one removed, |
3415 | /// including the case_end() iterator. It returns an iterator for the next |
3416 | /// case. |
3417 | CaseIt removeCase(CaseIt I); |
3418 | |
3419 | unsigned getNumSuccessors() const { return getNumOperands()/2; } |
3420 | BasicBlock *getSuccessor(unsigned idx) const { |
3421 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 3421, __PRETTY_FUNCTION__)); |
3422 | return cast<BasicBlock>(getOperand(idx*2+1)); |
3423 | } |
3424 | void setSuccessor(unsigned idx, BasicBlock *NewSucc) { |
3425 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 3425, __PRETTY_FUNCTION__)); |
3426 | setOperand(idx * 2 + 1, NewSucc); |
3427 | } |
3428 | |
3429 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
3430 | static bool classof(const Instruction *I) { |
3431 | return I->getOpcode() == Instruction::Switch; |
3432 | } |
3433 | static bool classof(const Value *V) { |
3434 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
3435 | } |
3436 | }; |
3437 | |
3438 | template <> |
3439 | struct OperandTraits<SwitchInst> : public HungoffOperandTraits<2> { |
3440 | }; |
3441 | |
3442 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 3442, __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-9~svn360825/include/llvm/IR/Instructions.h" , 3442, __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); } |
3443 | |
3444 | //===----------------------------------------------------------------------===// |
3445 | // IndirectBrInst Class |
3446 | //===----------------------------------------------------------------------===// |
3447 | |
3448 | //===--------------------------------------------------------------------------- |
3449 | /// Indirect Branch Instruction. |
3450 | /// |
3451 | class IndirectBrInst : public Instruction { |
3452 | unsigned ReservedSpace; |
3453 | |
3454 | // Operand[0] = Address to jump to |
3455 | // Operand[n+1] = n-th destination |
3456 | IndirectBrInst(const IndirectBrInst &IBI); |
3457 | |
3458 | /// Create a new indirectbr instruction, specifying an |
3459 | /// Address to jump to. The number of expected destinations can be specified |
3460 | /// here to make memory allocation more efficient. This constructor can also |
3461 | /// autoinsert before another instruction. |
3462 | IndirectBrInst(Value *Address, unsigned NumDests, Instruction *InsertBefore); |
3463 | |
3464 | /// Create a new indirectbr instruction, specifying an |
3465 | /// Address to jump to. The number of expected destinations can be specified |
3466 | /// here to make memory allocation more efficient. This constructor also |
3467 | /// autoinserts at the end of the specified BasicBlock. |
3468 | IndirectBrInst(Value *Address, unsigned NumDests, BasicBlock *InsertAtEnd); |
3469 | |
3470 | // allocate space for exactly zero operands |
3471 | void *operator new(size_t s) { |
3472 | return User::operator new(s); |
3473 | } |
3474 | |
3475 | void init(Value *Address, unsigned NumDests); |
3476 | void growOperands(); |
3477 | |
3478 | protected: |
3479 | // Note: Instruction needs to be a friend here to call cloneImpl. |
3480 | friend class Instruction; |
3481 | |
3482 | IndirectBrInst *cloneImpl() const; |
3483 | |
3484 | public: |
3485 | /// Iterator type that casts an operand to a basic block. |
3486 | /// |
3487 | /// This only makes sense because the successors are stored as adjacent |
3488 | /// operands for indirectbr instructions. |
3489 | struct succ_op_iterator |
3490 | : iterator_adaptor_base<succ_op_iterator, value_op_iterator, |
3491 | std::random_access_iterator_tag, BasicBlock *, |
3492 | ptrdiff_t, BasicBlock *, BasicBlock *> { |
3493 | explicit succ_op_iterator(value_op_iterator I) : iterator_adaptor_base(I) {} |
3494 | |
3495 | BasicBlock *operator*() const { return cast<BasicBlock>(*I); } |
3496 | BasicBlock *operator->() const { return operator*(); } |
3497 | }; |
3498 | |
3499 | /// The const version of `succ_op_iterator`. |
3500 | struct const_succ_op_iterator |
3501 | : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator, |
3502 | std::random_access_iterator_tag, |
3503 | const BasicBlock *, ptrdiff_t, const BasicBlock *, |
3504 | const BasicBlock *> { |
3505 | explicit const_succ_op_iterator(const_value_op_iterator I) |
3506 | : iterator_adaptor_base(I) {} |
3507 | |
3508 | const BasicBlock *operator*() const { return cast<BasicBlock>(*I); } |
3509 | const BasicBlock *operator->() const { return operator*(); } |
3510 | }; |
3511 | |
3512 | static IndirectBrInst *Create(Value *Address, unsigned NumDests, |
3513 | Instruction *InsertBefore = nullptr) { |
3514 | return new IndirectBrInst(Address, NumDests, InsertBefore); |
3515 | } |
3516 | |
3517 | static IndirectBrInst *Create(Value *Address, unsigned NumDests, |
3518 | BasicBlock *InsertAtEnd) { |
3519 | return new IndirectBrInst(Address, NumDests, InsertAtEnd); |
3520 | } |
3521 | |
3522 | /// Provide fast operand accessors. |
3523 | 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; |
3524 | |
3525 | // Accessor Methods for IndirectBrInst instruction. |
3526 | Value *getAddress() { return getOperand(0); } |
3527 | const Value *getAddress() const { return getOperand(0); } |
3528 | void setAddress(Value *V) { setOperand(0, V); } |
3529 | |
3530 | /// return the number of possible destinations in this |
3531 | /// indirectbr instruction. |
3532 | unsigned getNumDestinations() const { return getNumOperands()-1; } |
3533 | |
3534 | /// Return the specified destination. |
3535 | BasicBlock *getDestination(unsigned i) { return getSuccessor(i); } |
3536 | const BasicBlock *getDestination(unsigned i) const { return getSuccessor(i); } |
3537 | |
3538 | /// Add a destination. |
3539 | /// |
3540 | void addDestination(BasicBlock *Dest); |
3541 | |
3542 | /// This method removes the specified successor from the |
3543 | /// indirectbr instruction. |
3544 | void removeDestination(unsigned i); |
3545 | |
3546 | unsigned getNumSuccessors() const { return getNumOperands()-1; } |
3547 | BasicBlock *getSuccessor(unsigned i) const { |
3548 | return cast<BasicBlock>(getOperand(i+1)); |
3549 | } |
3550 | void setSuccessor(unsigned i, BasicBlock *NewSucc) { |
3551 | setOperand(i + 1, NewSucc); |
3552 | } |
3553 | |
3554 | iterator_range<succ_op_iterator> successors() { |
3555 | return make_range(succ_op_iterator(std::next(value_op_begin())), |
3556 | succ_op_iterator(value_op_end())); |
3557 | } |
3558 | |
3559 | iterator_range<const_succ_op_iterator> successors() const { |
3560 | return make_range(const_succ_op_iterator(std::next(value_op_begin())), |
3561 | const_succ_op_iterator(value_op_end())); |
3562 | } |
3563 | |
3564 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
3565 | static bool classof(const Instruction *I) { |
3566 | return I->getOpcode() == Instruction::IndirectBr; |
3567 | } |
3568 | static bool classof(const Value *V) { |
3569 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
3570 | } |
3571 | }; |
3572 | |
3573 | template <> |
3574 | struct OperandTraits<IndirectBrInst> : public HungoffOperandTraits<1> { |
3575 | }; |
3576 | |
3577 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 3577, __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-9~svn360825/include/llvm/IR/Instructions.h" , 3577, __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); } |
3578 | |
3579 | //===----------------------------------------------------------------------===// |
3580 | // InvokeInst Class |
3581 | //===----------------------------------------------------------------------===// |
3582 | |
3583 | /// Invoke instruction. The SubclassData field is used to hold the |
3584 | /// calling convention of the call. |
3585 | /// |
3586 | class InvokeInst : public CallBase { |
3587 | /// The number of operands for this call beyond the called function, |
3588 | /// arguments, and operand bundles. |
3589 | static constexpr int NumExtraOperands = 2; |
3590 | |
3591 | /// The index from the end of the operand array to the normal destination. |
3592 | static constexpr int NormalDestOpEndIdx = -3; |
3593 | |
3594 | /// The index from the end of the operand array to the unwind destination. |
3595 | static constexpr int UnwindDestOpEndIdx = -2; |
3596 | |
3597 | InvokeInst(const InvokeInst &BI); |
3598 | |
3599 | /// Construct an InvokeInst given a range of arguments. |
3600 | /// |
3601 | /// Construct an InvokeInst from a range of arguments |
3602 | inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
3603 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3604 | ArrayRef<OperandBundleDef> Bundles, int NumOperands, |
3605 | const Twine &NameStr, Instruction *InsertBefore); |
3606 | |
3607 | inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
3608 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3609 | ArrayRef<OperandBundleDef> Bundles, int NumOperands, |
3610 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
3611 | |
3612 | void init(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
3613 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3614 | ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr); |
3615 | |
3616 | /// Compute the number of operands to allocate. |
3617 | static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) { |
3618 | // We need one operand for the called function, plus our extra operands and |
3619 | // the input operand counts provided. |
3620 | return 1 + NumExtraOperands + NumArgs + NumBundleInputs; |
3621 | } |
3622 | |
3623 | protected: |
3624 | // Note: Instruction needs to be a friend here to call cloneImpl. |
3625 | friend class Instruction; |
3626 | |
3627 | InvokeInst *cloneImpl() const; |
3628 | |
3629 | public: |
3630 | static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
3631 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3632 | const Twine &NameStr, |
3633 | Instruction *InsertBefore = nullptr) { |
3634 | int NumOperands = ComputeNumOperands(Args.size()); |
3635 | return new (NumOperands) |
3636 | InvokeInst(Ty, Func, IfNormal, IfException, Args, None, NumOperands, |
3637 | NameStr, InsertBefore); |
3638 | } |
3639 | |
3640 | static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
3641 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3642 | ArrayRef<OperandBundleDef> Bundles = None, |
3643 | const Twine &NameStr = "", |
3644 | Instruction *InsertBefore = nullptr) { |
3645 | int NumOperands = |
3646 | ComputeNumOperands(Args.size(), CountBundleInputs(Bundles)); |
3647 | unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo); |
3648 | |
3649 | return new (NumOperands, DescriptorBytes) |
3650 | InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, NumOperands, |
3651 | NameStr, InsertBefore); |
3652 | } |
3653 | |
3654 | static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
3655 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3656 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
3657 | int NumOperands = ComputeNumOperands(Args.size()); |
3658 | return new (NumOperands) |
3659 | InvokeInst(Ty, Func, IfNormal, IfException, Args, None, NumOperands, |
3660 | NameStr, InsertAtEnd); |
3661 | } |
3662 | |
3663 | static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
3664 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3665 | ArrayRef<OperandBundleDef> Bundles, |
3666 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
3667 | int NumOperands = |
3668 | ComputeNumOperands(Args.size(), CountBundleInputs(Bundles)); |
3669 | unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo); |
3670 | |
3671 | return new (NumOperands, DescriptorBytes) |
3672 | InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, NumOperands, |
3673 | NameStr, InsertAtEnd); |
3674 | } |
3675 | |
3676 | static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal, |
3677 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3678 | const Twine &NameStr, |
3679 | Instruction *InsertBefore = nullptr) { |
3680 | return Create(Func.getFunctionType(), Func.getCallee(), IfNormal, |
3681 | IfException, Args, None, NameStr, InsertBefore); |
3682 | } |
3683 | |
3684 | static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal, |
3685 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3686 | ArrayRef<OperandBundleDef> Bundles = None, |
3687 | const Twine &NameStr = "", |
3688 | Instruction *InsertBefore = nullptr) { |
3689 | return Create(Func.getFunctionType(), Func.getCallee(), IfNormal, |
3690 | IfException, Args, Bundles, NameStr, InsertBefore); |
3691 | } |
3692 | |
3693 | static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal, |
3694 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3695 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
3696 | return Create(Func.getFunctionType(), Func.getCallee(), IfNormal, |
3697 | IfException, Args, NameStr, InsertAtEnd); |
3698 | } |
3699 | |
3700 | static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal, |
3701 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3702 | ArrayRef<OperandBundleDef> Bundles, |
3703 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
3704 | return Create(Func.getFunctionType(), Func.getCallee(), IfNormal, |
3705 | IfException, Args, Bundles, NameStr, InsertAtEnd); |
3706 | } |
3707 | |
3708 | // Deprecated [opaque pointer types] |
3709 | static InvokeInst *Create(Value *Func, BasicBlock *IfNormal, |
3710 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3711 | const Twine &NameStr, |
3712 | Instruction *InsertBefore = nullptr) { |
3713 | return Create(cast<FunctionType>( |
3714 | cast<PointerType>(Func->getType())->getElementType()), |
3715 | Func, IfNormal, IfException, Args, None, NameStr, |
3716 | InsertBefore); |
3717 | } |
3718 | |
3719 | // Deprecated [opaque pointer types] |
3720 | static InvokeInst *Create(Value *Func, BasicBlock *IfNormal, |
3721 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3722 | ArrayRef<OperandBundleDef> Bundles = None, |
3723 | const Twine &NameStr = "", |
3724 | Instruction *InsertBefore = nullptr) { |
3725 | return Create(cast<FunctionType>( |
3726 | cast<PointerType>(Func->getType())->getElementType()), |
3727 | Func, IfNormal, IfException, Args, Bundles, NameStr, |
3728 | InsertBefore); |
3729 | } |
3730 | |
3731 | // Deprecated [opaque pointer types] |
3732 | static InvokeInst *Create(Value *Func, BasicBlock *IfNormal, |
3733 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3734 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
3735 | return Create(cast<FunctionType>( |
3736 | cast<PointerType>(Func->getType())->getElementType()), |
3737 | Func, IfNormal, IfException, Args, NameStr, InsertAtEnd); |
3738 | } |
3739 | |
3740 | // Deprecated [opaque pointer types] |
3741 | static InvokeInst *Create(Value *Func, BasicBlock *IfNormal, |
3742 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3743 | ArrayRef<OperandBundleDef> Bundles, |
3744 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
3745 | return Create(cast<FunctionType>( |
3746 | cast<PointerType>(Func->getType())->getElementType()), |
3747 | Func, IfNormal, IfException, Args, Bundles, NameStr, |
3748 | InsertAtEnd); |
3749 | } |
3750 | |
3751 | /// Create a clone of \p II with a different set of operand bundles and |
3752 | /// insert it before \p InsertPt. |
3753 | /// |
3754 | /// The returned invoke instruction is identical to \p II in every way except |
3755 | /// that the operand bundles for the new instruction are set to the operand |
3756 | /// bundles in \p Bundles. |
3757 | static InvokeInst *Create(InvokeInst *II, ArrayRef<OperandBundleDef> Bundles, |
3758 | Instruction *InsertPt = nullptr); |
3759 | |
3760 | /// Determine if the call should not perform indirect branch tracking. |
3761 | bool doesNoCfCheck() const { return hasFnAttr(Attribute::NoCfCheck); } |
3762 | |
3763 | /// Determine if the call cannot unwind. |
3764 | bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); } |
3765 | void setDoesNotThrow() { |
3766 | addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind); |
3767 | } |
3768 | |
3769 | // get*Dest - Return the destination basic blocks... |
3770 | BasicBlock *getNormalDest() const { |
3771 | return cast<BasicBlock>(Op<NormalDestOpEndIdx>()); |
3772 | } |
3773 | BasicBlock *getUnwindDest() const { |
3774 | return cast<BasicBlock>(Op<UnwindDestOpEndIdx>()); |
3775 | } |
3776 | void setNormalDest(BasicBlock *B) { |
3777 | Op<NormalDestOpEndIdx>() = reinterpret_cast<Value *>(B); |
3778 | } |
3779 | void setUnwindDest(BasicBlock *B) { |
3780 | Op<UnwindDestOpEndIdx>() = reinterpret_cast<Value *>(B); |
3781 | } |
3782 | |
3783 | /// Get the landingpad instruction from the landing pad |
3784 | /// block (the unwind destination). |
3785 | LandingPadInst *getLandingPadInst() const; |
3786 | |
3787 | BasicBlock *getSuccessor(unsigned i) const { |
3788 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 3788, __PRETTY_FUNCTION__)); |
3789 | return i == 0 ? getNormalDest() : getUnwindDest(); |
3790 | } |
3791 | |
3792 | void setSuccessor(unsigned i, BasicBlock *NewSucc) { |
3793 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 3793, __PRETTY_FUNCTION__)); |
3794 | if (i == 0) |
3795 | setNormalDest(NewSucc); |
3796 | else |
3797 | setUnwindDest(NewSucc); |
3798 | } |
3799 | |
3800 | unsigned getNumSuccessors() const { return 2; } |
3801 | |
3802 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
3803 | static bool classof(const Instruction *I) { |
3804 | return (I->getOpcode() == Instruction::Invoke); |
3805 | } |
3806 | static bool classof(const Value *V) { |
3807 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
3808 | } |
3809 | |
3810 | private: |
3811 | |
3812 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
3813 | // method so that subclasses cannot accidentally use it. |
3814 | void setInstructionSubclassData(unsigned short D) { |
3815 | Instruction::setInstructionSubclassData(D); |
3816 | } |
3817 | }; |
3818 | |
3819 | InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
3820 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3821 | ArrayRef<OperandBundleDef> Bundles, int NumOperands, |
3822 | const Twine &NameStr, Instruction *InsertBefore) |
3823 | : CallBase(Ty->getReturnType(), Instruction::Invoke, |
3824 | OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands, |
3825 | InsertBefore) { |
3826 | init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr); |
3827 | } |
3828 | |
3829 | InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, |
3830 | BasicBlock *IfException, ArrayRef<Value *> Args, |
3831 | ArrayRef<OperandBundleDef> Bundles, int NumOperands, |
3832 | const Twine &NameStr, BasicBlock *InsertAtEnd) |
3833 | : CallBase(Ty->getReturnType(), Instruction::Invoke, |
3834 | OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands, |
3835 | InsertAtEnd) { |
3836 | init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr); |
3837 | } |
3838 | |
3839 | //===----------------------------------------------------------------------===// |
3840 | // CallBrInst Class |
3841 | //===----------------------------------------------------------------------===// |
3842 | |
3843 | /// CallBr instruction, tracking function calls that may not return control but |
3844 | /// instead transfer it to a third location. The SubclassData field is used to |
3845 | /// hold the calling convention of the call. |
3846 | /// |
3847 | class CallBrInst : public CallBase { |
3848 | |
3849 | unsigned NumIndirectDests; |
3850 | |
3851 | CallBrInst(const CallBrInst &BI); |
3852 | |
3853 | /// Construct a CallBrInst given a range of arguments. |
3854 | /// |
3855 | /// Construct a CallBrInst from a range of arguments |
3856 | inline CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, |
3857 | ArrayRef<BasicBlock *> IndirectDests, |
3858 | ArrayRef<Value *> Args, |
3859 | ArrayRef<OperandBundleDef> Bundles, int NumOperands, |
3860 | const Twine &NameStr, Instruction *InsertBefore); |
3861 | |
3862 | inline CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, |
3863 | ArrayRef<BasicBlock *> IndirectDests, |
3864 | ArrayRef<Value *> Args, |
3865 | ArrayRef<OperandBundleDef> Bundles, int NumOperands, |
3866 | const Twine &NameStr, BasicBlock *InsertAtEnd); |
3867 | |
3868 | void init(FunctionType *FTy, Value *Func, BasicBlock *DefaultDest, |
3869 | ArrayRef<BasicBlock *> IndirectDests, ArrayRef<Value *> Args, |
3870 | ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr); |
3871 | |
3872 | /// Compute the number of operands to allocate. |
3873 | static int ComputeNumOperands(int NumArgs, int NumIndirectDests, |
3874 | int NumBundleInputs = 0) { |
3875 | // We need one operand for the called function, plus our extra operands and |
3876 | // the input operand counts provided. |
3877 | return 2 + NumIndirectDests + NumArgs + NumBundleInputs; |
3878 | } |
3879 | |
3880 | protected: |
3881 | // Note: Instruction needs to be a friend here to call cloneImpl. |
3882 | friend class Instruction; |
3883 | |
3884 | CallBrInst *cloneImpl() const; |
3885 | |
3886 | public: |
3887 | static CallBrInst *Create(FunctionType *Ty, Value *Func, |
3888 | BasicBlock *DefaultDest, |
3889 | ArrayRef<BasicBlock *> IndirectDests, |
3890 | ArrayRef<Value *> Args, const Twine &NameStr, |
3891 | Instruction *InsertBefore = nullptr) { |
3892 | int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size()); |
3893 | return new (NumOperands) |
3894 | CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, None, |
3895 | NumOperands, NameStr, InsertBefore); |
3896 | } |
3897 | |
3898 | static CallBrInst *Create(FunctionType *Ty, Value *Func, |
3899 | BasicBlock *DefaultDest, |
3900 | ArrayRef<BasicBlock *> IndirectDests, |
3901 | ArrayRef<Value *> Args, |
3902 | ArrayRef<OperandBundleDef> Bundles = None, |
3903 | const Twine &NameStr = "", |
3904 | Instruction *InsertBefore = nullptr) { |
3905 | int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size(), |
3906 | CountBundleInputs(Bundles)); |
3907 | unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo); |
3908 | |
3909 | return new (NumOperands, DescriptorBytes) |
3910 | CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, |
3911 | NumOperands, NameStr, InsertBefore); |
3912 | } |
3913 | |
3914 | static CallBrInst *Create(FunctionType *Ty, Value *Func, |
3915 | BasicBlock *DefaultDest, |
3916 | ArrayRef<BasicBlock *> IndirectDests, |
3917 | ArrayRef<Value *> Args, const Twine &NameStr, |
3918 | BasicBlock *InsertAtEnd) { |
3919 | int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size()); |
3920 | return new (NumOperands) |
3921 | CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, None, |
3922 | NumOperands, NameStr, InsertAtEnd); |
3923 | } |
3924 | |
3925 | static CallBrInst *Create(FunctionType *Ty, Value *Func, |
3926 | BasicBlock *DefaultDest, |
3927 | ArrayRef<BasicBlock *> IndirectDests, |
3928 | ArrayRef<Value *> Args, |
3929 | ArrayRef<OperandBundleDef> Bundles, |
3930 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
3931 | int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size(), |
3932 | CountBundleInputs(Bundles)); |
3933 | unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo); |
3934 | |
3935 | return new (NumOperands, DescriptorBytes) |
3936 | CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, |
3937 | NumOperands, NameStr, InsertAtEnd); |
3938 | } |
3939 | |
3940 | static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest, |
3941 | ArrayRef<BasicBlock *> IndirectDests, |
3942 | ArrayRef<Value *> Args, const Twine &NameStr, |
3943 | Instruction *InsertBefore = nullptr) { |
3944 | return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest, |
3945 | IndirectDests, Args, NameStr, InsertBefore); |
3946 | } |
3947 | |
3948 | static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest, |
3949 | ArrayRef<BasicBlock *> IndirectDests, |
3950 | ArrayRef<Value *> Args, |
3951 | ArrayRef<OperandBundleDef> Bundles = None, |
3952 | const Twine &NameStr = "", |
3953 | Instruction *InsertBefore = nullptr) { |
3954 | return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest, |
3955 | IndirectDests, Args, Bundles, NameStr, InsertBefore); |
3956 | } |
3957 | |
3958 | static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest, |
3959 | ArrayRef<BasicBlock *> IndirectDests, |
3960 | ArrayRef<Value *> Args, const Twine &NameStr, |
3961 | BasicBlock *InsertAtEnd) { |
3962 | return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest, |
3963 | IndirectDests, Args, NameStr, InsertAtEnd); |
3964 | } |
3965 | |
3966 | static CallBrInst *Create(FunctionCallee Func, |
3967 | BasicBlock *DefaultDest, |
3968 | ArrayRef<BasicBlock *> IndirectDests, |
3969 | ArrayRef<Value *> Args, |
3970 | ArrayRef<OperandBundleDef> Bundles, |
3971 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
3972 | return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest, |
3973 | IndirectDests, Args, Bundles, NameStr, InsertAtEnd); |
3974 | } |
3975 | |
3976 | /// Create a clone of \p CBI with a different set of operand bundles and |
3977 | /// insert it before \p InsertPt. |
3978 | /// |
3979 | /// The returned callbr instruction is identical to \p CBI in every way |
3980 | /// except that the operand bundles for the new instruction are set to the |
3981 | /// operand bundles in \p Bundles. |
3982 | static CallBrInst *Create(CallBrInst *CBI, |
3983 | ArrayRef<OperandBundleDef> Bundles, |
3984 | Instruction *InsertPt = nullptr); |
3985 | |
3986 | /// Return the number of callbr indirect dest labels. |
3987 | /// |
3988 | unsigned getNumIndirectDests() const { return NumIndirectDests; } |
3989 | |
3990 | /// getIndirectDestLabel - Return the i-th indirect dest label. |
3991 | /// |
3992 | Value *getIndirectDestLabel(unsigned i) const { |
3993 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 3993, __PRETTY_FUNCTION__)); |
3994 | return getOperand(i + getNumArgOperands() + getNumTotalBundleOperands() + |
3995 | 1); |
3996 | } |
3997 | |
3998 | Value *getIndirectDestLabelUse(unsigned i) const { |
3999 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 3999, __PRETTY_FUNCTION__)); |
4000 | return getOperandUse(i + getNumArgOperands() + getNumTotalBundleOperands() + |
4001 | 1); |
4002 | } |
4003 | |
4004 | // Return the destination basic blocks... |
4005 | BasicBlock *getDefaultDest() const { |
4006 | return cast<BasicBlock>(*(&Op<-1>() - getNumIndirectDests() - 1)); |
4007 | } |
4008 | BasicBlock *getIndirectDest(unsigned i) const { |
4009 | return cast<BasicBlock>(*(&Op<-1>() - getNumIndirectDests() + i)); |
4010 | } |
4011 | SmallVector<BasicBlock *, 16> getIndirectDests() const { |
4012 | SmallVector<BasicBlock *, 16> IndirectDests; |
4013 | for (unsigned i = 0, e = getNumIndirectDests(); i < e; ++i) |
4014 | IndirectDests.push_back(getIndirectDest(i)); |
4015 | return IndirectDests; |
4016 | } |
4017 | void setDefaultDest(BasicBlock *B) { |
4018 | *(&Op<-1>() - getNumIndirectDests() - 1) = reinterpret_cast<Value *>(B); |
4019 | } |
4020 | void setIndirectDest(unsigned i, BasicBlock *B) { |
4021 | *(&Op<-1>() - getNumIndirectDests() + i) = reinterpret_cast<Value *>(B); |
4022 | } |
4023 | |
4024 | BasicBlock *getSuccessor(unsigned i) const { |
4025 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 4026, __PRETTY_FUNCTION__)) |
4026 | "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-9~svn360825/include/llvm/IR/Instructions.h" , 4026, __PRETTY_FUNCTION__)); |
4027 | return i == 0 ? getDefaultDest() : getIndirectDest(i - 1); |
4028 | } |
4029 | |
4030 | void setSuccessor(unsigned idx, BasicBlock *NewSucc) { |
4031 | assert(idx < getNumIndirectDests() + 1 &&((idx < getNumIndirectDests() + 1 && "Successor # out of range for callbr!" ) ? static_cast<void> (0) : __assert_fail ("idx < getNumIndirectDests() + 1 && \"Successor # out of range for callbr!\"" , "/build/llvm-toolchain-snapshot-9~svn360825/include/llvm/IR/Instructions.h" , 4032, __PRETTY_FUNCTION__)) |
4032 | "Successor # out of range for callbr!")((idx < getNumIndirectDests() + 1 && "Successor # out of range for callbr!" ) ? static_cast<void> (0) : __assert_fail ("idx < getNumIndirectDests() + 1 && \"Successor # out of range for callbr!\"" , "/build/llvm-toolchain-snapshot-9~svn360825/include/llvm/IR/Instructions.h" , 4032, __PRETTY_FUNCTION__)); |
4033 | *(&Op<-1>() - getNumIndirectDests() -1 + idx) = |
4034 | reinterpret_cast<Value *>(NewSucc); |
4035 | } |
4036 | |
4037 | unsigned getNumSuccessors() const { return getNumIndirectDests() + 1; } |
4038 | |
4039 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
4040 | static bool classof(const Instruction *I) { |
4041 | return (I->getOpcode() == Instruction::CallBr); |
4042 | } |
4043 | static bool classof(const Value *V) { |
4044 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4045 | } |
4046 | |
4047 | private: |
4048 | |
4049 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
4050 | // method so that subclasses cannot accidentally use it. |
4051 | void setInstructionSubclassData(unsigned short D) { |
4052 | Instruction::setInstructionSubclassData(D); |
4053 | } |
4054 | }; |
4055 | |
4056 | CallBrInst::CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, |
4057 | ArrayRef<BasicBlock *> IndirectDests, |
4058 | ArrayRef<Value *> Args, |
4059 | ArrayRef<OperandBundleDef> Bundles, int NumOperands, |
4060 | const Twine &NameStr, Instruction *InsertBefore) |
4061 | : CallBase(Ty->getReturnType(), Instruction::CallBr, |
4062 | OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands, |
4063 | InsertBefore) { |
4064 | init(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, NameStr); |
4065 | } |
4066 | |
4067 | CallBrInst::CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, |
4068 | ArrayRef<BasicBlock *> IndirectDests, |
4069 | ArrayRef<Value *> Args, |
4070 | ArrayRef<OperandBundleDef> Bundles, int NumOperands, |
4071 | const Twine &NameStr, BasicBlock *InsertAtEnd) |
4072 | : CallBase( |
4073 | cast<FunctionType>( |
4074 | cast<PointerType>(Func->getType())->getElementType()) |
4075 | ->getReturnType(), |
4076 | Instruction::CallBr, |
4077 | OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands, |
4078 | InsertAtEnd) { |
4079 | init(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, NameStr); |
4080 | } |
4081 | |
4082 | //===----------------------------------------------------------------------===// |
4083 | // ResumeInst Class |
4084 | //===----------------------------------------------------------------------===// |
4085 | |
4086 | //===--------------------------------------------------------------------------- |
4087 | /// Resume the propagation of an exception. |
4088 | /// |
4089 | class ResumeInst : public Instruction { |
4090 | ResumeInst(const ResumeInst &RI); |
4091 | |
4092 | explicit ResumeInst(Value *Exn, Instruction *InsertBefore=nullptr); |
4093 | ResumeInst(Value *Exn, BasicBlock *InsertAtEnd); |
4094 | |
4095 | protected: |
4096 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4097 | friend class Instruction; |
4098 | |
4099 | ResumeInst *cloneImpl() const; |
4100 | |
4101 | public: |
4102 | static ResumeInst *Create(Value *Exn, Instruction *InsertBefore = nullptr) { |
4103 | return new(1) ResumeInst(Exn, InsertBefore); |
4104 | } |
4105 | |
4106 | static ResumeInst *Create(Value *Exn, BasicBlock *InsertAtEnd) { |
4107 | return new(1) ResumeInst(Exn, InsertAtEnd); |
4108 | } |
4109 | |
4110 | /// Provide fast operand accessors |
4111 | 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; |
4112 | |
4113 | /// Convenience accessor. |
4114 | Value *getValue() const { return Op<0>(); } |
4115 | |
4116 | unsigned getNumSuccessors() const { return 0; } |
4117 | |
4118 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
4119 | static bool classof(const Instruction *I) { |
4120 | return I->getOpcode() == Instruction::Resume; |
4121 | } |
4122 | static bool classof(const Value *V) { |
4123 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4124 | } |
4125 | |
4126 | private: |
4127 | BasicBlock *getSuccessor(unsigned idx) const { |
4128 | llvm_unreachable("ResumeInst has no successors!")::llvm::llvm_unreachable_internal("ResumeInst has no successors!" , "/build/llvm-toolchain-snapshot-9~svn360825/include/llvm/IR/Instructions.h" , 4128); |
4129 | } |
4130 | |
4131 | void setSuccessor(unsigned idx, BasicBlock *NewSucc) { |
4132 | llvm_unreachable("ResumeInst has no successors!")::llvm::llvm_unreachable_internal("ResumeInst has no successors!" , "/build/llvm-toolchain-snapshot-9~svn360825/include/llvm/IR/Instructions.h" , 4132); |
4133 | } |
4134 | }; |
4135 | |
4136 | template <> |
4137 | struct OperandTraits<ResumeInst> : |
4138 | public FixedNumOperandTraits<ResumeInst, 1> { |
4139 | }; |
4140 | |
4141 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 4141, __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-9~svn360825/include/llvm/IR/Instructions.h" , 4141, __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); } |
4142 | |
4143 | //===----------------------------------------------------------------------===// |
4144 | // CatchSwitchInst Class |
4145 | //===----------------------------------------------------------------------===// |
4146 | class CatchSwitchInst : public Instruction { |
4147 | /// The number of operands actually allocated. NumOperands is |
4148 | /// the number actually in use. |
4149 | unsigned ReservedSpace; |
4150 | |
4151 | // Operand[0] = Outer scope |
4152 | // Operand[1] = Unwind block destination |
4153 | // Operand[n] = BasicBlock to go to on match |
4154 | CatchSwitchInst(const CatchSwitchInst &CSI); |
4155 | |
4156 | /// Create a new switch instruction, specifying a |
4157 | /// default destination. The number of additional handlers can be specified |
4158 | /// here to make memory allocation more efficient. |
4159 | /// This constructor can also autoinsert before another instruction. |
4160 | CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest, |
4161 | unsigned NumHandlers, const Twine &NameStr, |
4162 | Instruction *InsertBefore); |
4163 | |
4164 | /// Create a new switch instruction, specifying a |
4165 | /// default destination. The number of additional handlers can be specified |
4166 | /// here to make memory allocation more efficient. |
4167 | /// This constructor also autoinserts at the end of the specified BasicBlock. |
4168 | CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest, |
4169 | unsigned NumHandlers, const Twine &NameStr, |
4170 | BasicBlock *InsertAtEnd); |
4171 | |
4172 | // allocate space for exactly zero operands |
4173 | void *operator new(size_t s) { return User::operator new(s); } |
4174 | |
4175 | void init(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumReserved); |
4176 | void growOperands(unsigned Size); |
4177 | |
4178 | protected: |
4179 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4180 | friend class Instruction; |
4181 | |
4182 | CatchSwitchInst *cloneImpl() const; |
4183 | |
4184 | public: |
4185 | static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest, |
4186 | unsigned NumHandlers, |
4187 | const Twine &NameStr = "", |
4188 | Instruction *InsertBefore = nullptr) { |
4189 | return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr, |
4190 | InsertBefore); |
4191 | } |
4192 | |
4193 | static CatchSwitchInst *Create(Value *ParentPad, BasicBlock *UnwindDest, |
4194 | unsigned NumHandlers, const Twine &NameStr, |
4195 | BasicBlock *InsertAtEnd) { |
4196 | return new CatchSwitchInst(ParentPad, UnwindDest, NumHandlers, NameStr, |
4197 | InsertAtEnd); |
4198 | } |
4199 | |
4200 | /// Provide fast operand accessors |
4201 | 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; |
4202 | |
4203 | // Accessor Methods for CatchSwitch stmt |
4204 | Value *getParentPad() const { return getOperand(0); } |
4205 | void setParentPad(Value *ParentPad) { setOperand(0, ParentPad); } |
4206 | |
4207 | // Accessor Methods for CatchSwitch stmt |
4208 | bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; } |
4209 | bool unwindsToCaller() const { return !hasUnwindDest(); } |
4210 | BasicBlock *getUnwindDest() const { |
4211 | if (hasUnwindDest()) |
4212 | return cast<BasicBlock>(getOperand(1)); |
4213 | return nullptr; |
4214 | } |
4215 | void setUnwindDest(BasicBlock *UnwindDest) { |
4216 | assert(UnwindDest)((UnwindDest) ? static_cast<void> (0) : __assert_fail ( "UnwindDest", "/build/llvm-toolchain-snapshot-9~svn360825/include/llvm/IR/Instructions.h" , 4216, __PRETTY_FUNCTION__)); |
4217 | assert(hasUnwindDest())((hasUnwindDest()) ? static_cast<void> (0) : __assert_fail ("hasUnwindDest()", "/build/llvm-toolchain-snapshot-9~svn360825/include/llvm/IR/Instructions.h" , 4217, __PRETTY_FUNCTION__)); |
4218 | setOperand(1, UnwindDest); |
4219 | } |
4220 | |
4221 | /// return the number of 'handlers' in this catchswitch |
4222 | /// instruction, except the default handler |
4223 | unsigned getNumHandlers() const { |
4224 | if (hasUnwindDest()) |
4225 | return getNumOperands() - 2; |
4226 | return getNumOperands() - 1; |
4227 | } |
4228 | |
4229 | private: |
4230 | static BasicBlock *handler_helper(Value *V) { return cast<BasicBlock>(V); } |
4231 | static const BasicBlock *handler_helper(const Value *V) { |
4232 | return cast<BasicBlock>(V); |
4233 | } |
4234 | |
4235 | public: |
4236 | using DerefFnTy = BasicBlock *(*)(Value *); |
4237 | using handler_iterator = mapped_iterator<op_iterator, DerefFnTy>; |
4238 | using handler_range = iterator_range<handler_iterator>; |
4239 | using ConstDerefFnTy = const BasicBlock *(*)(const Value *); |
4240 | using const_handler_iterator = |
4241 | mapped_iterator<const_op_iterator, ConstDerefFnTy>; |
4242 | using const_handler_range = iterator_range<const_handler_iterator>; |
4243 | |
4244 | /// Returns an iterator that points to the first handler in CatchSwitchInst. |
4245 | handler_iterator handler_begin() { |
4246 | op_iterator It = op_begin() + 1; |
4247 | if (hasUnwindDest()) |
4248 | ++It; |
4249 | return handler_iterator(It, DerefFnTy(handler_helper)); |
4250 | } |
4251 | |
4252 | /// Returns an iterator that points to the first handler in the |
4253 | /// CatchSwitchInst. |
4254 | const_handler_iterator handler_begin() const { |
4255 | const_op_iterator It = op_begin() + 1; |
4256 | if (hasUnwindDest()) |
4257 | ++It; |
4258 | return const_handler_iterator(It, ConstDerefFnTy(handler_helper)); |
4259 | } |
4260 | |
4261 | /// Returns a read-only iterator that points one past the last |
4262 | /// handler in the CatchSwitchInst. |
4263 | handler_iterator handler_end() { |
4264 | return handler_iterator(op_end(), DerefFnTy(handler_helper)); |
4265 | } |
4266 | |
4267 | /// Returns an iterator that points one past the last handler in the |
4268 | /// CatchSwitchInst. |
4269 | const_handler_iterator handler_end() const { |
4270 | return const_handler_iterator(op_end(), ConstDerefFnTy(handler_helper)); |
4271 | } |
4272 | |
4273 | /// iteration adapter for range-for loops. |
4274 | handler_range handlers() { |
4275 | return make_range(handler_begin(), handler_end()); |
4276 | } |
4277 | |
4278 | /// iteration adapter for range-for loops. |
4279 | const_handler_range handlers() const { |
4280 | return make_range(handler_begin(), handler_end()); |
4281 | } |
4282 | |
4283 | /// Add an entry to the switch instruction... |
4284 | /// Note: |
4285 | /// This action invalidates handler_end(). Old handler_end() iterator will |
4286 | /// point to the added handler. |
4287 | void addHandler(BasicBlock *Dest); |
4288 | |
4289 | void removeHandler(handler_iterator HI); |
4290 | |
4291 | unsigned getNumSuccessors() const { return getNumOperands() - 1; } |
4292 | BasicBlock *getSuccessor(unsigned Idx) const { |
4293 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 4294, __PRETTY_FUNCTION__)) |
4294 | "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-9~svn360825/include/llvm/IR/Instructions.h" , 4294, __PRETTY_FUNCTION__)); |
4295 | return cast<BasicBlock>(getOperand(Idx + 1)); |
4296 | } |
4297 | void setSuccessor(unsigned Idx, BasicBlock *NewSucc) { |
4298 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 4299, __PRETTY_FUNCTION__)) |
4299 | "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-9~svn360825/include/llvm/IR/Instructions.h" , 4299, __PRETTY_FUNCTION__)); |
4300 | setOperand(Idx + 1, NewSucc); |
4301 | } |
4302 | |
4303 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
4304 | static bool classof(const Instruction *I) { |
4305 | return I->getOpcode() == Instruction::CatchSwitch; |
4306 | } |
4307 | static bool classof(const Value *V) { |
4308 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4309 | } |
4310 | }; |
4311 | |
4312 | template <> |
4313 | struct OperandTraits<CatchSwitchInst> : public HungoffOperandTraits<2> {}; |
4314 | |
4315 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 4315, __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-9~svn360825/include/llvm/IR/Instructions.h" , 4315, __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); } |
4316 | |
4317 | //===----------------------------------------------------------------------===// |
4318 | // CleanupPadInst Class |
4319 | //===----------------------------------------------------------------------===// |
4320 | class CleanupPadInst : public FuncletPadInst { |
4321 | private: |
4322 | explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args, |
4323 | unsigned Values, const Twine &NameStr, |
4324 | Instruction *InsertBefore) |
4325 | : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values, |
4326 | NameStr, InsertBefore) {} |
4327 | explicit CleanupPadInst(Value *ParentPad, ArrayRef<Value *> Args, |
4328 | unsigned Values, const Twine &NameStr, |
4329 | BasicBlock *InsertAtEnd) |
4330 | : FuncletPadInst(Instruction::CleanupPad, ParentPad, Args, Values, |
4331 | NameStr, InsertAtEnd) {} |
4332 | |
4333 | public: |
4334 | static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args = None, |
4335 | const Twine &NameStr = "", |
4336 | Instruction *InsertBefore = nullptr) { |
4337 | unsigned Values = 1 + Args.size(); |
4338 | return new (Values) |
4339 | CleanupPadInst(ParentPad, Args, Values, NameStr, InsertBefore); |
4340 | } |
4341 | |
4342 | static CleanupPadInst *Create(Value *ParentPad, ArrayRef<Value *> Args, |
4343 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
4344 | unsigned Values = 1 + Args.size(); |
4345 | return new (Values) |
4346 | CleanupPadInst(ParentPad, Args, Values, NameStr, InsertAtEnd); |
4347 | } |
4348 | |
4349 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
4350 | static bool classof(const Instruction *I) { |
4351 | return I->getOpcode() == Instruction::CleanupPad; |
4352 | } |
4353 | static bool classof(const Value *V) { |
4354 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4355 | } |
4356 | }; |
4357 | |
4358 | //===----------------------------------------------------------------------===// |
4359 | // CatchPadInst Class |
4360 | //===----------------------------------------------------------------------===// |
4361 | class CatchPadInst : public FuncletPadInst { |
4362 | private: |
4363 | explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args, |
4364 | unsigned Values, const Twine &NameStr, |
4365 | Instruction *InsertBefore) |
4366 | : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values, |
4367 | NameStr, InsertBefore) {} |
4368 | explicit CatchPadInst(Value *CatchSwitch, ArrayRef<Value *> Args, |
4369 | unsigned Values, const Twine &NameStr, |
4370 | BasicBlock *InsertAtEnd) |
4371 | : FuncletPadInst(Instruction::CatchPad, CatchSwitch, Args, Values, |
4372 | NameStr, InsertAtEnd) {} |
4373 | |
4374 | public: |
4375 | static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args, |
4376 | const Twine &NameStr = "", |
4377 | Instruction *InsertBefore = nullptr) { |
4378 | unsigned Values = 1 + Args.size(); |
4379 | return new (Values) |
4380 | CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertBefore); |
4381 | } |
4382 | |
4383 | static CatchPadInst *Create(Value *CatchSwitch, ArrayRef<Value *> Args, |
4384 | const Twine &NameStr, BasicBlock *InsertAtEnd) { |
4385 | unsigned Values = 1 + Args.size(); |
4386 | return new (Values) |
4387 | CatchPadInst(CatchSwitch, Args, Values, NameStr, InsertAtEnd); |
4388 | } |
4389 | |
4390 | /// Convenience accessors |
4391 | CatchSwitchInst *getCatchSwitch() const { |
4392 | return cast<CatchSwitchInst>(Op<-1>()); |
4393 | } |
4394 | void setCatchSwitch(Value *CatchSwitch) { |
4395 | assert(CatchSwitch)((CatchSwitch) ? static_cast<void> (0) : __assert_fail ( "CatchSwitch", "/build/llvm-toolchain-snapshot-9~svn360825/include/llvm/IR/Instructions.h" , 4395, __PRETTY_FUNCTION__)); |
4396 | Op<-1>() = CatchSwitch; |
4397 | } |
4398 | |
4399 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
4400 | static bool classof(const Instruction *I) { |
4401 | return I->getOpcode() == Instruction::CatchPad; |
4402 | } |
4403 | static bool classof(const Value *V) { |
4404 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4405 | } |
4406 | }; |
4407 | |
4408 | //===----------------------------------------------------------------------===// |
4409 | // CatchReturnInst Class |
4410 | //===----------------------------------------------------------------------===// |
4411 | |
4412 | class CatchReturnInst : public Instruction { |
4413 | CatchReturnInst(const CatchReturnInst &RI); |
4414 | CatchReturnInst(Value *CatchPad, BasicBlock *BB, Instruction *InsertBefore); |
4415 | CatchReturnInst(Value *CatchPad, BasicBlock *BB, BasicBlock *InsertAtEnd); |
4416 | |
4417 | void init(Value *CatchPad, BasicBlock *BB); |
4418 | |
4419 | protected: |
4420 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4421 | friend class Instruction; |
4422 | |
4423 | CatchReturnInst *cloneImpl() const; |
4424 | |
4425 | public: |
4426 | static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB, |
4427 | Instruction *InsertBefore = nullptr) { |
4428 | assert(CatchPad)((CatchPad) ? static_cast<void> (0) : __assert_fail ("CatchPad" , "/build/llvm-toolchain-snapshot-9~svn360825/include/llvm/IR/Instructions.h" , 4428, __PRETTY_FUNCTION__)); |
4429 | assert(BB)((BB) ? static_cast<void> (0) : __assert_fail ("BB", "/build/llvm-toolchain-snapshot-9~svn360825/include/llvm/IR/Instructions.h" , 4429, __PRETTY_FUNCTION__)); |
4430 | return new (2) CatchReturnInst(CatchPad, BB, InsertBefore); |
4431 | } |
4432 | |
4433 | static CatchReturnInst *Create(Value *CatchPad, BasicBlock *BB, |
4434 | BasicBlock *InsertAtEnd) { |
4435 | assert(CatchPad)((CatchPad) ? static_cast<void> (0) : __assert_fail ("CatchPad" , "/build/llvm-toolchain-snapshot-9~svn360825/include/llvm/IR/Instructions.h" , 4435, __PRETTY_FUNCTION__)); |
4436 | assert(BB)((BB) ? static_cast<void> (0) : __assert_fail ("BB", "/build/llvm-toolchain-snapshot-9~svn360825/include/llvm/IR/Instructions.h" , 4436, __PRETTY_FUNCTION__)); |
4437 | return new (2) CatchReturnInst(CatchPad, BB, InsertAtEnd); |
4438 | } |
4439 | |
4440 | /// Provide fast operand accessors |
4441 | 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; |
4442 | |
4443 | /// Convenience accessors. |
4444 | CatchPadInst *getCatchPad() const { return cast<CatchPadInst>(Op<0>()); } |
4445 | void setCatchPad(CatchPadInst *CatchPad) { |
4446 | assert(CatchPad)((CatchPad) ? static_cast<void> (0) : __assert_fail ("CatchPad" , "/build/llvm-toolchain-snapshot-9~svn360825/include/llvm/IR/Instructions.h" , 4446, __PRETTY_FUNCTION__)); |
4447 | Op<0>() = CatchPad; |
4448 | } |
4449 | |
4450 | BasicBlock *getSuccessor() const { return cast<BasicBlock>(Op<1>()); } |
4451 | void setSuccessor(BasicBlock *NewSucc) { |
4452 | assert(NewSucc)((NewSucc) ? static_cast<void> (0) : __assert_fail ("NewSucc" , "/build/llvm-toolchain-snapshot-9~svn360825/include/llvm/IR/Instructions.h" , 4452, __PRETTY_FUNCTION__)); |
4453 | Op<1>() = NewSucc; |
4454 | } |
4455 | unsigned getNumSuccessors() const { return 1; } |
4456 | |
4457 | /// Get the parentPad of this catchret's catchpad's catchswitch. |
4458 | /// The successor block is implicitly a member of this funclet. |
4459 | Value *getCatchSwitchParentPad() const { |
4460 | return getCatchPad()->getCatchSwitch()->getParentPad(); |
4461 | } |
4462 | |
4463 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
4464 | static bool classof(const Instruction *I) { |
4465 | return (I->getOpcode() == Instruction::CatchRet); |
4466 | } |
4467 | static bool classof(const Value *V) { |
4468 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4469 | } |
4470 | |
4471 | private: |
4472 | BasicBlock *getSuccessor(unsigned Idx) const { |
4473 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 4473, __PRETTY_FUNCTION__)); |
4474 | return getSuccessor(); |
4475 | } |
4476 | |
4477 | void setSuccessor(unsigned Idx, BasicBlock *B) { |
4478 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 4478, __PRETTY_FUNCTION__)); |
4479 | setSuccessor(B); |
4480 | } |
4481 | }; |
4482 | |
4483 | template <> |
4484 | struct OperandTraits<CatchReturnInst> |
4485 | : public FixedNumOperandTraits<CatchReturnInst, 2> {}; |
4486 | |
4487 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 4487, __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-9~svn360825/include/llvm/IR/Instructions.h" , 4487, __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); } |
4488 | |
4489 | //===----------------------------------------------------------------------===// |
4490 | // CleanupReturnInst Class |
4491 | //===----------------------------------------------------------------------===// |
4492 | |
4493 | class CleanupReturnInst : public Instruction { |
4494 | private: |
4495 | CleanupReturnInst(const CleanupReturnInst &RI); |
4496 | CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values, |
4497 | Instruction *InsertBefore = nullptr); |
4498 | CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, unsigned Values, |
4499 | BasicBlock *InsertAtEnd); |
4500 | |
4501 | void init(Value *CleanupPad, BasicBlock *UnwindBB); |
4502 | |
4503 | protected: |
4504 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4505 | friend class Instruction; |
4506 | |
4507 | CleanupReturnInst *cloneImpl() const; |
4508 | |
4509 | public: |
4510 | static CleanupReturnInst *Create(Value *CleanupPad, |
4511 | BasicBlock *UnwindBB = nullptr, |
4512 | Instruction *InsertBefore = nullptr) { |
4513 | assert(CleanupPad)((CleanupPad) ? static_cast<void> (0) : __assert_fail ( "CleanupPad", "/build/llvm-toolchain-snapshot-9~svn360825/include/llvm/IR/Instructions.h" , 4513, __PRETTY_FUNCTION__)); |
4514 | unsigned Values = 1; |
4515 | if (UnwindBB) |
4516 | ++Values; |
4517 | return new (Values) |
4518 | CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertBefore); |
4519 | } |
4520 | |
4521 | static CleanupReturnInst *Create(Value *CleanupPad, BasicBlock *UnwindBB, |
4522 | BasicBlock *InsertAtEnd) { |
4523 | assert(CleanupPad)((CleanupPad) ? static_cast<void> (0) : __assert_fail ( "CleanupPad", "/build/llvm-toolchain-snapshot-9~svn360825/include/llvm/IR/Instructions.h" , 4523, __PRETTY_FUNCTION__)); |
4524 | unsigned Values = 1; |
4525 | if (UnwindBB) |
4526 | ++Values; |
4527 | return new (Values) |
4528 | CleanupReturnInst(CleanupPad, UnwindBB, Values, InsertAtEnd); |
4529 | } |
4530 | |
4531 | /// Provide fast operand accessors |
4532 | 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; |
4533 | |
4534 | bool hasUnwindDest() const { return getSubclassDataFromInstruction() & 1; } |
4535 | bool unwindsToCaller() const { return !hasUnwindDest(); } |
4536 | |
4537 | /// Convenience accessor. |
4538 | CleanupPadInst *getCleanupPad() const { |
4539 | return cast<CleanupPadInst>(Op<0>()); |
4540 | } |
4541 | void setCleanupPad(CleanupPadInst *CleanupPad) { |
4542 | assert(CleanupPad)((CleanupPad) ? static_cast<void> (0) : __assert_fail ( "CleanupPad", "/build/llvm-toolchain-snapshot-9~svn360825/include/llvm/IR/Instructions.h" , 4542, __PRETTY_FUNCTION__)); |
4543 | Op<0>() = CleanupPad; |
4544 | } |
4545 | |
4546 | unsigned getNumSuccessors() const { return hasUnwindDest() ? 1 : 0; } |
4547 | |
4548 | BasicBlock *getUnwindDest() const { |
4549 | return hasUnwindDest() ? cast<BasicBlock>(Op<1>()) : nullptr; |
4550 | } |
4551 | void setUnwindDest(BasicBlock *NewDest) { |
4552 | assert(NewDest)((NewDest) ? static_cast<void> (0) : __assert_fail ("NewDest" , "/build/llvm-toolchain-snapshot-9~svn360825/include/llvm/IR/Instructions.h" , 4552, __PRETTY_FUNCTION__)); |
4553 | assert(hasUnwindDest())((hasUnwindDest()) ? static_cast<void> (0) : __assert_fail ("hasUnwindDest()", "/build/llvm-toolchain-snapshot-9~svn360825/include/llvm/IR/Instructions.h" , 4553, __PRETTY_FUNCTION__)); |
4554 | Op<1>() = NewDest; |
4555 | } |
4556 | |
4557 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
4558 | static bool classof(const Instruction *I) { |
4559 | return (I->getOpcode() == Instruction::CleanupRet); |
4560 | } |
4561 | static bool classof(const Value *V) { |
4562 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4563 | } |
4564 | |
4565 | private: |
4566 | BasicBlock *getSuccessor(unsigned Idx) const { |
4567 | assert(Idx == 0)((Idx == 0) ? static_cast<void> (0) : __assert_fail ("Idx == 0" , "/build/llvm-toolchain-snapshot-9~svn360825/include/llvm/IR/Instructions.h" , 4567, __PRETTY_FUNCTION__)); |
4568 | return getUnwindDest(); |
4569 | } |
4570 | |
4571 | void setSuccessor(unsigned Idx, BasicBlock *B) { |
4572 | assert(Idx == 0)((Idx == 0) ? static_cast<void> (0) : __assert_fail ("Idx == 0" , "/build/llvm-toolchain-snapshot-9~svn360825/include/llvm/IR/Instructions.h" , 4572, __PRETTY_FUNCTION__)); |
4573 | setUnwindDest(B); |
4574 | } |
4575 | |
4576 | // Shadow Instruction::setInstructionSubclassData with a private forwarding |
4577 | // method so that subclasses cannot accidentally use it. |
4578 | void setInstructionSubclassData(unsigned short D) { |
4579 | Instruction::setInstructionSubclassData(D); |
4580 | } |
4581 | }; |
4582 | |
4583 | template <> |
4584 | struct OperandTraits<CleanupReturnInst> |
4585 | : public VariadicOperandTraits<CleanupReturnInst, /*MINARITY=*/1> {}; |
4586 | |
4587 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 4587, __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-9~svn360825/include/llvm/IR/Instructions.h" , 4587, __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); } |
4588 | |
4589 | //===----------------------------------------------------------------------===// |
4590 | // UnreachableInst Class |
4591 | //===----------------------------------------------------------------------===// |
4592 | |
4593 | //===--------------------------------------------------------------------------- |
4594 | /// This function has undefined behavior. In particular, the |
4595 | /// presence of this instruction indicates some higher level knowledge that the |
4596 | /// end of the block cannot be reached. |
4597 | /// |
4598 | class UnreachableInst : public Instruction { |
4599 | protected: |
4600 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4601 | friend class Instruction; |
4602 | |
4603 | UnreachableInst *cloneImpl() const; |
4604 | |
4605 | public: |
4606 | explicit UnreachableInst(LLVMContext &C, Instruction *InsertBefore = nullptr); |
4607 | explicit UnreachableInst(LLVMContext &C, BasicBlock *InsertAtEnd); |
4608 | |
4609 | // allocate space for exactly zero operands |
4610 | void *operator new(size_t s) { |
4611 | return User::operator new(s, 0); |
4612 | } |
4613 | |
4614 | unsigned getNumSuccessors() const { return 0; } |
4615 | |
4616 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
4617 | static bool classof(const Instruction *I) { |
4618 | return I->getOpcode() == Instruction::Unreachable; |
4619 | } |
4620 | static bool classof(const Value *V) { |
4621 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4622 | } |
4623 | |
4624 | private: |
4625 | BasicBlock *getSuccessor(unsigned idx) const { |
4626 | llvm_unreachable("UnreachableInst has no successors!")::llvm::llvm_unreachable_internal("UnreachableInst has no successors!" , "/build/llvm-toolchain-snapshot-9~svn360825/include/llvm/IR/Instructions.h" , 4626); |
4627 | } |
4628 | |
4629 | void setSuccessor(unsigned idx, BasicBlock *B) { |
4630 | llvm_unreachable("UnreachableInst has no successors!")::llvm::llvm_unreachable_internal("UnreachableInst has no successors!" , "/build/llvm-toolchain-snapshot-9~svn360825/include/llvm/IR/Instructions.h" , 4630); |
4631 | } |
4632 | }; |
4633 | |
4634 | //===----------------------------------------------------------------------===// |
4635 | // TruncInst Class |
4636 | //===----------------------------------------------------------------------===// |
4637 | |
4638 | /// This class represents a truncation of integer types. |
4639 | class TruncInst : public CastInst { |
4640 | protected: |
4641 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4642 | friend class Instruction; |
4643 | |
4644 | /// Clone an identical TruncInst |
4645 | TruncInst *cloneImpl() const; |
4646 | |
4647 | public: |
4648 | /// Constructor with insert-before-instruction semantics |
4649 | TruncInst( |
4650 | Value *S, ///< The value to be truncated |
4651 | Type *Ty, ///< The (smaller) type to truncate to |
4652 | const Twine &NameStr = "", ///< A name for the new instruction |
4653 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
4654 | ); |
4655 | |
4656 | /// Constructor with insert-at-end-of-block semantics |
4657 | TruncInst( |
4658 | Value *S, ///< The value to be truncated |
4659 | Type *Ty, ///< The (smaller) type to truncate to |
4660 | const Twine &NameStr, ///< A name for the new instruction |
4661 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
4662 | ); |
4663 | |
4664 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
4665 | static bool classof(const Instruction *I) { |
4666 | return I->getOpcode() == Trunc; |
4667 | } |
4668 | static bool classof(const Value *V) { |
4669 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4670 | } |
4671 | }; |
4672 | |
4673 | //===----------------------------------------------------------------------===// |
4674 | // ZExtInst Class |
4675 | //===----------------------------------------------------------------------===// |
4676 | |
4677 | /// This class represents zero extension of integer types. |
4678 | class ZExtInst : public CastInst { |
4679 | protected: |
4680 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4681 | friend class Instruction; |
4682 | |
4683 | /// Clone an identical ZExtInst |
4684 | ZExtInst *cloneImpl() const; |
4685 | |
4686 | public: |
4687 | /// Constructor with insert-before-instruction semantics |
4688 | ZExtInst( |
4689 | Value *S, ///< The value to be zero extended |
4690 | Type *Ty, ///< The type to zero extend to |
4691 | const Twine &NameStr = "", ///< A name for the new instruction |
4692 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
4693 | ); |
4694 | |
4695 | /// Constructor with insert-at-end semantics. |
4696 | ZExtInst( |
4697 | Value *S, ///< The value to be zero extended |
4698 | Type *Ty, ///< The type to zero extend to |
4699 | const Twine &NameStr, ///< A name for the new instruction |
4700 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
4701 | ); |
4702 | |
4703 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
4704 | static bool classof(const Instruction *I) { |
4705 | return I->getOpcode() == ZExt; |
4706 | } |
4707 | static bool classof(const Value *V) { |
4708 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4709 | } |
4710 | }; |
4711 | |
4712 | //===----------------------------------------------------------------------===// |
4713 | // SExtInst Class |
4714 | //===----------------------------------------------------------------------===// |
4715 | |
4716 | /// This class represents a sign extension of integer types. |
4717 | class SExtInst : public CastInst { |
4718 | protected: |
4719 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4720 | friend class Instruction; |
4721 | |
4722 | /// Clone an identical SExtInst |
4723 | SExtInst *cloneImpl() const; |
4724 | |
4725 | public: |
4726 | /// Constructor with insert-before-instruction semantics |
4727 | SExtInst( |
4728 | Value *S, ///< The value to be sign extended |
4729 | Type *Ty, ///< The type to sign extend to |
4730 | const Twine &NameStr = "", ///< A name for the new instruction |
4731 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
4732 | ); |
4733 | |
4734 | /// Constructor with insert-at-end-of-block semantics |
4735 | SExtInst( |
4736 | Value *S, ///< The value to be sign extended |
4737 | Type *Ty, ///< The type to sign extend to |
4738 | const Twine &NameStr, ///< A name for the new instruction |
4739 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
4740 | ); |
4741 | |
4742 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
4743 | static bool classof(const Instruction *I) { |
4744 | return I->getOpcode() == SExt; |
4745 | } |
4746 | static bool classof(const Value *V) { |
4747 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4748 | } |
4749 | }; |
4750 | |
4751 | //===----------------------------------------------------------------------===// |
4752 | // FPTruncInst Class |
4753 | //===----------------------------------------------------------------------===// |
4754 | |
4755 | /// This class represents a truncation of floating point types. |
4756 | class FPTruncInst : public CastInst { |
4757 | protected: |
4758 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4759 | friend class Instruction; |
4760 | |
4761 | /// Clone an identical FPTruncInst |
4762 | FPTruncInst *cloneImpl() const; |
4763 | |
4764 | public: |
4765 | /// Constructor with insert-before-instruction semantics |
4766 | FPTruncInst( |
4767 | Value *S, ///< The value to be truncated |
4768 | Type *Ty, ///< The type to truncate to |
4769 | const Twine &NameStr = "", ///< A name for the new instruction |
4770 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
4771 | ); |
4772 | |
4773 | /// Constructor with insert-before-instruction semantics |
4774 | FPTruncInst( |
4775 | Value *S, ///< The value to be truncated |
4776 | Type *Ty, ///< The type to truncate to |
4777 | const Twine &NameStr, ///< A name for the new instruction |
4778 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
4779 | ); |
4780 | |
4781 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
4782 | static bool classof(const Instruction *I) { |
4783 | return I->getOpcode() == FPTrunc; |
4784 | } |
4785 | static bool classof(const Value *V) { |
4786 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4787 | } |
4788 | }; |
4789 | |
4790 | //===----------------------------------------------------------------------===// |
4791 | // FPExtInst Class |
4792 | //===----------------------------------------------------------------------===// |
4793 | |
4794 | /// This class represents an extension of floating point types. |
4795 | class FPExtInst : public CastInst { |
4796 | protected: |
4797 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4798 | friend class Instruction; |
4799 | |
4800 | /// Clone an identical FPExtInst |
4801 | FPExtInst *cloneImpl() const; |
4802 | |
4803 | public: |
4804 | /// Constructor with insert-before-instruction semantics |
4805 | FPExtInst( |
4806 | Value *S, ///< The value to be extended |
4807 | Type *Ty, ///< The type to extend to |
4808 | const Twine &NameStr = "", ///< A name for the new instruction |
4809 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
4810 | ); |
4811 | |
4812 | /// Constructor with insert-at-end-of-block semantics |
4813 | FPExtInst( |
4814 | Value *S, ///< The value to be extended |
4815 | Type *Ty, ///< The type to extend to |
4816 | const Twine &NameStr, ///< A name for the new instruction |
4817 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
4818 | ); |
4819 | |
4820 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
4821 | static bool classof(const Instruction *I) { |
4822 | return I->getOpcode() == FPExt; |
4823 | } |
4824 | static bool classof(const Value *V) { |
4825 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4826 | } |
4827 | }; |
4828 | |
4829 | //===----------------------------------------------------------------------===// |
4830 | // UIToFPInst Class |
4831 | //===----------------------------------------------------------------------===// |
4832 | |
4833 | /// This class represents a cast unsigned integer to floating point. |
4834 | class UIToFPInst : public CastInst { |
4835 | protected: |
4836 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4837 | friend class Instruction; |
4838 | |
4839 | /// Clone an identical UIToFPInst |
4840 | UIToFPInst *cloneImpl() const; |
4841 | |
4842 | public: |
4843 | /// Constructor with insert-before-instruction semantics |
4844 | UIToFPInst( |
4845 | Value *S, ///< The value to be converted |
4846 | Type *Ty, ///< The type to convert to |
4847 | const Twine &NameStr = "", ///< A name for the new instruction |
4848 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
4849 | ); |
4850 | |
4851 | /// Constructor with insert-at-end-of-block semantics |
4852 | UIToFPInst( |
4853 | Value *S, ///< The value to be converted |
4854 | Type *Ty, ///< The type to convert to |
4855 | const Twine &NameStr, ///< A name for the new instruction |
4856 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
4857 | ); |
4858 | |
4859 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
4860 | static bool classof(const Instruction *I) { |
4861 | return I->getOpcode() == UIToFP; |
4862 | } |
4863 | static bool classof(const Value *V) { |
4864 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4865 | } |
4866 | }; |
4867 | |
4868 | //===----------------------------------------------------------------------===// |
4869 | // SIToFPInst Class |
4870 | //===----------------------------------------------------------------------===// |
4871 | |
4872 | /// This class represents a cast from signed integer to floating point. |
4873 | class SIToFPInst : public CastInst { |
4874 | protected: |
4875 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4876 | friend class Instruction; |
4877 | |
4878 | /// Clone an identical SIToFPInst |
4879 | SIToFPInst *cloneImpl() const; |
4880 | |
4881 | public: |
4882 | /// Constructor with insert-before-instruction semantics |
4883 | SIToFPInst( |
4884 | Value *S, ///< The value to be converted |
4885 | Type *Ty, ///< The type to convert to |
4886 | const Twine &NameStr = "", ///< A name for the new instruction |
4887 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
4888 | ); |
4889 | |
4890 | /// Constructor with insert-at-end-of-block semantics |
4891 | SIToFPInst( |
4892 | Value *S, ///< The value to be converted |
4893 | Type *Ty, ///< The type to convert to |
4894 | const Twine &NameStr, ///< A name for the new instruction |
4895 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
4896 | ); |
4897 | |
4898 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
4899 | static bool classof(const Instruction *I) { |
4900 | return I->getOpcode() == SIToFP; |
4901 | } |
4902 | static bool classof(const Value *V) { |
4903 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4904 | } |
4905 | }; |
4906 | |
4907 | //===----------------------------------------------------------------------===// |
4908 | // FPToUIInst Class |
4909 | //===----------------------------------------------------------------------===// |
4910 | |
4911 | /// This class represents a cast from floating point to unsigned integer |
4912 | class FPToUIInst : public CastInst { |
4913 | protected: |
4914 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4915 | friend class Instruction; |
4916 | |
4917 | /// Clone an identical FPToUIInst |
4918 | FPToUIInst *cloneImpl() const; |
4919 | |
4920 | public: |
4921 | /// Constructor with insert-before-instruction semantics |
4922 | FPToUIInst( |
4923 | Value *S, ///< The value to be converted |
4924 | Type *Ty, ///< The type to convert to |
4925 | const Twine &NameStr = "", ///< A name for the new instruction |
4926 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
4927 | ); |
4928 | |
4929 | /// Constructor with insert-at-end-of-block semantics |
4930 | FPToUIInst( |
4931 | Value *S, ///< The value to be converted |
4932 | Type *Ty, ///< The type to convert to |
4933 | const Twine &NameStr, ///< A name for the new instruction |
4934 | BasicBlock *InsertAtEnd ///< Where to insert the new instruction |
4935 | ); |
4936 | |
4937 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
4938 | static bool classof(const Instruction *I) { |
4939 | return I->getOpcode() == FPToUI; |
4940 | } |
4941 | static bool classof(const Value *V) { |
4942 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4943 | } |
4944 | }; |
4945 | |
4946 | //===----------------------------------------------------------------------===// |
4947 | // FPToSIInst Class |
4948 | //===----------------------------------------------------------------------===// |
4949 | |
4950 | /// This class represents a cast from floating point to signed integer. |
4951 | class FPToSIInst : public CastInst { |
4952 | protected: |
4953 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4954 | friend class Instruction; |
4955 | |
4956 | /// Clone an identical FPToSIInst |
4957 | FPToSIInst *cloneImpl() const; |
4958 | |
4959 | public: |
4960 | /// Constructor with insert-before-instruction semantics |
4961 | FPToSIInst( |
4962 | Value *S, ///< The value to be converted |
4963 | Type *Ty, ///< The type to convert to |
4964 | const Twine &NameStr = "", ///< A name for the new instruction |
4965 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
4966 | ); |
4967 | |
4968 | /// Constructor with insert-at-end-of-block semantics |
4969 | FPToSIInst( |
4970 | Value *S, ///< The value to be converted |
4971 | Type *Ty, ///< The type to convert to |
4972 | const Twine &NameStr, ///< A name for the new instruction |
4973 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
4974 | ); |
4975 | |
4976 | /// Methods for support type inquiry through isa, cast, and dyn_cast: |
4977 | static bool classof(const Instruction *I) { |
4978 | return I->getOpcode() == FPToSI; |
4979 | } |
4980 | static bool classof(const Value *V) { |
4981 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
4982 | } |
4983 | }; |
4984 | |
4985 | //===----------------------------------------------------------------------===// |
4986 | // IntToPtrInst Class |
4987 | //===----------------------------------------------------------------------===// |
4988 | |
4989 | /// This class represents a cast from an integer to a pointer. |
4990 | class IntToPtrInst : public CastInst { |
4991 | public: |
4992 | // Note: Instruction needs to be a friend here to call cloneImpl. |
4993 | friend class Instruction; |
4994 | |
4995 | /// Constructor with insert-before-instruction semantics |
4996 | IntToPtrInst( |
4997 | Value *S, ///< The value to be converted |
4998 | Type *Ty, ///< The type to convert to |
4999 | const Twine &NameStr = "", ///< A name for the new instruction |
5000 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
5001 | ); |
5002 | |
5003 | /// Constructor with insert-at-end-of-block semantics |
5004 | IntToPtrInst( |
5005 | Value *S, ///< The value to be converted |
5006 | Type *Ty, ///< The type to convert to |
5007 | const Twine &NameStr, ///< A name for the new instruction |
5008 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
5009 | ); |
5010 | |
5011 | /// Clone an identical IntToPtrInst. |
5012 | IntToPtrInst *cloneImpl() const; |
5013 | |
5014 | /// Returns the address space of this instruction's pointer type. |
5015 | unsigned getAddressSpace() const { |
5016 | return getType()->getPointerAddressSpace(); |
5017 | } |
5018 | |
5019 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
5020 | static bool classof(const Instruction *I) { |
5021 | return I->getOpcode() == IntToPtr; |
5022 | } |
5023 | static bool classof(const Value *V) { |
5024 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
5025 | } |
5026 | }; |
5027 | |
5028 | //===----------------------------------------------------------------------===// |
5029 | // PtrToIntInst Class |
5030 | //===----------------------------------------------------------------------===// |
5031 | |
5032 | /// This class represents a cast from a pointer to an integer. |
5033 | class PtrToIntInst : public CastInst { |
5034 | protected: |
5035 | // Note: Instruction needs to be a friend here to call cloneImpl. |
5036 | friend class Instruction; |
5037 | |
5038 | /// Clone an identical PtrToIntInst. |
5039 | PtrToIntInst *cloneImpl() const; |
5040 | |
5041 | public: |
5042 | /// Constructor with insert-before-instruction semantics |
5043 | PtrToIntInst( |
5044 | Value *S, ///< The value to be converted |
5045 | Type *Ty, ///< The type to convert to |
5046 | const Twine &NameStr = "", ///< A name for the new instruction |
5047 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
5048 | ); |
5049 | |
5050 | /// Constructor with insert-at-end-of-block semantics |
5051 | PtrToIntInst( |
5052 | Value *S, ///< The value to be converted |
5053 | Type *Ty, ///< The type to convert to |
5054 | const Twine &NameStr, ///< A name for the new instruction |
5055 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
5056 | ); |
5057 | |
5058 | /// Gets the pointer operand. |
5059 | Value *getPointerOperand() { return getOperand(0); } |
5060 | /// Gets the pointer operand. |
5061 | const Value *getPointerOperand() const { return getOperand(0); } |
5062 | /// Gets the operand index of the pointer operand. |
5063 | static unsigned getPointerOperandIndex() { return 0U; } |
5064 | |
5065 | /// Returns the address space of the pointer operand. |
5066 | unsigned getPointerAddressSpace() const { |
5067 | return getPointerOperand()->getType()->getPointerAddressSpace(); |
5068 | } |
5069 | |
5070 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
5071 | static bool classof(const Instruction *I) { |
5072 | return I->getOpcode() == PtrToInt; |
5073 | } |
5074 | static bool classof(const Value *V) { |
5075 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
5076 | } |
5077 | }; |
5078 | |
5079 | //===----------------------------------------------------------------------===// |
5080 | // BitCastInst Class |
5081 | //===----------------------------------------------------------------------===// |
5082 | |
5083 | /// This class represents a no-op cast from one type to another. |
5084 | class BitCastInst : public CastInst { |
5085 | protected: |
5086 | // Note: Instruction needs to be a friend here to call cloneImpl. |
5087 | friend class Instruction; |
5088 | |
5089 | /// Clone an identical BitCastInst. |
5090 | BitCastInst *cloneImpl() const; |
5091 | |
5092 | public: |
5093 | /// Constructor with insert-before-instruction semantics |
5094 | BitCastInst( |
5095 | Value *S, ///< The value to be casted |
5096 | Type *Ty, ///< The type to casted to |
5097 | const Twine &NameStr = "", ///< A name for the new instruction |
5098 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
5099 | ); |
5100 | |
5101 | /// Constructor with insert-at-end-of-block semantics |
5102 | BitCastInst( |
5103 | Value *S, ///< The value to be casted |
5104 | Type *Ty, ///< The type to casted to |
5105 | const Twine &NameStr, ///< A name for the new instruction |
5106 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
5107 | ); |
5108 | |
5109 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
5110 | static bool classof(const Instruction *I) { |
5111 | return I->getOpcode() == BitCast; |
5112 | } |
5113 | static bool classof(const Value *V) { |
5114 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
5115 | } |
5116 | }; |
5117 | |
5118 | //===----------------------------------------------------------------------===// |
5119 | // AddrSpaceCastInst Class |
5120 | //===----------------------------------------------------------------------===// |
5121 | |
5122 | /// This class represents a conversion between pointers from one address space |
5123 | /// to another. |
5124 | class AddrSpaceCastInst : public CastInst { |
5125 | protected: |
5126 | // Note: Instruction needs to be a friend here to call cloneImpl. |
5127 | friend class Instruction; |
5128 | |
5129 | /// Clone an identical AddrSpaceCastInst. |
5130 | AddrSpaceCastInst *cloneImpl() const; |
5131 | |
5132 | public: |
5133 | /// Constructor with insert-before-instruction semantics |
5134 | AddrSpaceCastInst( |
5135 | Value *S, ///< The value to be casted |
5136 | Type *Ty, ///< The type to casted to |
5137 | const Twine &NameStr = "", ///< A name for the new instruction |
5138 | Instruction *InsertBefore = nullptr ///< Where to insert the new instruction |
5139 | ); |
5140 | |
5141 | /// Constructor with insert-at-end-of-block semantics |
5142 | AddrSpaceCastInst( |
5143 | Value *S, ///< The value to be casted |
5144 | Type *Ty, ///< The type to casted to |
5145 | const Twine &NameStr, ///< A name for the new instruction |
5146 | BasicBlock *InsertAtEnd ///< The block to insert the instruction into |
5147 | ); |
5148 | |
5149 | // Methods for support type inquiry through isa, cast, and dyn_cast: |
5150 | static bool classof(const Instruction *I) { |
5151 | return I->getOpcode() == AddrSpaceCast; |
5152 | } |
5153 | static bool classof(const Value *V) { |
5154 | return isa<Instruction>(V) && classof(cast<Instruction>(V)); |
5155 | } |
5156 | |
5157 | /// Gets the pointer operand. |
5158 | Value *getPointerOperand() { |
5159 | return getOperand(0); |
5160 | } |
5161 | |
5162 | /// Gets the pointer operand. |
5163 | const Value *getPointerOperand() const { |
5164 | return getOperand(0); |
5165 | } |
5166 | |
5167 | /// Gets the operand index of the pointer operand. |
5168 | static unsigned getPointerOperandIndex() { |
5169 | return 0U; |
5170 | } |
5171 | |
5172 | /// Returns the address space of the pointer operand. |
5173 | unsigned getSrcAddressSpace() const { |
5174 | return getPointerOperand()->getType()->getPointerAddressSpace(); |
5175 | } |
5176 | |
5177 | /// Returns the address space of the result. |
5178 | unsigned getDestAddressSpace() const { |
5179 | return getType()->getPointerAddressSpace(); |
5180 | } |
5181 | }; |
5182 | |
5183 | /// A helper function that returns the pointer operand of a load or store |
5184 | /// instruction. Returns nullptr if not load or store. |
5185 | inline Value *getLoadStorePointerOperand(Value *V) { |
5186 | if (auto *Load = dyn_cast<LoadInst>(V)) |
5187 | return Load->getPointerOperand(); |
5188 | if (auto *Store = dyn_cast<StoreInst>(V)) |
5189 | return Store->getPointerOperand(); |
5190 | return nullptr; |
5191 | } |
5192 | |
5193 | /// A helper function that returns the pointer operand of a load, store |
5194 | /// or GEP instruction. Returns nullptr if not load, store, or GEP. |
5195 | inline Value *getPointerOperand(Value *V) { |
5196 | if (auto *Ptr = getLoadStorePointerOperand(V)) |
5197 | return Ptr; |
5198 | if (auto *Gep = dyn_cast<GetElementPtrInst>(V)) |
5199 | return Gep->getPointerOperand(); |
5200 | return nullptr; |
5201 | } |
5202 | |
5203 | /// A helper function that returns the alignment of load or store instruction. |
5204 | inline unsigned getLoadStoreAlignment(Value *I) { |
5205 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 5206, __PRETTY_FUNCTION__)) |
5206 | "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-9~svn360825/include/llvm/IR/Instructions.h" , 5206, __PRETTY_FUNCTION__)); |
5207 | if (auto *LI = dyn_cast<LoadInst>(I)) |
5208 | return LI->getAlignment(); |
5209 | return cast<StoreInst>(I)->getAlignment(); |
5210 | } |
5211 | |
5212 | /// A helper function that returns the address space of the pointer operand of |
5213 | /// load or store instruction. |
5214 | inline unsigned getLoadStoreAddressSpace(Value *I) { |
5215 | 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-9~svn360825/include/llvm/IR/Instructions.h" , 5216, __PRETTY_FUNCTION__)) |
5216 | "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-9~svn360825/include/llvm/IR/Instructions.h" , 5216, __PRETTY_FUNCTION__)); |
5217 | if (auto *LI = dyn_cast<LoadInst>(I)) |
5218 | return LI->getPointerAddressSpace(); |
5219 | return cast<StoreInst>(I)->getPointerAddressSpace(); |
5220 | } |
5221 | |
5222 | } // end namespace llvm |
5223 | |
5224 | #endif // LLVM_IR_INSTRUCTIONS_H |
1 | //===- llvm/Use.h - Definition of the Use class -----------------*- 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 | /// \file |
9 | /// |
10 | /// This defines the Use class. The Use class represents the operand of an |
11 | /// instruction or some other User instance which refers to a Value. The Use |
12 | /// class keeps the "use list" of the referenced value up to date. |
13 | /// |
14 | /// Pointer tagging is used to efficiently find the User corresponding to a Use |
15 | /// without having to store a User pointer in every Use. A User is preceded in |
16 | /// memory by all the Uses corresponding to its operands, and the low bits of |
17 | /// one of the fields (Prev) of the Use class are used to encode offsets to be |
18 | /// able to find that User given a pointer to any Use. For details, see: |
19 | /// |
20 | /// http://www.llvm.org/docs/ProgrammersManual.html#UserLayout |
21 | /// |
22 | //===----------------------------------------------------------------------===// |
23 | |
24 | #ifndef LLVM_IR_USE_H |
25 | #define LLVM_IR_USE_H |
26 | |
27 | #include "llvm-c/Types.h" |
28 | #include "llvm/ADT/PointerIntPair.h" |
29 | #include "llvm/Support/CBindingWrapping.h" |
30 | #include "llvm/Support/Compiler.h" |
31 | |
32 | namespace llvm { |
33 | |
34 | template <typename> struct simplify_type; |
35 | class User; |
36 | class Value; |
37 | |
38 | /// A Use represents the edge between a Value definition and its users. |
39 | /// |
40 | /// This is notionally a two-dimensional linked list. It supports traversing |
41 | /// all of the uses for a particular value definition. It also supports jumping |
42 | /// directly to the used value when we arrive from the User's operands, and |
43 | /// jumping directly to the User when we arrive from the Value's uses. |
44 | /// |
45 | /// The pointer to the used Value is explicit, and the pointer to the User is |
46 | /// implicit. The implicit pointer is found via a waymarking algorithm |
47 | /// described in the programmer's manual: |
48 | /// |
49 | /// http://www.llvm.org/docs/ProgrammersManual.html#the-waymarking-algorithm |
50 | /// |
51 | /// This is essentially the single most memory intensive object in LLVM because |
52 | /// of the number of uses in the system. At the same time, the constant time |
53 | /// operations it allows are essential to many optimizations having reasonable |
54 | /// time complexity. |
55 | class Use { |
56 | public: |
57 | Use(const Use &U) = delete; |
58 | |
59 | /// Provide a fast substitute to std::swap<Use> |
60 | /// that also works with less standard-compliant compilers |
61 | void swap(Use &RHS); |
62 | |
63 | /// Pointer traits for the UserRef PointerIntPair. This ensures we always |
64 | /// use the LSB regardless of pointer alignment on different targets. |
65 | struct UserRefPointerTraits { |
66 | static inline void *getAsVoidPointer(User *P) { return P; } |
67 | |
68 | static inline User *getFromVoidPointer(void *P) { |
69 | return (User *)P; |
70 | } |
71 | |
72 | enum { NumLowBitsAvailable = 1 }; |
73 | }; |
74 | |
75 | // A type for the word following an array of hung-off Uses in memory, which is |
76 | // a pointer back to their User with the bottom bit set. |
77 | using UserRef = PointerIntPair<User *, 1, unsigned, UserRefPointerTraits>; |
78 | |
79 | /// Pointer traits for the Prev PointerIntPair. This ensures we always use |
80 | /// the two LSBs regardless of pointer alignment on different targets. |
81 | struct PrevPointerTraits { |
82 | static inline void *getAsVoidPointer(Use **P) { return P; } |
83 | |
84 | static inline Use **getFromVoidPointer(void *P) { |
85 | return (Use **)P; |
86 | } |
87 | |
88 | enum { NumLowBitsAvailable = 2 }; |
89 | }; |
90 | |
91 | private: |
92 | /// Destructor - Only for zap() |
93 | ~Use() { |
94 | if (Val) |
95 | removeFromList(); |
96 | } |
97 | |
98 | enum PrevPtrTag { zeroDigitTag, oneDigitTag, stopTag, fullStopTag }; |
99 | |
100 | /// Constructor |
101 | Use(PrevPtrTag tag) { Prev.setInt(tag); } |
102 | |
103 | public: |
104 | friend class Value; |
105 | |
106 | operator Value *() const { return Val; } |
107 | Value *get() const { return Val; } |
108 | |
109 | /// Returns the User that contains this Use. |
110 | /// |
111 | /// For an instruction operand, for example, this will return the |
112 | /// instruction. |
113 | User *getUser() const LLVM_READONLY__attribute__((__pure__)); |
114 | |
115 | inline void set(Value *Val); |
116 | |
117 | inline Value *operator=(Value *RHS); |
118 | inline const Use &operator=(const Use &RHS); |
119 | |
120 | Value *operator->() { return Val; } |
121 | const Value *operator->() const { return Val; } |
122 | |
123 | Use *getNext() const { return Next; } |
124 | |
125 | /// Return the operand # of this use in its User. |
126 | unsigned getOperandNo() const; |
127 | |
128 | /// Initializes the waymarking tags on an array of Uses. |
129 | /// |
130 | /// This sets up the array of Uses such that getUser() can find the User from |
131 | /// any of those Uses. |
132 | static Use *initTags(Use *Start, Use *Stop); |
133 | |
134 | /// Destroys Use operands when the number of operands of |
135 | /// a User changes. |
136 | static void zap(Use *Start, const Use *Stop, bool del = false); |
137 | |
138 | private: |
139 | const Use *getImpliedUser() const LLVM_READONLY__attribute__((__pure__)); |
140 | |
141 | Value *Val = nullptr; |
142 | Use *Next; |
143 | PointerIntPair<Use **, 2, PrevPtrTag, PrevPointerTraits> Prev; |
144 | |
145 | void setPrev(Use **NewPrev) { Prev.setPointer(NewPrev); } |
146 | |
147 | void addToList(Use **List) { |
148 | Next = *List; |
149 | if (Next) |
150 | Next->setPrev(&Next); |
151 | setPrev(List); |
152 | *List = this; |
153 | } |
154 | |
155 | void removeFromList() { |
156 | Use **StrippedPrev = Prev.getPointer(); |
157 | *StrippedPrev = Next; |
158 | if (Next) |
159 | Next->setPrev(StrippedPrev); |
160 | } |
161 | }; |
162 | |
163 | /// Allow clients to treat uses just like values when using |
164 | /// casting operators. |
165 | template <> struct simplify_type<Use> { |
166 | using SimpleType = Value *; |
167 | |
168 | static SimpleType getSimplifiedValue(Use &Val) { return Val.get(); } |
169 | }; |
170 | template <> struct simplify_type<const Use> { |
171 | using SimpleType = /*const*/ Value *; |
172 | |
173 | static SimpleType getSimplifiedValue(const Use &Val) { return Val.get(); } |
174 | }; |
175 | |
176 | // Create wrappers for C Binding types (see CBindingWrapping.h). |
177 | DEFINE_SIMPLE_CONVERSION_FUNCTIONS(Use, LLVMUseRef)inline Use *unwrap(LLVMUseRef P) { return reinterpret_cast< Use*>(P); } inline LLVMUseRef wrap(const Use *P) { return reinterpret_cast <LLVMUseRef>(const_cast<Use*>(P)); } |
178 | |
179 | } // end namespace llvm |
180 | |
181 | #endif // LLVM_IR_USE_H |